/// <reference name="MicrosoftAjax.js" />
/// <reference path="GSK.PopupManager.js" />
/// <reference path="s_code_gskquitmastersuk.js" />


function SwitchControlView(anchorID, linkButtonID)
{
	if (typeof $ != "undefined" && $)
	{
		$('#' + anchorID).hide();
		$('#' + linkButtonID).show();
	}
}

function ManageEnabled(controlID, enabled)
{
	if (typeof $ != "undefined" && $)
	{
		enabled ? $('#' + controlID).enable() : $('#' + controlID).disable();
	}
}
GSK = function() {
    /// <summary>This is the main namespace and place for custom javascript objects and methods.
    /// It is work as a sigleton and cannot be created more than once.
    /// </summary>
    /// <returns>GSK</returns>
    var type = 'GSKManager';
    var version = '0.1';
    var SubmitForm = function(url, target) {
        $.post(url, ReadForm(target), GSK.MarkerMethod);
    }
    var ReadForm = function(target) {
        var formDict = {};
        $('form#aspnetForm input,select,textarea').each(
			function() {
			    formDict[$(this).attr("name")] = $(this).attr("value");
			});
        formDict['__EVENTTARGET'] = target;
        return formDict;
    }
    return {
        Type: function() { return type; },
        Version: function() { return version; },
        IsJqueryEnabled: function() { return typeof $ != "undefined"; },
        MarkerMethod: function() { },
        PostBackManager: function() {
            var onTopClass = '';
            var onCallerClass = '';
            var callerID = '';
            var modify;

            var clickOnceClass = '';
            var clickOnceCallerID = '';
            var clickOnceUsed = false;

            var progressClass = '';

            function OnRequestComplete() {
                if (modify) {
                    if (callerID) {
                        $('#' + callerID).scrollTo(0);
                    }
                    else {
                        $.scrollTo(0);
                    }
                    modify = false;
                }
            }
            function OnBeginTop(e) {
                modify = true;
            }
            function OnBeginCaller(e) {
                if (e && e.srcElement) {
                    callerID = e.srcElement.id;
                }
                modify = true;
            }
            function OnClickOnceClick(e) {
                //clickOnceCallerID = e.srcElement.id;
                clickOnceUsed++;
            }
            function OnShowProgressClick(e) {
                if (typeof showProgressGif != 'undefined') { showProgressGif(); }
            }
            function CancelRequests(sender, args) {
                //if (args.get_postBackElement().id == clickOnceCallerID && clickOnceUsed > 1)
                //var prm = Sys.WebForms.PageRequestManager.getInstance();
                //prm.isInAsyncPostback()
                var containClass = args.get_postBackElement().className.indexOf(clickOnceClass) > -1;
                if (clickOnceUsed > 1 && containClass) {
                    args.set_cancel(true);
                }
            }
            function Bind() {
                $('.' + onTopClass).bind("click", OnBeginTop);
                $('.' + onCallerClass).bind("click", OnBeginCaller);
            }
            function BindClickOnce() {
                $('.' + clickOnceClass).bind("click", OnClickOnceClick);
                clickOnceUsed = 0;
            }
            function BindShowProgress() {
                $('.' + progressClass).bind("click", OnShowProgressClick);
            }
            function OnDocumentComplete() {
                try {
                    Sys.Application.add_load(Bind);
                    var prm = Sys.WebForms.PageRequestManager.getInstance();
                    prm.add_endRequest(OnRequestComplete);
                } catch (err) { }
            }
            function DisableAfterClick() {
                $btn = $('#' + clickOnceCallerID);
                if ($btn.lenght == 1) {
                    $btn.attr('href', '');
                    $btn.attr('disabled', 'disabled');
                    clickOnceCallerID = '';
                }
            }
            return {
                InitPosition: function(settings) {
                    onTopClass = settings.onTopClass;
                    onCallerClass = settings.onCallerClass;
                    $(document).ready(OnDocumentComplete);
                },
                InitClickOnce: function(settings) {
                    clickOnceClass = settings.clickOnceClass;
                    Sys.Application.add_load(BindClickOnce);
                },
                InitShowProgress: function(settings) {
                    progressClass = settings.progressClass;
                    Sys.Application.add_load(BindShowProgress);
                },
                Init: function() {
                    try {
                        var prm = Sys.WebForms.PageRequestManager.getInstance();
                        //prm.add_beginRequest(DisableAfterClick);
                        prm.add_initializeRequest(CancelRequests);
                    }
                    catch (err) { }
                }
            }
        } (),
        CufonUpdater: function() {
            var items = new Array();
            var baseClass = '.cufon';
            selectors = new Array('h1', 'h2', 'h3', 'h4');
            context = { hover: true, fontFamily: 'Arial Rounded MT Bold' };
            function Combine(parent) {
                ///<summary>Combines all selectors with given parent id.</summary>
                var combined = '';
                for (j in selectors) {
                    combined += ' #' + parent + ' ' + selectors[j] + ', ';
                }
                combined += ' #' + parent + ' ' + baseClass;
                /// <returns type="String" >Selectors</returns>
                return combined;
            };
            function ForEach(parent) {
                for (j in selectors) {
                    Cufon.replace('#' + parent + ' ' + selectors[j], context);
                }
                //$('#' + parent + ' ' + baseClass).each(function() { Cufon.replace(this, context); });
                Cufon.replace('#' + parent + ' ' + baseClass, context);
            };
            return {
                Add: function(parent) {
                    items.push(parent);
                },
                Refresh: function() {
                    //console.time('refresh');
                    for (i in items) {
                        var combinedString = selectors;
                        combinedString = Combine(items[i]);
                        //ForEach(items[i]);
                        Cufon.replace(combinedString, context);
                    }
                    //console.timeEnd('refresh');
                }
            };
        } (),
        FeedbackManager: function() {
            var containerId;
            return {
                Set: function(context) {
                    containerId = context.id;
                    $(containerId).fadeIn();
                }
            }
        } (),
        ProgressBar: function() {
            var count;
            var meter;
            var value;
            var inter = null;
            function UpdateCompleteness() {
                count++;
                meter.find('.meter-value').css('width', count + "%");
                meter.find('.meter-text').text(count + "%");
                if (count == value || count > 100) {
                    clearInterval(inter);
                }
            }
            return {
                Set: function(context) {
                    meter = $('#meter-' + context.id);
                    count = 0;
                    value = context.completeness;
                    if (value > 0) {
                        inter = setInterval(UpdateCompleteness, context.interval);
                    }
                }
            }
        } (),
        UpDownNumeric: function() {
            numerics = {};

            /// <summary>Helper for up/down numeric control. Allows user to maintain numeric textbox with two buttons.</summary>
            function ValidateDigits(e) {
                var digit = true;
                var charCode = (e.which) ? e.which : e.keyCode;
                if (charCode < 48 || charCode > 57) {
                    digit = false;
                }
                return digit;
            };
            function Update(inputID, step) {
                /// <summary>Updates the value of control with given id.</summary>
                /// <param Name="inputID">Id control wchich can be </param>
                /// <param Name="step">Mofier. Describes value which will be applied to the control's value.</param>
                if (GSK.IsJqueryEnabled()) {
                    var input = $("#" + inputID);
                    if (input.length > 0) {
                        var oldValue = input.attr('value');
                        var numericOldValue = parseInt(oldValue) > 0 ? parseInt(oldValue) : 0;
                        var newValue = numericOldValue + step;
                        if (newValue < 0) {
                            newValue = 0;
                        }
                        input.val(newValue);
                    }
                }
            };
            function Watch(name) {
                var numericPair = numerics[name];
                if (numericPair) {
                    $ver = $('#' + numericPair.ver);
                    $other = $('#' + numericPair.other);

                    var verifierValue = parseInt($ver.val());
                    var otherValue = parseInt($other.val());

                    if (otherValue > verifierValue) {
                        $other.val(verifierValue);
                    }
                }
            }
            return {
                BindDigitValidation: function(inputID) {
                    $('#' + inputID).keypress(ValidateDigits);
                },
                BindUpdate: function(btnId, inputID, value, name) {
                    $('#' + btnId).click(function() { Update(inputID, value, name); });
                },
                BindPair: function(settings) {
                    numerics[settings.name] =
                    {
                        ver: settings.ver,
                        other: settings.other,
                        name: settings.name
                    };
                    Sys.Application.add_load(function() {
                        $('#' + settings.other).bind('change', function() { Watch(settings.name); });
                        $('#' + settings.ver).bind('change', function() { Watch(settings.name); });
                    });
                },
                Watch: function(name) { Watch(name); }
            }
        } (),
        ProfileNotifier: function() {
            var url = '';
            var type = 'POST';
            var method = 'FORM';
            return {
                Bind: function(url, target) {
                    $(window).bind('unload', function(sender, e) { SubmitForm(url, target); });
                }
            };
        } (),
        ButtonGroupManager: function() {
            var groups = {};
            return {
                Type: function() { return 'ButtonGroupManager'; },
                Add: function(name, group) {
                    groups[name] = group;
                },
                Remove: function(name) {
                    groups[name] = null;
                },
                New: function() {
                    return new GSK.ButtonGroup();
                },
                Get: function(name) { return groups[name]; },
                Change: function(groupName, buttonID) {
                    var group = Get(groupName);
                    if (group) {
                        group.SelectItem(buttonID);
                    }
                }
            };
        } (),
        FormValidationHelper: function() {
            var helpers = {};
            HelperItem = function(name, context) {
                var validationGroup = context.group;
                var cssClass = context.cssClass;
                var submitID = context.submitID;
                var name = name;
                function ManageValidation(e, args) {
                    var formInput = e.currentTarget;
                    var valid = true;
                    if (formInput.nodeName == "SPAN") {
                        formInput = $(formInput).children()[0];
                        valid = formInput.checked;
                    }
                    if ($(formInput).is('input[type=checkbox]')) {
                        valid = formInput.checked;
                    }
                    else if (formInput.Validators) {
                        for (var i = 0; i < formInput.Validators.length; i++) {
                            if (!formInput.Validators[i].isvalid) {
                                valid = false;
                                $(formInput.Validators[i]).addClass('display-block').removeClass('display-none');
                            }
                            else {
                                $(formInput.Validators[i]).addClass('display-none').removeClass('display-block');
                            }
                        }
                    }
                    if (valid) {
                        $(formInput).removeClass(formInput.nodeName == 'SELECT' ? 'error-select' : 'error-input');
                    }
                    else {
                        $(formInput).addClass(formInput.nodeName == 'SELECT' ? 'error-select' : 'error-input');
                    }
                    $(GSK.FormValidationHelper.Get(name)).trigger('validation', { target: formInput, group: validationGroup, cssClass: cssClass, valid: valid });
                }
                function ManageValidationOnSubmit() {
                    Page_ClientValidate(validationGroup)
                    $('.' + cssClass).each(
					function(e) {
					    ManageValidation({ currentTarget: this }, null);
					});
                    $(GSK.FormValidationHelper.Get(name)).trigger('submit', { target: $('#' + submitID)[0], group: validationGroup, cssClass: cssClass });
                }
                return {
                    GetValidationGroup: function() { return validationGroup; },
                    GetCssClass: function() { return cssClass; },
                    Bind: function() {
                        $('.' + cssClass).each(function() { $(this).bind('blur', ManageValidation); });
                        // Hack for <asp:Checkbox
                        $('.' + cssClass).children('input[type=checkbox]').each(function() {
                            $(this).bind('click', ManageValidation);
                        });
                        //		
                        if (validationGroup) {
                            $('#' + submitID).bind('click', ManageValidationOnSubmit);
                        }
                    }
                }
            }
            return {
                Register: function(name, context) {
                    var item = new HelperItem(name, context);
                    helpers[name] = item;
                    item.Bind();
                    /// <return type="GSK.FormValidationHelper.HelperItem" >Helper item.</return>"
                    return item;
                },
                Get: function(name) {
                    return helpers[name];
                }
            }
        } (),
        RegisterManager: function() {
            var validationGroup;
            var userNameValid = undefined;
            var emailValid = undefined;
            var userMigrated = false;
            var passwordValid = undefined;
            var textboxNameID = false;
            var textboxEmailID = false;
            var cbAgreeID = undefined;
            var cbDataID = undefined;
            var divMigrationID = undefined;
            var vals = {};
            var cssValid = 'green';
            function OnSuccess(result, context) {
                if (result) {
                    if (context.ctrlToShow) {
                        $('#' + context.ctrlToShow).show();
                        $('#' + context.ctrl).text('').hide();
                        $(context.textbox).addClass('error-input');
                    }
                    else {
                        if (!userMigrated) {
                            $('#' + context.ctrl).text(context.messageValid).addClass('display-block ' + cssValid);
                            $(context.textbox).removeClass('error-input');
                        }
                    }
                }
                else {
                    if (context.ctrlToShow) {
                        $('#' + context.ctrlToShow).hide();
                        if (!emailValid) {
                            $('#' + context.ctrl).text(context.messageInvalid).removeClass(cssValid).addClass('display-block');
                            $(context.textbox).addClass('error-input');
                        }
                        else {
                            $('#' + context.ctrl).text(context.messageValid).addClass('display-block ' + cssValid);
                            $(context.textbox).removeClass('error-input');
                        }
                    }
                    else {
                        $('#' + context.ctrl).text(context.messageInvalid).removeClass(cssValid).addClass('display-block');
                        $(context.textbox).addClass('error-input');
                    }
                }
                if (context.type == 'email') {
                    emailValid = result;
                }
                else if (context.type == 'username') {
                    userNameValid = result;
                }
                else if (context.type == 'migration') {
                    userMigrated = result;
                }
            }
            function OnFail(error, context) {
                $('#' + context.ctrl).text('').hide();
            }
            function Check(textbox, context, method, OnSuccessCustom) {
                if (typeof GSKUtils != 'undefined') {
                    for (i in textbox.Validators) {
                        if (!textbox.Validators[i].isvalid && !$(textbox.Validators[i]).hasClass('ignore')) {
                            OnFail(null, context)
                            return true;
                        }
                    }
                    context.textbox = textbox;
                    var methodOnSuccess = OnSuccessCustom ? OnSuccessCustom : OnSuccess;
                    method(textbox.value, methodOnSuccess, OnFail, context);
                }
                return true;
            }
            function CustomValidationOnSubmit() {
                if (textboxEmailID && !emailValid && !userMigrated && typeof emailValid != 'undefined') { //if emailValid or userNameValid are == to 'undefined' means that emailValid was set so it's part of validation.
                    $('#' + textboxEmailID).addClass('error-input');
                }
                if (textboxNameID && !userNameValid && typeof userNameValid != 'undefined') {
                    $('#' + textboxNameID).addClass('error-input');
                }
                for (var i in Page_Validators) {
                    var val = Page_Validators[i];
                    if (!val.isvalid) {
                        for (var j in vals) {
                            if (vals[j] == val.id) {
                                var cb = $('#' + j);
                                setTimeout(function() { cb.focus(); }, 200);
                            }
                        }
                        break;
                    }
                }

                return emailValid && userNameValid && !userMigrated;
            }
            function CustomValidationEmailOnSubmit() {
                if (textboxEmailID && !emailValid) {
                    $('#' + textboxEmailID).addClass('error-input');
                }
                return emailValid;
            }
            function ValidateCheckBoxOnChange(context, args) {
                //{ target: formInput, group: validationGroup, cssClass: cssClass, valid: valid }
                for (var i in Page_Validators) {
                    var val = Page_Validators[i];
                    if (val.clientvalidationfunction && val.clientvalidationfunction.indexOf('GSK') != -1
                        && vals[args.target.id] == val.id) {
                        if (args.valid) {
                            $(val).removeClass('display-block');
                            $(val).addClass('display-none');
                        }
                        else {
                            $(val).removeClass('display-none');
                            $(val).addClass('display-block');
                        }
                    }
                }
                if (args.target.id == textboxEmailID) {
                    var hide = false;
                    for (i in args.target.Validators) {
                        if (!args.target.Validators[i].valid) {
                            hide = true;
                            break;
                        }
                    }
                    if (hide) {
                        $('#' + divMigrationID).hide();
                    }
                }
            }
            function OnMailSuccess(result, context) {
                emailValid = result == GSKUtils.UsernameStatus.Available;
                userMigrated = result == GSKUtils.UsernameStatus.Migration;
                if (userMigrated) {
                    $('#' + context.ctrlToShow).show();
                    $('#' + context.ctrl).text('').hide();
                    $(context.textbox).addClass('error-input');
                }
                else {
                    $('#' + context.ctrlToShow).hide();
                    if (emailValid) {
                        $('#' + context.ctrl).text(context.messageValid).addClass('display-block ' + cssValid);
                        $(context.textbox).removeClass('error-input');
                    }
                    else {
                        $('#' + context.ctrl).text(context.messageInvalid).removeClass(cssValid).addClass('display-block');
                        $(context.textbox).addClass('error-input');
                    }
                }
            }
            return {
                CheckEmail: function(textbox, messageCtrlID, messValid, messInvalid) {
                    if (textbox.value) {
                        var context = { ctrl: messageCtrlID, messageValid: messValid, messageInvalid: messInvalid, type: 'email' };
                        Check(textbox, context, GSKUtils.RegistrationHelper.CheckEmail, OnSuccess);
                    }
                },
                CheckUsername: function(textbox, messageCtrlID, messValid, messInvalid) {
                    if (textbox.value) {
                        var context = { ctrl: messageCtrlID, messageValid: messValid, messageInvalid: messInvalid, type: 'username' };
                        Check(textbox, context, GSKUtils.RegistrationHelper.CheckUsername, OnSuccess);
                    }
                },
                CheckMigration: function(textbox, migrationDiv, messageCtrlID, messValid, messInvalid) {
                    if (textbox.value) {
                        var context = { ctrlToShow: migrationDiv, ctrl: messageCtrlID, messageValid: messValid, messageInvalid: messInvalid, type: 'migration' };
                        Check(textbox, context, GSKUtils.RegistrationHelper.CheckEmailExtended, OnMailSuccess);
                    }
                },
                Init: function(context) {
                    validationGroup = context.group;
                    textboxEmailID = context.textboxEmailID;
                    textboxNameID = context.textboxNameID;
                    cbAgreeID = context.cbAgreeID;
                    cbDataID = context.cbDataID;
                    vals[cbAgreeID] = context.valAgreeID;
                    vals[cbDataID] = context.valDataID;
                    divMigrationID = context.divMigrationID;
                    var item = GSK.FormValidationHelper.Register('Registration', context);
                    $(item).bind('submit', CustomValidationOnSubmit);
                    $(item).bind('validation', ValidateCheckBoxOnChange);
                },
                InitDetails: function(name, context) {
                    validationGroup = context.group;
                    textboxEmailID = context.textboxEmailID;
                    emailValid = true;
                    var item = GSK.FormValidationHelper.Register(name, context);
                    $(item).bind('submit', CustomValidationEmailOnSubmit);
                },
                ValidatorEmail: function(e, args) {
                    if (typeof emailValid != 'undefined') {
                        args.IsValid = emailValid;
                    }
                },
                ValidatorMigrated: function(e, args) {
                    args.IsValid = !userMigrated;
                },
                ValidatorUsername: function(e, args) {
                    if (typeof userNameValid != 'undefined') {
                        args.IsValid = userNameValid;
                    }
                },
                ValidatorPassword: function(e, args) {
                    if (typeof passwordValid != 'undefined') {
                        args.IsValid = passwordValid;
                    }
                },

                ValidateAgreeCheckBox: function(source, args) {
                    args.IsValid = document.getElementById(cbAgreeID).checked;
                },
                ValidateDataCheckBox: function(source, args) {
                    args.IsValid = document.getElementById(cbDataID).checked;
                }
            }
        } (),
        TermsAndConditionsHelper: function() {

            return {
                Init: function(e, args) {

                }
            }
        } (),
        CalendarHelper: function() {
            var calendarID = null;
            var targetID = null;
            var hfMessagesID = null;
            var messagesEnabled;
            var readonly;
            var today;

            var txtQuitID;
            var txtReduceID;
            var siteLocation;
            var dateQuitValid = false;
            var dateReduceValid = false;

            ReduceDateSettings = null;
            QuitDateSettings = null;
            var cssValid = 'green';

            var validateOnlyReduce = false;

            function changeSendMessages(obj) {
                var current = $('#' + hfMessagesID).val();
                if (current == "True") {
                    obj.src = "/images/product-selection/check-box-no.png";
                    $('#' + hfMessagesID).val("False");
                }
                else {
                    obj.src = "/images/product-selection/check-box-selected.png";
                    $('#' + hfMessagesID).val("True");
                }

            }
            function OnSuccess(result, context) {
                if (result.Valid) {
                    $('#' + context.ctrl).text(context.messageValid).addClass('display-block ' + cssValid);
                    $(context.textbox).removeClass('error-input');
                    if (result.RelatedDate) {
                        context.dateTextBox.value = result.RelatedDate;
                    }
                }
                else {
                    $('#' + context.ctrl).text(context.messageInvalid).addClass('display-block').removeClass(cssValid);
                    $(context.textbox).addClass('error-input');
                }
                if (context.type == 'quit') {
                    dateQuitValid = result.Valid;
                }
                else if (context.type == 'reduce') {
                    dateReduceValid = result.Valid;
                }
            }
            function OnFail(error, context) {
                $('#' + context.ctrl).text('').hide();
            }
            function Check(settings) {
                if (typeof GSKUtils != 'undefined') {
                    for (i in settings.sender.Validators) {
                        if (!settings.sender.Validators[i].isvalid &&
                            !$(settings.sender.Validators[i]).hasClass('ignore')) {
                            OnFail(null, settings.context)
                            return true;
                        }
                    }
                    settings.context.sender = settings.sender;
                    settings.context.validationTextBox = settings.validationTextBox;
                    settings.context.dateTextBox = settings.dateTextBox;
                    if (settings.context.validationTextBox) {
                        settings.method(settings.context.validationTextBox.value,
                            settings.sender.value, OnSuccess, OnFail, settings.context);
                    }
                    else {
                        settings.method(settings.sender.value, OnSuccess, OnFail, settings.context);
                    }
                }
                return true;
            }
            function CustomValidationOnSubmit() {
                if (!dateQuitValid && !validateOnlyReduce) {
                    $('#' + txtQuitID).addClass('error-input');
                    OnSuccess(false, QuitDateSettings);
                }
                if (!dateReduceValid) {
                    $('#' + txtReduceID).addClass('error-input');
                    OnSuccess(false, ReduceDateSettings);
                }
            }
            function OnSubmit() {
                CustomValidationOnSubmit();
                if (!dateQuitValid) { $('#' + txtQuitID).focus(); }
                if (!dateReduceValid) { $('#' + txtReduceID).focus(); }
                if (dateQuitValid && dateReduceValid) {
                    var uniqueID = this.id.replace(/_/gi, '$');
                    __doPostBack(uniqueID, '');

                }
                return false;
            }
            return {
                MousePointer: function(e, args) {
                    e.currentTarget.style.cursor = 'pointer';
                },
                MousePointerOut: function(e, args) {
                    e.currentTarget.style.cursor = '';
                },
                AddLoad: function(context) {
                    readonly = context.readOnly;
                    targetID = context.targetID;
                    calendarID = context.ID;
                    hfMessagesID = context.hiddenMessageID;
                    messagesEnabled = context.messageEnabled;
                    Date.format = context.dateFormat;
                    if (context.firstDay) {
                        Date.firstDayOfWeek = context.firstDay;
                    }
                    else {
                        Date.firstDayOfWeek = 0;
                    }
                    today = context.now;
                    var currDate = $('#' + targetID).val();
                    if (readonly) {
                        var picker = $('#' + calendarID).datePicker({ inline: true, startDate: currDate, endDate: currDate });
                    }
                    else {
                        var picker = $('#' + calendarID).datePicker({ inline: true, startDate: context.startDate });
                    }
                    picker.dpSetSelected(currDate);
                    picker.bind('change', GSK.CalendarHelper.SelectedDateChanged);
                    if (txtQuitID) {
                        this.QuitDateValidation();
                    }
                    if (txtReduceID) {
                        this.ReduceDateValidation();
                    }
                },
                SelectedDateChanged: function() {
                    var dateSelected = $('#' + calendarID).dpGetSelected()[0];
                    $('#' + targetID).val(dateSelected.asString());
                    if (messagesEnabled) {
                        var weekAfter = new Date();
                        weekAfter.setDate(weekAfter.getDate() + 7);
                        if (dateSelected[0] > weekAfter) {
                            $('#cb-messages').bind('mouseover', GSK.CalendarHelper.MousePointer);
                            $('#cb-messages').unbind('mouseover', GSK.CalendarHelper.MousePointerOut);
                            $('#cb-messages').bind('click', GSK.CalendarHelper.SelectedMessagesChanged);
                        }
                        else {
                            $('#cb-messages').unbind('mouseover', GSK.CalendarHelper.MousePointer);
                            $('#cb-messages').bind('mouseover', GSK.CalendarHelper.MousePointerOut);
                            $('#cb-messages').unbind('click', GSK.CalendarHelper.SelectedMessagesChanged);
                            $('#cb-messages').attr('src', '/images/product-selection/check-box-no.png');
                            $('#' + hfMessagesID).val(false);
                        }
                    }
                },
                SelectedMessagesChanged: function(e, args) {
                    changeSendMessages(e.currentTarget);
                },
                InitInline: function(settings) {
                    $('#' + settings.ID).calendar(
                    {
                        dateFormat: settings.dateFormat
                    });
                },
                InitDateValidation: function(settings) {
                    validationGroup = settings.group;
                    txtQuitID = settings.txtQuitId;
                    txtReduceID = settings.txtReduceId;
                    dateQuitValid = settings.dateQuitValid || settings.onlyReduce;
                    dateReduceValid = settings.dateReduceValid;

                    var item = GSK.FormValidationHelper.Register('DateValidation', settings);
                    if (validationGroup) {
                        $(item).bind('submit', CustomValidationOnSubmit);
                    }
                    if (settings.submitID) {
                        $btn = $('#' + settings.submitID);
                        $btn.attr('href', '');
                        $btn.bind('click', OnSubmit);
                    }


                    ReduceDateSettings = settings.reduceDateSett;
                    QuitDateSettings = settings.quitDateSett;

                    QuitDateSettings.textbox = $('#' + txtQuitID);
                    ReduceDateSettings.textbox = $('#' + txtReduceID);

                    validateOnlyReduce = settings.onlyReduce;

                    if (!validateOnlyReduce && $('#' + txtQuitID).val()) {
                        this.QuitDateValidation();
                    }
                    if ($('#' + txtReduceID).val()) {
                        this.ReduceDateValidation();
                    }
                },
                QuitDateValidation: function() {
                    var textbox = $('#' + txtQuitID)[0];
                    if (textbox && textbox.value) {
                        Check({
                            sender: textbox,
                            context: QuitDateSettings,
                            method: GSKUtils.RegistrationHelper.CheckQuitDate,
                            validationTextBox: $('#' + txtReduceID)[0]
                        });
                    }
                    else {
                        OnSuccess(false, QuitDateSettings);
                    }
                },
                ReduceDateValidation: function() {
                    var textbox = $('#' + txtReduceID)[0];
                    if (tetbox && textbox.value) {
                        Check({
                            sender: textbox,
                            context: ReduceDateSettings,
                            method: GSKUtils.RegistrationHelper.CheckReduceDate,
                            dateTextBox: $('#' + txtQuitID)[0]
                        });
                        if (!validateOnlyReduce) {
                            GSK.CalendarHelper.QuitDateValidation();
                        }
                    }
                    else {
                        OnSuccess(false, ReduceDateSettings);
                    }
                }
            };
        } (),
        ProductsHelper: function() {
            var hiddenID;
            var products = {};
            var warningID;
            var hiddenPurchasedID;
            var purchased;
            var linkButtonID;

            //var selectorExpanded = "div[id^='registration-description-']";
            //var selectorCollapsed = "div[id^='registration-content-']";
            var parent;

            function ShowHideWarning(className, product) {
                $('#' + warningID).attr('class', '');
                $('#' + warningID).addClass(className);
                $('#' + warningID + '-footer').attr('class', '');
                $('#' + warningID + '-footer').addClass(className);
                if (product) {
                    $('#' + warningID + '-text').html(unescape(product.message));
                }
                else {
                    $('#' + warningID + '-text').html('');
                }
            }
            function showContent(thisId) {
                $(thisId).slideDown(450);
            }
            function hideContent() {
                $('#' + parent + " div[id^='registration-content-']").slideUp(450, function() {
                    hideDescription(hideId);
                });
            }
            function hideDescription(thisId) {
                $('#' + parent + " div[id^='registration-description-']").show();
                $(thisId).hide();
            }
            function swap(obj) {
                hideContent(hideId);
                var groupId = $(obj).parent().get(0).id;
                var hyphenPos = groupId.lastIndexOf("-");
                var groupNo = groupId.substring(hyphenPos);
                var displayId = "#registration-content" + groupNo;
                showContent(displayId);
                $('.chk-text', '#content').width('414px');
                var hideId = "#registration-description" + groupNo;

            }
            function changePurchase(obj) {
                purchased = !purchased;
                $('#' + hiddenPurchasedID).val(purchased ? "True" : "False");
                setPurchased(obj);
            }
            function setPurchasedSelected(obj, selected) {
                if (obj) {
                    if (selected) {
                        obj.src = "/images/product-selection/check-box-selected.png";
                        //$("div[id^='recommended-']").hide();
                    }
                    else {
                        obj.src = "/images/product-selection/check-box-no.png";
                        //$("div[id^='recommended-']").show();
                    }
                }
            }
            function setPurchased(obj) {
                if (obj) {
                    setPurchasedSelected(obj, purchased);
                    /*if (purchased)
                    {
                    ShowHideWarning('hide');
                    }
                    else
                    {
                    var currentProd = products[$('#' + hiddenID).val()];
                    if (currentProd)
                    {
                    ShowHideWarning(currentProd.recommended
                    ? 'hide' : 'show', currentProd);
                    }
                    }*/
                }
            }
            function Selectproduct(productID) {
                var product = products[productID];
                if (product) {
                    $('#' + hiddenID).val(product.id);
                    var productTick = $('#' + product.handlerId + '-' + product.id)[0];
                    if (productTick) {
                        swap(productTick);
                        //if (!purchased || product.warnAlways)                        
                        //{
                        ShowHideWarning(product.recommended && !product.warnAlways
                                ? 'hide' : 'show', product);
                        //}
                    }
                }
            };
            function PostBack(productID) {
                var product = products[productID];
                if (product) {
                    if (product.postback) {
                        var timeout = setTimeout(function() { __doPostBack(linkButtonID, ''); clearTimeout(timeout); }, 1);
                    }
                }
            };
            return {
                Show: function(productID) {
                    Selectproduct(productID);
                    PostBack(productID);
                },
                MousePointer: function(item) { item.style.cursor = 'pointer'; },
                PurchaseChanged: function(obj) { changePurchase(obj); },
                RegisterProduct: function(product) {
                    products[product.id] = product;
                },
                RadioButtons: function() {
                    function Bind(selector) {
                        ///<summary>Creates jQuery's radio buttons for a given container selector.</summary>         
                        if ($().customInput) {
                            $(selector).customInput();
                        }
                    }
                    return {
                        Init: function(selector, refreshAfterPostback) {
                            if (refreshAfterPostback) {
                                Sys.Application.add_load(function() { Bind(selector); });
                            }
                            else {
                                Bind(selector);
                            }
                        }
                    };
                } (),
                AddLoad: function(productId, warningId, selectionId,
                    alreadyPurchased, purchasedId, readonly, btnId, parentId) {
                    purchased = alreadyPurchased;
                    hiddenPurchasedID = purchasedId;
                    hiddenID = selectionId;
                    warningID = warningId;
                    linkButtonID = btnId;
                    parent = parentId;
                    $('#' + parent + " div[id^='registration-content-']").hide();
                    setPurchasedSelected($('#cb-purchased')[0], purchased);
                    ShowHideWarning('hide');
                    Selectproduct(productId);
                    if (readonly) {
                        $("img[id^='product-handler-']").unbind('click', GSK.ProductsHelper.Show);
                        $("img[id^='product-handler-']").attr('onclick', '');
                        $("img[id^='product-handler-']").unbind('mouseover', GSK.ProductsHelper.MousePointer);
                        $("img[id^='product-handler-']").attr('onmouseover', '');

                        $('#cb-purchased').attr('onmouseover', '');
                        $('#cb-purchased').attr('onclick', '');
                    }
                }
            };
        } (),
        CookiesHelper: function() {

            return {
                CreateCookie: function(name, value, days) {
                    if (days) {
                        var date = new Date();
                        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                        var expires = "; expires=" + date.toGMTString();
                    }
                    else var expires = "";
                    document.cookie = name + "=" + value + expires + "; path=/";
                },
                ReadCookie: function(name) {
                    var nameEQ = name + "=";
                    var ca = document.cookie.split(';');
                    for (var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                    }
                    return null;
                },
                EraseCookie: function(name) {
                    createCookie(name, "", -1);
                }
            }
        } (),
        PopUpHelper: function() {
            var popups = {};
            function HideMask() {
                $(this).hide();
                $('.window').hide();
                $('#select-free').hide();
                $(this).unbind('click');
            };
            function HideMaskSett(obj, settings) {
                $(obj).hide();
                $('#' + settings.Id).hide();
                $(obj).unbind('click');
            };
            function BindTarget(target, settings) {
                //select all the a tag with name equal to modal
                target.click(function(e) {
                    if (settings.PreventDefault) {
                        //Cancel the link behavior
                        e.preventDefault();
                    }

                    //Get the screen height and width
                    var maskHeight = $(document).height();
                    var maskWidth = $(window).width();

                    //Set height and width to mask to fill up the whole screen
                    $('#maskPopup').css({ 'width': maskWidth, 'height': maskHeight });
                    $('#select-free').css({ 'width': maskWidth, 'height': maskHeight }).show();

                    //transition effect
                    $('#maskPopup').fadeIn(200);
                    $('#maskPopup').fadeTo("fast", 0.8);

                    //Get the window height and width
                    var winH = $(window).height();
                    var winW = $(window).width();

                    var scrollTop = $(window).scrollTop();
                    //Set the popup window to center
                    $('#' + settings.Id).css('top', (winH / 2 - $('#' + settings.Id).outerHeight() / 2) + scrollTop);
                    $('#' + settings.Id).css('left', winW / 2 - $('#' + settings.Id).outerWidth() / 2);

                    //transition effect
                    $('#' + settings.Id).fadeIn(500);

                    if (settings.PreventBubble) {
                        if (e.stopImmediatePropagation) {
                            e.stopImmediatePropagation();
                        }
                        e.cancelBubble = true;
                    }
                    return !settings.PreventBubble;
                });

                //if close button is clicked
                $('.window .close').click(function(e) {
                    //Cancel the link behavior
                    e.preventDefault();
                    if (settings.PostBack && settings.SubmitID == e.currentTarget.id) {
                        var uniqueId = e.currentTarget.id.replace(/_/gi, '$');
                        __doPostBack(uniqueId, '');
                    }

                    $('#maskNew').hide();
                    $('#maskPopup').hide();
                    $('#maskPopup').unbind('click');
                    $('.window').hide();
                    $('#select-free').hide();

                });

                if (!settings.MaskNotClickable) {
                    //if mask is clicked
                    $('#maskPopup').click(HideMask);
                }
            };
            function BindShow(settings) {
                var timeout = setTimeout(function() {
                    //if close button is clicked
                    $('#' + settings.Id + ' .close').click(function(e) {
                        //Cancel the link behavior
                        e.preventDefault();

                        $('#maskPopup').hide();
                        $('#maskPopup').unbind('click');
                        $('#' + settings.Id).hide();
                    });

                    if (!settings.MaskNotClickable) {
                        //if mask is clicked
                        $('#maskPopup').click(function() { HideMaskSett(this, settings); });
                    }
                    //Get the screen height and width
                    var maskHeight = $(document).height();
                    var maskWidth = $(window).width();

                    //Set height and width to mask to fill up the whole screen
                    $('#maskPopup').css({ 'width': maskWidth, 'height': maskHeight });
                    $('#select-free').css({ 'width': maskWidth, 'height': maskHeight }).show();

                    //transition effect  
                    $('#mask').fadeIn(200);
                    $('#mask').fadeTo("fast", 0.8);

                    //transition effect
                    $('#maskPopup').fadeIn(200);
                    $('#maskPopup').fadeTo("fast", 0.8);

                    //Get the window height and width
                    var winH = $(window).height();
                    var winW = $(window).width();

                    //Set the popup window to center
                    $('#' + settings.Id).css('top', winH / 2 - $('#' + settings.Id).outerHeight() / 2);
                    $('#' + settings.Id).css('left', winW / 2 - $('#' + settings.Id).outerWidth() / 2);
                    $('#' + settings.Id).css('zIndex', 9999);
                    //transition effect
                    $('#' + settings.Id).fadeIn(500);
                    clearTimeout(timeout);
                }, settings.interval);
            };
            function Init(settings) {
                Sys.Application.add_load(function() {
                    targetID = settings.TargetId.split(' ');
                    for (var i in targetID) {
                        if (targetID[i]) {
                            var target = $('#' + targetID[i]);
                            if (target.length > 0 && typeof target != 'undefined') {
                                BindTarget(target, settings);
                            }
                        }
                    }
                });
            };
            return {
                Register: function(settings) {
                    if (!popups[settings.id]) {
                        var item = new GSK.PopUpItem();
                        item.Id = settings.id;
                        item.TargetId = settings.target;
                        item.ShowOnLoad = settings.show;
                        item.ShowInterval = settings.interval;
                        item.TextFieldID = settings.textId;
                        item.PreventDefault = settings.prevent;
                        item.PreventBubble = settings.bubble;
                        item.PostBack = settings.postBack;
                        item.SubmitID = settings.btnConfirmID;
                        item.MaskNotClickable = settings.maskNotClickable;
                        popups[settings.id] = item;
                        Init(item);
                    }
                },
                Show: function(name) {
                    var item = popups[name];
                    if (item) {
                        BindShow(item);
                    }
                },
                UpdateText: function(name, text) {
                    var item = popups[name];
                    if (item) {
                        $('#' + item.TextFieldID).html(text);
                    }
                },
                ShowWarning: function(settings) {
                    $(document).ready(function() {
                        var id = settings.selector;
                        if ($(id)) {
                            $('#wrapper').append($(id));

                            setTimeout(function() {

                                //Get the screen height and width
                                var maskHeight = $(document).height();
                                var maskWidth = $(window).width();

                                //Set height and width to mask to fill up the whole screen
                                $('#mask').css({ 'width': maskWidth, 'height': maskHeight });
                                $('#select-free').css({ 'width': maskWidth, 'height': maskHeight }).show();
                                //transition effect		
                                $('#mask').fadeIn(200);
                                $('#mask').fadeTo("fast", 0.8);

                                //Get the window height and width
                                var winH = $(window).height();
                                var winW = $(window).width();

                                //Set the popup window to center
                                $(id).css('top', winH / 2 - $(id).outerHeight() / 2);
                                $(id).css('left', winW / 2 - $(id).outerWidth() / 2);

                                //transition effect
                                $(id).fadeIn(500);
                            }, 10);
                        }
                    });
                },
                BindForgotten: function(anchorId) {
                    $(document).ready(function() {
                        //select all the a tag with name equal to modal
                        $('#' + anchorId).click(function(e) {
                            //Cancel the link behavior
                            e.preventDefault();

                            //Get the A tag
                            var id = $(this).attr('href');

                            //Get the screen height and width
                            var maskHeight = $(document).height();
                            var maskWidth = $(window).width();

                            //Set height and width to mask to fill up the whole screen
                            $('#maskPopup').css({ 'width': maskWidth, 'height': maskHeight });
                            $('#select-free').css({ 'width': maskWidth, 'height': maskHeight }).show();
                            //transition effect
                            $('#maskPopup').fadeIn(200);
                            $('#maskPopup').fadeTo("fast", 0.8);

                            //Get the window height and width
                            var winH = $(window).height();
                            var winW = $(window).width();

                            //Set the popup window to center
                            $(id).css('top', winH / 2 - $(id).outerHeight() / 2);
                            $(id).css('left', winW / 2 - $(id).outerWidth() / 2);

                            //transition effect
                            $(id).fadeIn(500);

                        });

                        //if close button is clicked
                        $('.window .close').click(function(e) {
                            //Cancel the link behavior
                            e.preventDefault();

                            $('#maskPopup').hide();
                            $('.window').hide();
                            $('#select-free').hide();
                        });
                    });
                }
            };
        } (),
        TermsAndConditionsHelper: function() {
            var popups = {};
            function HideMask() {
                $(this).hide();
                $('.window').hide();
                $('#select-free').hide();
                $(this).unbind('click');
            };
            function HideMaskSett(obj, settings) {
                $(obj).hide();
                $('#' + settings.Id).hide();
                $(obj).unbind('click');
            };
            function BindShow(settings) {
                var timeout = setTimeout(function() {
                    //if close button is clicked
                    $('.window .close').click(function(e) {
                        //Cancel the link behavior
                        e.preventDefault();
                        //DO POST BACK
                        var uniqueId = e.currentTarget.id.replace(/_/gi, '$');
                        $('#wrapper').hide();
                        $('#footer-wrapper').hide();

                        __doPostBack(uniqueId, '');

                        $('#maskNew').hide();
                        $('#maskPopup').hide();
                        $('#maskPopup').unbind('click');
                        $('.window').hide();
                        $('#select-free').hide();
                    });

                    if (!settings.MaskNotClickable) {
                        //if mask is clicked
                        $('#maskPopup').click(function() { HideMaskSett(this, settings); });
                    }

                    //Disable the save and close button
                    $('.close .hygieneBtn').attr('disabled', true);
                    $('.close .hygieneBtn').addClass('disabled');

                    //Get the screen height and width
                    var maskHeight = $(document).height();
                    var maskWidth = $(window).width();

                    //Set height and width to mask to fill up the whole screen
                    $('#maskPopup').css({ 'width': maskWidth, 'height': maskHeight });
                    $('#select-free').css({ 'width': maskWidth, 'height': maskHeight }).show();

                    //transition effect  
                    $('#mask').fadeIn(200);
                    $('#mask').fadeTo("fast", 0.8);

                    //transition effect
                    $('#maskPopup').fadeIn(200);
                    $('#maskPopup').fadeTo("fast", 0.8);

                    //Get the window height and width
                    var winH = $(window).height();
                    var winW = $(window).width();

                    //Set the popup window to center
                    $('#' + settings.Id).css('top', winH / 2 - $('#' + settings.Id).outerHeight() / 2);
                    $('#' + settings.Id).css('left', winW / 2 - $('#' + settings.Id).outerWidth() / 2);
                    $('#' + settings.Id).css('zIndex', 9999);
                    //transition effect
                    $('#' + settings.Id).fadeIn(500);
                    clearTimeout(timeout);
                }, settings.interval);
            };
            function toggleAllCheckBoxes(checked) {
                $.each($(".hygieneCheckBox"), function() {
                    $(this).attr('checked', checked);
                });
            };
            return {
                Register: function(settings) {
                    if (!popups[settings.id]) {
                        var item = new GSK.PopUpItem();
                        item.Id = settings.id;
                        item.ShowInterval = settings.interval;
                        item.MaskNotClickable = true;
                        item.SaveImage = settings.saveImage;
                        item.HoverSaveImage = settings.hoverSaveImage;
                        item.DisabledImage = settings.disabledImage;
                        item.TargetID = settings.targetID;
                        item.TargetImageID = settings.targetImageID;
                        popups[settings.id] = item;
                    }
                },
                Show: function(name) {
                    var item = popups[name];
                    if (item) {
                        BindShow(item);
                    }
                },
                OnSelection: function(name) {
                    var item = popups[name];
                    if (item) {
                        var allChecked = true;
                        $.each($(".hygieneCheckBox"), function() {
                            if (!$(this).attr('checked')) {
                                allChecked = false;
                            }
                        });

                        var ref = "#" + item.TargetID;
                        var imgRef = '#' + item.TargetImageID;
                        $(imgRef).unbind('mouseover');
                        $(imgRef).unbind('mouseout');
                        $(ref).unbind('click');
                        if (allChecked) {
                            $(ref).click(function(e) {
                                //Cancel the link behavior
                                e.preventDefault();
                                //DO POST BACK
                                var uniqueId = e.currentTarget.id.replace(/_/gi, '$');
                                __doPostBack(uniqueId, '');
                            });
                            $(ref).removeAttr('disabled');
                            $(imgRef).attr('src', item.SaveImage);
                            $(imgRef).mouseover(function() {
                                $(this).attr("src", item.HoverSaveImage);
                            });
                            $(imgRef).mouseout(function() {
                                $(this).attr("src", item.SaveImage);
                            });
                        } else {
                            $(imgRef).attr('src', item.DisabledImage);
                            $(ref).attr('disabled', 'disabled');
                        }
                    }
                }
            };
        } ()
    };
} ();
GSK.PopUpItem = function()
{
    return {
        Id: '',
        Selector: '',
        TargetId: '',
        ShowOnLoad: false,
        ShowInterval: 0,
        TextFieldID: ''
    };
};
GSK.ButtonGroupItem = function()
{
	var id = '';
	var srcNormal = '';
	var srcSelected = '';
	var Item = function()
	{
		return $('#' + this.id);
	};
	return {
		Type: "ButtonGroupItem",
		ID: function() { return this.id; },
		Selected: function()
		{
			return Item().attr('src') == this.srcSelected;
		},
		Select: function()
		{
			Item().attr('src', this.srcSelected);
		},
		Unselect: function()
		{
			Item().attr('src', this.srcNormal);
		} };
};
GSK.ButtonGroupItem.Create = function(id, srcNormal, srcSelected)
{
	var item = new GSK.ButtonGroupItem();
	item.id = id;
	item.srcNormal = srcNormal;
	item.srcSelected = srcSelected;
	return item;
}
GSK.ButtonGroup = function(name)
{
	var name = name;
	var items = {};
	return {
		Type: 'ButtonGroup',
		Name: function() { return name; },
		SelectItem: function(itemID)
		{
			if (items[itemID])
			{
				for (var i in items)
				{
					items[i].Unselect();
				}
				items[itemID].Select();
			}
		},
		GetItem: function(itemID)
		{
			return items[itemID];
		},
		AddItem: function(item) { items[item.ID()] = item; },
		AddAndCreate: function(id, srcNormal, srcSelected)
		{
			var item = new GSK.ButtonGroupItem();
			item.id = id;
			item.srcNormal = srcNormal;
			item.srcSelected = srcSelected;
			item[id] = item;
		}
	};
}
GSK.ButtonGroup.Create = function(name, buttons)
{
	var group = new GSK.ButtonGroup(name);
	for (var i in buttons)
	{
		group.AddItem(buttons[i]);
	}
	return group;
}
AC_FL_RunContent = 0;

