﻿var DEBUG = false;
var PATH_BASE = "/BRWEB/";
var PATH_DISTPORTAL = PATH_BASE + "DistPortal/";
var PATH_RHINOVISION = PATH_BASE + "RhinoVision/";
var PATH_RHINOWAY = PATH_BASE + "CorpPortal/RhinoWay/";

var PATH_AJAX = PATH_BASE + "BRCAjax/";

var popupDisplayOptions = "scrollbars=1,resizable=1,status=1,menubar=0,toolbar=0";

/*************************************************************
    Blue Rhino Common Functions

    Common functions which are used across all Blue Rhino sites.
**************************************************************/
function getElement(id) {
    try {
        var e = document.getElementById(id);
        if (!e) {
            if (DEBUG) {
                alert(id + " is not a valid document element.");
            }
            return null;
        } else {
            return e;
        }
    } catch (ex) {
        if (DEBUG) {
            alert(ex);
        }
        return null;
    }
}

//--show(id)---------------------------------------------
// Takes the given element ID and makes it visible.
//-------------------------------------------------------
function show(id) {
	var e = getElement(id);
	if (e) {
	    e.style.display = "block";
	}
}

//--hide(id)---------------------------------------------
// Takes the given element ID and hides it.
//-------------------------------------------------------
function hide(id) {
	var e = getElement(id);
	if (e) {
	    e.style.display = "none";
	}
}

//--ShowHideSwitch(id)-----------------------------------
// Takes the given element and shows it if it's hidden or
// hides it if it's showing.
//-------------------------------------------------------
function ShowHideSwitch(id) {
    var e = getElement(id);
    if (e) {
        if (e.style.display == "none") {
            show(id);
        } else {
            hide(id);
        }
    }
}

//AssignOnEnterClick
//Used to assign a button to simulate a click on when the user presses
//the Return/Enter key on a form input.
function AssignOnEnterClick(e,buttonID) {
    if (event.which || event.keyCode) {
        if ((event.which == 13) || (event.keyCode == 13)) {
            document.getElementById(buttonID).click();
            return false;
        }
    } else if (e) {
        if (e.keyCode == 13) {
            document.getElementById(buttonID).click();
            return false;
        }
    } else {
        return true;
    }
}

//KeyPressHandler
//Takes the event, key code of the key to capture, and a function to run if the key code matches
//the key code passed in.
function KeyPressHandler(e, keyCode, runFunction) {
    if (event.which || event.keyCode) {
        if ((event.which == keyCode) || (event.keyCode == keyCode)) {
            eval(runFunction);
            return false;
        }
    } else if (e) {
        if (e.keyCode == keyCode) {
            eval(runFunction);
            return false;
        }
    } else {
        return true;
    }
}

function getSelectedValue(selectElement) {
    if (selectElement.type == "select-one" || selectElement.type == "select-multiple") {
        if (selectElement.selectedIndex > -1) {
            return selectElement[selectElement.selectedIndex].value;
        } else {
            return null;
        }
    } else {
        alert("Invalid select element passed to getSelectedValue() (br_common.js).");
        return null;
    }
}

function setSelectedValue(selectElement, value) {
    if (selectElement.type == "select-one" || selectElement.type == "select-multiple") {
        var sValue = new String(value);
        for (var i=0; i<selectElement.length; i++) {
            if (selectElement[i].value == sValue) {
                selectElement[i].selected = true;
                return true;
            }
        }
        //value not found, return false
        return false;
    } else {
        alert("Invalid select element passed to setSelectedValue() (br_common.js).");
        return null;
    }
}

function removeDropdownOptions(fieldid) {
	useField = document.getElementById(fieldid);
	if (useField.type == "select-one" || useField.type == "select-multiple") {
		for (var i = useField.length-1; i >= 0; i--) {
			useField.remove(i);
		}
	}
}

//.NET postback functions
//--doPostback(controlID, eventArg)----------------------------------
// Fires a .NET postback even for the control matching the ID passed
// in. The controlID does not have to be the final rendered .ClientID
// eventArg can be an empty string (for most postbacks this is what it
// should be).
//-------------------------------------------------------------------
function doPostback(controlID, eventArg) {
    __doPostBack(controlID, eventArg);
}

//--doDelayedPostback(controlID, eventArg, msDelay)------------------
// Does a delayed postback. Postback event will fire after msDelay
// milleseconds. Returns a timeout handler for canceling the postback,
// if necessary.
//-------------------------------------------------------------------
function doDelayedPostback(controlID, eventArg, msDelay) {
    return setTimeout("doPostback('" + controlID + "','" + eventArg + "');", msDelay);
}

