/* Utility Javascript functions common across pages
 *  $Author:  Rick Critchett
 *  $Date: 11-Sep-03
 */

// Initialization
//
var isCS = false;
var isInUpgradePath = false;
// Browser determination
var bName = navigator.appName;
var NS = (bName == "Netscape");
var IE = (bName == "Microsoft Internet Explorer");
var bVer = parseInt(navigator.appVersion);
var NS4 = (NS && bVer < 5);
var NS6 = (NS && bVer >= 5);
// rwc: 15-Sep-03. the above works!  Use these vars.
// kgh: 27-Aug-04. IESP2 indicates IE with Service Pack 2
var IESP2 = (window.navigator.userAgent.indexOf("SV1") != -1);

var winVar = null;
var actionVar;
// Global reference variables
var docRef = "document.";
if(NS4)  docRef = "document.";
if(NS6)  docRef = "document.";
if(IE)  docRef = "document.all.";

//Netscape seems to need these document array initialized here and not lazily
document.preloadArray = new Array();
document.chosenPhotos = new Array();
chosenCaptions = new Array();
var chosenPhotoIMGobjectName = "chosenPhotoIMG";
var chosenPhotoDIVobjectName = "chosenPhotoCaption";
// Vehicle information
var currMake = null;
var currModel = null;

/*
 * swapImage FUNCTION
 * @param refName name of the IMG object
 * @param imgName name of the image-not a complete filename
 * @param imgState desired state of the image-used to complete filename
 */
function swapImage(refName,imgName,imgState)
{
    var imgRef = eval(docRef + refName);
    imgRef.src = "images/" + imgName + imgState + ".gif";
}

/*
 * preloadImages FUNCTION
 * General functions for preloading a set of images
 *
 */
function preloadImages()
{
    if (document.images)
    {
        var imgFiles = preloadImages.arguments;
        if (document.preloadArray==null)
            document.preloadArray = new Array();
        var i = document.preloadArray.length;
        with (document) for (var j=0; j<imgFiles.length; j++)
            if (imgFiles[j].charAt(0)!="#")
            {
                preloadArray[i] = new Image;
                preloadArray[i++].src = imgFiles[j];
            }
    }
}


/*
 * preloadChosenPhoto FUNCTION
 * @param imageFile an image filename to put into the chosenPhotos array of Image objects
   example: preloadChosenPhoto('/stock/386x258/225885.jpg');
*/
function preloadChosenPhoto(imageFile, caption)
{
  if (document.images)
  {
    if (document.chosenPhotos==null)
    {
        document.chosenPhotos = new Array();
    }
    var p = document.chosenPhotos.length;

    if (imageFile.charAt(0)!="#")
    {
        document.chosenPhotos[p] = new Image;
        document.chosenPhotos[p].src = imageFile;
        chosenCaptions[p] = caption;
    }
  }
}

/*
 * getPhotoCaption(index)
 * @param index which photo of the list 
 *
 */
var shownRegExp = new RegExp(" shown", "i");
var appendShown = true;
function getPhotoCaption(index)
{
    if (index < chosenCaptions.length && null != chosenCaptions[index])
    {
        var caption = chosenCaptions[index];
        caption = caption.replace(shownRegExp, '');
        if (null == caption || "" == caption.replace(/ /g, ""))
        {
            caption = chosenPhotoDIVobjectText;  // reset to default
        }
        else if (appendShown)
        {
            /* only append shown if caption not empty */
            caption += " shown&nbsp;";
        }
        return caption;
    }
}

/*
 * choosePhoto FUNCTION
 * Put the cached image at index 'n' as Chosen Image
 * Uses chosenPhotos variable of large vehicle Image objects and
 * "chosenPhotoIMG" IMG object
 * With highlighting of thumbnail as chosen, use convention that the
 * thumbnail images are named tnImgX where X is passed "n".
 * @param n index into chosenPhotos array of Image objects
*/
function choosePhoto(n)
{
    var imgRef = eval(docRef + chosenPhotoIMGobjectName);
    if (null != imgRef && n < document.chosenPhotos.length)
    {
        imgRef.src = document.chosenPhotos[n].src;
        updateChosenPhotoCaption(n);
        imgRef.className = "photo";
        //imgRef.border = 2;
        highlightPhoto('tnImg' + n);
    }
}

/*
 * highlightPhoto FUNCTION
 * Reference the given image object and change its class so it is highlighted.
 * Must keep a state of currently highlighted image to reset the previous.
 * @param imgName name of image object to highlight
*/
var highlightedPhoto = null;
function highlightPhoto(imgName)
{
    var imgRef = eval(docRef + imgName);
    if (null != imgRef)
    {
        if (null != highlightedPhoto){
            highlightedPhoto.className = "photo";
            highlightedPhoto.width=66;
            highlightedPhoto.height=44;
        }
        imgRef.className = "photoHighlight";
        imgRef.width=59;
        imgRef.height=38;
        highlightedPhoto = imgRef;
    }
}

/* updateChosenPhotoCaption
 * Attempt to update the caption for the Chosen Photo
 * using the rules shown, assets shown below.
 * @param n index into all the photos and their assets
 */
