﻿
/*Headlines rotator*/
var c = "ctl00_MainContent_"
var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline = 0;
var tabId = "Li1";
$.ui.dialog.defaults.bgiframe = true;

var pn = {}; //entered part number set of info
var sn = {}; //supersession part number set of info
var ln = "";
var sid;//sets the current supersession idreturn "";
var id; //sets the current id
var oldQty; //sets the previous/old value on the textbox
var q; //sets the New(user input) value on the textbox
var line = "";
var isDup = false;
var binArray = new Array();

var sessionExpired = false;
var sessionTimeout = 10000;

var dialogArray = new Array();

//http://forums.asp.net/p/1426825/3183546.aspx


function Alert(mess, show) {
    show = false;
    if (show) {
        alert(mess);
    }
}

function Alert2(mess, show) {
    show = false;
    if (show) {
        alert(mess);
    }
}

function Alert3(mess, show) {
    show = false;
    if (show) {
        alert(mess);
    }
}

function _Alert(mess, show) {
    show = show;
    if (show) {
        alert(mess);
    }
}

function CurrentPage() {
    var pg0 = $('#aspnetForm').attr('action');
    var pg = null;
    if (pg0) {
        pg = pg0.substring(0, pg0.indexOf("?"));
    }
    if (pg) {
        return pg.toLowerCase();
    }
    if (pg0) {
        return pg0.toLowerCase();
    }
    return "";
}

$(document).ready(function() {
    LoadDocument();
});        //end of $(document).ready function


function LoadDocument() {
    LoadImage();
    //_Alert("in document.ready", false);
    var pg0 = $('#aspnetForm').attr('action');
    var pg = CurrentPage();

    switch (pg || pg0) {
        case 'stockorder_additems.aspx': addItemLoad(); break;
        case 'stock_order.aspx': stockOrderLoad(); break;
        case 'stock_order_new.aspx': stockOrderLoad(); break;
        case 'stock_orders.aspx': stockOrderLoad(); break;
        case 'returns.aspx': returnsLoad(); break;
        //case 'locator.aspx': locatorLoad(); break;
        //case 'select_dealer.aspx': selectDealerLoad(); break;    
        case 'overrides.aspx': overridesLoad(); break;
        //case 'smartgauge.aspx': smartGaugeLoad("td SmartBoxHeader"); break;             
        case 'smartgauge.aspx':
            smartGaugeLoad("div.smartBox_photoShop td a.SmartBoxHeader");
            break;
        case 'smartgaugeaging.aspx': smartGaugeLoad("td.HoverLink a"); break;
        case 'support.aspx': supportLoad(); break;

        default:
            break;
    }

    generalLoad();
    CloseImage();//close the loading image
}

function LoadImage() {
    if (CurrentPage() == "stock_order.aspx" && $('#ctl00_MC_udp_stock_progress')) {
        $('#stock_progress').css('display', 'block');//hide this one to prevent duplicate images from being displayed
        //_Alert("LoadImage is called", false);
        $('#ctl00_MC_udp_stock_progress').css('display', 'block');
        grayOutGrid(true, { 'zindex': '100', 'bgcolor': '#808080', 'opacity': '50' }, 'ctl00_MC_gv1');  
        SetTimeOut("CloseImage()", 60);
    } else {
        //_Alert("Image will not be loaded", false);
    }
}

function CloseImage() {

    if (CurrentPage() == "stock_order.aspx" && $('#ctl00_MC_udp_stock_progress')) {
        //_Alert("CloseImage is called", false);
        $('#stock_progress').css('display', 'none');
        $('#ctl00_MC_udp_stock_progress').css('display', 'none');
        grayOutGrid(false, { 'zindex': '100', 'bgcolor': '#808080', 'opacity': '50' }, 'ctl00_MC_gv1');  
    }
}


function SetTimeOut(functionName, timeoutSeconds) {
    window.setTimeout(functionName, timeoutSeconds*1000);
}

