﻿/*
* General utility functions
*/
function getQuerystring(queryString, key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(queryString);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

/*
* Visual feedback for partial postbacks
*/
$(document).ready(function() {
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);

});

var lastTriggeredUpdatePanel;
var buttonProgressUpdateImageToHideWhenPageIsLoaded;

function beginRequestHandler(sender, args) {
    
    var postbackElement = $('#' + args.get_postBackElement().id);
    
    if(postbackElement.attr('class').indexOf('showProgressButton') > 0) {
        showButtonUpdateProgress(postbackElement);
        return;
    }
    
    var updatePanel;
    
    if (postbackElement.data('updatePanelToShowProgressStatusFor') != undefined) {
        updatePanel = $('#' + postbackElement.data('updatePanelToShowProgressStatusFor'));
    }
    else if (postbackElement.attr('class').indexOf('genericUpdateProgressUpdatePanel') >= 0) {
        updatePanel = postbackElement;
    }

    if (updatePanel == undefined) {
        lastTriggeredUpdatePanel = undefined;
        return;
    }
        
    lastTriggeredUpdatePanel = updatePanel;
    var updateProgressOverlayID = updatePanel.attr('id') + 'updateProgressOverlay';
    var updateProgressOverlay = $('#' + updateProgressOverlayID);

    if (updateProgressOverlay.length == 0) {
        var updateProgressOverlay = $("#updateProgressOverlay").clone();
        updateProgressOverlay.attr({ 'id': updateProgressOverlayID });
        $('body').append(updateProgressOverlay);
    }
    
    var position = updatePanel.offset();
    var width = updatePanel.width();
    var height = updatePanel.height();
    updateProgressOverlay.css({ "left": (position.left) + "px", "top": position.top + "px", "width": width + "px", "height": height + "px" });

    var image = updateProgressOverlay.children("img");
    var imageWidth = image.width();
    var imageHeight = image.height();
    var imageLeft = updateProgressOverlay.width() / 2 - imageWidth / 2;
    var imageTop = updateProgressOverlay.height() / 2 - imageHeight / 2;
    image.css({ "left": imageLeft + "px", "top": imageTop + "px" });
    
    updateProgressOverlay.show();
}

function showButtonUpdateProgress(postbackElement){
    
    postbackElement.parent().css('visibility', 'hidden');
    
    var updateProgressImageID = postbackElement.attr('id') + 'updateProgressImage';
    var updateProgressImage = $('#' + updateProgressImageID);
    
    if (updateProgressImage.length == 0) {
        var updateProgressImage = $("#updateProgressImage").clone();
        updateProgressImage.attr({ 'id': updateProgressImageID });
        $('body').append(updateProgressImage);
    }
    
    var position = postbackElement.offset();
    
    var imageWidth = updateProgressImage.width();
    var imageHeight = updateProgressImage.height();
    var imageLeft = position.left + postbackElement.width() / 2 - imageWidth / 2;
    var imageTop = position.top + postbackElement.height() / 2 - imageHeight / 2;
    updateProgressImage.css({ "left": imageLeft + "px", "top": imageTop + "px", "position": "absolute", "z-index": "999" });
    
    buttonProgressUpdateImageToHideWhenPageIsLoaded = updateProgressImage;
    
    updateProgressImage.show();
}

function pageLoadedHandler(sender, args) {
    if(buttonProgressUpdateImageToHideWhenPageIsLoaded != undefined)
        buttonProgressUpdateImageToHideWhenPageIsLoaded.hide();
    
    var updatePanels = args.get_panelsUpdated();
    
    if(updatePanels.length == 0)
        return;
        
    var genericUpdateProgressPanelUpdated = false;
    for (i = 0; i < updatePanels.length; i++) {
        if ($('#' + updatePanels[i].id + 'updateProgressOverlay').length > 0)
            $('#' + updatePanels[i].id + 'updateProgressOverlay').hide();
        
        var panel = $('#' + updatePanels[i].id);
        if(panel)
        {
            var className = panel.className;
        }

        if(className &&  className.indexOf('genericUpdateProgressUpdatePanel') > -1)
            genericUpdateProgressPanelUpdated = true;
    }
    
    if(!genericUpdateProgressPanelUpdated)
        return;
    
    if(lastTriggeredUpdatePanel != undefined && lastTriggeredUpdatePanel.attr('class').indexOf('scrollToWhenUpdated') > -1)
    {
        //If less than 200 pixels of the updatepanel is in the viewport scroll to it
        if($(window).height()+$(window).scrollTop() - lastTriggeredUpdatePanel.offset().top < 200)
        {
            $.scrollTo($(lastTriggeredUpdatePanel), 400);
        }
     }
}

