﻿/**
* Global variables
*/
var popup, popup2, popup3;
var serverSetting = "http://store.microsoft.com"; /* use this value for country selector countrylist */

/**
* @name hideCurrentMediaSelector
* @description hide the media selector pop-up
*/
function hideCurrentMediaSelector() {
    if (popup != null) {
        popup.style.visibility = "hidden";
        popup.style.display = "none";
        //popup.style.zindex = "0";
    }

    var globalnavlbar = $("div.globalnav_lbar");
    var colRight = $("div.columnRight");
    if (null != globalnavlbar && null != colRight) {
        globalnavlbar.removeClass("globalNavBarColOnBottom");
        colRight.removeClass("rightColOnTop");
    }

    var fullWidthColHelper = $("div.fullWidthColHelper");
    if (null != globalnavlbar && null != fullWidthColHelper) {
        fullWidthColHelper.removeClass("rightColOnTop");
    }
}

/**
* @name utf8_encode
* @description encodes text strings in UTF-8 (used for url encoding)
* @param txt a string that will be encoded in UTF-8
* @return [string] returns the UTF-8 encoded string given by parameter 'txt'
*/
function utf8_encode(txt) {
    txt = txt.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < txt.length; n++) {
        var c = txt.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;
}

/**
* @name initSearchBar(searchUrl, textboxId, searchButtonId)
* @description register the search event on the global search (textbox and button)
* @example initSearchBar('http://localhost/uk/Search', 'ctl00_PageHeader1_tbSearchQuery', 'ArvatoServices.Web.Localization.Controls.Hyperlink');
* @param searchUrl the url the search page
* @param textboxId the element id of the textbox containing the search string
* @param searchButtonId the element id of the button triggering the search
* @return [bool] true if the event listeners were successfully installed; otherwise false
*/
function initSearchBar(searchUrl, textboxId, searchButtonId) {
    var tbQuery = $("#" + textboxId), btnSearch = $("#" + searchButtonId);
    if (tbQuery == null || btnSearch == null) { return false; }

    /* search function */
    var search = function() {
        var query = $(tbQuery).val();
        if (query.length != null) {
            var url = searchUrl + '?q=' + escape(utf8_encode(query)) + '&n=5&i=1';
            try {
                /* try this for normal browsers */
                parent.window.location = url;
            } catch (browserErr) {
                try {
                    /* try this for the ie6 */
                    parent.location.replace(url);
                } catch (IE6err) { }
            }
        }
    };

    /* on button click */
    $(btnSearch).click(function(e) { search(); });

    /* on return */
    $(tbQuery).keydown(function(e) {
        var keycode = e.keyCode;
        if (keycode == 13) {
            /* trigger the search */
            search();

            /* prevent default behaviour */
            return false;
        }

        return true;
    });

    return true;
}

/**
* @name initSearchEvents
* @description attach eventlistener to search page controls
*/
function initSearchEvents() {
    var classname = ".searchresultcount";
    $(classname).each(function(i) {
        var control = $(this);

        /**
        * @name searchResultCountChangedEvent
        * @description switches the pagesize parameter of the current page location
        */
        var searchResultCountChangedEvent = function(e) {
            var ddl = $(e.target);
            var count = ddl.val();

            var previousUrl = window.location.href;

            try {
                /* set PageSize so selected value */
                var rePageSize = /n=(\d+)/ig;
                var matches = previousUrl.match(rePageSize);

                var newUrl = '';
                if (matches != null) {
                    newUrl = previousUrl.replace(rePageSize, "n=" + count);
                } else {
                    newUrl = previousUrl + "&n=" + count;
                }

                /* reset PageIndex to first page */
                var rePageIndex = /i=(\d+)/ig;
                matches = newUrl.match(rePageIndex);

                if (matches != null) {
                    newUrl = newUrl.replace(rePageIndex, "i=1");
                } else {
                    newUrl = newUrl + "&i=1";
                }

                window.location = newUrl;
            } catch (e) { };
        };

        control.change(searchResultCountChangedEvent);
    });
}