function showProgressGif(async) {
    if ($('#mask2').css('height') != '0px') {
        return;
    }
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask2').css({ 'width': maskWidth, 'height': maskHeight });
    $('#select-free-ajax').css({ 'width': maskWidth, 'height': maskHeight }).show();
    
    var winH = $(window).height();
    var winW = $(window).width();
    var scrollTop = $(window).scrollTop();

    var top = scrollTop + winH / 2 - 130;
    var left = winW / 2 - 20;

    $('#mask2').css('background-position', left + 'px ' + top + 'px');

    $('#mask2').fadeTo("fast", 0.5);
    $('#mask2').fadeIn();

    if (async) {
        var progressInterval = setInterval(function()
        {
            if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
            {
                hideProgressGif();
                ResizeDivT();
                clearInterval(progressInterval);
            }
        }, 1000);
    }
}

function hideProgressGif() {
    $('#mask2').hide();
    $('#mask2').css('height', 0);
    $('#select-free-ajax').hide();
}

function ResizeDivT()
{
    UAGENT = navigator.userAgent.toUpperCase();
    if (UAGENT.indexOf("MSIE") >= 0)
    {
        var timeout = setTimeout(function()
        {
            $(".t").css('height', '99%').css('height', '100%');
				IERefreshView();
            clearTimeout(timeout);
        }, 100);
    }
}