var chosenPhotoDIVobjectText = null;
function updateChosenPhotoCaption(n)
{
    var divRef = null;
    // Find DIV reference first
    if (IE || NS4)
    {
        divRef = eval(docRef + chosenPhotoDIVobjectName);
    }
    else
    {
        divRef = document.getElementById(chosenPhotoDIVobjectName);
    }

    // Then set its text 
    if (null != divRef)
    {
        // Set the default caption from first time thru
        if (null == chosenPhotoDIVobjectText)
        {
            chosenPhotoDIVobjectText = divRef.innerHTML;
        }

        var caption = getPhotoCaption(n, chosenPhotoDIVobjectText);
        if (null == caption || "" == caption.replace(/ /g, ""))
        {
            divRef.innerHTML = chosenPhotoDIVobjectText;  // reset to default
        }
        else
        {
            divRef.innerHTML = caption;
        }
            
    }
}


/*
 * imageInfoWindow
 * Simple new window with text placed inside.
 * @param contents text contents for the window
 * @param imgSrc URL to an image relating to the text contents
 */
function imageInfoWindow(contents, imgSrc)
{
    newWindow = window.open("", "information",
        "toolbar=yes, location=yes, scrollbars=yes, resizable=yes, height=800, width=400");
    newWindow.document.writeln("<html><head><title>"+imgSrc+"</title></head><body>");
    if (null != imgSrc && "" != imgSrc) newWindow.document.writeln("<img src='"+imgSrc+"'><br>");
    newWindow.document.write(contents);
    newWindow.document.writeln("</body></html>");
    newWindow.document.close();
    newWindow.focus();
}

/*
 * replaceChars
 * Simple function wrapper to the String.replace() function.
 *
 */
function replaceChars(str, regexp, replacement)
{
    newstr = "";
    if (str != null)
    {
        newstr = str.replace(regexp, replacement);
    }
    return newstr;
}

/**   checkEmailAddress Function
 *    this function checks the email address to ensure it is not 
 *    blank and that it is in the correct format
 *    @param emailAddressElement       the email address form element that you want to check
 *    @param emailAddressErrorMessage  the error message to throw if the email is incorrect
 */
function checkEmail(emailAddressElement, emailAddressErrorMessage) {
   var AtSym=emailAddressElement.value.indexOf('@');
   var Period=emailAddressElement.value.lastIndexOf('.');
   var Space=emailAddressElement.value.indexOf(' ');
   var wwwdot=emailAddressElement.value.indexOf('www.');
   var Length=emailAddressElement.value.length - 1;  
   var errorMessage = 'The e-mail address \"' + emailAddressElement.value + '\" appears to have errors in it. Please check to make sure you have entered it correctly.'
   if (emailAddressElement.value==""){
      alert(emailAddressErrorMessage);
      emailAddressElement.focus();
      return false;
   } 
   else if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1) || (wwwdot != -1)) {  
      alert(errorMessage);
      emailAddressElement.focus();
      return false;
   }
   return true;
}



/*
 * setMainURLwClose
 * Go back to main window and set its location URL
 */
function setMainURLwClose(newURL)
{    
    // Stay within this window if now opener/parent window

    if ((window.opener == null)||(top.window.opener.name=="videopopup"))
    {
        location.href = newURL;
    }
    else
    {
        // Get the window opener and set its location
        window.opener.location.href = newURL;
        window.opener.focus();
        window.window.close();
    }
}




/*
 * setMainURL
 * Go back to main window and set its location URL
 */
function setMainURL(newURL)
{    
    // Stay within this window if now opener/parent window

    //if ((window.opener == null)||(top.window.opener.name=="videopopup"))
    //{
        location.href = newURL;
    //}
    //else
    //{
        // Get the window opener and set its location
    //    window.opener.location.href = newURL;
    //    window.opener.focus();
    //    window.window.close();
    //}
}

/* *
 * buildVehicle
 * Opens the builder page from a popup.
 * Requires that this be called from a popup AND that the main window
 * has a form called 'quote'.
 */
function buildVehicle(){
    opener.document.forms['quote'].submit();
    self.close();
}

/*
 * openPopup
 * Opens a new window with given URL, name and properties.
 * @param url which page to display in the new window.
 * @param name name of the new window
 * @param properties string of properties
 */
function openPopup(url, name, properties)
{
    if (null != url)
    {
        var popupWin = window.open(url, name, properties);
  		popupWin.focus();
    }
}

/* open Panorama popup
   can be used as a resizer if null is passed in. 
   Gallery and Ipix share the same window.
   */
function openPanorama(url){
    if (null == url || window.name == "mediapopup")
    {
        //window.properties = properties;
        if (null != url) location.href = url;
        window.resizeTo(650, 510);
    }
    else
    {
        openPopup(url,"mediapopup","width=650,height=510,left=50,top=50,scrollbars=yes");
    }
}
function openIpix(url){
    openPanorama(url);
}


/* open Gallery popup
   can be used as a resizer if null is passed in. */