function masterPageInit() {
    //1000 = 1
    //10000 = 10 sec
    //30000 = 30 sec
    window.setTimeout("endSession();", sessionTimeout);

    $("#dialogMaster").dialog({
        autoOpen: false,
        title: '',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            }
        },
        close: function(event, ui) {
            if (sessionExpired) {
                __doPostBack('session_timeout', 'submit');
            }
        }
    });
}

function endSession() {
    //make an ajax call to set the session expired variable set to true
     
     var response = "";
     $.ajax({
         type: "GET",
         url: "query.aspx?qry=se",
         cache: false,
         dataType: "text",
         success: function(text) {
             sessionExpired = (text == "true");
             //alert("Session Expired = " + sessionExpired);
             if (sessionExpired) {
                 $("#dialogMaster_txt").text("Your session is about to expire. You will be redirected to the login page.");
                 $("#dialogMaster").dialog("open");
             }
             else {
                 //reset the timeout
                 window.setTimeout("endSession();", sessionTimeout);
             }
         }, //closes the success code
         error: function(XMLHttpRequest, textStatus, message) {
             alert("There was an error on the process please try again");
             return;
             //ERROR ACTION - NEEDS TO BE FILLED WITH PROPER CODE
         }
     });
}


/*
function scriptLoad() {
    $('').click(function() {
        $.download('/export.php', 'filename=mySpreadsheet&format=xls&content=' + spreadsheetData);
    });
}
*/

function BrowerIsEI()
{
    var browserName=navigator.appName; 

    if (browserName=="Microsoft Internet Explorer")
    {
        return true;
    }else{
        return false;
    }

}

function ArrayContains(arr, searchValue)
{
    for (var i = 0; i < arr.length; i++) {
        if(arr[i] == searchValue){
            return true;
        }
    }
    return false;
}


function CleanBinChars(str) {
    //bin sort click - save before sorting
    var validStr = " 1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ";
    var invalidStr = "";
    var validBin = "";
    var bad = [];
    for (var i = 0; i < str.length; i++) {
        //if the current charinvalid
        var ch = str.charAt(i);
        if (validStr.indexOf(ch) == -1) {
            //append it to the list of invalid characters if we don't already have it saved
            if (!ArrayContains(bad, ch)) {
                invalidStr = invalidStr + " " + ch;
                bad.push(ch);
            }
        } else {
            validBin = validBin + ch;
        }
    }
    binObj = new Object();
    binObj.invalidChars = invalidStr;
    binObj.cleanChars = validBin;
    binObj.isValid = (bad.length == 0);
    return binObj;
}

