﻿var validationString = null;
var _mainControl;
var _id;

$(".fixed").css("top", eval(document.body.clientHeight-$("#tickerHeight").attr("value"))+"px");

var prm = Sys.WebForms.PageRequestManager.getInstance();
//prm.add_pageLoaded(pageLoaded);
prm.add_endRequest(pageAsyncRequestEnded);
prm.add_initializeRequest(initializeRequest);
//prm.add_pageLoading(pageLoadingHandler)

var _panels, _count;
var isFormEnabled = true;


function SetBeta() {
    if (Get_Cookie("betaAlert") != "true") {
        $("#betaAlert").dialog({ autoOpen: true, modal: true, title: 'Beta', resizable: false, draggable: false, buttons: { "Ok": function() { $(this).dialog("close"); } } });
    }
    Set_Cookie("betaAlert", "true", "100");
}

function Set_Cookie(name, value, expires, path, domain, secure ){
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

// this function gets the cookie, if it exists
// don't use this, it's weak and does not handle some cases
// correctly, this is just to maintain legacy information
function Get_Cookie(name) {

    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) &&
    (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}



function onUpdateProgressSucces(result) {
    var div = GetNetElementByServerTagId('div', 'divProgressPercent');
    $(div).attr('width', result);
}

function SetUniqueRadioButton(elm,parentID) 
{
    if (parentID) {
        $("#" + parentID + ' input:radio').attr('checked ', false);
        $(elm).attr('checked',true);
    } else {
        $('.page input:radio').attr('checked',false);
        $(elm).attr('checked',true);
    }
}

function initializeRequest(sender, args) {
    if (isFormEnabled == true) {
        DisableForm();
        ShowHideWaiting(1);
    } else {
        args.set_cancel(true);
    }
}

function updateFeedBack() {
    hfFeedback = GetControlInputContainedEnd("hfForFeedback");
    if (hfFeedback != null) {
        $('#slideMessageValue').val($(hfFeedback).val());
        $('#slideMessageToggle').val($(hfFeedback).attr('toggle'));
        $('#slideMessageClass').val($(hfFeedback).attr('myClass'));
        $(hfFeedback).val('');
    }
}

function DisableForm() {
    //$('aspnetForm').submit(function() { return false; });
    //alert(isFormEnabled);
    isFormEnabled = false;
    
    //alert(isFormEnabled);
    //$("aspnetForm").attr("disabled", "disabled");

}
function EnableForm() {
    //$('aspnetForm').submit(function() { return false; });
    isFormEnabled = true;
}


_isUp = true;
_showWaiting = true;
function ShowHideWaiting(direction) {
    //alert('_isUp ' +  _isUp);
    //alert('_showWaiting' + _showWaiting);
    //alert('direction - ' + direction);
    if (_showWaiting != undefined && _showWaiting == false && _isUp == true) {
        //alert('ShowHideWaiting - true');
        _showWaiting = true;
        return false;
    }

    _showWaiting = true;
    //1 - down
    //0 - up
    if (direction == 1 && _isUp==false) {
        return false; 
    }
    if (direction == 0 && _isUp==true) {
        return false; 
    }
    
    if (_isUp)
        _isUp = false;
    else
        _isUp = true; 

    $('.loading').css({ left: '45%' });
    $('.loading').toggle('slide', { direction: 'up' });
    return false;
}

function GetNetElementByServerTagId(tag,id) {
    var f1 = document.forms["aspnetForm"];
    var tags;

    if (document.all == undefined)
        tags = document.getElementsByTagName(tag);
    else
        tags = document.all.tags(tag);
    for (var x = 0; x < tags.length; x++) {
        if (tags[x].id.indexOf(id) >= 0) {
            return tags[x];
        }
    }
    return null;
}




function IsMessageEmty() {
    var obj = GetNetElementByServerTagId('div', 'divMessage');

    if (obj!=null && obj.innerHTML.length > 0)
        return true;
    return false;
}

function SetErrorLabels() {
    if (IsMessageEmty()) {
        var objHidden = GetNetElementByServerTagId('input', 'hfErrorLabels');
        var arrLabels;
        if (objHidden!=null && objHidden.value.length > 0) {
            if (objHidden.value.indexOf(",") > -1) {
                arrLabels = objHidden.value.split(",");

                for (i = 0; i < arrLabels.length; i++) {
                    var obj =   ('label', arrLabels[i]);
                    if (obj!=null)
                        obj.className = "error";
                }
            }
            else {
                arrLabels = objHidden.value;
                var obj = GetNetElementByServerTagId('label', arrLabels);
                if (obj!=null)
                    obj.className = "error";
            }
        }
    }
}

function pageAsyncRequestEnded(sender, args) {
    SetErrorLabels();
    ShowHideWaiting(0);
    EnableForm();
    //objFileRenamed.style.display = 'inline';
    //objFileRenamed.innerHTML = objFileNewName.value;
    //objFileNewName.style.display = 'none';

    //var bodyTag = 'divMessage';
    //alert($find(bodyTag));

    //var panels = args.get_panelsUpdated();
    //var updatedPanels = sender._panelsToRefreshIDs;
    //alert(updatedPanels);
    //if (panels.length > 0) {
    //_panels = new Array(panels.length);

    //for (i = 0; i < panels.length; i++)
    //_panels[i] = new Sys.UI.Control(panels[i]);

    //}

    if (args.get_error() != undefined) {

        //alert('test');
        alert(args.get_error().message);
        //var errorMessage = args.get_error().message;
        //alert(errorMessage);
        //args.set_errorHandled(true);
        //ToggleAlertDiv('visible');
        //$get(messageElem).innerHTML = errorMessage;
    }
}

//function pageLoaded(sender, args) {
    //var panels = args.get_panelsUpdated();
    //alert(panels.length);
    //if (_panels != undefined && _panels.length > 0) {
        //alert('test');
    //}

    //var panels = args.get_panelsUpdated();
    //alert(panels.length,);
//}



//finds a control(//TO-DO: asumes only one) of type !input! that ends with !ObjName!
function GetControlInputContainedEnd(ObjName) {

    var f1 = document.forms["aspnetForm"];
    var tags;

    if (document.all == undefined)
        tags = document.getElementsByTagName("input");
    else
        tags = document.all.tags("input");

    var id = 0;
    var cnt = 0;
    var n = "";

    //find selected - should be only one
    for (var x = 0; x < f1.length; x++) {
        if (f1[x].tagName == "INPUT" || f1[x].tagName == "input") {
            var ObjLen = ObjName.toString().length;
            var inLen = f1[x].id.toString().length;
            if (inLen > ObjLen) {
                var end = f1[x].id.toString().substring(inLen - ObjLen, inLen);
                if (end == ObjName)
                    return f1[x];
            }
        }
    }
}

function updateDependencies(sender, dependence, textBox, controlTypeToChangeClass) {
    if (!$(GetControlInputContainedEnd(dependence)) || $(GetControlInputContainedEnd(dependence)).val() == "0" || $(GetControlInputContainedEnd(dependence)).val() == "") {
        if (!($("#inlineMessage_" + dependence).length > 0)) {
            $(GetControlInputContainedEnd(textBox)).parents(controlTypeToChangeClass).addClass("error");
        }
        $(GetControlInputContainedEnd(textBox)).focus();
    }
}


function removeDependencies(sender, controlTypeToChangeClass) {
        if ($(sender).parents(controlTypeToChangeClass) && $(sender).parents(controlTypeToChangeClass).attr("class")=="error") {
            $(sender).parents(controlTypeToChangeClass).removeClass();
    }
}


function validateHidden(sender) {
    if (validationString == null && $(sender).val(''))//if was pre-inserted
    {
        $(sender).next().val('0');
        return "0";
    }
    else if (validationString != $(sender).val()) {
        if ($(sender).attr('rel') === undefined) {//becouse of watermarks
            $(sender).val('');
        }
        $(sender).next().val('0');
        $(sender).focus;
        return "0";
    }
}


function validateHiddenWithFreeText(sender) {
    if (validationString != $(sender).val()) {
        $(sender).next().val('0');
    }
}

function onSelectedTextBox(sender) {
    validationString = $(sender).val();
}

function JBK_clickButton(e, buttonid) {
    var bt = document.getElementById(buttonid);

    if (typeof (bt) == 'object') {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            eval(decodeURIComponent(bt.href));
        }
    }
}