function openGallery(url){
    if (window.name == "mediapopup")
    {
        //window.properties = properties;
        if (null != url) location.href = url;
        window.resizeTo(562, 685);
    }
    else
    {
        openPopup(url,"mediapopup","width=562,height=685,left=50,top=50,scrollbars=yes,resizable=yes");
    }
    
}

/* Taken from model reports */
function openPopupSmall(url){
    openPopup(url,"smallPopUp","width=385,height=289,left=50,top=50,scrollbars,resizable");
}

/* Taken from model reports */
function openPopupTall(url){
    openPopup(url,"tallPopUp","width=385,height=480,left=50,top=50,scrollbars,resizable");
}

/* Taken from model reports */
function openWarranty(url){
    openPopup(url,"warrantyPop","width=385,height=300,left=50,top=50");
}

/* Taken from model reports */
function openCompare(url){
    openPopup(url,"compPopUp","width=640,height=480,left=50,top=50,scrollbars,resizable");
}

/* Taken from model reports */
function openTrim(url)
{
    openPopup(url, "trimlistPop","width=590,height=400,left=200,top=200,scrollbars,resizable");
}

/* Taken from model reports */
function openPrint(url){
    openPopup(url, "printlist","width=385,height=375,left=200,top=200,scrollbars,resizable");
}

/* openPhoto
 * opens popup to display a large photo.
 */
function openPhoto(url){
    openPopup(url, "largephoto","width=620,height=495,left=50,top=50,scrollbars");
    //openGallery(url); rwc took out 3-9-04
}


function openJDP(url){
	openPopup(url, "popup-jdp","width=590,height=400,left=200,top=200,toolbar=no,menubar=no,location=no");
}

/* Taken from model reports */
function loadDisclaimer() {               openPopup("http://newcars.cars.com/disclaimer/disclaimer_brief.html","wndDisclaimer","height=475,width=300,status=yes,toolbar=no,menubar=no,location=no");
}

/* Taken from model reports */
function loadResidual(url){
    openPopup(url,"residualValues","width=550,height=500,left=50,top=50,resizable,scrollbars");
}
/* Open a link in them main window if in a popup */
function openMain (URL) {
       openURL = URL;
       
       if (window.opener){
       
          if (window.opener.closed) {
             var newMain = window.open(URL,'');   
             window.opener = newMain;           
          }  
          else {      
             window.opener.location = URL;
          } 
      } else {
          var newMain = window.open(URL,'');   
          window.opener = newMain;
       } 
    }  

/*Strip whitespace from a string*/
var whitespace = " \t\n\r";

function stripCharsInBag (s, bag){   
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function stripWhitespace (s){   
   return stripCharsInBag (s, whitespace)
}

function trimLeadTrail(strText) {
strText = stripCharsInBag(strText, "\t\n\r");
	while (strText.substring(0,1) == ' ') 
	        strText = strText.substring(1, strText.length);
	while (strText.substring(strText.length-1,strText.length) == ' ')
	        strText = strText.substring(0, strText.length-1);
	return strText;
	}

/*Find the value of the selected option in a select list*/
function findSelectedValue(field){
   var selected = "";
   for(var i=0; i < field.length; i++) {
      if(field.options[i].selected == true) {
         selected=field.options[i].value;
         break;
      }
   }
   return selected;
}

function checkEnter(event)
{ 	
	var code = 0;	
	if (NS4)
		code = event.which;
	else
		code = event.keyCode;
	return code;
}



function popUp(url,winName,features){
	popWin=window.open(url,winName,features);
	popWin.focus();
}

		function getCookie(name) {
			var dc = document.cookie;
		  	var prefix = name + "=";
		  	var begin = dc.indexOf("; " + prefix);
		  	
		  	if (begin == -1) {
		    	begin = dc.indexOf(prefix);
			    if (begin != 0) return null;
			} else
		    	begin += 2;
			  var end = document.cookie.indexOf(";", begin);
			  
			if (end == -1)
		    end = dc.length;
		  	return unescape(dc.substring(begin + prefix.length, end));
		}
		
	
function writeAdCookie(adId){

	var expiration_date = new Date("January 1, 3000");
	var expiration_date = expiration_date.toGMTString();

	var adsList = '';
	var updated = false;


		// if we have a cookie already
		if(getCookie('lastFive') != null){
				
			currentList = getCookie('lastFive');
			
			if(currentList.indexOf(adId) == -1){
				splitList = currentList.split('|',4);
				adsList = '';
				for (i=0; i<splitList.length; i++) {
					// Collect maximum previous 4 AdIds
					if (splitList[i].length > 0) {
						adsList = adsList + splitList[i] +'|';
					}
				}
				adsList = adId + '|' +adsList; // Prepend new AdId
				updated = true;
			}
/* Old way
			if(currentList.indexOf(adId) == -1){
				adsList = adId + '|' + currentList.substring(0,31);
				updated = true;
			}
*/			
		}else{
			//if we do not have a cookie at all
			adsList = adId + '|';
/* Old way
			adsList = adId;
			adsList += '|0000000|0000000|0000000|0000000';
*/
			updated = true;			
		}//else
		if (updated){document.cookie = "lastFive=" + adsList + "; path=/; expires=" + expiration_date;} }

	
	