﻿$(document).ready(function () {
    // Overwrite the standard alert and use the new ISN Alert Dialog.    
    window.alert = function (msg, title) {
        msg = msg.replace(new RegExp("\r\n", "g"), "<br/>");

        Alert(msg, title);
    }

    //Move from master page for top navigation
    var statusBarCookie = readCookie('statusBar');
    if (statusBarCookie == 'statusBar=t') {
        $('#help-bar').show();
    }
    else {
        $('#help-bar').hide();
        $('#help-bar').slideDown(1500);
        createCookie('statusBar', 'statusBar=t', 0);
    }

    var x = readCookie('isnPreferences')

    // Show/Hide advanced Menu/Features
    if (x != "advanced=t") {
        if ($('#submenu').is(':visible')) {
            $('#submenu').hide();
            $('#padding').hide();
            $('#divHide').hide();
            $('#divMore').show();
            $("#wrapp").css("margin-top", "0px")
        }
    } else {
        $('#submenu').show();
        $('#padding').show();
        $('#divHide').show();
        $('#divMore').hide();
        $("#wrapp").css("margin-top", "20px")
    }

    $('#divMore').click(function () {
        showOrHideAdvanced();
    });

    $('#divHide').click(function () {
        showOrHideAdvanced();
    });

    //drop down menus
    $(".ddMenu").hide();

    $(".ddMenu").mouseleave(function (e) {
        if (e.pageY < 50 || e.pageY > 100) {
            $(this).hide();
            $(".hover").removeClass("hover");
        }
    });

    $(".button").mouseover(function () {
        if ($(this).hasClass("hover") == false) {
            $(".ddMenu").hide();
            $(".hover").removeClass("hover");
        }
    });

    $(document).mousemove(function (e) {
        if (e.pageY < 50) {
            $(".ddMenu").hide();
            $(".hover").removeClass("hover");
        }
    });
    //end top navigation 

    //This automatically opens a pop up for the user.
    if ($.trim($("#divPopup").html()) != "") {
        $("#divPopup").dialog({
            stack: true,
            modal: false
        });

        $('#divPopup').parent().appendTo('form');
    }
    
    //Added by Paris. This adds tooltips to all drop downs and list boxes that have this class.
    $(".showToolTip").each(function () {
        var i = 0;
        var s = this;

        for (i = 0; i < s.length; i++)
            s.options[i].title = s.options[i].text;

        if (s.selectedIndex > -1)
            s.onmousemove = function () { s.title = s.options[s.selectedIndex].text; };
    });

    documentReady();
});

//Alert function
function Alert(Msg, Title) {
    if ($.trim(Msg) != "") {
        $("#divPopup").html(Msg);
        $("#divPopup").dialog({
            modal: true,
            title: Title?Title:'ISN Alert',
            buttons: { "Close": function(){$(this).dialog("close");}
                        }
        });
    }       
}

//Confirm function
function Confirm(Ctl, Msg, Title, IsPostBack, OkFunc, CancelFunc) {
    if (IsPostBack == undefined)
        IsPostBack = true;
    
    $('#divConfirm').html(Msg);

    $('#divConfirm').dialog({
        title: (Title == undefined) ? 'Please Confirm' : Title,
        modal: true,
        stack: true,
        buttons: {
            'Ok': function () {
                if (OkFunc != undefined) {
                    eval(OkFunc);

                    if (IsPostBack) {
                        __doPostBack(Ctl.name, '');
                    }

                    $(this).dialog("close");
                }
                else {
                    if (IsPostBack) {
                        __doPostBack(Ctl.name, '');
                    }

                    $(this).dialog("close");
                }
            },
            'Cancel': function () {
                if (CancelFunc != undefined) {
                    eval(CancelFunc);
                }

                $(this).dialog('close');
            }
        }
    });

    $('#divConfirm').parent().appendTo('form');

    $('#divConfirm').dialog('open');
}

//confirmation functions
function Confirmation(Msg, options) {
    if (!Msg) {
        return false;
    }
    $(".confirmation").html(Msg);
    if (options)
        ConfirmationShow(options);
    else
        ConfirmationShow();
}