function DateAdd(objDate, strInterval, intIncrement)
{
    if(typeof(objDate) == "string")
    {
        objDate = new Date(objDate);

        if (isNaN(objDate))
        {
            throw("DateAdd: Date is not a valid date");
        }
    }
    else if(typeof(objDate) != "object" || objDate.constructor.toString().indexOf("Date()") == -1)
    {
        throw("DateAdd: First parameter must be a date object");
    }

    switch(strInterval)
    {
        case "M":
        objDate.setMonth(parseInt(objDate.getMonth()) + parseInt(intIncrement));
        break;

        case "D":
        objDate.setDate(parseInt(objDate.getDate()) + parseInt(intIncrement));
        break;

        case "Y":
        objDate.setYear(parseInt(objDate.getYear()) + parseInt(intIncrement));
        break;

        case "h":
        objDate.setHours(parseInt(objDate.getHours()) + parseInt(intIncrement));
        break;

        case "m":
        objDate.setMinutes(parseInt(objDate.getMinutes()) + parseInt(intIncrement));
        break;

        case "s":
        objDate.setSeconds(parseInt(objDate.getSeconds()) + parseInt(intIncrement));
        break;

        case "uM":
        objDate.setUTCMonth(parseInt(objDate.getUTCMonth()) + parseInt(intIncrement));
        break;

        case "uD":
        objDate.setUTCDate(parseInt(objDate.getUTCDate()) + parseInt(intIncrement));
        break;

        case "uY":
        objDate.setUTCFullYear(parseInt(objDate.getUTCFullYear()) + parseInt(intIncrement));
        break;

        case "uh":
        objDate.setUTCHours(parseInt(objDate.getUTCHours()) + parseInt(intIncrement));
        break;

        case "um":
        objDate.setUTCMinutes(parseInt(objDate.getUTCMinutes()) + parseInt(intIncrement));
        break;

        case "us":
        objDate.setUTCSeconds(parseInt(objDate.getUTCSeconds()) + parseInt(intIncrement));
        break;
    }
    return objDate;
}

