/*
	Last published on : 15-Dec-11 11:35
	Location          : \commercial\selfassist\cms\selfassist\static\js
	Filename          : selfassist.js
*/
var SelfAssist = function (country, lang) { 
    //General 
    this.base_url = "/commercial/selfassist/faq-web";
    this.loading_url = 'loading.htm';
    this.popup = 0;

    //Language Settings
    this.country = 'nl';
    this.lang = 'en';
  
  /*if(country == null && lang == null && YAHOO.util.Cookie.get("countryLanguage") != null){
    var sLanguageSetting = YAHOO.util.Cookie.get("countryLanguage");
    this.country = sLanguageSetting.split('_')[0];
    this.lang = sLanguageSetting.split('_')[1];
  }else{*/
    if (typeof country !== 'undefined' && country !== null) {
        this.country = country;
    }
    if (typeof lang !== 'undefined' && lang !== null) {
        this.lang = lang;
    }
  //}

    if (YAHOO.util.Cookie && YAHOO.util.Cookie.get("popup") !== null) {
        this.popup = YAHOO.util.Cookie.get("popup");
    } else if (this.getCookie("popup") !== null) {
        this.popup = this.getCookie("popup");
    }
    //Self Assist controls
    //Container
    this.container = YAHOO.util.Dom.get("sa-container");
    this.container.style.display = 'block';

    var parentContainer = this.container.parentNode;
    this.layOver = new Overlay(parentContainer, {speed: .9, opacity: .8, animate: true, id:'sa-overlay'});
    this.layOver.addOnClickHandler(this);

    //Form
    this.defaultInput = YAHOO.util.Dom.get("mySearch");
    this.defaultButton = YAHOO.util.Dom.get("supportZoekLink");
    this.addForm(this.defaultInput, this.defaultButton);

    //Tabs
    this.searchTab = YAHOO.util.Dom.get("zoektab");
    this.catTab = YAHOO.util.Dom.get("tabcat");
    YAHOO.util.Event.addListener(this.catTab.getElementsByTagName('a')[0], 'click', this.onTabClickHandler, this.catTab)
    this.faqTab = YAHOO.util.Dom.get("tabfaq");
    YAHOO.util.Event.addListener(this.faqTab.getElementsByTagName('a')[0], 'click', this.onTabClickHandler, this.faqTab)
    this.closeTab = YAHOO.util.Dom.get("tabclose");
    YAHOO.util.Event.addListener(this.closeTab.getElementsByTagName('a')[0], 'click', this.onTabClickHandler, this.closeTab)

    //Iframe
    this.iframe = YAHOO.util.Dom.get("sa-iframe");
    this.iframe.style.visibility = "hidden";
    YAHOO.util.Event.addListener(this.iframe, 'load', this.resetTabs, this);

    //Default SearchTerm
    this.searchTerm = "";
    this.defaultSearchTerm = this.defaultInput.value;

    //Load QueryString Listener
    this.loadFromQueryString(window.location.search.substring(1));
};

/** getQSVar
 * Get a variable value from the querystring
 * @param varname
 */
SelfAssist.prototype.getQSVar = function (varname) {
    var hu, gy, returnValue, i, ft;
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i += 1) {
        ft = gy[i].split("=");
        if (ft[0] === varname) {
          returnValue = ft[1];
        }
    }
    return returnValue;
};

SelfAssist.prototype.getCookie = function (c_name) {
    var c_start;
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start !== -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end === -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return null;
};

/** loadFromQueryString
 * Checks for variables used in the querystring that loads the SelfAssist Popup
 * @param queryString
 */
SelfAssist.prototype.loadFromQueryString = function (queryString) {
    if (this.getQSVar("sa_url") !== null) {
        //By URL
        this.loadUri(Url.decode(this.getQSVar("sa_url")));
    } else if (this.getQSVar('q') !== null) {
        //By Question
        this.ask(this.getQSVar('q'));
    } else if (this.getQSVar('q_cat') !== null) {
        //By Category
        this.cat(this.getQSVar('q_cat'));
    } else if (this.getQSVar('q_faq') !== null) {
        //By FAQ Category (If category is '1', general top 10 will be opened)
        if (this.getQSVar('q_faq') !== 1) {
          this.faq(this.getQSVar('q_faq'));
        } else {
          this.faq();
        }
    }
};