if (typeof GskTools == 'undefined')
{
    GskTools = function() { }
}
GskTools.OmnitureFix = function()
{
    var omnitureMouseDown;
    var omnitureTags = ['cufon', 'cufoncanvas', 'cvml', 'rect', 'canvas'];
    var omnitureNamePrefix = 's_i_';

    function IsInTags(tag)
    {
        var result = false;
        for (var i in omnitureTags)
        {
            if (omnitureTags[i].toLowerCase() == tag.toLowerCase())
            {
                result = true;
                break;
            }
        }
        if (typeof console != 'undefined' && console && console.log) { console.log("Is in cufon tags? " + result); }
        return result;
    }

    function RebindEventArgs(evt, myEvent, myTarget)
    {
        if (myEvent.target)
        {
            evt.target = myTarget.parentNode;
        }
        if (myEvent.srcElement)
        {
            evt.srcElement = myTarget.parentNode;
        }
        return evt;
    }

    function RemoveImage()
    {
        $img = $("img[name='" + omnitureNamePrefix + s_account + "']");
        if ($img.length == 1)
        {
            //var omniturePixel = $img.get(0);
            //$img.remove();
            // omniturePixel = null;
            $img.attr('src', '');
        }
    }

    function InsertImage()
    {
        var img = s_wd[omnitureNamePrefix + s_account];
        $(document.body).append(img);
    }

    function PrepareImage()
    {
        var img = s_wd[omnitureNamePrefix + s_account];
        img.id += '_s';
    }

    function CustomMouseDown(evt)
    {
        var myEvent = evt || window.event;
        var myTarget = myEvent.target || myEvent.srcElement;
        if (typeof console != 'undefined' && console && console.log) { console.log("Mouse down on: " + myTarget.tagName); }
        try
        {
            if (!IsInTags(myTarget.tagName))
            {
                PrepareImage();
                //RemoveImage();
                setTimeout(function() { omnitureMouseDown(evt); /*InsertImage();*/ }, 1);

            }
            else
            {
                evt = RebindEventArgs(evt, myEvent, myTarget);
                CustomMouseDown(evt);
            }
        }
        catch (err)
        {
            alert('Omniture proxy error on cufon. Error: ' + err);
        }
    }

    function CustomBodyClick(evt)
    {
        var myEvent = evt || window.event;
        var myTarget = myEvent.target || myEvent.srcElement;
        if (typeof console != 'undefined' && console && console.log) { console.log("Click on body, element: " + myTarget.tagName); }
        try
        {
            if (!IsInTags(myTarget.tagName))
            {
                setTimeout(function() { s_bc(evt); }, 1);
            }
            else
            {
                evt = RebindEventArgs(evt, myEvent, myTarget)
                CustomBodyClick(evt);
            }
        }
        catch (err)
        {
            alert('Omniture proxy error on cufon. Error: ' + err);
        }
    }

    function CleanUp()
    {
        $(document.body).unbind('click', CustomBodyClick);
        $(document).unbind('mousedown', CustomMouseDown);
    }

    function Init()
    {
        omnitureMouseDown = document.onmousedown;
        document.onmousedown = null;
        $(document).bind('mousedown', CustomMouseDown);
        $(document.body).bind('click', CustomBodyClick);
        if (document.body.detachEvent)
        {
            document.body.detachEvent('onclick', s_bc);
        }
        else if (document.body.removeEventListener)
        {
            document.body.removeEventListener('click', s_bc, false);
        }
        $(window).bind('unload', CleanUp);
    }

    return {
        Init: function()
        {
            if (typeof s_pageName != 'undefined')
            {
                UAGENT = navigator.userAgent.toUpperCase();
                if (UAGENT.indexOf("MSIE") > -1)
                {
                    Init();
                }
            }
        }
    }
} ();