//DOUBLE AND SINGLE CLICK HANDLERS
function handleMe(which) {
   document.forms[0].elements[0].value += which + " fired... Then ";
 }
 
 var dcTime=500;    // doubleclick time
 var dcDelay=100;   // no clicks after doubleclick
 var dcAt=0;        // time of doubleclick
 var savEvent=null; // save Event for handling doClick().
 var savEvtTime=0;  // save time of click event.
 var savTO=null;    // handle of click setTimeOut
 var type = ""; // which list - outcall or retail

 function showMe(form, txt) {
   document.forms[form].elements[0].value += txt;
 }
 
 function hadDoubleClick() {
   var d = new Date();
   var now = d.getTime();

   if ((now - dcAt) < dcDelay) {
     return true;
   }
   return false;
 }
 
 //handles user clicking or doubleclicking a listbox, introduces a small delay
 //on a single click event in case they are indeed doing a double click.
 //which - the event we're looking for, click or dblclick
 //handlerFunction - name of the function to run when the click or doubleclick has been confirmed
  function handleWisely(which,handlerFunction) {
   switch (which) {
     case "click": 

       // If we've just had a doubleclick then ignore it
       if (hadDoubleClick()) { return false; }
       
       // Otherwise set timer to act.  It may be preempted by a doubleclick.
       savEvent = which;
       d = new Date();
       savEvtTime = d.getTime();
       savTO = setTimeout("doClick(savEvent,\"" + handlerFunction + "\")", dcTime);
       break;

     case "dblclick":
       doDoubleClick(which,handlerFunction);
       break;
     default:
   }
 }
 
 function doClick(which,handlerFunction) {
   // preempt if DC occurred after original click.
   if (savEvtTime - dcAt <= 0) {
     return false;
   }
   
   eval(handlerFunction);
 }
 
 function doDoubleClick(which,handlerFunction) {
   var d = new Date();
   dcAt = d.getTime();
   if (savTO != null) 
        {
         clearTimeout( savTO );          // Clear pending Click  
         savTO = null;
       }
    eval(handlerFunction);
 }

//PAGE LOCATION MANIPULATION
//-------------------------------------------------------------
// First, attempts to reload the page through AJAX by calling
// the LoadRetailer(rid,product) function. If that function does
// not exist, then it reloads the current page with rid and
// product querystring variables added, appended or replaced.
// Note: LoadRetailer is defined on individual pages
//-------------------------------------------------------------
function ReloadPage(rid, product) {
    if (rid == undefined && product == undefined) {
        //just force a refresh of the page
        window.location.reload();
        return true;
    }
    try {
        LoadRetailer(rid, product);
    } catch (e) {
        var href = window.location.href;
        var url = href.split("?")[0];
        var qString = href.split("?")[1];
        if (qString) {
            var i = 0;
            //split name/value pairs
            var pairs = qString.split("&");
            for (i=0; i<pairs.length; i++) {
                //split each pair into name and value. pairs[i][0] == name, pairs[i][1] == value
                pairs[i] = pairs[i].split("=");
            }
            var ridSet = false;
            var productSet = false;
            //now see if rid or product already exists in the query string
            for (i=0; i<pairs.length; i++) {
                if (pairs[i][0] == "rid") {
                    pairs[i][1] = rid.toString();
                    ridSet = true;
                } else if (pairs[i][0] == "product") {
                    pairs[i][1] = product;
                    productSet = true;
                }
            }
            //if rid or product was not found in the querystring, add them to the array
            if (!ridSet) {
                var ridArr = new Array(2);
                ridArr[0] = "rid";
                ridArr[1] = rid.toString();
                pairs.push(ridArr);
            }
            if (!productSet) {
                var prodArr = new Array(2);
                prodArr[0] = "product";
                prodArr[1] = product;
                pairs.push(prodArr);
            }
            //rebuild query string from array
            for (i=0; i<pairs.length; i++) {
                pairs[i] = pairs[i].join("=");
            }
            qString = "?" + pairs.join("&");
        } else {
            //no query string currently on url, so we can just add it
            qString = "?rid=" + rid + "&product=" + product;
        }
        window.location = url + qString;
    }
}

function GoToAnchor(anchorName) {
    var href = window.location.href;
    var url = href.split("#")[0].split("?")[0];
    var qString;
    try {
        qString = href.split("?")[1].split("#")[0];
    } catch (e) {}
    
    if (qString) {
        qString = "?" + qString;
    } else {
        qString = "";
    }
    window.location = url + qString + "#" + anchorName;
}
 
//POPUPS
//--PopupCustomerAddress(selName)-------------------------
// Expects a reference to a select element whose value is
// made up of a retailer id and a product seperated by ||.
// eg. "10202||T"
//--------------------------------------------------------
function PopupCustomerAddress(selName) {
    var e = getElement(selName);
    var selItem = getSelectedValue(e);
    var selArray = selItem.split("||");
    var rid = selArray[0];
    var prod = selArray[1];
    var newWin = "http://" + window.location.host + PATH_DISTPORTAL + "Popups/CustomerAddress.aspx?rid=" + rid.toString() + "&product=" + prod;
    
    var p = window.open(newWin, "cAddress", "width=400,height=300,screenX=200,screenY=70,resizable=1,location=0,menubar=0,toolbar=0");
    p.focus();
    
    return false;
}