//###########################################################################################################
//General Functions
//rotator
function generalLoad() {
    headline_count = $("div.headline a").size();
    $("div.headline a:eq(" + current_headline + ")").css('top', '5px');
    headline_interval = setInterval(headline_rotate, 6000);
    $('#scrollup').hover(function() {
        clearInterval(headline_interval);
    }, function() {
        headline_interval = setInterval(headline_rotate, 6000);
        headline_rotate();
    });
    //this assign click events to the scrolls on the header
    $("div.headline a").click(function() {
        var e = document.URL.substring(document.URL.lastIndexOf("/") + 1);
        if (e != "Default.aspx") {
            //          document.location = "http://staging.partseye.net/Default.aspx";

        }
        else {
            closeAll();
            var id = $(this).attr("title");
            $("#" + id).addClass("down");
            // AJAX Call to the article.aspx to load details
            $.get("reporting/articles.aspx?id=" + id, function(data) {
            //$.get("articles.aspx?id=" + id, function(data) {
                $("#details" + id).html(data);
            });
            $("#details" + id).addClass("news_detail");
            showLink(id);
        }
    });

    //this assign click events to the view detail links of the hot topics
    $(".view").click(function() {
        closeAll();
        var id = $(this).attr("title");
        $("#" + id).addClass("down");
        //AJAX Call to the article.aspx to load details
        $.get("reporting/articles.aspx?id=" + id, function(data) {
        //$.get("articles.aspx?id=" + id, function(data) {
            $("#details" + id).html(data);
        });
        $("#details" + id).addClass("news_detail");
        showLink(id);
    })
    //this is hiding the Hide Details link
    $(".tog").click(function() {
        closeAll();
    })
    var ids = new Array("Li1", "Li2", "Li3", "Li4", "Li5", "Li6", "Li7", "Li8", "Li9", c+"Li10");
    for (var i = 0; i < ids.length; i++) {
        $("#" + ids[i]).removeClass("current");
    }
    var pg = $('#aspnetForm').attr('action');
    if (pg) {
        pg = pg.substring(0, pg.indexOf("?"));
    }
    //    switch (pg ||$('form').attr('action'))
    switch (pg || $("#aspnetForm").attr("action")) {
        case "smartgauge.aspx":
        case "smartGaugeAging.aspx":
            tabId = "Li2"; break;
        case "reports.aspx":
        case "inventory_list.aspx":
        case "orders.aspx":
        case "order_detail.aspx":
        case "special_order.aspx":
        case "special_report.aspx":
        case "suggested_report.aspx":
        case "ppi.aspx":
        case "parts.aspx":
        case "reports_email.aspx":
        case "return_summary.aspx":
        case "return_detail.aspx":
            tabId = "Li3"; break;
        case "stock_order.aspx":
        case "stock_orders.aspx":
        case "stock_order_new.aspx":
        case "stockorder_additems.aspx":
            tabId = "Li4"; break;
        case "locator.aspx":
            tabId = "Li5"; break;
        case "returns.aspx":
            tabId = "Li6"; break;
        case "support.aspx":
        case "support_faq.aspx":
        case "script.aspx":
            tabId = "Li7"; break;
        case "overrides.aspx":
            tabId = "Li8"; break;
        case "select_dealer.aspx":
            tabId = "Li9"; break;
        case "errors.aspx":
            tabId = "Li10"; break;
        default:
            tabId = "Li1";
            break;
    }
    $("#" + tabId).addClass("current"); //this assigns the active tab

    //this selects the calendar in the Manual Override list and tooltip fuctions
    if($("#"+c+"from_tb"))
    {
        $("#"+c+"from_tb").datepicker();
    }
    if($("#" + c + "to_tb")){
        $("#" + c + "to_tb").datepicker();
    }
    //Alert("is stock tool tip",true);
    
    //use this class for image hooking of ajax
    //$("img.tooltips, .tooltip a").tooltip({
    $("img.tooltips, .tooltip a").tooltip({
        bodyHandler: function() {
           
            var part = "";
            if (CurrentPage().indexOf("stock_order") >= 0) {
                part = $('#' + this.id.replace("hist", "part_hl")).attr("title");
            }
            else {
                part = $(this).attr("href");
                if (part) {
                    part = part.substring(1, part.length);
                } else {
                    //user this part if getting it directly from image
                    part = $(this).attr("id");
                }
            }
            if (!part) {
                $(this).tooltip($.tooltip.block);
                return ""; 
            }

            var retVal = "Tool Tip Failed";

            $.ajax({
                type: "GET",
                url: "override_history.aspx?part=" + part,
                data: {},
                cache: false,
                async: false,
                success: function(html) {
                    retVal = html;
                },
                error: function(XMLHttpRequest, textStatus, message) {
                    //alert("There was an error on the process please try to enter the part again");
                    //ERROR ACTION - NEEDS TO BE FILLED WITH PROPER CODE
                    retVal = "Tool Tip Failed " + textStatus + " " + message;
                }
            });

            return retVal;
        },
        track: false,
        delay: 0,
        showURL: false,
        positionLeft: true,
        //top: -40,
        top: 17,
        //left: -15
        left: 55
    });

    InitHistoryDialog();

    $("#dialogMaster").dialog({
        autoOpen: false,
        title: '&nbsp;&nbsp;',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            "OK": function() {
                $(this).dialog("close");
            }
        }
        , close: function(event, ui) { }
    });

    $("#invalidContactDialog").dialog({
        autoOpen: false,
        title: '&nbsp;&nbsp;Found Invalid Contact Information',
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            "OK": function() {
                $(this).dialog("close");
            }
        }
        , close: function(event, ui) { }
    });
    
} //end of generalLoad()
//###########################################################################################################

