// Global JavaScript that can be at the bottom of the pages.

// Validate a zip code.
function ValidateZip(sZip)
{
    ret = false;
    
    if (sZip != null || sZip != "")
    {        
        ret = g_regexZip.test(sZip);  
    }
    
    return ret;
}

function ClearErrBkg(elm)
{
    removeCssClass(elm, "orangeBack");
}

function SetErrBkg(elm)
{
    addCssClass(elm, "orangeBack");
}

function SetDDLInnerHtml(ddlName, html)
{
    ddl = $get(ddlName);
    
    if(null == ddl)
    { return; }

    // IE has a problem replacing a dropdown inner HTML. Hence, we are manually putting the entries
    // from the HTML string into the dropdown.
    if($get('hiddenIE'))
    {
        ddl.options.length = 0;
     
        /* This loses the handlers on the drop down.   
        ddl.outerHTML = ddl.outerHTML.replace(/>\s*</g, ">" + html + "<");
        */

		var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
		xmlDoc.async = false;
		xmlDoc.loadXML("<list>" + html + "</list>");
		var root = xmlDoc.documentElement;
        
        while (root.hasChildNodes())
		{	
			objNode = root.firstChild;

			var oOption = document.createElement("OPTION");
			ddl.options.add(oOption);
			oOption.innerText = objNode.text;
			if(null != objNode.selectSingleNode("@value"))
			{
    			oOption.value = objNode.selectSingleNode("@value").text;	
    	    }

			root.removeChild(root.firstChild);
		}

    }
    
    else
    {
        ddl.innerHTML = html;
    }
}

// Select an item in a drop down list matching the item value not the displayed text
function fnSetDDLByValue(ddlName, strValue) 
{
    var retValue = false;
	var objList = $get(ddlName);

    // This assumes the first entry is a place holder or label that we can
    // default to.
	objList.selectedIndex=0;

	if ("" != strValue)
	{
		for (i=0;i<=objList.options.length-1;i++)
		{
			if (objList.options[i].value==strValue) 
			{
				objList.selectedIndex=i;
				retValue = true;
				break;
			}
		}
	}
	
	return retValue;
}

function showAlertBackground()
{
        hideDropDownVarList();
        showDIV('alertBackground');
}

function hideAlertBackground()
{
        hideDIV('alertBackground');
        showDropDownVarList();
}

function showDropDownVarList()
{
    if('undefined' != typeof(dropDownVarList))
    { showHideDropDowns('visible', dropDownVarList); }
}

function hideDropDownVarList()
{
    if('undefined' != typeof(dropDownVarList))
    { showHideDropDowns('hidden', dropDownVarList); }
}

function showHideDropDowns(tmpvar, dropDownVarList)
{
    if(dropDownVarList)
    {
        for (i=0; i<dropDownVarList.length; i++)
        {                 
            $get(dropDownVarList[i]).style.visibility = tmpvar;
        }
    }
}

function showHideDropDownsNew(tmpvar, dropDownVarList)
{
    var ddList = document.getElementsByTagName("select");
    var parentEx = $get('advancedSearch');

    for (i=0; i<ddList.length; i++)
    {  
        if(parentEx && (null == $get(ddList[i].id, parentEx)))
        {               
            ddList[i].style.display = tmpvar;
        }
    }    
}

function setPopupDivPosition(divName)
{
    //get the height of the user's browser window
    myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        myHeight = document.body.clientHeight;
    }
    //get the scroll position
    scrollY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        scrollY = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )         {
        scrollY = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        scrollY = document.documentElement.scrollTop;
    }
    
    divElm = $get(divName);
    var divBnds = Sys.UI.DomElement.getBounds(divElm);
    
    //set the top position of the popup to be at mid screen based on user's scroll position
    if ((((myHeight/2) - (divBnds.height/2)) + scrollY) > 0)
    {
        divElm.style.top = ((myHeight/2) - (divBnds.height/2)) + scrollY + "px";
    }
    else
    {
        divElm.style.top = "0px";
    }
}

