var sessionExpirationTimerId;

window.onerror = function(message, url, line)
{
    if(/MSIE (\d+\.\d+);/.test(navigator.userAgent))
    {
        var browser=navigator.appName;
        var b_version=navigator.appVersion;
        var version=parseFloat(b_version);
        var msg = "URL : " + url.replace(/&/g,'$');
        msg += " Line No : " + line ;
        msg += " Error : " + message;
        msg += " Browser name: " + browser;
        if (navigator.appVersion.indexOf("MSIE") != -1)    
            version = parseFloat(navigator.appVersion.split("MSIE")[1]); 
        msg += " Browser version: " + version;
        
        callAjaxPrime2('/aspx/xml/general/JSErrorHandler.aspx?JSError=' + msg , 'common_JSErrorHandler_CallBack' , 'errorFailure' )
    }
}
function common_JSErrorHandler_CallBack(xmlDoc)
{
    if( xmlDoc.getElementsByTagName('error')[0].firstChild.data == "OK" )
    {
        alert('There was an error while processing your request. The Technical Support Team has been notified. Please try the request later.');
    }
}
function AF_getEvent(e) {
    if (window.event){
        var e = window.event;
    }
    return e;
}
function $(strElementID){
	return document.getElementById(strElementID);
}


function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

// returns an array of width and height - cross browser compatible in strict and quirks mode
function getClientWidthHeight(){
  var myWidth = 0, myHeight = 0;
  if(typeof(window.innerWidth) == 'number'){
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  }else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)){
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  }else if(document.body && (document.body.clientWidth || document.body.clientHeight)){
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth,myHeight];
}

// returns an array of scrollTop/Left
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [scrOfX, scrOfY];
}

// global mouse position
var AF_MouseX, AF_MouseY;

function getMousePos(e){
    if (!e)
    var e = window.event||window.Event;
    
    if('undefined' != typeof e.pageX){
        AF_MouseX = e.pageX;
        AF_MouseY = e.pageY;
    }else{
        AF_MouseX = e.clientX + getScrollXY()[0]; //document.body.scrollLeft;
        AF_MouseY = e.clientY + getScrollXY()[1]; //document.body.scrollTop;
    }
}
// You need to tell Mozilla to start listening:
if(window.Event && document.captureEvents){ document.captureEvents(Event.MOUSEMOVE); }
// Then assign the mouse handler
//document.onmousemove = getMousePos;
addEvent(document,'mouseover',getMousePos);

function clone(obj)
{
    if(obj == null || typeof(obj) != 'object')
        return obj;
    var temp = obj.constructor();
    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}
function getCookieValue(cookieName,key)
{
    var results = document.cookie.match ( '(^|;) ?' + cookieName + '=([^;]*)(;|$)' );
    if(results)
    {
        results = unescape(results[2]);
        var values = results.split('&');
        var value;
        for(var i=0; i<values.length; i++)
        {
            value = values[i].split('=');
            if(value.length == 2)
            {
                if(value[0] == key)
                {
                    if(values[i].split('=')[1] == null || values[i].split('=')[1] == 'undefined')
                    {
                        window.location.href='/ASPX/common/SessionExpiration.aspx';
                    }
                    else
                    {
                        return values[i].split('=')[1];
                    }
                }
            }
        }        
        window.location.href='/ASPX/common/SessionExpiration.aspx';
    }
    else
    {
        window.location.href='/ASPX/common/SessionExpiration.aspx';
    }
}
// isValidDate( month, day, year) --> returns [true] || [a string which is the error]

// noSpecialChar	(object)
// noSpecialChar2	(object)
// noNumbers		(object)
// onlyNumbers		(object)
// onlyNumbersNoDec	(object) 

//---------------------------------------
function gotoFocus ( objID ) {
	if ( objID.length >  0 ) { 
		if( document.getElementById(objID) ) { 	document.getElementById(objID).focus() ;  } 
	} 
}