//all Functions out of document ready
function closeAll() {
    $(".news_detail").addClass("hide");
    $(".news_detail").removeClass("news_detail"); //hides all other details
    $(".down").removeClass("down"); //corrects all arrows
    $(".view").addClass("show"); //shows all other View Details link 
    $(".tog").removeClass("show");
    $(".tog").addClass("hide"); //hides all other Hide Details link
}
function showLink(id) {
    $("#view" + id).removeClass("show");
    $("#view" + id).addClass("hide");
    $("#hide" + id).removeClass("hide");
    $("#hide" + id).addClass("show");
}


//rotator functions
function headline_rotate() {
    current_headline = (old_headline + 1) % headline_count;
    $("div.headline a:eq(" + old_headline + ")")
 .animate({ top: -205 }, "slow", function() {
     $(this).css('top', '210px');
 });

    $("div.headline a:eq(" + current_headline + ")")
 .animate({ top: 5 }, "slow");
    old_headline = current_headline;
}

function ChangeCheckBoxState(id, checkState) {
    var cb = document.getElementById(id);
    if (cb != null)
        cb.checked = checkState;
}
function ChangeAllCheckBoxStates(checkState) {
    if (CheckBoxIDs != null) {
        for (var i = 0; i < CheckBoxIDs.length; i++)
            ChangeCheckBoxState(CheckBoxIDs[i], checkState);
    }
}

//Locator page - search options box hide and show function
function displaySearch(id) {
    
    if (id == "hideLnk") {
        $("#showLnk").removeClass("hide");
        $("#showLnk").addClass("show");
        $("#hideLnk, #locator").removeClass("show");
        $("#hideLnk, #locator").addClass("hide");
    }
    else {
        $("#showLnk").removeClass("show");
        $("#showLnk").addClass("hide");
        $("#hideLnk, #locator").removeClass("hide");
        $("#hideLnk, #locator").addClass("show");
    }
}

//Report printing for pages: order and order_detail 
function popUp(url, width, height) {
    sealWin = window.open
        (url, "win", 'toolbar=0,location=1,directories=0,status=0,menubar=0,scrollbars=yes,resizable=0,width='
            + width + ',height=' + height);
    self.name = "mainWin";
}

function OpenPage() {
    //mywindow = window.open('reporting/PrintSmartGauge.aspx', 'mywindow', 'resizable=yes,scrollbars=yes,location=1,status=0,menubar=1,toolbar=1,height=1000, width=1000');
    //moved page to base
    mywindow = window.open('PrintSmartGauge.aspx', 'mywindow', 'resizable=yes,scrollbars=yes,location=1,status=0,menubar=1,toolbar=1,height=1000, width=1000');
    mywindow.focus();
}


//###########################################################################################################
//stock_order page general functions
function addLineArray(tbValue) {
    for (var i = 0; i < binArray.length; i++) {
        if (tbValue == binArray[i]) {
            tbValue = "";
            return
        }
    }
    binArray.push(tbValue);
    $("#" + c + "arrayContainer").val(binArray);
}


