var CommonSetting = {
    imageBaseUrl: '', //'http://sears.qa-rovia.com/App_Themes/Portal/images/',
    graphicsUrl: '' //'http://graphics.rovia.com/Images/'
};

function hideDiv(id) {

    if (document.getElementById(id) != null) {
        document.getElementById(id).style.display = "none";
        document.getElementById(id).style.visibility = "hidden";
    }
    return;
}

function showDiv(id) {
    if (document.getElementById(id) != null) {
        document.getElementById(id).style.display = "block";
        document.getElementById(id).style.visibility = "visible";
    }

    return;
}
//function ShowMFHome() {
//    showDiv('divMultiFlight');
//    hideDiv('divRoundTrip');
//}
//function ShowRTHome() {
//    showDiv('divRoundTrip'); 
//    showDiv('divReturnDate');
//    hideDiv('divMultiFlight');

//}
//function ShowOWHome() {
//    showDiv('divRoundTrip');
//    hideDiv('divReturnDate');
//    hideDiv('divMultiFlight');
//}
function hideDivByName(parentDivId, id) {
    if (document.getElementsByName(id) != null) {
        var div = new Array();
        div = document.getElementById(parentDivId).getElementsByTagName('div');
        for (var i = 0; i < div.length; i++) {
            if (div.item(i).getAttribute('name') == id) {

                div.item(i).style.display = "none";
                div.item(i).style.visibility = "hidden";
            }
        }
    }
    return;
}

function showDivByName(parentDivId, id) {
    if (document.getElementsByName(id) != null) {
        var div = new Array();
        div = document.getElementById(parentDivId).getElementsByTagName('div');
        for (var i = 0; i < div.length; i++) {
            if (div.item(i).getAttribute('name') == id) {
                div.item(i).style.display = "block";
                div.item(i).style.visibility = "visible";
            }
        }
    }
    return;
}

function checkDate(month, day, year) {
    if (month == null || day == null || year == null || month == "" || day == "" || year == "")
        return false;

    var dayPattern = new RegExp("^[0-3]{0,1}[0-9]$");
    var monthPattern = new RegExp("0?[1-9]|(1[012])");
    var yearPattern = new RegExp("19|20[0-9]{2}");

    if (!month.match(monthPattern) || !day.match(dayPattern) || !year.match(yearPattern))
        return false;

    var inputDate;
    month = month - 1;
    inputDate = new Date(year, month, day);

    return ((day == inputDate.getDate())
			 && (month == inputDate.getMonth())
			 && (year == inputDate.getFullYear()));

}

//takes the date in the format mm/dd/yyyy
function validateDate(dateString) {
    var dateArray = dateString.split("/", 3);
    return checkDate(dateArray[0], dateArray[1], dateArray[2]);
}

function empty() { return; }

function toggleDiv(id) {

    var divToToggle = document.getElementById(id);
    if (divToToggle == null)
        return;

    if (divToToggle.style.visibility == 'hidden') {
        divToToggle.style.visibility = 'visible';
        divToToggle.style.display = '';
    }
    else {
        divToToggle.style.visibility = 'hidden';
        divToToggle.style.display = 'none';
    }

    return;
}
function showSectionDiv(divid, section) {
    var ypos = document.getElementById(section).offsetTop;
    var xpos = 0;
    showDivAt(divid, xpos, ypos);
    return;
}

//x position changed
function showSectionDiv1(divid, section) {
    var ypos = document.getElementById(section).offsetTop;
    var xpos = 500;
    showDivAt(divid, xpos, ypos);
    return;
}


function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function SetSelection(id, value) {
    if (document.getElementById(id) != null)
        document.getElementById(id).value = value;
    //alert(id)
    //alert(value);
}


/*handling Water Mark for date text boxes */
function OnFocus(elementId, defaultText) {
    if (document.getElementById(elementId).value == defaultText) {
        document.getElementById(elementId).className = "normal";
        document.getElementById(elementId).value = "";
    }
}
function OnBlur(elementId, defaultText) {
    var textValue = document.getElementById(elementId).value;

    if (textValue == defaultText || textValue.length == 0) {
        document.getElementById(elementId).className = "watermark";
        document.getElementById(elementId).value = defaultText;
    }
    else
        document.getElementById(elementId).className = "normal";
}