/*
* Checkbox group
*/
$(document).ready(function() {
    $('.checkBoxGroup .checkBoxGroupAllBox input[type=checkbox]').click(function() {
        if ($(this).attr('checked')) {
            $(this).parents('.checkBoxGroup').filter(':first').find('input[type=checkbox]:not(.checkBoxGroupAllBox input[type=checkbox])').attr('checked', false);
        }
    });
    
    $('.checkBoxGroup .checkBoxAllChecker input[type=checkbox]').click(function() {
        if ($(this).attr('checked')) {
            $(this).parents('.checkBoxGroup').filter(':first').find('.checkBoxGroupAllBox input[type=checkbox]').attr('checked', true);
        }
    });

    $('.checkBoxGroup input[type=checkbox]:not(.checkBoxGroupAllBox input[type=checkbox])').click(function() {
        if ($(this).attr('checked')) {
                $(this).parents('.checkBoxGroup').filter(':first').find('.checkBoxGroupAllBox input[type=checkbox]').attr('checked', false);
        }
        });
});

/*
* Validation
*/
function validateDefaultValueTextBox(source, args) {
    var textBoxID = $(source).data('textBoxToValidate');
    var textBoxToValidate = $('#' + textBoxID);

    var trimmedValue = jQuery.trim(args.Value);
    if (trimmedValue == "") {
        args.IsValid = false;
    }

    if (args.IsValid) {
        var defaultValue = textBoxToValidate.data('defaultValue');
        defaultValue = jQuery.trim(defaultValue);

        if (trimmedValue == defaultValue) {
            args.IsValid = false;
        }
    }

    var textBoxToValidateClone = $('#' + textBoxID + 'Clone');

    if (!args.IsValid) {
        textBoxToValidate.addClass('error');

        if (textBoxToValidateClone.length > 0)
            textBoxToValidateClone.addClass('error');
    }
    else {
        textBoxToValidate.removeClass('error');

        if (textBoxToValidateClone.length > 0)
            textBoxToValidateClone.removeClass('error');
    }
}

/*
* Google maps activation
*/
function gMapLoad(containerElementID, latitude, longitude, icon) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById(containerElementID));
        map.setCenter(new GLatLng(latitude, longitude), 15);
        map.setMapType(G_NORMAL_MAP);
        map.addControl(new GSmallZoomControl3D());
        var shIcon = new GIcon();
        if(icon != undefined && icon != "") shIcon.image = "/images/" + icon; else shIcon.image = "/images/plupp.png";
        shIcon.iconSize = new GSize(111, 59);
        shIcon.iconAnchor = new GPoint(55, 50);
        markerOptions = { icon: shIcon };
        var point = new GLatLng(latitude, longitude);
        map.addOverlay(new GMarker(point, markerOptions));
    }
}

/*
* Masked input
*/
$(document).ready(function() {
    $('.onlyNumericValuesTextBox').keyup(function(e) {
        this.value = this.value.replace(/[^0-9]/, '');
    });
});

/*
* Expandable page elements
*/
$(document).ready(function() {
    $('.expandableGroup').find('.expandableItemToggleLink').click(function() {
        $(this).toggleClass('contract');
        $(this).parents('.expandableGroup').filter(':first').find('.group').toggle();
    });

    var groupsToContract = $('.expandableGroup.contractOnLoad');
    groupsToContract.find('.group').hide();
    groupsToContract.find('.expandableItemToggleLink').removeClass('contract');
});

/*
* Fix for bug in Firebug when cloning input boxes
*/
$(document).ready(function() {
    $('input[type="password"]').attr('autocomplete', 'false');
});

/*
* Show not authorized popup methods
*/
function initializeNotAuthorizedPopupLinks(triggersClass) {
    $(triggersClass).click(function() {
        showNotAuthorizedPopup();
        return false;
    });
}