/*
action = 0, return true or false for empty status
action = 1, add value if not found, return true or false for addition status 
action = 2, remove if found, return or false for remove status
action = 3, return true or false with no action peformed
*/
function Arrayfunc(array, value, action) {
    var foundValue = false;
    var removedItems = false;
    var isEmpty = true;
    
    if (action == 0 && array.length == 0) {
        return isEmpty;
    }

    for (var i = 0; i < array.length; i++) {
        if (array[i] != "" && array[i] != null && action == 0) {
            isEmpty = false;
            return false;
        } 
        if (value == array[i]) {
            foundValue = true;
            switch(action){
                case 2:
                    array[i] = "";
                    removedItems = true;
                    break;
                    //dont return so we canremove duplicate values
                case 3: 
                    return true;
            }
        }
    }


    switch (action) {
        case 0: return isEmpty;
        case 1:
            //check the status of addition
            if (foundValue) {
                return false;//report no add
            }
            else{
                array.push(value);
                return true;//report add success
            }
            break;
        case 2:
            return removedItems;
        //dont return so we canremove duplicate values
        case 3:
            return false; //report that no item was found
            
    }
}


function SetFocus(id) {
    var elem = $("#" + id);
    if (elem) {
        elem.focus();
    }
}

function ShowSelectDealerDialog() {
    var elem = $('#selectDealerDialog');
    if (elem) {
        var status = $('#ctl00_MainContent_dealerStatus').val();
        if (status && status == "1") {
            //alert("User has not selected a dealer");
            $('#selectDealerDialog').dialog('open');
        }
    }
}

function _GB(elem) {

var part = $(elem).attr("title");
//var href = $(elem).attr("href");
var href = "/details.aspx?pn=" + part;
var message = 'Part Detail for ' + part + ' - Click the X on the right to return to the previous page';
//alert("messag2= " + message + " href = " + href);
return GB_showPage(message, href);
}

/*
This function is used for displaying the roating headline in a gray box
ex.
return _GBH('Click the X on the right to return to the previous page', this.href)
*/
function _GBH(elem) {

    var part = $(elem).attr("title");
    var href = "/articles.aspx?id=" + part;
    var message = "Click the X on the right to return to the previous page";
    //alert("messag2= " + message + " href = " + href);
    return GB_showPage(message, href);
}


/************************ JQUERY functions *********************/
/*
jQuery Url Plugin
* Version 1.0
* 2009-03-22 19:30:05
* URL: http://ajaxcssblog.com/jquery/url-read-get-variables/
* Description: jQuery Url Plugin gives the ability to read GET parameters from the actual URL
* Author: Matthias Jäggli
* Copyright: Copyright (c) 2009 Matthias Jäggli under dual MIT/GPL license.

var make = $.url.param('make');
*/
(function($) {
    $.url = {};
    $.extend($.url, {
        _params: {},
        init: function() {
            var paramsRaw = "";
            try {
                paramsRaw =
					(document.location.href.split("?", 2)[1] || "").split("#")[0].split("&") || [];
                for (var i = 0; i < paramsRaw.length; i++) {
                    var single = paramsRaw[i].split("=");
                    if (single[0])
                        this._params[single[0]] = unescape(single[1]);
                }
            }
            catch (e) {
                alert(e);
            }
        },
        param: function(name) {
            return this._params[name] || "";
        },
        paramAll: function() {
            return this._params;
        }
    });
    $.url.init();
})(jQuery);