function OpenPopupWindow(url) {
    popWindow = window.open(url, "mywindow", "location=1,status=1,scrollbars=1,resizable=1,toolbar=1,menubar=1,height=auto,width=auto");
    return false;
}
function OpenPopupWindowWithHeightWidth(url) {
    popWindow = window.open(url, "mywindow", "location=1,status=1,scrollbars=1,resizable=1,toolbar=1,menubar=1,height=650,width=850");
    return false;
}





function hasOptions(obj) {
    if (obj != null && obj.options != null) { return true; }
    return false;
}


function sortSelect(obj) {
    var o = new Array();
    if (!hasOptions(obj)) { return; }
    for (var i = 0; i < obj.options.length; i++) {
        o[o.length] = new Option(obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected);
    }
    if (o.length == 0) { return; }
    o = o.sort(
		function(a, b) {
		    if ((a.text + "") < (b.text + "")) { return -1; }
		    if ((a.text + "") > (b.text + "")) { return 1; }
		    return 0;
		}
		);

    for (var i = 0; i < o.length; i++) {
        obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
    }
}



/****Tab script start**************************************************************************************************/



function createCookie(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 = "";
    var cookieContent = name + "=" + value + expires + "; path=/";
    document.cookie = cookieContent;
}

function readCookie(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;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


/***************************   SessionService function ***********************/

function SessionService(servicePath, siteId) {
    var sessionItems = new Array();
    this.addItem = addItem;
    this.getItem = getItem;
    this.deleteItem = deleteItem;
    this.addObject = addObject;

    function addItem(key, value) {
        var newItem = new Object();
        newItem.key = key;
        newItem.value = value;
           $.ajax({
                type: "POST",
                contentType: "application/json",
                url: servicePath + "/addItem/" + "Session" + "/" + key + "/" + value + "/0/" + siteId,
                data: null, 
                cache: false,
                processData: false,
                success:
               function(result)
               {
                   //Check if item already exists. If so, update its value
                   var isPresent = false;
                   for (var i = 0; i < sessionItems.length; i++)
                   {
                       if (sessionItems[i] != "" && sessionItems[i] != null && sessionItems[i].key.toString().toLowerCase() == key.toString().toLowerCase())
                       {
                           sessionItems[i].value = value;
                           isPresent = true;
                           break;
                       }
                   }
                   if (!isPresent)
                       sessionItems.push(newItem);

               },
                error:
                   function(XMLHttpRequest, textStatus, errorThrown)
                   {
                       //alert("Error");
                   }
            });
        }

        function addObject(key, value)
        {
            var newItem = new Object();
            newItem.key = key;
            newItem.value = value;
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: servicePath + "/addItem/" + "Session" + "/" + key + "/0/" + siteId,
                data: value,
                cache: false,
                processData: false,
                success:
               function(result)
               {
                   //Check if item already exists. If so, update its value
                   var isPresent = false;
                   for (var i = 0; i < sessionItems.length; i++)
                   {
                       if (sessionItems[i] != "" && sessionItems[i] != null && sessionItems[i].key.toString().toLowerCase() == key.toString().toLowerCase())
                       {
                           sessionItems[i].value = value;
                           isPresent = true;
                           break;
                       }
                   }
                   if (!isPresent)
                       sessionItems.push(newItem);

               },
                error:
                   function(XMLHttpRequest, textStatus, errorThrown)
                   {
                       //alert("Error");
                   }
            });
        }

    function getItem(key) {
        if (sessionItems != null && sessionItems != "") {
            for (var i = 0; i < sessionItems.length; i++) {
                if (sessionItems[i] != "" && sessionItems[i] != null && sessionItems[i].key.toString().toLowerCase() == key.toString().toLowerCase()) {
                    return sessionItems[i].value;
                }
            }
        }
    }
    function deleteItem(key) {

        for (var i = 0; i < sessionItems.length; i++) {
            if (sessionItems[i] != "" && sessionItems[i] != null && sessionItems[i].key.toString().toLowerCase() == key.toString().toLowerCase() && sessionItems[i].SessionId == sessionId) {

                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: servicePath + "/deleteItem/" + "Session" + "/" + key + "/0/" + siteId,
                        data: null,
                        cache: false,
                        processData: false,
                        success:
                        function(result)
                        {
                            sessionItems[i].key = 0;
                            sessionItems[i].value = 0;
                        },
                        error:
                        function(XMLHttpRequest, textStatus, errorThrown)
                        {
                           //alert("Error");
                        }
                    });
            }
        }
    }

    function init() {

        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: servicePath + "/getItems/" + "Session" + "/0/" + siteId,
            data: null,
            cache: false,
            processData: false,
            success:
                        function(result)
                        {
                            
//                            if (result == null || result == "")
//                                sessionItems = "";
//                            else
                                sessionItems = result;
                        },
            error:
                        function(XMLHttpRequest, textStatus, errorThrown)
                        {
                            
                            //alert("Error");
                        }
        });
    }

    init();
}
/**************** End of StateService function *********************************************/

