﻿/**
 * Global variables
 */
var popup, popup2, popup3;

function detect_os()
{
    try {
        var win_xp = ((navigator.userAgent.indexOf('Windows NT 5.1') > -1 || navigator.userAgent.indexOf('Windows NT 5.2') > -1)),
	    ff = (navigator.userAgent.indexOf('Firefox/3') > -1),
        ff5 = (navigator.userAgent.indexOf('Firefox/5') > -1),
	    add_class = ' ';

        if (win_xp) {
            add_class += 'xp';

            if (ff) {
                add_class += ' xp_ff3';
            }
            $('body').attr('class', $('body').attr('class') + add_class);
        }

        if (ff5) {
            add_class += 'ff5';

            $('body').attr('class', $('body').attr('class') + add_class);
        }
    }
    catch (e) {
    }
}

/**
* @name hideCurrentMediaSelector
* @description hide the media selector pop-up
*/
function hideCurrentMediaSelector()
{
    if (popup != null)
    {
        popup.style.visibility = "hidden";
        popup.style.display = "none";
    }

    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 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 */
            var redirectUrl = baseurl + 'Error/NoCookies.aspx';

            if (typeof (window.location.href.split('/')[4]) === 'string' && window.location.href.split('/')[4].length === 5) {
                redirectUrl += '?culture=' + window.location.href.split('/')[4];
            }

            window.location.href = redirectUrl;
        } 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) { }
}

/**
* 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;
}

/**
* @description: A bunch of functions that will be triggered once the DOM is ready
*/
$(document).ready(function (e)
{

    detect_os();

    /* cookie check */
    cookieCheck(function ()
    {
        /* redirect to error page */
        var redirectUrl = baseurl + 'Error/NoCookies.aspx';

        if (typeof (window.location.href.split('/')[4]) === 'string' && window.location.href.split('/')[4].length === 5) {
            redirectUrl += '?culture=' + window.location.href.split('/')[4];
        }

        window.location.href = redirectUrl;
    });

    /* set browser-specific css classes */
    SetBrowserSpecificStyles();

    /* product set navigator */
    InitializeProductSetNavigator();

    /* 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));
    });

});