/** addForm
 * Add a form to listen to. When the button is clicked SelfAssist will handle the click event.
 * @param oInput
 * @param oButton
 */
SelfAssist.prototype.addForm = function (oInput, oButton) {
    YAHOO.util.Event.purgeElement(oInput, true);
    YAHOO.util.Event.purgeElement(oButton, true);
    YAHOO.util.Event.addListener(oButton, "click", this.onSubmitHandler, oInput, true);
    YAHOO.util.Event.addListener(oInput, "keyup", this.onSubmitHandler, oInput, true);
    YAHOO.util.Event.addListener(oInput, "focus", this.inputFocus, oInput, true);
    YAHOO.util.Event.addListener(oInput, "blur", this.inputBlur, oInput, true);
};

/** ask
 * Loads a searchresult for selfassist.
 * @param query
 */
SelfAssist.prototype.ask = function (query) {
    if (query !== this.defaultSearchTerm) {
        this.searchTerm = query;
    }
    if (query !== this.defaultSearchTerm && query !== ''){
        this.loadUri('ask.htm', '&query=' + encodeURIComponent(query));
    } else {
        this.loadUri('start.htm');
    }
    this.defaultInput.value = '';
    this.defaultButton.focus();
    this.inputBlur(null, this.defaultInput);
};

/** cat
 * Loads a categoryoverview by default. 
 * When a category id is supplied the top 10 for that category is loaded.
 * @param category_id (optional)
 */
SelfAssist.prototype.cat = function (category_id) {
    if (!!category_id) {
        this.loadUri('categoryQuestions.htm', '&cid=' + category_id);
    } else {
        this.loadUri('categories.htm');
    }
};

/** faq
 * Loads a faq10 for general category by default. 
 * When a category id is supplied the top 10 for that category is loaded.
 * @param category_id (optional)
 */
SelfAssist.prototype.faq = function (category_id) {
    if (!!category_id) {
        this.loadUri('categoryQuestions.htm', '&cid=' + category_id);
    } else {
        this.loadUri('topx.htm');
    }
};

/** loadUri
 * Loads an url into the iframe.
 * @param url
 */
SelfAssist.prototype.loadUri = function (url) {
    var params = '', uri = '', idx = '';
    if (url.indexOf('?') < 0) {
        params = '?locale=' + this.country + '_' + this.lang + '&popup=' + this.popup;
        if (arguments.length > 1) {
            params = params + arguments[1];
        }
    }

    //Only relative urls are allowed.
    if (url.indexOf(':') >= 0 && url.indexOf(':') <= 10) {
        idx = url.lastIndexOf('/');
        url = idx < 15 ? '404.htm' : url.substr(idx + 1);
    }

    uri = this.base_url + '/' + url + params;

    //if layover is hidden, open it.
    if (this.container.className !== "open") {
        this.layOver.show();
        this.open(uri);
    } else {
        this.iframe.src = uri;
    }
};

/** resetTabs
 * Selects the current tab and deselects the others.
 * @param oTab
 */
SelfAssist.prototype.resetTabs = function (e, obj) {
    var oActiveTab = null;
    var uri = obj.iframe.contentWindow.document.location.href;
    if (uri.match("categories.htm") || uri.match("allCategoryQuestions.htm") || uri.match("categoryQuestions.htm")) {
        oActiveTab = obj.catTab;
    } else if (uri.match("topx.htm")) {
        oActiveTab = obj.faqTab;
    } else {
        oActiveTab = obj.searchTab;
    }
    //reset css classes
    YAHOO.util.Dom.removeClass(obj.searchTab.id, 'actief');
    YAHOO.util.Dom.removeClass(obj.catTab.id, 'actief');
    YAHOO.util.Dom.removeClass(obj.faqTab.id, 'actief');
    YAHOO.util.Dom.removeClass(obj.closeTab.id, 'actief');
    YAHOO.util.Dom.addClass(oActiveTab, 'actief');
}

/** finishOpen 
 * Callback function for open event. Shows the iframe.
 */
SelfAssist.prototype.finishOpen = function (type, args, uri) {
    this.sa.iframe.src = uri;
    this.sa.iframe.style.visibility = "visible";
};

/** finishClose
 * Callback function for close event. Hides the iframe.
 */
SelfAssist.prototype.finishClose = function () {
    this.sa.container.className = "closed";
    this.sa.inputBlur();
};

/** open 
 * Opens the layover in an animation.
 */