//---------------------------------------
function isValidDate( month, day, year) {
	month = parseInt(month,10) ; day = parseInt(day,10) ; year = parseInt(year,10) ; 
	if ( ( month == "" || day == "" || year == "" ) || (isNaN(month)||isNaN(day)||isNaN(year)) )	{ return ("Not a valid date -->\n") ; }
	else if ( (month > 12 ) || isNaN(month) ) 		{ return ("Not a valid month \n") ;}
	else if ( (day > 31 ) || isNaN(day) ) 			{ return ("Not a valid date \n") ;}
	else if ( (year<1900)||(year>2080) ) 			{ return ("Not a valid year \n") ;}
	else	{
		var arrDate = new Array("0","31","28","31","30","31","30","31","31","30","31","30","31")    
		if ( month != 2)	{
			if ( day > parseInt(arrDate[month]) ) {
				return ("The date selected should be less than or equal to " + arrDate[month].toString() + " in " + myGetMonth(month).toString() + "--> \n")
			}
		}
		else	{
			if ((year % 4) == 0)	{
				if( day > 29 )	{ return ( "The date selected should be less than or equal to 29 in February, " + year + " -->\n" ) }
			}			
			else if( day > 28) { return (" The date selected should be less than or equal to 28 in February, " + year + " -->\n") }
		}
	}
	
	return true ;
		
	function myGetMonth( int ) {
		int = parseInt(int)
		var monthIndex = new Array ( 2 )
		monthIndex[0] = new Array ( 1,2,3,4,5,6,7,8,9,10,11,12 )
		monthIndex[1] = new Array ( "January",'Febuary','March','April','May','June','July','August','September','October','November','December' )
		for ( q = 1 ; q!=12 ; ++q ) {
			if ( int == monthIndex[0][q] ) {
				return ( monthIndex[1][q] )
			}
		}
		return ( "" )
	}

}

function selectValueSet(selectName, value) {
    eval('selectObject = document.getElementById("' + selectName + '");');
    for(i=0; i<selectObject.length; i++)
    {
        if(selectObject[i].value == value)
        {
            selectObject.selectedIndex = i;
            break;
        }
    }
}

function GetPagingLinks(intCurrentPage, intPageSize, intTotalRows, strJSFunctionName)
{
    var numVeh = intTotalRows;
    var currentPage = intCurrentPage;
    var getPageLinksURL = "";
    var VehPerPage = intPageSize;

    var TotalPages_Count = (Math.floor(numVeh / VehPerPage)) + 1;
    if((numVeh % VehPerPage) == 0 &&  numVeh != 0){
        TotalPages_Count -= 1;
    }

    if(currentPage > 0){
        getPageLinksURL += "<a href='javascript:void(0);' onclick='" + strJSFunctionName + "(0)'>First Page</a>";
        getPageLinksURL += " | ";
        getPageLinksURL += "<a href='javascript:void(0);' onclick='" + strJSFunctionName + "(" + (currentPage - 1) + ")'>Previous</a>";
        getPageLinksURL += " | ";
    }

    var Npg, n_First, n_Last, myText;
    Npg = Math.max(0, (currentPage - 2));

    var N;
    for(N = 0; N <= 4; N++){

        if(Npg < TotalPages_Count){
            if(N != 0){
                getPageLinksURL += " | ";
            }
            n_First = (Npg * VehPerPage) + 1;
            n_Last = Math.min((n_First + VehPerPage) - 1, numVeh);
            if(n_First == n_Last){
                myText = n_First;
            }else{
                myText = n_First + " - " + n_Last;
            }

            if(currentPage == Npg){
                getPageLinksURL += myText + " of " + numVeh + " ";
            }else{
                getPageLinksURL += "<a href='javascript:void(0);' onclick='" + strJSFunctionName + "(" + Npg + ")'>" + myText + "</a>";
            }
        }
        Npg += 1;
    }

    if(currentPage != (TotalPages_Count - 1)){
        getPageLinksURL += " | ";
        getPageLinksURL += "<a href='javascript:void(0);' onclick='" + strJSFunctionName + "(" + (currentPage + 1) + ")'>Next Page</a>";
        getPageLinksURL += " | ";
        getPageLinksURL += "<a href='javascript:void(0);' onclick='" + strJSFunctionName + "(" + (TotalPages_Count - 1) + ")'>Last Page</a>";
    }
    return getPageLinksURL;   
}

function checkAllCheckBoxes(tableId){
    if (document.getElementById(tableId) != null) {
        var objInputs = document.getElementById(tableId).getElementsByTagName("input");
        for(var i=0; i<objInputs.length; i++)
        {
            if (objInputs[i].type == 'checkbox')
            {
                objInputs[i].checked = 'checked';
            }
        }
        
    }
}

function uncheckAllCheckBoxes(tableId) {
    if (document.getElementById(tableId) != null) {
        var objInputs = document.getElementById(tableId).getElementsByTagName("input");
        for(var i=0; i<objInputs.length; i++)
        {
            if (objInputs[i].type == 'checkbox')
            {
                objInputs[i].checked = '';
            }
        }
        
    }
}