function ConfirmationShow(options) {
    //Confirmation box in the bottom
    if ($.trim($(".confirmation").html()) != "") {

        var inTime = 1500;
        var delay=6000;
        var outTime = 6000;

        if(options&&(options.delay))
        {
        delay=options.delay;
        }

        if (options && (options.inTime))
            inTime = options.inTime;

    if (options && (options.outTime))
        outTime = options.outTime;

    $('.confirmation').attr("style", "display:none").stop().slideDown(inTime, function () {
        $(this).animate({opacity:1},delay, function () {
            $(this).fadeOut(outTime);
        });
    });
  
    }
    //end confirmation box in the bottom
}
//confirmation functions end


function SystemWideNotification() {
    //SystemWideNotification box 
    if ($.trim($(".SystemNotification").html()) != "") {
        $('.SystemNotification').dialog({
            modal: true,
            width: 550,
            title: 'System Wide Notification'
        });
    }
    //end SystemWideNotification box 
}

///seperated this because if a page uses ajaxtoolkit on page_load this function can be called to replicate document.ready.
function documentReady() {
    ConfirmationShow()
    SystemWideNotification()

    //page navigations control
    var blnCheckChange = false;

    // auto adds commas on inputs that contain numbers
    $('input.formatCommas').keyup(function () {
        var $this = $(this);
        var num = $this.val().replace(/,/g, '');
        $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
    });

    // auto adds highlighting of rows on mouseover
    $('.message-center tr').mouseover(function () {
        if (!$(this).hasClass('highlight')) {
            $(this).addClass('highlight');
        }
    });

    // auto removes highlighting of rows on mouseover
    $('.message-center tr').mouseout(function () {
        if ($(this).hasClass('highlight')) {
            if ($(this).attr('selected') == undefined)
                $(this).removeClass('highlight');
        }
    });

    //looks to see if anything changed on the form
    $(".checkForChange").change(function () {
        blnCheckChange = false;
        $(this).addClass("dirty");
        $('a').not(".DontCheckForChange").unbind('click');
        $('a').not(".DontCheckForChange").click(function () {
            Confirm(this, 'Changes have not been saved<br /><br />Are you sure you want to leave this page?', 'Please Confirm', false, 'window.location.href = "' + $(this).attr('href').replace(/"/g, "'") + '";');
            return false; 
        });
    });

    //ie fix for check boxes and radio
    $("input").click(function () {
        if ($(this).parent().hasClass("checkForChange")) {
            blnCheckChange = false;
            $(this).addClass("dirty");
            $(this).parent().addClass("dirty");
            $('a').not(".DontCheckForChange").unbind('click');
            $('a').not(".DontCheckForChange").click(function () {
                Confirm(this, 'Changes have not been saved<br /><br />Are you sure you want to leave this page?', 'Please Confirm', false, 'window.location.href = "' + $(this).attr('href').replace(/"/g, "'") + '";');
                return false;
            });
        }
    });

    $("a").not(".DontCheckForChange").click(function () {
        if ($("input").hasClass("dirty") || $("table").hasClass("dirty") || $("span").hasClass("dirty")) {
            Confirm(this, 'Changes have not been saved<br /><br />Are you sure you want to leave this page?', 'Please Confirm', false, 'window.location.href = "' + $(this).attr('href').replace(/"/g, "'") + '";');
            return false;
        }
    });

    $(".checkForm").click(function () {
        if ((blnCheckChange == false) && ($("input").hasClass("dirty") || $("table").hasClass("dirty") || $("span").hasClass("dirty"))) {
            Confirm(this, 'Changes have not been saved<br /><br />Are you sure you want to leave this page?', 'Please Confirm', false, '(function () { blnCheckChange = true; this.focus(); window.location.href = "' + $(this).attr('href').replace(/"/g, "'") + '"; })()', '(function () { blnCheckChange = false; })()');
            return false;
        }
    });
    //end of page navigation

    //Make input fields a shade of yellow
    $(':input:not(input[type=submit]):not(input[type=button]):not(button[type=button]):not(input[type=file]):not(input[type=checkbox]):not(input[type=radio]):not(input[type=image]):not(select)').css('border-style', 'solid').css('border-width', '1').css('border-color', '#E6E6E6').css('background-color', '#FFFFE5').mouseover(function () {
        if ($(this).is('select') == false && $(this).hasClass('tbX') == false) {
            $(this).css('background-color', '#E6E6E6');
            $(this).css('border-style', 'solid');
            $(this).css('border-color', 'Black');
            $(this).css('border-width', '1');
            
        }
        Req(this);
    }).mouseout(function () {
        if ($(this).hasClass('hasFocus') == false) {
            if ($(this).is('select') == false && $(this).hasClass('tbX') == false) {
                $(this).css('background-color', '#FFFFE5');
                $(this).css('border-color', '#E6E6E6');
                Req(this);
            }
        }
    }).focus(function () {
    if($(this).hasClass('tbX') == false)
    {
        $(this).addClass('hasFocus');
        $(this).css('border-width', '1');
        $(this).css('background-color', '#E6E6E6');
        $(this).css('border-style', 'solid');
        $(this).css('border-color', 'Black');
        $(this).css('border-width', '1');
        Req(this);
        }
    }).blur(function () {
        if ($(this).hasClass('tbX') == false)
        {
        $(this).removeClass('hasFocus');
        $(this).css('border-width', '1');
        $(this).css('background-color', '#FFFFE5');
        $(this).css('border-color', '#E6E6E6');
        Req(this);
        }
    })

    //Row Hover. When you hover over a row with this class, the color will change to shade of yellow
    //Created by Paris on 11/3/2010
    $('.rowHover').hover(function () {
        $(this).css('background-color', '#ffffe5');
    },
                     function () {
                         $(this).css('background-color', '');
                     });

    $('.Req').css('border-left-width', '2px');
    $('.Req').css('border-left-color', '#F26D45');
    $('.Req').css('border-left-style', 'solid');


    //icon image mouse over
    $("img[src*='icon-list.png']").hover(function () {        
        $(this).attr("src", $(this).attr("src").replace("-list.png", "-list-orange.png"));
    }, function() {
        $(this).attr("src", $(this).attr("src").replace("-list-orange.png", "-list.png"));
    });
    

}

//required field validator class function
function Req(input) {
    if ($(input).hasClass('Req') == true) {
        $(input).css('border-left-color', '#F26D45');
        $(input).css('border-left-width', '2px');
        $(input).css('border-left-style', 'solid');
    }
}

//Validators
//Validates required field. 
function ValidateRequired(ClassName) {
    var ret = true;

    $("." + ClassName).each(function () {
        var id = $(this).attr("id");
        var ctrl = $("#" + id);
        var span = "<span id='span" + id + "'>&nbsp;&nbsp;<img src='../Images/navDot-red.png' /></span>"
        if ($.trim(ctrl.val()) == "") {
            if ($("#span" + id).length == false) {
                $(span).insertAfter(ctrl);
            }
            ret = false;
            ctrl.focus().select();
        }
        else {
            if ($("#span" + id).length == true) {
                $("#span" + id).remove();
            }
        }
    });    
    return ret;
}

// this function validates all controls with css class Number
function ValidateNumber() {
    var ret = true;
    $("[class*=Number]").each(function () {

        var id = $(this).attr("id");
        var ctrl = $("#" + id);
        
        var span = "<span id='spanN" + id + "'>&nbsp;&nbsp;<img src='../Images/navDot-red.png' /></span>"
        if ($.trim(ctrl.val()) != "" && isNaN(ctrl.val())) {
            if ($("#spanN" + id).length == false) {
                $(span).insertAfter(ctrl);
            }
            ret = false;
            ctrl.focus().select();
        }
        else {
            if ($("#spanN" + id).length == true) {
                $("#spanN" + id).remove();
            }
        }
    });

    return ret;
}


//Sub menu hide and show function
function showOrHideAdvanced() {

    if ($('#submenu').is(':visible')) {
        $('#submenu').slideUp();
        $('#padding').slideUp();
        $('#divMore').show();
        $('#divHide').hide();
        //$("#wrapp").css("margin-top","0px")
        $("#wrapp").animate({ marginTop: '0px' }, 500);
        createCookie('isnPreferences', 'advanced=f', 30);
       
    }
    else {
        $('#submenu').removeClass('hidden');
        $('#submenu').slideDown()
        $('#padding').slideDown();
        $('#divMore').hide();
        $('#divHide').show();
        //$("#wrapp").css("margin-top", "20px")
        $("#wrapp").animate({ marginTop: '20px' }, 500);
        createCookie('isnPreferences', 'advanced=t', 30);        
    }
        
}


//Cookie Related Functions
//Created by Saks on 10/15/10
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 = "";
    document.cookie = name + "=" + value + expires + "; path=/";


}

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);
}

//Drop down menu related functions
function OpenMenu(hylLink, divMenu) {
    var timer;
    $(hylLink).hover(function () {
        timer = setTimeout(function () {
            if ($(hylLink).hasClass("hover") == false) {
                $(".hover").removeClass("hover");
                $(hylLink).addClass("hover");
                $(".ddMenu").hide();

                var Position = $(hylLink).position();
                $("#" + divMenu).css("top", Position.top + 86);
                $("#" + divMenu).css("left", Position.left - 20);
                $("#" + divMenu).show("blind");
            }
        }, 300);
    }, function () {
        clearTimeout(timer);
        timer = null;
    });            
}

/************** Created by Aaron Bowers on 02/22/11 *****************************

Example Browser Detect usage
	
BrowserDetect.browser <- returns Browser that is being used
	
if(BrowserDetect.browser == "Explorer")
dosomethingInIE();
	
if(BrowserDetect.browser == "Firefox")
dosomethingInFirefox();		
	
BrowserDetect.browser <- returns the name of the browser being used
BrowserDetect.version <- returns the version of the browser being used
BrowserDetect.OS <- returns the operating system being used
**************************************************************************/
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};

BrowserDetect.init();

/************** Created by Jerry Wang on 10/03/2011 *****************************
Generic Function for Ajax Call, both input & output in JSON Object. 
*/

if(!ISN)
var ISN = {};
ISN.AJAXQueue = {};
ISN.AJAXNoQueue = {};
ISN.JSONCall = function (URL, params, beforeFunc, successFunc, failFunc) {
    if (ISN.AJAXQueue[URL])
        ISN.AJAXQueue[URL].abort();
    var call = $.ajax({
        type: "POST",
        url: URL,
        data: params,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend: function () {
            if (beforeFunc) {
                beforeFunc()
            }

        },
        success: function (message) {
            if (successFunc) {
                var r = JSON.parse(message.d);
                if(r.Success)
                successFunc(r.Result,r.Message);
                else
                {
                if(failFunc)
                {
                failFunc(r.Message);
                }
                }
            }
        },
        error: function (request, textStatus, errorThrown) {
            if (failFunc)
                failFunc(request.responseText);
            return textStatus + " : " + request.responseText;
        }
    });

    if(!ISN.AJAXNoQueue[URL])
    ISN.AJAXQueue[URL] = call;
}

////Validation Function
$(document).ready(function () {
    $(".numericOnly").live("keydown", function (e) {
        var key = e.charCode || e.keyCode || 0;
        // allow backspace, tab, delete, arrows, numbers,comma, and keypad numbers ONLY
        return (
                key == 8 ||
                key == 188 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105)
          );
    });
});



/* Created By: Jerry Wang
   Description: A Jquery plugin to high light container. No options needed
   Example : $("#container").vHighLight();
*/
(function ($) {
    $.fn.vHighLight = function (options) {
        $(this).stop().animate({ "background-color": "#e25D35" }, 500, function () {
            $(this).css("background-color", "");
        });
    };
    $.fn.resetForm = function () {
        $(':text, :password, :file', $(this)).val('');
        $(':input', $(this)).removeAttr('checked').removeAttr('selected').removeAttr("disabled");
        $('textarea', $(this)).val('');
        return $(this);
    };
})(jQuery);


/* Created By: Jerry Wang
Description: Alert for IE 6 users
*/
$(document).ready(function () {
    if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
        var popup = 'We have identified that you are currently using Microsoft Internet Explorer 6.0 (IE6).\r\n\r\nISNetworld is not compatible with IE6. \r\n\r\nWe highly recommend that you consult your company\'s IT department and upgrade to a newer version of IE or use another web browser.'
        if ($("#ibLogin").length > 0)
            $("#ibLogin").click(function () {
                return confirm(popup);
            });
    }

    // if help-bar not exists, means before login. 
    if ($("#help-bar").length == 0) {
        return;
    }
    if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
        //var text = "Internet Explorer 6 is known to have compatibility issues with ISNetworld. <a id='detail-ie6'>Detail</a> <a id='hide-ie6'>Hide</a>";
        var text = "You are using Internet Explorer 6.0. ISNetworld is not compatible with IE6.  >><a id='hide-ie6'>Hide</a>";
        var box = $("<div id='ie6-alert'>" + text + "</div>");
        $("body").append(box);
        $("#hide-ie6", box).click(function () {
            $("#ie6-alert").slideUp("slow");
        });


    }
});