// Start Slide message

var timeOut;
function showSlideMessage(){
    if ($('#slideMessageValue').val()) {
        if (timeOut != null) {
            clearTimeout(timeOut);
        }//clear timeout
        
        $('#slideMessage').queue(function() {
            $(this).slideUp();
            $(this).dequeue();
        });//slide up
        
        $('#slideMessage').queue(function() {
            $('#slideMessageText').html($('#slideMessageValue').val());
            $(this).dequeue();
        });//set text

        $('#slideMessage').queue(function() {
            $(this).removeClass($(this).attr('class'));
            $(this).addClass($('#slideMessageClass').val());
            $(this).dequeue();
        });  //set class
        
        
        $('#slideMessage').queue(function() {
            $(this).slideDown();
            $(this).dequeue();
        });//slide down
        
        if ($('#slideMessageToggle').val() != 'false') {
            timeOut = $('#slideMessage').queue(function() {
                setTimeout("$('#slideMessage').slideUp()", 4000);
                $(this).dequeue()
            });//slide up

            $('#slideMessage').queue(function() {
                $('#slideMessageValue').val('');
                $(this).dequeue()
            }); //init text


            $('#slideMessageClass').queue(function() {
                $(this).val('slideMessage');
                $(this).dequeue();
            });  //init class
        }
    }
}

var originalBaseUrl = $("base").attr("href"); ;
function ChangeBaseTagBack() {
    //$("base").attr("href", $("#page_path").attr("value"));
    var baseElement = $("base");
    var newurl = baseElement.attr("href", originalBaseUrl);
    //alert(baseElement.attr("href"));
}


function ChangeBaseTag() {
    return;
    //$("base").attr("href", $("#page_path").attr("value"));
    var baseElement = $("base");
    var newURL = $("#page_path");
    var newurl = baseElement.attr("href", newURL.attr("value"));
    //alert($("form").attr("action"));
    $("form").attr("action", baseElement.attr("href") + $("form").attr("action"));
    //alert($("form").attr("action"));
    //alert($(form).attr("action"));
    //alert(baseElement.attr("href"));
}


function ChangeBaseTagFromCustomTag(tag) {
    return;
    var baseElement = $("base");
    var newURL = $("#" + tag);
    var newurl = baseElement.attr("href", newURL.attr("value"));
}
/*ResetLink("li[id$='liAccount']");
ResetLink("li[id$='liShoppingCart']");
ResetLink("li[id$='liLogOut']");
function ResetLink(link)
{
    if ($(link) == undefined)
        return;
    if ($(link).attr("id") == undefined)
        return;
    //var virtual_path = $(link + " a:first-child").attr("pathname");
    var virtual_path = $(link + " a:first-child").attr("pathname") + $(link + " a:first-child").attr("search");
    if (virtual_path.substr(0, 1) == "/")
        virtual_path = virtual_path.substr(1);
    $(link + " a:first-child").attr("href", originalBaseUrl + virtual_path);
}
*/
//Sys.Appplication.remove_init(MyInit);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(pageEndRequest);