function onlyNumbers(o) {
	if ( !isNaN(o.value) ){ return ; }

	var n = 0 , A, D ;
	while ( n < o.value.length ) {
		A = ( (o.value.charAt(n) >= '0' ) && (o.value.charAt(n) <= '9' ) )
		D =   (o.value.charAt(n) == '.' ) 
		if 	( A || D ) { ++n }
		else {
			if( n==0 ){ o.value = o.value.slice(n+1,o.value.length) }
			else if ( n == o.value.length) { o.value = o.value.slice(0,n-1) }
			else { 	o.value = o.value.slice(0,n) + o.value.slice(n+1,o.value.length) }
		}
		
	}
}
function onlyNumbersNoDec(o) {
	if ( !isNaN(o.value) ){
		return
	}

	var n = 0 , A, D ;
	while ( n < o.value.length ) {
		A = ( (o.value.charAt(n) >= '0' ) && (o.value.charAt(n) <= '9' ) )
		if 	( A ) { ++n }
		else {
			if( n==0 ){ o.value = o.value.slice(n+1,o.value.length) }
			else if ( n == o.value.length) { o.value = o.value.slice(0,n-1) }
			else { o.value = o.value.slice(0,n) + o.value.slice(n+1,o.value.length) }
		}
		
	}
}
function tableRowOver( obj , direction ) {
	if( direction == "1") {
		if( obj.className == "row_A") { 	obj.className = "row_A_u" }
		else if( obj.className == "row_B") { obj.className = "row_B_u" }
	}
	else if ( direction == "0") {
		if( obj.className == "row_A_u") { obj.className = "row_A" }
		else if( obj.className == "row_B_u") { obj.className = "row_B" }
	}
}

function fixRowFormating( tableID , val0 ) {
	var classValue = "row_A"
	
	for( var i = val0 ; i != document.getElementById(tableID).getElementsByTagName('tr').length ; ++i) {
		if (((document.getElementById(tableID).getElementsByTagName('tr')[i].style.display).length == 0 ) ||( (document.getElementById(tableID).getElementsByTagName('tr')[i].style.display).toLowerCase()  == "block"   )) {
			document.getElementById(tableID).getElementsByTagName('tr')[i].className = classValue
			if(classValue == "row_A") { classValue = "row_B" }
			else { classValue = "row_A" }
		}
		
	}
}

//used with 'onKeyPress' -------------
//Ex: onKeyPress="formatOnlyNumbersWithPeriod()"
function onKeyPressOnlyNumbersWithPeriod() {
    var event = AF_getEvent(window.event);
	if(event.keyCode <48 || event.keyCode>57) {
		if(event.keyCode != 46) {
			return event.returnValue = false;
		}
	}
	
}
function onKeyPressOnlyNumbers() {
    var event = AF_getEvent(window.event);
	if(event.keyCode <48 || event.keyCode>57) {
			return event.returnValue = false;
	}
	
}

function getObjOffsetPos(obj,mode) {
    var iPos = 0 ;
    while(obj.tagName != "BODY" && obj.tagName != "HTML") {
    if (mode == "L") { iPos += obj.offsetLeft; }
    else if(mode == "T") { iPos += obj.offsetTop; }
    obj = obj.offsetParent;
    }
    return iPos;
}

function clearRowsFromTable(tableID,KeeperRowNum ) {
	if ( document.getElementById(tableID) ) {
		var tbl = document.getElementById(tableID)
		var lastRow = tbl.rows.length;
		while(lastRow > KeeperRowNum) { tbl.deleteRow(lastRow - 1); lastRow = tbl.rows.length ; }
	}
}


//---------------------------------------
// Used to set the style for the new "Input.buttons"
function btn0(oThis,mode) {
	oThis.getElementsByTagName('IMG')[0].src = "/IMAGES/buttons/btn"+mode+"_L.gif"
	oThis.getElementsByTagName('IMG')[1].src = "/IMAGES/buttons/btn"+mode+"_R.gif"
	oThis.getElementsByTagName('TD')[1].className = "btn"+mode+"txt"
}


function trim(stringToTrim)
{
    stringToTrim = String(stringToTrim);
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}    	

//Check for null values for double and integer..
function checkForMinVal(val,type)
{
   if (type == "double")
   {
        if (decRound(val) == decRound(-1.7976931348623157e+308))
           val = '';
   }             
   else if (type == "int")
   {
        if (val == -2147483648)
           val = '';
   }
   else if(type == "decimal")
   {
        if (val == -7.922816251426434e+28)
            val = '';
   }        
   return val;       
}


