﻿/**
* 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 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
* @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 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 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) {
        if (noCookieCallback == null) {
            /* default behaviour: redirect to error page */
            window.location.href = 'Error/NoCookies.aspx';
        } else {
            /* execute callback function */
            noCookieCallback();
        }

        return false;
    }

    return true;
}

function ShowBeforeYouBuyPopup(popupid) {
    if (document.getElementById(popupid) != null) {
        document.getElementById(popupid).style.display = "block";
    }
}
function HideBeforeYouBuyPopup(popupid, child) {
    if (document.getElementById(popupid) != null) {
        document.getElementById(popupid).style.display = "none";
    }
}

$(document).ready(function(e) {
    /* cookie check */
    var _funcCookieCallback = function() { /* redirect to error page */window.location.href = 'Error/NoCookies.aspx'; };
    cookieCheck(_funcCookieCallback);

    /* 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) { }
});

/*
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.
*/
function GetDynamicContentValue(portalid, key) {

    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    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 the decoded value ready to be used in the html code
                        */
                        var processReturnValue = function(val) {
                            val = unescape(val);
                            val = val.replace("+", " ");
                            return val;
                        };

                        returnvalue = processReturnValue(returnvalue);
                        return returnvalue;
                    }
                }

                break;
            }
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function AssignDynamicValue(portalid, elementId, parameterName) {
    var cookieValue = GetDynamicContentValue(portalid, parameterName);
    var elem = document.getElementById(elementId);    
    if(elem!=null && cookieValue != null)
        elem.innerHTML = cookieValue;
    return null;
}