function PopupPage(page, name, width, height) {
    var p = window.open(page, name, "width=" + width + ",height=" + height + ",resizable=1,location=0,menubar=0,toolbar=0,status=1,scrollbars=1");
    p.focus();
    
    return false;
}

//VALIDATION
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=2002;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) {
             return false;
        }
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) {
            returnString += c;
        }
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}

//--isDate(dtStr,field)-------------------------------------
//
//----------------------------------------------------------
function isDate(dtStr,field){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) {
	    strDay=strDay.substring(1);
	}
	if (strMonth.charAt(0)=="0" && strMonth.length>1) {
	    strMonth=strMonth.substring(1);
	}
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) {
		    strYr=strYr.substring(1);
		}
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy for " + field);
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month for " + field);
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day for " + field);
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear + " for " + field);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date for " + field);
		return false;
	}
return true;
}

/*************REPORT CENTER********************************/        
function PopupReport(url) {
    url = GBL_CORP_PORTAL_REPORTS_URL + url;
    if (url.indexOf("?") > -1) {
        url += '&who=' + GBL_USERID;
    } else {
        url += '?who=' + GBL_USERID;
    }
    window.open(url, "popupReport", popupDisplayOptions);
}

/***********MANUAL TICKETS********************************/
function PopupManualTicket(url) {
    url = GBL_MANUAL_TICKETS_URL + url;
    if (url.indexOf("?") > -1) {
        url += '&who=' + GBL_USERID;
    } else {
        url += '?who=' + GBL_USERID;
    }
    window.open(url, "popupManualTicket", popupDisplayOptions);
}

/*********ROUTING TOOL***********************************/
function PopupRoutingTool() {
    url = GBL_ROUTING_TOOL_URL;
    if (url.indexOf("?") > -1) {
        url += '&who=' + GBL_USERID;
    } else {
        url += '?who=' + GBL_USERID;
    }
    window.open(url, "popupRoutingTool", popupDisplayOptions);
}

/********MONTH END REPORTS*******************************/
function PopupMonthEnd(url) {
    url = GBL_MONTH_END_REPORTS_URL + url;
    if (url.indexOf("?") > -1) {
        url += '&user=' + GBL_USERID;
    } else {
        url += '?user=' + GBL_USERID;
    }
    window.open(url, "popupMonthEnd", popupDisplayOptions);
}

//ISSUE LOG / OUTCALLS
function CreateCall(rid, product, resultsFunction) {
    var searchParams = "";
    var dpPath = PATH_DISTPORTAL;
    searchParams = buildParamList(searchParams, "rid", rid);
    searchParams = buildParamList(searchParams, "product", product);
    searchParams = buildParamList(searchParams, "rFN", resultsFunction);
    var popupUrl = dpPath + "Popups/NewOutcall.aspx?" + searchParams;
    var options = "width=600,height=650," + popupDisplayOptions;
    var ncWindow = window.open(popupUrl, "newCall", options);
    ncWindow.focus();
    return false;
}

function StatusHistoryUpdate(rid, product, statusOnly, resultsFunction) {
    var searchParams = "";
    var dpPath = PATH_DISTPORTAL;
    searchParams = buildParamList(searchParams, "rid", rid);
    searchParams = buildParamList(searchParams, "product", product);
    searchParams = buildParamList(searchParams, "so", statusOnly);
    searchParams = buildParamList(searchParams, "rFN", resultsFunction);
    var popupUrl = dpPath + "Popups/StatusHistoryUpdate.aspx?" + searchParams;
    var options = "width=500,height=500," + popupDisplayOptions;
    var shcWindow = window.open(popupUrl, "statusHistoryUpdate", options);
    shcWindow.focus();
    return false;
}

//RETAILER INFORMATION
function PopupLegend() {
    var dpPath = PATH_DISTPORTAL;
    var popupUrl = dpPath + "Popups/Legend.aspx";
    var options = "width=500,height=600," + popupDisplayOptions;
    var lgndWindow = window.open(popupUrl, "viewLegend", options);
    lgndWindow.focus();
    return false;
}

function PopInstallStore(rid, product, status) {
    var searchParams = "";
    searchParams = buildParamList(searchParams, "rid", rid);
    searchParams = buildParamList(searchParams, "product", product);
    searchParams = buildParamList(searchParams, "status", status);
    var popupUrl = dpPath + "Work-Centers/Install-Center/Install-Store.aspx?" + searchParams;
    var options = "";
    var insWindow = window.open(popupUrl, "InstallStore", options);
    insWindow.focus();
    return false;
}