//http: //www.hunlock.com/blogs/Snippets:_Howto_Grey-Out_The_Screen
function grayOut(vis, options) {
    // Pass true to gray out screen, false to ungray  
    // options are optional.  This is a JSON object with the following (optional) properties  
    // opacity:0-100         
    // Lower number = less grayout higher = more of a blackout   
    // zindex: #             
    // HTML elements with a higher zindex appear on top of the gray out  
    // bgcolor: (#xxxxxx)    
    // Standard RGB Hex color code  
    // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});  
    // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
    // in any order.  Pass only the properties you need to set.  var options = options || {};

    var zindex = options.zindex || 50; 
    var opacity = options.opacity || 70;
    var opaque = (opacity / 100); 
    var bgcolor = options.bgcolor || '#000000';
    var dark = document.getElementById('darkenScreenObject');
    if (!dark) {
        // The dark layer doesn't exist, it's never been created.  So we'll
        // create it here and apply some basic styles.
        // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
        var tbody = document.getElementsByTagName("body")[0];
        var tnode = document.createElement('div');
        // Create the layer.        
        tnode.style.position = 'absolute';
        // Position absolutely        
        tnode.style.top = '0px';
        // In the top        
        tnode.style.left = '0px';
        // Left corner of the page       
        tnode.style.overflow = 'hidden';
        // Try to avoid making scroll bars                    
        tnode.style.display = 'none';
        // Start out Hidden        
        tnode.id = 'darkenScreenObject';
        // Name it so we can find it later    
        tbody.appendChild(tnode);
        // Add it to the web page    
        dark = document.getElementById('darkenScreenObject');
        // Get the object.  
    }
    if (vis) {
        // Calculate the page width and height     
        if (document.body && (document.body.scrollWidth || document.body.scrollHeight)) {
            var pageWidth = document.body.scrollWidth + 'px';
            var pageHeight = document.body.scrollHeight + 'px';
        }
        else if (document.body.offsetWidth) {
            var pageWidth = document.body.offsetWidth + 'px';
            var pageHeight = document.body.offsetHeight + 'px';
        }
        else {
            var pageWidth = '100%';
            var pageHeight = '100%';
        }
        //set the shader to cover the entire page and make it visible.    
        dark.style.opacity = opaque;
        dark.style.MozOpacity = opaque;
        dark.style.filter = 'alpha(opacity=' + opacity + ')';
        dark.style.zIndex = zindex;
        dark.style.backgroundColor = bgcolor;
        dark.style.width = pageWidth;
        dark.style.height = pageHeight;
        dark.style.display = 'block';
    }
    else {
        dark.style.display = 'none';
    }
}

/*
See default.css for styling
*/
function grayOutGrid(vis, options, gridID) {
    // Pass true to gray out screen, false to ungray  
    // options are optional.  This is a JSON object with the following (optional) properties  
    // opacity:0-100         
    // Lower number = less grayout higher = more of a blackout   
    // zindex: #             
    // HTML elements with a higher zindex appear on top of the gray out  
    // bgcolor: (#xxxxxx)    
    // Standard RGB Hex color code  
    // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});  
    // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
    // in any order.  Pass only the properties you need to set.  var options = options || {};

    var zindex = options.zindex || 50;
    var opacity = options.opacity || 50;
    var opaque = (opacity / 100);
    var bgcolor = options.bgcolor || '#000000';
    var dark = document.getElementById('grayedOutGrid');
    
    if (!dark) {
        // The dark layer doesn't exist, it's never been created.  So we'll
        // create it here and apply some basic styles.
        // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
        var tbody = document.getElementsByTagName("body")[0];
        var tnode = document.createElement('div');
        var div = document.getElementById('grayedOutGridDiv');
      
        // Create the layer.        
        tnode.style.position = 'absolute';
        // Position absolutely
        //tnode.style.top = gridElem.style.top;
        // In the top
        //tnode.style.left = "";
        // Left corner of the page       
        tnode.style.overflow = 'hidden';
        // Try to avoid making scroll bars                    
        tnode.style.display = 'none';
        // Start out Hidden
        tnode.id = 'grayedOutGrid';
        // Name it so we can find it later
       
        if (div) {
            div.appendChild(tnode);
        }
        else {
            tbody.appendChild(tnode);
        }
        // Add it to the web page
       
        dark = document.getElementById('grayedOutGrid');
        // Get the object.  
    }
    if (vis) {
        //logic has been moved to the css style
        //set the shader to cover the entire page and make it visible.
        
        dark.style.opacity = opaque;
        dark.style.MozOpacity = opaque;
        dark.style.filter = 'alpha(opacity=' + opacity + ')';
        dark.style.zIndex = zindex;
        dark.style.backgroundColor = bgcolor;
        dark.style.display = 'block';
    }
    else {
        dark.style.display = 'none';
    }

    //_Alert($("grayedOutGrid").html(), true);
}


function _SH(part) {
    ShowHistory(histDivOrSpan);
}

function _SH2(partNum) {
    ShowHistoryPart(partNum);
}