if (jQuery().ready) {
    jQuery().ready(function() {
        //Accordion part
        AccordionInit();
        EnablePartsAfterLogin();
        PrepareNews();
        PrepareGSMNews();
    });
}

function survey_custom_text_en()
{
    (document.getElementById('txtCustom')).disabled = !(document.getElementById('rbCustom').checked);
}

var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline = 0;
var news_show_time = $('#news_show_time').attr("value");

function PrepareNews() {
    headline_count = $("div.headline").size();
    $("div.headline:eq(" + current_headline + ")").css('top', '5px');
    
    news_show_time *= 1000;
    if (headline_count>1)
        headline_interval = setInterval(headline_rotate, news_show_time); //time in milliseconds

    ShowNews(false);
}

function ShowNews(show) {
    if (show) {
        if ($(lastBlock).attr("id") == "divNews") {
            $("div[id*='_news_container']").css("visibility", "visible");
            return;
        }
    }
    $("div[id*='_news_container']").css("visibility", "hidden");
}

function headline_rotate() {
    if ($(lastBlock).attr("id") != "divNews") {
        ShowNews(false);
        return;
    }
    ShowNews(true);
    current_headline = (old_headline + 1) % headline_count;
    $("div.headline:eq(" + old_headline + ")").animate({ top: -205 }, "slow", function() {
        $(this).css('top', '210px');
    });
    $("div.headline:eq(" + current_headline + ")").show().animate({ top: 5 }, "slow");
    old_headline = current_headline;
}

var gsmheadline_count;
var gsmold_headline = 0;
var gsmcurrent_headline = 0;

function PrepareGSMNews() {
    gsmheadline_count = $("div.gsmheadline").size();
    //alert(gsmheadline_count);
    $("div.gsmheadline:eq(" + gsmcurrent_headline + ")").css('top', '5px');
    //alert(gsmcurrent_headline);

    //news_show_time *= 1000;
    if (gsmheadline_count>1)
        headline_interval = setInterval(gsmheadline_rotate, news_show_time); //time in milliseconds
}

function gsmheadline_rotate() {
    //alert('gsmheadline_rotate');
    gsmcurrent_headline = (gsmold_headline + 1) % gsmheadline_count;
    $("div.gsmheadline:eq(" + gsmold_headline + ")").animate({ top: -205 }, "slow", function() {
        //alert('animate');
        $(this).css('top', '210px');
    });
    $("div.gsmheadline:eq(" + gsmcurrent_headline + ")").show().animate({ top: 5 }, "slow");
    gsmold_headline = gsmcurrent_headline;
}

function AccordionInit() {
    lastBlock = $("#divCalendar");
    maxWidth = 550;
    minWidth = 33;
    if ($("ul.bottomAccordion li div.wrapper")!=undefined){
        $("ul.bottomAccordion li div.wrapper").mousedown(
          function() {
              $(lastBlock).animate({ width: minWidth + "px" }, { queue: false, duration: 400 });
              $(this).animate({ width: maxWidth + "px" }, { queue: false, duration: 400 });
              lastBlock = this;
              ShowNews(true);
          }
        );
      }
      $("#" + $("#accordionDefault").attr("value")).trigger("mousedown");
}
function EnableUpperHelpLinksAfterLogin(toDisable) {
    if ($("li[id$='liAccount']").attr("id") != undefined)
    {
        if (toDisable == true)
            $("li[id$='liAccount']").css("visibility", "hidden");
        else
            $("li[id$='liAccount']").css("visibility", "visible");
    }
    if ($("li[id$='liShoppingCart']").attr("id") != undefined)
    {
        if (toDisable == true)
            $("li[id$='liShoppingCart']").css("visibility", "hidden");
        else
            $("li[id$='liShoppingCart']").css("visibility", "visible");
    }
    if ($("li[id$='liLogOut']").attr("id") != undefined)
    {
        if (toDisable == true)
            $("li[id$='liLogOut']").css("visibility", "hidden");
        else
            $("li[id$='liLogOut']").css("visibility", "visible");
    }
}
function EnablePartsAfterLogin() {
    if ($("div[id$='member_profile']").attr("id") != undefined && $("div[id$='member_profile']").css("display") == 'block' && $("#liProfileRealName").attr("id") != undefined && $("#" + $("#liProfileRealName").attr("value")).css("visibility") != "visible") {
        $("#" + $("#liProfileRealName").attr("value")).css("visibility", "visible");
        $("#divProfile").trigger("mousedown");
        EnableUpperHelpLinksAfterLogin(false);
    } else {
    if ($("div[id$='member_profile']").attr("id") != undefined && $("div[id$='member_profile']").css("display") == 'none' && $("#liProfileRealName").attr("id") != undefined && $("#" + $("#liProfileRealName").attr("value")).css("visibility") == "visible") {
            $("#" + $("#liProfileRealName").attr("value")).css("visibility", "hidden");
            $("#divCalendar").trigger("mousedown");
            EnableUpperHelpLinksAfterLogin(true);
        }
    }
}

      function pageEndRequest(sender) {
        ///////////////////////////////////
        //Login part
          ///////////////////////////////////
          EnablePartsAfterLogin();
        ///////////////////////////////////
      }