function getDollar(value)
{
    value = value + ''
    if (value.indexOf('-') == 0)
        value = "-" + "$" + value.replace(/-/,'');
    else
        value = "$" + value;
        
    return value;
}

function getCharCount(obj){
    if(typeof obj != 'object'){ obj = document.getElementById(obj); }
    return obj.value.length;
}

function getNumeric(str){  // returns a string.
    var alpha, code, newstr = '';
    for(var i = 0; i < str.length; ++i){
        alpha = str.charAt(i);
		code = alpha.charCodeAt(0);
		if((code > 47 && code<58)){
		    newstr += alpha;
		}
    }
    return newstr;
}

function getAlphaNumeric(str){  // returns a string.
    var alpha, code, newstr = '';
    for(var i = 0; i < str.length; ++i){
        alpha = str.charAt(i);
		code = alpha.charCodeAt(0);
		if((code > 47 && code<58) || (code > 64 && code<91) || (code > 96 && code<123)){
		    newstr += alpha;
		}
    }
    return newstr;
}

function only_AlphaNumeric(o){
	var n = 0 , A, D ;
	while (n < o.value.length){
		A = ((o.value.charAt(n) >= '0' ) && (o.value.charAt(n) <= '9' ) || ((o.value.charAt(n) >= 'A') && (o.value.charAt(n) <= 'Z')) || ((o.value.charAt(n) >= 'a') && (o.value.charAt(n) <= 'z')))
		if(A){ 
		    ++n; 
		}else{
			if(n==0){ o.value = o.value.slice(n+1,o.value.length); }
			else if(n == o.value.length) { o.value = o.value.slice(0,n-1); }
			else{ o.value = o.value.slice(0,n) + o.value.slice(n+1,o.value.length); }
		}
	}
}


function SetMouseoverClass(obj, mode)
{
    if(mode == 1){
        obj.className='comboOff';
    }else if(mode == 2){ obj.className='comboOn'; }
}


//------------------------------------------------------------------------------------------------------------------------------------------------
//Layered popup call while page is getting loaded

var GE_myPopup_IsPageLoaded = false     //this variable is reset in Global_Embeded.inc.htm
var GE_myPopup_invoked_function_param = '';   //this variable would have the param which identifies the user invoked layared popup start function.

function GE_myPopup_invoke_start_function(arg)
{
    if (GE_myPopup_IsPageLoaded)
    {
        GE_processingDisplayWindow(0);
        switch (arg)
        {
            case ('Tool_NADA') :
                myPopup_Nada_Load();
                break;
            case ('Tool_Galves') :
                myPopup_Galves_Load()
                break; 
            case ('Element_Settings') :
                myPopup_Element_Settings_Open2()
                break; 
            case ('postCraigsList') :
                myPopupManageInventory_Detail_PostCraigsList(myPopup_postCraigsList_iID,myPopup_postCraigsList_days);
                break; 
            case ('DealerFeedback') :
                GE_DealerFeedback_openPopup2();
                break; 
            case ('Tool_FedExShip') :
                myPopup_Fedex_Load();
                break; 
            case ('Tool_FedExTrack') :
                myPopup_Fedex_Tracker_Load();
                break; 
            case ('NewVehicle') :
                myPopup_ManageInventory_Detail_start(0);
                break;
            case ('EditVehicle_Direct') : //Inventory -> Inventory List -> Edit
                myPopup_ManageInventory_Detail_start(inventory_MainList_InventoryId, inventory_MainList_SequenceId);
                break; 
            case ('EditVehicle_Deal') : //Deal -> Inventory List -> Edit
                inventory_GetMainList_CheckPurchaseType(inventory_MainList_InventoryId, inventory_MainList_Vin, inventory_MainList_MilesOut);
                break;
            case ('Tool_CCRecharge') :
                myPopup_CreditCard_Charge_Load();
                break;  
             case ('Deal_Stage') :
                myPopup_ManageDeal_Stage_Load1(myPopup_ManageDeal_Stage_DealID);
                break;  
            case ('Form_Print') :
				startPrintPopup_main(GE_PrintForms_mode,GE_PrintForms_ButtonID ,GE_PrintForms_oBaseValueType ,GE_PrintForms_oBaseValueID , GE_PrintForms_FormNameQuery)
                break; 
            case ('NewCustomer') :
                myPopup_ManageCustomer_Detail_Start(0); 
                break;
            case ('EditCustomer_Direct') : //Customer -> Customer List -> Edit
                myPopup_ManageCustomer_Detail_Start(Customer_MainList_CustomerId, Customer_MainList_RowId);
                break; 
            case ('EditCustomer_Deal') : //Deal -> Customer List -> Edit
                customer_GetMainList_GoToDealsPage(Customer_MainList_CustomerId);
                break;
            case ('pageLoad_DisableVendorFields') : //myPopupv2_genericVendors-main.js
                pageLoad_DisableVendorFields_Main();
                break;
        }
        GE_myPopup_invoked_function_param = '';
        //if(arg != 'EditVehicle_Direct' && arg != 'EditVehicle_Deal'){ GE_processingDisplayWindow(0); }
    }
    else
    {
        GE_myPopup_invoked_function_param = arg;
        GE_processingDisplayWindow(1);
    }
    

}