/*    Messaging service        */

var MessagingService = function(servicePath, siteId)
{
    this.removeMessage = function()
    {
        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: servicePath + "/removeMessage/" + siteId,
            processData: false,
            cache:false,
            success: function(result)
            {
                if (result == '')
                {
                    return false;
                }
                return result;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                return false;
            }
        });
    };
    
    
    this.addMessage = function(message)
    {
        $.ajax(
        {
            type: "POST",
            contentType: "application/json",
            url: servicePath + "/addMessage/" + siteId,
            data: Sys.Serialization.JavaScriptSerializer.serialize(message),
            processData: false,
            cache:false,
            success: function(result)
            {
                if (result == '')
                {
                    return false;
                }
                return true;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                return false;
            }
        });
    };

};

// AddToCart jquery plug-in
(function($)
{

    $.extend({
        add2cart: function(source_id, target_id, callback)
        {

            var source = $('#' + source_id);
            var target = $('#' + target_id);

            var shadow = $('#' + source_id + '_shadow');
            if (!shadow.attr('id'))
            {
                $('body').prepend('<div id="' + source.attr('id') + '_shadow" style="display: none; background-color: #999999; border: solid 1px darkgray; position: static; top: 0px; z-index: 100000;">&nbsp;</div>');
                var shadow = $('#' + source.attr('id') + '_shadow');
            }

            if (!shadow)
            {
                alert('Cannot create the shadow div');
            }

            shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.5).show();
            shadow.css('position', 'absolute');

            shadow.animate({ width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: 300 })
        .animate({ opacity: 0 }, { duration: 1000, complete: callback });

        }
    });
})(jQuery);

//**************************************************************************************************

function ToggleProfileAddressType(ddlId, divStdAddr, divMltAddr)
{
    var ddlEle = $get(ddlId);  ///$("#" + ddlId);
    if (ddlEle != null)
    {
        if (ddlEle.value == 'Military')
        {
            showDiv(divMltAddr);
            hideDiv(divStdAddr);
        }
        else
        {
            hideDiv(divMltAddr);
            showDiv(divStdAddr);
        }
    }
}

function hideDiv(id)
{

    if ($("#" + id) != null)
    {
        $("#" + id).hide();
        $("#" + id).css("visibility", "hidden");
    }
    return;
}

function showDiv(id)
{
    if ($("#" + id) != null)
    {
        $("#" + id).show();
        $("#" + id).css("visibility", "visible");
    }

    return;
}

//Toggle status of all child validator controls in the control tree
function toggleAllChildValidators(status, control)
{
    if (control == null)
        return;

    //check if the control is a validation control
    if (control.controltovalidate != null)
    {
        ValidatorEnable(control, status)
    }

    for (var i = 0; i < control.childNodes.length; i++)
    {
        toggleAllChildValidators(status, control.childNodes[i]);
    }
} 