var callBack_OK_Button;
$(function() {  
    $('#t2fConfirm').dialog({
        bgiframe: true,
        autoOpen: false,
        height: 250,
        width: 400,
        modal: true,
        resizable: false,
        buttons: {
            'CANCEL': function() {
                $(this).dialog('close');},
            'OK': function() {
                $(this).dialog('close');
                if (callBack_OK_Button && callBack_OK_Button.todo)
                    callBack_OK_Button.todo();
            }
        }
    })
})
function showConfirm(callBackOK, strQuestion)
{
    callBack_OK_Button = callBackOK;
    $('#strConfirmMessage').text(strQuestion);
    $('#t2fConfirm').dialog('open');
}
$(function() {  
    $('#t2fAlert').dialog({
        bgiframe: true,
        autoOpen: false,
        height: 250,
        width: 400,
        modal: true,
        resizable: false,
        buttons: {
            'CANCEL': function() {
                $(this).dialog('close')
            }
        }
    })
})
function showErrorMessage(strMessage)
{
    //$('#strAlertMessage').text(strMessage);
    $('#strAlertMessage').empty();
    $('#strAlertMessage').append($('<p>'+strMessage+'</p>'));
    
    $('#t2fAlert').dialog('open');
}

function SearchOnKeyPress(event)
{
    if (event.keyCode == 13)
    {
        location.href = $("#base_url").val() + 'public/Search.aspx?s=' + $("#menu_input_search").val();
        return false;
    }
    else
    {
        return true;
    }
}


/*
function ChangeLanguage(UICulture)
    {
        //var root_base_length = $("#page_path").val().substr(0,$("#page_path").val().indexOf("public")).length;
        //var arr_path = window.location.href.substring(root_base_length,window.location.href.length).split('/');
        //var new_path = $("#page_path").val().substr(0,$("#page_path").val().indexOf("public"));
        if ($("#base_url").val() != window.location.href)
        {
            var arr_path = window.location.href.substring($("#base_url").val().length,window.location.href.length).split('/');
            var new_path = $("#base_url").val();
            if (arr_path[0].length == 2)
            {
                new_path = new_path + UICulture + '/';
                for (var i in arr_path)
                {
                    if (i != 0)
                    {
                    new_path = new_path + arr_path[i] + '/';
                    }
                }
            }
            else
            {
                new_path = new_path + UICulture + '/';
                for (var i in arr_path)
                {
                    new_path = new_path + arr_path[i] + '/';
                }
            }
            new_path = new_path.substring(0,new_path.length-1);
            location.href = new_path;
        }
        else
        {
            location.href = window.location.href + UICulture + '/' + "home.aspx";
        }
        return false;
    }
*/
/* BEGIN LivePerson Monitor. */var lpMTagConfig = {'lpServer' : "server.iad.liveperson.net",'lpNumber' : "75588346",'lpProtocol' : "https"}; function lpAddMonitorTag(src){if(typeof(src)=='undefined'||typeof(src)=='object'){src=lpMTagConfig.lpMTagSrc?lpMTagConfig.lpMTagSrc:'/hcp/html/mTag.js';}if(src.indexOf('http')!=0){src=lpMTagConfig.lpProtocol+"://"+lpMTagConfig.lpServer+src+'?site='+lpMTagConfig.lpNumber;}else{if(src.indexOf('site=')<0){if(src.indexOf('?')<0)src=src+'?';else src=src+'&';src=src+'site='+lpMTagConfig.lpNumber;}};var s=document.createElement('script');s.setAttribute('type','text/javascript');s.setAttribute('charset','iso-8859-1');s.setAttribute('src',src);document.getElementsByTagName('head').item(0).appendChild(s);} if (window.attachEvent) window.attachEvent('onload',lpAddMonitorTag); else window.addEventListener("load",lpAddMonitorTag,false);/*END LivePerson Monitor.*/