/**
* @name initDownloadControl
* @description initialize all download-controls on the current page / bind a onchange events on the dropdown-list
* @return true if the event listeners were successfully installed; otherwise false
*/
function initDownloadControl() {
    var baseclass = ".downloadcontrol";
    var linksectionclass = ".links";
    var messagesclass = ".messages";
    var messageentryclass = ".entry";

    /* foreach download control on the current page */
    $(document).find(baseclass).each(function(i) {
        var downloadcontrol = $(this);
        var dropdownlist = $(this).find("select:first");

        /**
        * @name displayDownloadSection(name)
        * @description display the download link section with the given name
        * @param name the internal  name/suffix of the download section which shall be displayed
        */
        var displayDownloadSection = function(name) {
            /* hide message: you have changed your selection */
            $(downloadcontrol).find(messagesclass + ">" + messageentryclass).each(function(i) {
                $(this).fadeOut("slow");
            });

            $(downloadcontrol).find(linksectionclass + ">div").each(function(i) {
                if ($(this).hasClass(name)) {
                    $(this).show();

                    /* display message: you have changed your selection */
                    $(downloadcontrol).find(messagesclass + ">" + messageentryclass).each(function(i) {
                        $(this).fadeIn("slow");
                    });
                } else {
                    $(this).hide();
                }
            });
        };

        /* download-options: onchange event */
        dropdownlist.change(function() {
            var selectedvalue = $(this).val();

            /* display links */
            displayDownloadSection(selectedvalue);
        });
    });
}

/**
* @name cookieCheck
* @description validates if the current browser accepts cookies or not; if the browser does not support cookies - redirect to an error page
* @example cookieCheck();
* @param noCookieCallback a function which will be executed if the current browser does not support cookies
* @return [bool] returns true if cookies are supported; otherwise false
*/
function cookieCheck(noCookieCallback) {
    var cookieName = 'test4Cookie' + (new Date().getTime());
    var cookieEnabled = (navigator.cookieEnabled) ? true : false

    /* if not IE4+ nor NS6+ */
    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie = cookieName + '=cookieValue';
        cookieEnabled = (document.cookie.indexOf(cookieName) != -1) ? true : false;
    } else if (!cookieEnabled) {
        if (document.cookie) {
            if (document.cookie == '') {
                /* try to set a cookie */
                document.cookie = cookieName + '=cookieValue';

                if (document.cookie.indexOf(cookieName) != -1) {
                    /* if it succeeds, set variable */
                    cookieEnabled = true;
                }
            } else {
                /* there was already a cookie */
                cookieEnabled = true;
            }
        }
    }

    if (!cookieEnabled && window.location.href.indexOf('Error/NoCookies.aspx') < 0) {
        if (noCookieCallback == null) {
            /* default behaviour: redirect to error page */
            window.location.href = baseurl + 'Error/NoCookies.aspx';
        } else {
            /* execute callback function */
            noCookieCallback();
        }

        return false;
    }

    return true;
}

/**
* @name InitializeProductSetNavigator()
* @description Converts the product set navigator link list into a drop-down list
* @return [bool] true if the product set navigator was successfully initialized; otherwise false
*/
function InitializeProductSetNavigator() {
    $('.ProductSetNavigator').each(function(i) {
        var navigator = $(this);
        var label = $(navigator).find('.label:first');
        var list = $(navigator).find('.list:first');
        var selector = $(navigator).find('.selector:first > select:first');

        $(selector).change(function(e) {
            $("select option:selected").each(function() {
                var targetUrl = $(this).val();
                if (targetUrl !== '') {
                    document.location = targetUrl;
                }
            });
        });
    });
}