var popupContainer;
function showNotAuthorizedPopup() {
    $('.centeredPopupContainer').hide();

    if (popupContainer == undefined)
        popupContainer = $('#notAuthorizedPopup .centeredPopupContainer');

    popupContainer.css("position", "absolute");
    popupContainer.css("top", (Math.round($(window).height() - popupContainer.height()) / 2 + $(window).scrollTop()) + "px");
    popupContainer.css("left", (Math.round($(window).width() - popupContainer.width()) / 2 + $(window).scrollLeft()) + "px");
    popupContainer.show();
}

function hideMemberToolAndShowNotAuthorizedPopup(hideElementID) {
    $('#' + hideElementID).hide();
    showNotAuthorizedPopup();
}


/*
* Show accept terms popup methods
*/

function initializeAcceptTermsPopupLinks(triggersClass) {
    $(triggersClass).click(function () {
        showAcceptTermsPopup();
        return false;
    });
}

var popupAcceptTermsContainer;
function showAcceptTermsPopup() {
    $('.centeredPopupContainer').hide();

    if (popupAcceptTermsContainer == undefined)
        popupAcceptTermsContainer = $('#acceptTermsPopup .centeredPopupContainer');
        
    popupAcceptTermsContainer.css("position", "absolute");
    popupAcceptTermsContainer.css("top", (Math.round($(window).height() - popupAcceptTermsContainer.height()) / 2 + $(window).scrollTop()) + "px");
    popupAcceptTermsContainer.css("left", (Math.round($(window).width() - popupAcceptTermsContainer.width()) / 2 + $(window).scrollLeft()) + "px");
    popupAcceptTermsContainer.show();
}

function hideAcceotTermsPopup(hideElementID) {
    $('#' + hideElementID).hide();
    showAcceptTermsPopup();
}


/*
*   Show and hide tabs when tab selector links are clicked
*/
var svenskHandelTabs = svenskHandelTabs || {};

svenskHandelTabs = {
    vars: {},

    init: function(tabSelectorLinkClass, tabQuerystringParameterQuerystringKey) {
        svenskHandelTabs.vars.tabQuerystringParameterQuerystringKey = tabQuerystringParameterQuerystringKey;
        $(tabSelectorLinkClass).click(this.tabSelectorLinkClick);
    },

    tabSelectorLinkClick: function() {
        var queryString = '';
        if (this.href.split('?').length > 0)
            queryString = '?' + this.href.split('?')[1];

        $(this).parent().parent().find('li').removeClass('current');
        $(this).parent().addClass('current');
        var queryGroupName = getQuerystring(queryString, svenskHandelTabs.vars.tabQuerystringParameterQuerystringKey);
        var tabNumber = getQuerystring(queryString, queryGroupName);

        $('.' + queryGroupName).hide();
        $('.' + queryGroupName).parent().find('.' + queryGroupName + ':eq(' + (tabNumber) + ')').show();

        return false;
    }
}

/*
* Partial postbacks
*/
var svenskHandelPartialPostBack = svenskHandelPartialPostBack || {};