//to handle specifically for Element settings layered popup
var myPopup_Element_Settings_elementCode = '';  
function myPopup_Element_Settings_Open(elementCode)
{
    myPopup_Element_Settings_elementCode = elementCode;
    GE_myPopup_invoke_start_function('Element_Settings');
}

//to handle specifically for Craiglist link in inventory list screen
var myPopup_postCraigsList_days = '';  
var myPopup_postCraigsList_iID = '';  
function postCraigsList2(iID, days)
{
    GE_AlertWindow_3a();
    myPopup_postCraigsList_iID = iID;
    myPopup_postCraigsList_days = days;
    GE_myPopup_invoke_start_function('postCraigsList');
}

//to handle specifically for Inventory Edit link in inventory list screen
var inventory_MainList_InventoryId = '';
var inventory_MainList_SequenceId = '';
function common_inventory_MainList_EditInventory_Direct(invId, seqId)
{
    inventory_MainList_InventoryId = invId;
    inventory_MainList_SequenceId = seqId;
    GE_myPopup_invoke_start_function('EditVehicle_Direct');
}

/* to handle specifically for Inventory Edit link in inventory list screen 
for inventory selection from Deals page */
var inventory_MainList_Vin = '';
var inventory_MainList_MilesOut = '';
function common_inventory_MainList_EditInventory_Deal(invId, vin, milesOut)
{
    inventory_MainList_InventoryId = invId;
    inventory_MainList_Vin = vin;
    inventory_MainList_MilesOut = milesOut;
    GE_myPopup_invoke_start_function('EditVehicle_Deal');
}

//to handle specifically for Customer Edit link in Customer list screen
var Customer_MainList_CustomerId = '';
var Customer_MainList_RowId = '';
function common_Customer_MainList_EditCustomer_Direct(custId, rowId)
{
    Customer_MainList_CustomerId = custId;
    Customer_MainList_RowId = rowId;
    GE_myPopup_invoke_start_function('EditCustomer_Direct');
}

/* to handle specifically for Inventory Edit link in inventory list screen 
for inventory selection from Deals page */
function common_Customer_MainList_EditCustomer_Deal(custId)
{
    Customer_MainList_CustomerId = custId;
    GE_myPopup_invoke_start_function('EditCustomer_Deal');
}


/* Deal module - Deal Stage*/
var myPopup_ManageDeal_Stage_DealID = '';
function myPopup_ManageDeal_Stage_Load(id)
{
    myPopup_ManageDeal_Stage_DealID = id;
    GE_myPopup_invoke_start_function('Deal_Stage');
}


function startPrintPopup(mode,ButtonID,oBaseValueType,oBaseValueID,FormNameQuery)
{
    GE_PrintForms_mode 				= mode;
    GE_PrintForms_oBaseValueType  	= oBaseValueType;
    GE_PrintForms_oBaseValueID  	= oBaseValueID;
    GE_PrintForms_ButtonID   		= ButtonID;
    GE_PrintForms_FormNameQuery 	= FormNameQuery;
	GE_myPopup_invoke_start_function('Form_Print');
}


function pageLoad_DisableVendorFields()
{
    GE_myPopup_invoke_start_function('pageLoad_DisableVendorFields')
}



function GE_DealerFeedback_openPopup()
{
    GE_myPopup_invoke_start_function('DealerFeedback')
}
//------------------------------------------------------------------------------------------------------------------------------------------------


function CopytoClip(id)
{
    window.clipboardData.setData('Text' , $(id).value );
}