/**
* @name GetBrowserName()
* @description Get the name of the user's browser. This function is able to distinguish between mozilla, webkit, msie, msie-8, msie-7, msie-6, opera & safari
* @return [string] The name of the current web browser (e.g. "mozilla"); if the browser is not detected this function will return an empty string
*/
function GetBrowserName() {
    var browserName = '';

    if (jQuery.browser.mozilla == true) {
        browserName = 'mozilla';
    } else if (jQuery.browser.webkit == true) {
    browserName = 'webkit';
    } else if (jQuery.browser.msie == true) {
        browserName = 'msie';

        /* sub versions of ie */
        if (jQuery.browser.version.substring(0, 1) == '8') {
            browserName = 'msie-8';
        } else if (jQuery.browser.version.substring(0, 1) == '7') {
            browserName = 'msie-7';
        } else if (jQuery.browser.version.substring(0, 1) == '6') {
            browserName = 'msie-6';
        }
    } else if (jQuery.browser.opera == true) {
        browserName = 'opera';
    }

    return browserName;
}

/**
* @name FileExists(url)
* @description Check if the given URL does exists or not
* @param url The file url (e.g. http://example.com/assets/styles.css)
* @param yesCallback A callback function that will be executed of the the given url does exist
* @param noCallback A callback function that will be executed of the the given url does NOT exist
* @return [void]
*/
function FileExists(url, yesCallback, noCallback) {
    try {
        $.ajax({
            'url': url,
            'type': 'HEAD',
            'error': function() {
                if (noCallback) {
                    noCallback();
                }
            },
            'success': function() {
                if (yesCallback) {
                    yesCallback();
                }
            }
        });
    } catch (ex) { }
}

/**
* @name SetBrowserSpecificStyles()
* @description Adds a browser-specific CSS class name to the document body (e.g. <body class="firefox">). This function is able to distinguish between mozilla, webkit, msie, opera & safari
* @return [bool] true if the browser specific class name was successfully set; otherwise false
*/
function SetBrowserSpecificStyles() {
    try {
        $('body:first').addClass(GetBrowserName());
        return true;
    } catch (ex) { }
    return false;
}

/**
* @name LoadBrowserSpecificStyles(cssFilePath, placeholder)
* @description Loads a browser specific version of the given CSS file (e.g. portaldata/styles/checkout-{browserName}.css --> portaldata/styles/checkout-mozilla.css)
* @param cssFilePath The file path to the CSS file which shall be loaded in a browser-specific version which includes a placeholder for the browser name (e.g. portaldata/styles/checkout-{browserName}.css)
* @param placeholder The placeholder string which was used in the cssFilePath param (e.g. "{browserName}")
* @return [void]
*/
function LoadBrowserSpecificStyles(cssFilePath, placeholder) {
    /* validate parameters */
    if ((cssFilePath == null || cssFilePath == '') ||
		(placeholder == null || placeholder == '')) {
        return;
    }

    try {
        /* replace browser name */
        cssFilePath = cssFilePath.replace(placeholder, GetBrowserName());

        FileExists(cssFilePath, function() {
            /* create a new link-tag */
            var link = document.createElement('link');
            $(link).attr('type', 'text/css');
            $(link).attr('rel', 'stylesheet');
            $(link).attr('href', cssFilePath);

            /* append link-tag to document header */
            $('head').append(link);
        }, function() { }
		);
    } catch (ex) { }
}