function toggleLayer( whichLayer )
{  
    var elem, vis;  
     if( document.getElementById )
         elem = $get( whichLayer );  
     else if( document.all ) 
         elem = document.all[whichLayer]; 
     else if( document.layers ) 
         elem = document.layers[whichLayer];  
         
    vis = elem.style;  
    if(vis.display=='' && elem.offsetWidth!=undefined && elem.offsetHeight!=undefined)    
    {
       vis.display = (elemoffset.Width!=0&&elem.offsetHeight!=0)?'block':'none';   
    }   
       vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}   

function toggleDisabled(el) 
{
    try {
        el.disabled = el.disabled ? false : true;
    }
    catch(E){}
    
    if (el.childNodes && el.childNodes.length > 0) {
        for (var x = 0; x < el.childNodes.length; x++) {
            toggleDisabled(el.childNodes[x]);
        }
    }
}  

// Start header image search functions.
var hdrSearchLF = null;
function HeaderVehSearch(path, qstring, sZip, make, model)
{
    if(null == hdrSearchLF)
    {
        hdrSearchLF = new LinkFactory();
    }
    // Save the URL so we know what one to use if the Zip Prompt is needed.
    hdrSearchLF._path = path;
    hdrSearchLF._qstring = qstring;
    
    if(ValidateZip(sZip))
    {
        HeaderVehSearchExec(sZip);
    }
    else
    {
        // We don't have a zip, prompt for it.
        var modelName = make + " " + model
        zipPromptVar.Open(modelName, HeaderVehSearchExec);
    }
    
}

// Execute the actual search after possible prompt for a zip.
function HeaderVehSearchExec(sZip)
{   
    // Insert the correct zip & distance into the URL.
    hdrSearchLF.ReplaceToken("xZIPx", sZip);
    
    fnNavToSearchResults(hdrSearchLF.FinalizeUrl());
}
// End header image search functions.

// Start navigation functions.
function navigateTo(destPage)
{
  if ($get('hiddenIE6'))
  {
    SideBar_RedirectUrl = destPage;
    setTimeout( "window.location.href = SideBar_RedirectUrl", 0 );
  }
  else
  {
     window.location.href = destPage;
  }

  return false;
}

function fnNavToSearchResults(url)
{
    fnShowSearchingProgress();
    
    navigateTo(url);
}

function fnShowSearchingProgress()
{
    // Get the background div for the searching progress div.
    var elt = $get("divSearching");
    // Try to posisition & size the bkg so that it covers the content area of the master page.
    var bounds = Sys.UI.DomElement.getBounds(elt.parentNode);
    var x = 2;//bounds.x;
    var y = bounds.y;
    Sys.UI.DomElement.setLocation(elt, x, y);
    elt.style.width  = "975px"; // bounds.width + 'px';
    elt.style.height  = bounds.height + 'px';

    hideDropDownVarList();
    showDIV('divSearching');
    showDIV('searchingSmall');
    LoadSwf();
}

function fnHideSearchingProgress()
{
    hideDIV('searchingSmall');
    hideDIV('divSearching');
    showDropDownVarList();
}

function openFooterLink(pathURL, pageTitle, pageWidth, pageHeight, scrollyn)
{
    window.open(pathURL,pageTitle,'width=' + pageWidth + ',height=' + pageHeight + ',resizable=yes,scrollbars=' + scrollyn + ',toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=100,top=100,screenX=100,screenY=100,modal=yes');
}

function openRegister(regUrl)
{
  var tempUrl = regUrl;
  window.open(tempUrl,'Register','width=800,height=750,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=0,top=100,screenX=0,screenY=100,modal=yes');
}