SelfAssist.prototype.open = function (uri) {
    var attributes = {
        width: {
            to: 907
        }, 
        height: {
            to: 460
        }
    }
    anim = new YAHOO.util.Anim(this.container, attributes, .9, YAHOO.util.Easing.easeOut);
    anim.sa = this;
    anim.onComplete.subscribe(function(){window.sa.iframe.src = uri; window.sa.iframe.style.visibility = "visible";});
    if (document.all) {
        setTimeout("anim.animate();", 10);
    } else {
        anim.animate();
    }
    this.container.className = "open";
};

/*EVENTHANDLERS*/

/** close
 * Closes the layover in an animation.
 */
SelfAssist.prototype.close = function (e, args) {
  /*//Measure variables
  var oMetron = new Metron();
  if(this.iframe._metron){
    oMetron.measureVariable('ti', this.iframe._metron.webtrends.WT['ti']);
    oMetron.measureVariable('z_qgo_language', this.iframe._metron.webtrends.WT['z_go_language']);
  }else{
    oMetron.measureVariable('ti', document.title);
    oMetron.measureVariable('z_qgo_language', 'en');
  }
  oMetron.measureVariable('z_application', 'Q-Go');
  oMetron.measureVariable('z_Country', this.country);
  oMetron.measureVariable('z_language', this.language);
  oMetron.measureVariable('z_qgo_eventtype', 'No-Q-Go page Exit');
  oMetron.measureVariable('z_qgo_event', 'close window');

  oMetron.measuresCommit();
  oMetron = null;*/
    this.defaultInput.value = this.defaultSearchTerm;
    YAHOO.util.Dom.removeClass(document.getElementsByTagName('body')[0], 'show-layover')
    //Load url into iFrame
    this.loadUri(this.loading_url);
    this.layOver.hide();
    this.iframe.style.visibility = "hidden";
    var attributes = {
        width: { to: 268 },
        height: { to: 45 }
    };
    anim = new YAHOO.util.Motion(this.container, attributes, .9, YAHOO.util.Easing.easeOut);
    anim.sa = this;
    anim.onComplete.subscribe(this.finishClose);
    anim.animate();
};

/** onSubmitHandler 
 * Handles the submitentries of the Selfassist forms.
 */
SelfAssist.prototype.onSubmitHandler = function (e, obj) {
    YAHOO.util.Event.preventDefault(e);
    if ((e.type === 'keyup' && e.keyCode === 13) || (e.type === 'click')) {
        window.sa.ask(obj.value);
    }
};

/** onTabClickHandler
* Handles tab clicks.
**/
SelfAssist.prototype.onTabClickHandler = function (e, obj) {
    switch (obj.id) {
        case window.sa.searchTab.id:
            window.sa.ask(window.sa.defaultInput.value);
            break;
        case window.sa.catTab.id:
            window.sa.cat();
            break;
        case window.sa.faqTab.id:
            window.sa.faq();
            break;
        case window.sa.closeTab.id:
            window.sa.close();
            break;
        default:
            break;
    }
};

/** inputFocus
 * When a form input element is focussed, this function will be called.
 * Sets style and value for the input field.
 */
SelfAssist.prototype.inputFocus = function (e, oInput) {
    if (oInput.title == "" || oInput.title == oInput.value) {
        oInput.title = oInput.value;
        oInput.value = "";
    }
    oInput.style.color = "#003145";
};

/**inputBlur
 * When a form input element is blurred, this function will be called.
 * Resets style and value for the input field.
 */
SelfAssist.prototype.inputBlur = function (e, oInput) {
    if (oInput.value === "" || oInput.title === oInput.value) {
        oInput.value = oInput.title;
        oInput.style.color = "";
    }
};

/*URL UTF-8 Encoder/Decoder Class*/
var Url = (function () {
    var encode, decode, _utf8_encode, _utf8_decode;

    // public method for url encoding
    encode = function (string) {
        return escape(_utf8_encode(string));
    };
    // public method for url decoding
    decode = function (string) {
        return _utf8_decode(unescape(string));
    };
    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        var utftext = "", c, n;
        string = string.replace(/\r\n/g, "\n");

        for (n = 0; n < string.length; n += 1) {
            c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    };
    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "", i = 0, c = c1 = c2 = 0;

        while (i < utftext.length) {
            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i += 1;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    };
    return {
        encode: encode,
        decode: decode
    };
})();