/**
* @name GetDynamicContentValue(portalid, key)
* @description This Function can be used to retrieve values from the dynamic cookie. It is needed to replace dynamic values in cached pages. This replacement is therefore done on the client, so that no server ressources are consumed.
* @param portalid An integer value which represents the the current portal id (e.g. 1 --> UK-Portal, 4 --> DE-Portal)
* @param key A string value which contains the the key that will be used to store the dynamic-content in a cookie
* @return [string] The value of the cookie with the given key/portal combination
*/
function GetDynamicContentValue(portalid, key) {
    /* first we'll split this cookie up into name/value pairs */
    var check_name = 'DynamicContent_Cookie_' + portalid;
    var a_all_cookies = document.cookie.split(';');

    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; /* set boolean t/f default f */

    for (i = 0; i < a_all_cookies.length; i++) {
        /* now we'll split apart each name=value pair */
        var index = a_all_cookies[i].indexOf("=");
        if (index != -1) {
            cookie_name = a_all_cookies[i].substr(0, index).replace(/^\s+|\s+$/g, '');
            /* if the extracted name matches passed check_name */
            if (cookie_name == check_name) {
                b_cookie_found = true;
                /* we need to handle case where cookie has no value but exists (no = sign, that is): */
                if (a_all_cookies[i].length > index) {
                    cookie_value = a_all_cookies[i].substring(index + 1).replace(/^\s+|\s+$/g, '');
                }
                /* cookie values found, now find the key's value */
                var entries = cookie_value.split('$');
                for (j = 0; j < entries.length; j++) {
                    var keyVal = entries[j].split(':');
                    if (keyVal[0] == key) {
                        var returnvalue = keyVal[1];

                        /**
                        * @name processReturnValue
                        * @description takes the cookie values and tries to decode it
                        * @param val the cookie value
                        * @return [string] the decoded value ready to be used in the html code
                        */
                        var processReturnValue = function(val) {
                            val = unescape(val);
                            val = val.replace(/\+/gi, ' ');
                            return val;
                        };

                        returnvalue = processReturnValue(returnvalue);
                        return returnvalue;
                    }
                }

                break;
            }
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

/**
* @name AssignDynamicValue(portalid, elementId, key)
* @description
* @param portalid An integer value which represents the the current portal id (e.g. 1 --> UK-Portal, 4 --> DE-Portal)
* @param elementId The id of the target html-node
* @param key A string value which contains the the key that will be used to store the dynamic-content in a cookie
* @return [void]
*/
function AssignDynamicValue(portalid, elementId, key) {
    var dynamicContent = GetDynamicContentValue(portalid, key);
    if ($("#" + elementId) != null && dynamicContent != null) {
        $("#" + elementId).html(dynamicContent);
    }
}

/**
* Fix z-index issues for the given element.
* @description:	This function will find the different "z-index-regions" of the site (e.g. header, content, footer) and automatically assign a higher z-index than the one of the region which contains the given element and all of its child element z-indizes
* @example:	FixZIndex($('.popupcontainer'));
* @param:	element	A HTML node element
* @return:	[void]
*/
function FixZIndex(element) {
    if ($(element) !== null) {
        var zIndexBaseValue = 1;
        var zIndexRegions = $('.z-index-region');
        var parentzIndexRegion = $(element).parents('.z-index-region:first');

        /*
        * GetZIndex
        * @description	Get the z-index of a given HTML element
        * @param:	element	An HTML element
        * @return:	[integer]	The z-index of the given HTML element; 0 if no z-index is specified
        */
        var GetZIndex = function(element) {
            if (element !== 'undefined' && element != null) {
                var zindex = $(element).css('z-index');
                if (zindex != null) {
                    if (zindex === 'auto') {
                        zindex = 0;
                    } else if (Number(zindex) !== 'NaN') {
                        zindex = Number(zindex);
                    } else {
                        zindex = 0;
                    }
                }

                return zindex;
            }
            return 0;
        };

        if ($(zIndexRegions) !== null && $(zIndexRegions).size() > 0) {
            /* determine the highest z-index of all z-index-regions */
            var highestRegionZIndex = 0;
            var highestElementZIndex = 0;

            $(zIndexRegions).each(function(i) {
                var regionzIndex = GetZIndex($(this));
                if (regionzIndex > highestRegionZIndex) {
                    highestRegionZIndex = regionzIndex;
                }

                /* determine the highest z-index of all elements within the z-index regions */
                $(this).find('*').each(function(i) {
                    var elementzIndex = GetZIndex($(this));
                    if (elementzIndex > highestElementZIndex) {
                        highestElementZIndex = elementzIndex;
                    }
                });
            });

            if ($(parentzIndexRegion) != null) {
                var newZIndex = highestRegionZIndex + highestElementZIndex + zIndexBaseValue + 1;
                $(element).css('z-index', newZIndex);
                (parentzIndexRegion).css('z-index', newZIndex);
            }
        }
    }
}

/**
 * Fix z-index issues with the country selector
 * @name: FixZIndexCountrySelector()
 * @resut: void
 */
function FixZIndexCountrySelector() {
    $('.countrySelector').mouseover(function() {
        $('.countrySelector').css('z-index', '1');
    });

    $('.countrySelector').mouseleave(function() {
        $('.countrySelector').css('z-index', '0');
    });
}

/**
* @name: FixNavigationHeightIssues()
* @description: Fix navigation height
* @return: bool True if the navigation-height issues were successfully resolved; otherwise false
*/
function FixNavigationHeightIssues() {
    var result = false;
    try {
        var _element_navigation = $('.subNavigation:first')[0];
        
        if (_element_navigation != null && _element_navigation != "undefined") {
            var _int_height_navigation = $(_element_navigation).height();
            var _element_columnleft = $('.columnLeft:first')[0];
            $(_element_columnleft).css('height', _int_height_navigation);
            result = true;   
        }
    } catch (err) { result = false; }
    return result;
}

/**
* Cookies
* @description: A set of functions and methods for reading, writing and deleting cookies
* @author: http://techpatterns.com/downloads/javascript_cookies.php
*/
var Cookies = {

    /**
    * Cookies.set(name, value, expires, path, domain, secure)
    * @description: Writes a cookie with the specified name and value
    * @param: [name] The cookie name
    * @param: [value] The cookie value
    * @param: [expires] The number of days until expiration (e.g. 10)
    * @param: [path] The cookie path (default = "/")
    * @param: [domain] The cookie domain (default = window.location.host)
    * @param: [secure] True or false (default = false)
    * @return: [void]
    */
    "set": function(name, value, expires, path, domain, secure) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());

        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" + value +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") +
		((path) ? ";path=" + path : ";path=/") +
		((domain) ? ";domain=" + domain : ";domain=" + window.location.host) +
		((secure) ? ";secure" : "");
    },

    /**
    * Cookies.get(check_name)
    * @description: Retrieve the value of the cookie with the specified name
    * @param: [check_name] The cookie name
    * @return: [string] The cookie value if the cookie was found; otherwise null
    */
    "get": function(check_name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for (var i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split('=');

            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }

        if (!b_cookie_found) {
            return null;
        }
    },

    /**
    * Cookies.del(name, path, domain)
    * @description: Delete a cookie which matches the specified name, path and domain
    * @param: [name] The cookie name
    * @param: [path] The cookie path (default = "/")
    * @param: [domain] The domain name (default = window.location.host)
    * @return: [void]
    */
    "del": function(name, path, domain) {
        if (!path) {
            path = "/";
        }

        if (!domain) {
            domain = window.location.host;
        }

        if (this.get(name)) {
            document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }
    }

};

/**
 * @description: A bunch of functions that will be triggered once the DOM is ready
 */
$(document).ready(function(e) {

    /* cookie check */
    cookieCheck(function() {
        /* redirect to error page */
        if (window.location.href.indexOf('Error/NoCookies.aspx') < 0) {
            window.location.href = baseurl + 'Error/NoCookies.aspx';
        }
    });

    /* set browser-specific css classes */
    SetBrowserSpecificStyles();

    /* product set navigator */
    InitializeProductSetNavigator();

    /* initialize the search bar */
    try {
        initSearchBar(SearchBar.searchUrl, SearchBar.textboxId, SearchBar.searchButtonId);
    } catch (eSearchBar) { }

    /* initialize search controls */
    try {
        initSearchEvents();
    } catch (eSearchControls) { }

    /* initialize download-controls */
    try {
        initDownloadControl();
    } catch (eDownloadControl) { }

    /* Fix navigation-height issues */
    FixNavigationHeightIssues();

    /* Fix z-index issues for the country selector */
    FixZIndexCountrySelector();

    // do not use for SEO relevant titles!
    $(".titleEqualsContent").each(function()
    {
        var text = $(this).text();
        $(this).attr("title", $.trim(text));
    });
});