function _SH(histDivOrSpan) {
    ShowHistory(histDivOrSpan);
}

function _CH() {
    CloseHistory();
}

function CloseHistory() {
    var dialogName = "history_div";
    var currPage = CurrentPage();
    /*
    //if (currPage == "smartgauge.aspx" || currPage == "smartgaugeaging.aspx") { 
    if(currPage.indexOf("smartgauge.aspx") >= 0 || currPage.indexOf("smartgaugeaging.aspx") >= 0){
        dialogName = "dialog_rpv_tooltip";
    }
    */
    if ($('#' + dialogName)) {
        var dialogOpen = $('#' + dialogName).dialog("isOpen");
        if (dialogOpen) {
            CloseDialog(dialogName);
        }
        else {
            //OpenDialog(dialogName);
        }
    }
}

/* Function used by the spart gauge report viewer to display a modal window version of the part # demand info*/
function InitHistoryDialog() {
    //reset html content used to display the tool tip
    //CreateHistoryDiv();
    $("#history_div").html("");
    $(".ui-widget-content a").css("display", "none"); //hide the top right default close button with the x image

    $("#history_div").dialog({
        autoOpen: false,
        //title: '&nbsp&nbsp',
        modal: false,
        //width: 625,
        width: 645,
        //width: 'auto',//this will make the width extremely large
        //maxWidth: 650,
        maxWidth: 800,
        height: 'auto',
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
        },
        //bgiframe:false,
        closeOnEscape: true,
        //draggable: true,
        position: 'top'
        /*,
        //position: { right: '100', top: '0'}
        
        close: function() {
            //reset modocal dialog back to default
        }
        */
    });
     
     /* 
    //hooking into mouseout only if not stock order page. This is now done directly to html function call
    if (CurrentPage() != "stock_order.aspx") {
        //This is now hooked in directly to element on html page
       
        $(".tooltips").mouseover(function(e) {
            //ShowHistory(this);
        });

        $(".tooltips").mouseout(function(e) {
            //CloseHistory();
        });
    }
    */
}

function CreateHistoryDiv()
{
    var histDiv = document.getElementById('historyDiv');
    
    if (!histDiv) {
        var body = document.getElementsByTagName("body")[0];
        var div = document.createElement('div');
        div.id = "historyDiv";
        body.appendChild(div);
        // Add it to the web page
        histDiv = document.getElementById('historyDiv');
    }
    
    return histDiv;
}

function ShowHistory(histDivOrSpan) {
    var img = $(histDivOrSpan).children(":img");
    var part = "";
    var id = $(img).attr("id");
    if (CurrentPage().indexOf("stock_order") >= 0) {
        part = $('#' + id.replace("hist", "part_hl")).attr("title");
    }
    else {
        part = $(img).attr("href");
        if (part) {
            part = part.substring(1, part.length);
        } else {
            //user this part if getting it directly from image
            part = $(img).attr("id");
        }
    }
    if (part) {
        LoadHistory("history_div", part);
        ShowDialog("history_div");
    }
    else {
        return "Tool Tip Failed for part " + part;
    }
}


function ShowHistoryPart(partNum)
{
    if (partNum) {
        LoadHistory("history_div", partNum);
        ShowDialog("history_div");
    }
    else {
        return "Tool Tip Failed for part " + partNum;
    }
}

/* Function used by the smartgauge.aspx's report viewer to display a modal window version of the part # demand info*/
function LoadHistory(srcElem, partNum) {
    //make an ajax call to retrive data from override_history page
    var retVal = "Tool Tip Failed";

    $.ajax({
        type: "GET",
        url: "override_history_stock.aspx?part=" + partNum,
        //url: "override_history.aspx?part=" + partNum,
        data: {},
        cache: false,
        async: false,
        success: function(html) {
            retVal = html;
            retVal = retVal.substring(retVal.indexOf("<!--begin-->"), retVal.indexOf("<!--end-->"))
            $("#" + srcElem).html(retVal);
        },
        error: function(XMLHttpRequest, textStatus, message) {
            //alert("There was an error on the process please try to enter the part again");
            //ERROR ACTION - NEEDS TO BE FILLED WITH PROPER CODE
            retVal = "Tool Tip Failed " + textStatus + " " + message;
        }
    });
}