function openPrint(regUrl)
{
  var tempUrl = regUrl;
  if ((null == tempUrl) ||(!tempUrl))
     tempUrl = printUrl;
     
  window.open(tempUrl,'Print','width=730,height=600,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=0,top=100,screenX=0,screenY=100,modal=yes');
}

function openDirections(mapPointUrl)
{
  var tempUrl = mapPointUrl;
  if ((null == mapPointUrl) ||(!mapPointUrl))
     tempUrl = mapPointUrl;
     
  window.open(tempUrl,'Map','width=780,height=760,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=0,top=100,screenX=0,screenY=100,modal=yes');
}
// End navigation functions.

// Start helpers for maping enter key to button press action.
function mapKeyToAction(evt)
{
    var targ;
    var retValue = false;
    var isReturn = false;
    
    // evt is a Sys.UI.DomEvent object
    if(evt && evt.charCode ==  13)
    {
        isReturn = true;
    }
    else if (window.event && window.event.keyCode == 13)
    { 
        evt = window.event;
        isReturn = true;
    }
    
    if(isReturn)
    {
        // Find the target of the event
	    if (evt.target) 
	        targ = evt.target;
	    else if (evt.srcElement) 
	        targ = evt.srcElement;
    	    
	    if (targ.nodeType == 3) // defeat Safari bug
		    targ = targ.parentNode;
    	
    	// Now check if the enter key should trigger the "form action" for the target.	
	    var tagName = targ.tagName.toUpperCase();
    		
	    if (tagName == "TEXTAREA")
	    {
	        retValue = false;
	    }
	    else if (tagName == "SELECT")
	    {
	        // When the the target is a drop down, only map the enter key to an action if
	        // the  DD has a ddlMapEnter attribute set to true.
	        if(('undefined' != typeof(targ.ddlMapEnter)) && targ.ddlMapEnter)
	        {
	            retValue = true;
	        }
	        else
	        {
	            retValue = false;
	        }
	    }
	    else
	    {
	        retValue = true;
	    }
	    
	    // set value of "enterPress" based upon browser
	    var userBrow = getUserBrowser();
	    if (userBrow == 'Chrome' || userBrow == 'Safari')
	    {
	        enterPress = true;
	    }
	}
	
	return retValue;
}

// For drop down (<select>) elements that do want to trigger an action on the enter key.
// If they don't want the enter key to trigger an action if the enter key is being used
// to change selection, this function should be called for (or as part of) the onchange
// event processing.
function DDLMapEnter_OnChange(ddl)
{
    ddl.ddlMapEnter = false;
    setTimeout("$get('" + ddl.id + "').ddlMapEnter = true;",200);
}

function getUserBrowser()
{
    return Sys.Browser.name;
}

function setEnterPress()
{
    var userBrow = getUserBrowser();
    if (userBrow == 'Opera')
    {
        enterPress = true;
    }
}

function setFixValidation()
{
    var userBrow = getUserBrowser();
    if (userBrow == 'Firefox' || userBrow == 'Opera')
    {
        fixValidation = true;
    }
}
// End helpers for maping enter key to button press action.


// Logout functions
function ReyLogout(uid)
{  
//   el = $get("progressAnimation");
//   if (el && null != el)
//   {
//     el.className = 'hide'; 
//   }
    
   Reynolds.CL.Web.WebServices.LoginFunctions.Logout(LogoutSuccess, LogoutFailure, uid);
}

// User was successfully logged out.
function LogoutSuccess(result, eventArgs)
{
    ReloadPage();
} 

function ReloadPage()
{
    try {
        if(typeof(Page_OnLogoutComplete) == 'function')
        {
            // If the page has something to do on logout, do that. (Profile page redirect to Home)
            Page_OnLogoutComplete();
        }
        else
        {
            // In general, reset the href to refresh the screen.
            var index = window.location.href.indexOf('#');
            var len = window.location.href.length;
            if (index > 0)
            {
                window.location.href = window.location.href.substr(0,index);
            }
            else
            {
                window.location = window.location;
            }
        }
    }
    catch(E){}
}

