// Global JavaScript that can be at the bottom of the pages.

// The register page calls this to refresh the login control when a user registers.
function doLoginRefresh()
{
    try {
        if(typeof(Page_OnLoginComplete) == 'function')
        {
            Page_OnLoginComplete();
        }
    }
    catch(E){}
    
    doPostBackAsync(login1UniqueIdVar);
}

// Validate a zip code.
function ValidateZip(sZip)
{
    ret = false;
    
    if (sZip != null || sZip != "")
    {        
        ret = g_regexZip.test(sZip);  
    }
    
    return ret;
}

function SetDDLInnerHtml(ddlName, html)
{
    ddl = $get(ddlName);
    
    if(null == ddl)
    { return; }

    // IE has a problem replacing a dropdown inner HTML. Hence, we are copying the outer HTML
    // so we can replace the whole thing.
    if($get('hiddenIE'))
    {
//        ddl.innerHTML = "";
        ddl.options.length = 0;
        var ddlModelOuter = ddl.outerHTML;
        ddl.outerHTML = ddlModelOuter.replace("><", ">" + html + "<");
    }
    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 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]);
        }
    }
}  

function showInfo(mess)
{
    var el;
    el = $get("messagediv");
    if (el && null != el)
    {
        el.innerHTML = mess;
        if (mess != '')
        {
            removeCssClass(el, "hide");
        }
        else
        {
            addCssClass(el, "hide");
        }
    }
}

// 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=650,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)
{
    doPostBackAsync(eventArgs);
} 

// User logout failed.
function LogoutFailure(err)
{
    alert(err.get_message());
}