function Destroy(dialog) {
    //The history div does not call this function, so it's safe to say that it's another dialog being closed
    Arrayfunc(dialogArray, dialog.id, 2); //remove dialog from list of open dialog
    //$(dialog).dialog("destroy");
    grayOutGrid(false, { 'zindex': '50', 'bgcolor': '#0000FF', 'opacity': '70' });
}


function CloseDialog(dialogName) {
    $("#" + dialogName).dialog("close");
}

function dialogNormalIsOpen() {
    var arrIsEmpty = Arrayfunc(dialogArray, "", 0);
    if (arrIsEmpty == true) { return false; }
    else { return true; }

}

function ShowDialog(dialogName) {
    var foundNormal = dialogNormalIsOpen();
    if (!dialogName) {
        dialogName = "history_div";
    }
    
    //don't open the history div if a regular dilaog is currently open
    if (dialogName == "history_div" && foundNormal) {
        //close the history if currenlty open and disable it temporarily
        CloseDialog("history_div");
        $("#history_div").dialog("disable");
        return;
    }

    if (dialogName == "history_div" || dialogName == "dialog_rpv_tooltip") {
        $("#" +dialogName).dialog("enable");
        $(".ui-dialog .ui-dialog-titlebar").css("display", "none"); //hide the top empty title bar
    }
    else {
        Arrayfunc(dialogArray, dialogName, 1); //add dialog to list of open dialog
        $(".ui-dialog .ui-dialog-titlebar").css("display", "block"); //hide the top empty title bar
        CloseDialog("history_div");
        $("#history_div").dialog("disable");
        grayOutGrid(true, { 'zindex': '50', 'bgcolor': '#808080', 'opacity': '70' });
    }
    //common properties for all dialog\
    //This has been moved to dialog_red.css
    //$(".ui-dialog").css("border", "2px solid blue"); //hide the top empty title bar
    //$(".ui-dialog .ui-dialog-titlebar").css("padding", "0px"); //hide the top empty title bar
    //$(".ui-dialog .ui-dialog-buttonpane").css("padding", "0px"); //hide the top empty title bar
    //$(".ui-widget-content a").css("color", "#0000FF"); //format the custom close window links
    //$(".ui-widget-content a").css("text-decoration", "underline"); //format the custom close window links
    //$(".ui-widget-header .ui-icon").css("background-color", "blue"); //set back color of default close image to red

    $("#" + dialogName).dialog("open");
}

//resource for validation regular expressions
//http://tools.netshiftmedia.com/regexlibrary/#

function IsValidEmailAddress(emailAddress) {
    //remove white spaces from the beginning and end of string
    emailAddress = jQuery.trim(emailAddress);
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

//http://javascript.about.com/library/blre.htm
//The phone number regular expression accepts phone number in both local format 
//(eg. 02 1234 5678 or 123 123 4567) or international format (eg. +61 (0) 2 1234 5678 or +1 123 123 4567). 
//It also accepts an optional extention of up to five digits prefixed by x or ext (eg. 123 123 4567 x89)
function IsValidPhoneNumber(phoneNumber, removeWhiteStaces) {
    if (removeWhiteStaces) {
        //replace two or more white spaces with a single white space
        //phoneNumber = phoneNumber.replace(/\s{1,}/g, " ");
        phoneNumber = phoneNumber.replace(/\s/g, "");
        //using standard trim function to remove the white extra ending white space not handle by the expression above
        phoneNumber = jQuery.trim(phoneNumber);
    }
    //var pattern = new RegExp(/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/);
    var pattern = new RegExp(/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(.){0,}$/);
    return pattern.test(phoneNumber);
}