svenskHandelPartialPostBack = {
    updatePanelToUpdateID: undefined,
    originalTriggerLinks: new Hash(),
    initialized: false,
    doPostBackPartialPostBack: true,
    latestPostBackHash: undefined,
    doPostBackLinkClass: undefined,
    updatePanelQuerystringKey: undefined,
    updatePanelCssNamePrefix: undefined,
    doPostBackLinkTriggerKey: undefined,

    init: function(doPostBackLinkClass, updatePanelQuerystringKey, updatePanelCssNamePrefix, doPostBackLinkTriggerKey) {
        svenskHandelPartialPostBack.doPostBackLinkClass = doPostBackLinkClass;
        svenskHandelPartialPostBack.updatePanelQuerystringKey = updatePanelQuerystringKey;
        svenskHandelPartialPostBack.updatePanelCssNamePrefix = updatePanelCssNamePrefix;
        svenskHandelPartialPostBack.doPostBackLinkTriggerKey = doPostBackLinkTriggerKey;

        $.history.init(svenskHandelPartialPostBack.callback);
        $('.' + svenskHandelPartialPostBack.doPostBackLinkClass).click(svenskHandelPartialPostBack.doPostBackLinkClick);

        //Save the original targets of all doPostBackLinks so that they can be restored if no hash value is present
        $('.' + svenskHandelPartialPostBack.doPostBackLinkClass).each(function() {
            svenskHandelPartialPostBack.originalTriggerLinks.put(this.id, this.href);
        });

        initialized = true;
    },

    doPostBackLinkClick: function() {
        var queryString = '';
        if (this.href.split('?').length > 0)
            queryString = '?' + this.href.split('?')[1];

        //Get the ID of the UpdatePanel that will trigger the postback from the querystring part of the links href attribute
        updatePanelToUpdateName = getQuerystring(queryString, svenskHandelPartialPostBack.updatePanelQuerystringKey);
        updatePanelToUpdateID = $('.' + svenskHandelPartialPostBack.updatePanelCssNamePrefix + svenskHandelPartialPostBack.updatePanelToUpdateName).attr('id');

        doPostBackPartialPostBack = true;

        queryString = Url.decode(queryString);
        queryString = Url.decode(queryString);
        $.history.load(queryString.replace(/^.*#/, ''));

        return false;
    },

    callback: function(hash) {

        if (hash != svenskHandelPartialPostBack.latestPostBackHash) {
            svenskHandelPartialPostBack.doPartialPostBack(hash);
        }
    },

    doPartialPostBack: function(hash) {
        //Store the previous update panel to update ID in case the hash does not contain a new one
        var oldUpdatePanelToUpdateID = svenskHandelPartialPostBack.updatePanelToUpdateID;

        //Get the ID of the UpdatePanel that will trigger the postback from the querystring part of the links href attribute
        updatePanelToUpdateName = getQuerystring(hash, svenskHandelPartialPostBack.updatePanelQuerystringKey);
        updatePanelToUpdateID = $('.' + svenskHandelPartialPostBack.updatePanelCssNamePrefix + updatePanelToUpdateName).attr('id');
        if (updatePanelToUpdateID != undefined) {
            __doPostBack(updatePanelToUpdateID, hash);
        }
        else if (oldUpdatePanelToUpdateID != undefined && oldUpdatePanelToUpdateID != "") {
            __doPostBack(oldUpdatePanelToUpdateID, hash);
        }

        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() {
            //Rebind all doPostBackLinks click event as new links which click events haven't been bound might have been rendered at the last partial postback
            $('.' + svenskHandelPartialPostBack.doPostBackLinkClass).unbind('click', svenskHandelPartialPostBack.doPostBackLinkClick);
            $('.' + svenskHandelPartialPostBack.doPostBackLinkClass).click(svenskHandelPartialPostBack.doPostBackLinkClick);

            svenskHandelPartialPostBack.updatePostBackLinkTargets(hash);
        });
    },

    updatePostBackLinkTargets: function(hash) {
        if ((window.location + '').indexOf('#') < 0) //No hash exists in the browser location
        {
            //Revert all doPostBackLinks href attributes to their original values
            $('.' + svenskHandelPartialPostBack.doPostBackLinkClass).each(function() {
                this.href = svenskHandelPartialPostBack.originalTriggerLinks.get(this.id);
            });
        }
        else {
            //Update all doPostBackLinks href attributes so that they will hold the current state 
            hash = hash.replace('?', '');
            var parameterNameAndValuePairs = hash.split('&');
            for (i = 0; i < parameterNameAndValuePairs.length; i++) {
                //Update all doPostBackLinks href attributes with the new value for the current parameter being iterated
                $('.' + svenskHandelPartialPostBack.doPostBackLinkClass).each(function() {
                    var parameter = parameterNameAndValuePairs[i].split('=')[0];
                    var value = parameterNameAndValuePairs[i].split('=')[1];

                    var queryString = this.href.split('?')[1];
                    var oldQueryString = queryString;
                    if (queryString == undefined) {
                        queryString = '';
                    }

                    var triggerKeys = getQuerystring(queryString, svenskHandelPartialPostBack.doPostBackLinkTriggerKey);
                    if (parameter != svenskHandelPartialPostBack.doPostBackLinkTriggerKey && triggerKeys.indexOf(parameter) < 0) //Check if the parameter is set as a trigger and not just to keep state
                    {
                        if (queryString.indexOf(parameter) < 0) //Parameter does not exist in the current querystring, add it
                        {
                            if (this.href.indexOf('?') > -1) {
                                queryString += '&' + parameter + '=' + value;
                            }
                            else {
                                queryString += '?' + parameter + '=' + value;
                            }
                        }
                        else //Parameter exist in the current querystring, replace it
                        {
                            var parameterAndValue = queryString.substring(queryString.indexOf(parameter), queryString.length);
                            var valueToReplace = '';
                            if (parameterAndValue.split('=')[1] != undefined)
                                valueToReplace = parameterAndValue.split('=')[1].split('&')[0];

                            queryString = queryString.replace(parameter + '=' + valueToReplace, parameter + '=' + value);
                        }

                        this.href = this.href.replace(oldQueryString, queryString);
                    }
                });
            }
        }
    }
}

/*
* Center element in viewport
*/
jQuery.fn.center = function() {
    this.appendTo($('form'));
    this.css("position", "absolute");
    this.css("top", (Math.round($(window).height() - this.height()) / 2 + $(window).scrollTop()) + "px");
    this.css("left", (Math.round($(window).width() - this.width()) / 2 + $(window).scrollLeft()) + "px");
    return this;
}

/*
* Show popup
*/
function showPopup(popupContainerID) {
    $('.centeredPopupContainer').hide();
    $('#' + popupContainerID).center().show();
}  

/*
* IEpngFix for alpha transparancy in ie5.5 & ie6
*/
//$(document).ready(function() { $(document).pngFix({ blankgif:'/Images/blank.gif' }); });


 function showCommentsBoxContainer()
 {
	$('#commentsBoxContainer').show();
 }

function initStartPage() {
    $('#indexFilter a').click(function (e) {
        e.preventDefault();

        var url = $(this).attr('href');
        $('#latestUpdates').load(url + ' #latestUpdates');

        $('#indexFilter a').removeClass('selected');
        $(this).addClass('selected');
    });

    $(".loading").ajaxStart(function () {
        $(this).show();
    });
    $(".loading").ajaxStop(function () {
        $(this).hide();
    });
}

$(document).ready(function () {


    $("#supportNavigationContainer .memberList").tooltip({
        position: "top left",
        relative: true,
        offset: [30, 30]
    }).dynamic({ bottom: { direction: 'down', bounce: true} });
    $(" #supportNavigationContainer .warning").tooltip({
        tip: '.tooltip2',
        position: "top left",
        relative: true,
        offset: [30, 30]
    }).dynamic({ bottom: { direction: 'down', bounce: true} });
    $(".cert img").tooltip({
        position: "top left",
        relative: true,
        offset: [10, 20]
    }).dynamic({ bottom: { direction: 'down', bounce: true} });
    $('div#supportNavigation fieldset input').focus(function () {
        $('#supportNavigation input.searchBtn').addClass('focus');
    });
    $('div#supportNavigation fieldset input').blur(function () {
        $('#supportNavigation input.searchBtn').removeClass('focus');
    });

    $('.contactFooter select').dropkick({
       
        change: function (value, label) {
            if (value && value.length > 0) {
                window.location.replace(value);
            }
        }
    });
    $('#headerToolbarContainer select').dropkick({
        change: function (value, label) {
            if (value && value.length > 0) {
                window.open(value);
            }
        }
    });
    $("body").click(function () {
        $(".loggedContainer, #headerToolbarContainer .login a").removeClass('open');
        $(' #loginBox').hide();
    });

    $("#loginBox,.loggedContainer, #headerToolbarContainer .login a").click(function (e) {
        e.stopPropagation();
    });
    $.each($('select'), function (index, value) {
        $(value).dropkick('close');
    });
});


function initFavorites() {
    $("input.favorite").bind("click", function () {
        var item = $(this);
        var pageId = item.val();

        if (pageId == null || !pageId > 0) {
            return;
        }

        if ($(this).hasClass("active")) {
            $.ajax({
                type: "POST",
                url: '/Services/FavoritesService.svc/RemoveFavorite',
                dataType: "json",
                contentType: "application/json",
                data: '{"pageId": "' + pageId + '"}',
                success: function (data) {
                    item.toggleClass("active");
                    item.parent().find(".favoriteLabel").toggleClass("hidden");      
                }
            });
        }
        else {
            $.ajax({
                type: "POST",
                url: '/Services/FavoritesService.svc/AddFavorite',
                dataType: "json",
                contentType: "application/json",
                data: '{"pageId": "' + pageId + '"}',
                success: function (data) {
                        item.toggleClass("active");                      
                        item.parent().find(".favoriteLabel").toggleClass("hidden");                                     
                    }
            });
        }
    });
}