// User logout failed.
function LogoutFailure(err)
{
    alert(err.get_message());
}

// Refresh the login area. 
// This is called from the Login control and the register page. 
function Master_RefreshLoginArea()
{
    try {
        if(typeof(Page_OnLoginComplete) == 'function')
        {
            Page_OnLoginComplete();
        }
    }
    catch(E){}
    
    $get(btnRefreshLoginAreaId).click();
}

function fnTrim(str) 
{
	return String(str).replace(/^\s+/g, '').replace(/\s+$/g, '');
}

// START - functions to populate Make drop down.
function PopulateMakes(makeListId, modelListId, includeNew, includeUsed, includeCert, preserveSelections)
{
    $get(makeListId).disabled = true;
    $get(modelListId).disabled = true;

    var context = new Object();
    context.makeListId = makeListId;
    context.modelListId = modelListId;
    context.preserveSelections = preserveSelections;
    
    if(preserveSelections)
    {
        context.makeListValue = $get(makeListId).value;
        context.modelListValue = $get(modelListId).value;
        context.includeNew = includeNew;
        context.includeUsed = includeUsed;
        context.includeCert = includeCert;
    }
    
    
    Reynolds.CL.Web.WebServices.VehicleFunctions.GetMakeDDList(
        WSKey, includeNew, includeUsed, includeCert,
        GetMakesSuccess, 
        GetMakesFailure, context);
}

// Makes drop down list successfully received from web service.
function GetMakesSuccess(result, context)
{
    SetDDLInnerHtml(context.makeListId, result);
    
    $get(context.makeListId).disabled = false;
    $get(context.modelListId).disabled = false;
    
    if(context.preserveSelections)
    {
        fnSetDDLByValue(context.makeListId, context.makeListValue);
        PopulateModels(context.makeListId, context.modelListId, context.includeNew, context.includeUsed, context.includeCert, true);
    }
} 

// Failure trying to makes drop down list from web service.
function GetMakesFailure(err, context)
{
    alert(err.get_message());
    
    $get(context.makeListId).innerHTML = "";
    $get(context.makeListId).disabled = false;
    $get(context.modelListId).innerHTML = "";
    $get(context.modelListId).disabled = false;
}
// END - functions to populate Make drop down.

// START - functions to populate a Model drop down when a selection is made in a Make drop down.
function PopulateModels(makeListId, modelListId, includeNew, includeUsed, includeCert, preserveSelections)
{  
    var context = new Object();
    context.modelListId = modelListId;
    context.preserveSelections = preserveSelections;
    
    if(preserveSelections)
    {
        context.modelListValue = $get(modelListId).value;
    }
    
    // Mark the drop down as "Loading".    
//    SetDDLInnerHtml(modelListId, "<option>[Loading...]</option>");
    $get(modelListId).disabled = true;

    if((0 < $get(makeListId).value.length) && (0 < $get(makeListId).value))
    {
        Reynolds.CL.Web.WebServices.VehicleFunctions.GetModelDDList(
            $get(makeListId).value, WSKey, includeNew, includeUsed, includeCert,
            GetModelsSuccess, 
            GetModelsFailure, context);
    }
    else
    {
        SetDDLInnerHtml(modelListId, "");
    }
} 

// Models drop down list successfully received from web service.
function GetModelsSuccess(result, context)
{
    SetDDLInnerHtml(context.modelListId, result);
    $get(context.modelListId).disabled = false;

    if(context.preserveSelections)
    {
        fnSetDDLByValue(context.modelListId, context.modelListValue);
    }
} 

// Failure trying to models drop down list from web service.
function GetModelsFailure(err, context)
{
    alert(err.get_message());
    
    $get(context.modelListId).innerHTML = "";
    $get(context.modelListId).disabled = false;
}
// END - functions to populate a Model drop down when a selection is made in a Make drop down.