/* function called by confirm button on registration screens - adds doubleclick tag */
function ValidateRegistration(doubleClickId) {
    Page_ClientValidate('details');
    if (Page_IsValid) {
        if (doubleClickId) {
            $.get('https://fls.doubleclick.net/activityi;src=2487865;type=quitm741;cat=' + doubleClickId + ';ord=1;num=1?');
        }

        //TriggerRegistrationSuccessful();
        
        return true;
    }
    else { return false; }
}

function TriggerRegistrationSuccessful() {
    s.linkTrackVars = "events,eVar4";
    s.linkTrackEvents = "event3";
    screen.eVar4 = "";
    s.events = "event3";
    s.tl(true, "o", "Account Creation");
    //console.log("TriggerRegistrationSuccessful Called");
}

function IERefreshView(){
	if($.browser.msie && parseInt($.browser.version)<=6){
		setTimeout(function(){
			var $button = $(".confirm-plan.move-bottom");
			$button.css({"position":"static"});
			$button.css({"position":"absolute", "bottom":0});
		},100);
	}
}

$(document).ready( function () {
	GskTools.OmnitureFix.Init;
	IERefreshView();
});

/* social bookmarking on article pages */
$(document).ready(function() {

    $(".btn-slide").click(function() {
        $(".panel").slideToggle("slow");
        $(this).toggleClass("active"); return false;
    });


});
