/* Utility Javascript functions common across pages
 *  $Author:  Rick Critchett
 *  $Date: 11-Sep-03
 */
 
// Initialization
// Browser determination
var bName = navigator.appName;
var agt = navigator.userAgent.toLowerCase();
var NS = (bName == "Netscape");
var IE = (bName == "Microsoft Internet Explorer");
var IE5x = (agt.indexOf("msie 5") != -1);
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.
var IESP2 = (agt.indexOf("sv1") != -1); // IE with Service Pack 2
var isMac = (agt.indexOf('mac') != -1);
var isMacIE5x = (isMac && IE5x);

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;

// global var to track currently enlarged photo when choosePhoto(n) is called
// this var is passed to the multi photo popup which autoscrolls to the corresponding pic
var lastChosenPhotoIndex = 0;

/*
 * 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;
var appendNAV = false;
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;";
            if (appendNAV) {
               caption += "(Not Actual Vehicle)";
            }
        }
        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,w,h)
{
    var imgRef = eval(docRef + chosenPhotoIMGobjectName);
    if (null != imgRef && n < document.chosenPhotos.length)
    {
        imgRef.src = document.chosenPhotos[n].src;
        if(w){
           if(document.chosenPhotos[n].width > w) {
              imgRef.width = w
           }
        }
        updateChosenPhotoCaption(n);
        highlightPhoto('tnImg' + n);
    }    
    lastChosenPhotoIndex = 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 emailFieldName = "";
   if (emailAddressElement.name == 'sender') emailFieldName = 'From'; else if (emailAddressElement.name == 'recip') emailFieldName = 'To'; else if (emailAddressElement.name == 'cc') emailFieldName = 'CC';
   var errorMessage = 'Make sure the email address in the \"' + emailFieldName + '\" field is entered in the proper format, \nsuch as \"user@domainname.com\". There is a limit of one email address per field.'
   if (emailAddressElement.value==""){
      alert(emailAddressErrorMessage);
      emailAddressElement.focus();
      return false;
   } 
   else if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1) || (wwwdot != -1)) {  
      if (emailAddressElement.name == "sender" || emailAddressElement.name == "recip") {
	  	alert(emailAddressErrorMessage);
	  }
	  else {
	  	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.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);
        if (null != popupWin) 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.name == "popup")
    {
        //window.properties = properties;
        if (null != url) location.href = url;
        resizeOuterTo(667,636)
    }
    else
    {
        openPopup(url,"mediapopup","width=655,height=605,left=50,top=50,scrollbars,resizable");
    }
}
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.name == "popup")
    {
        //window.properties = properties;
        if (null != url) location.href = url;
        window.resizeTo(795, 695);
    }
    else
    {
        openPopup(url,"mediapopup","width=795,height=695,left=50,top=50,scrollbars=yes,resizable=yes");
    }
    
}

function openVideoGallery(url){
	var popupName = "videopopup";
	if(location.href.indexOf('photogallery')!=-1) var popupName = window.name;
	openPopup(url,popupName,"width=740,height=600,left=50,top=50,scrollbars=no,resizable=yes");
}

/* motorweek videos */
function openMotorweek(url){
    openPopup(url,"motorweekPopUp","width=385,height=289,left=50,top=50,scrollbars,resizable");
}



/* 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=880,height=700,left=50,top=50,scrollbars");
    //openGallery(url); rwc took out 3-9-04
	//previous dimensions: width=620,height=495
}
/* openPhoto2
 * opens popup to display a large photo: used in the case of Stock photo, the window isn't as large as the IOTF window above
 */
function openPhotoSmall(url){
    openPopup(url, "largephoto","width=675,height=700,left=50,top=50,scrollbars");
    //openGallery(url); rwc took out 3-9-04
	//previous dimensions: width=620,height=495
}


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("/go/configurator/explainer.jsp","wndDisclaimer","height=385,width=450,left=170,top=20,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbar=no");
}

/* Taken from model reports */
function loadResidual(url){
    openPopup(url,"residualValues","width=550,height=500,left=50,top=50,resizable,scrollbars");
}


function openMain (URL) { 
   openURL = URL; 
   if (top.opener){
      if (top.opener.closed) {
         var newMain = window.open(URL,'');   
         top.opener = newMain; 
      } 
      else {  
         top.opener.top.location = URL;
         top.opener = top.opener.top;
      }         
   } 
   else {
      var newMain = window.open(URL,'');   
      top.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)
}

/*Ensure that the window resizes the same in netscape and IE*/
function resizeOuterTo(w,h) {
 if (parseInt(navigator.appVersion)>3) {
   if (navigator.appName=="Netscape") {
    top.outerWidth=w;
    top.outerHeight=h;
   }
   else top.resizeTo(w,h);
 }
}

/*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;
}

/*Find the value of cookie named cookieName*/
function getCookie(cookieName) {
   var cookieValue = "";
   var allCookies = document.cookie;
   var cookiePosition = allCookies.indexOf(cookieName + '=');   
   if(cookiePosition != -1){
      var valueStart = cookiePosition + cookieName.length + 1;
      var valueEnd = allCookies.indexOf(';', valueStart);
      if(valueEnd == -1) {
         valueEnd = allCookies.length;
      }
      cookieValue = allCookies.substring(valueStart, valueEnd);
      cookieValue = unescape(cookieValue);
   }
   return cookieValue
}

/*Set the value of cookie with cookieName, CookieValue)*/
function setCookie(cookieName, cookieValue) {
   document.cookie = cookieName + "=" + escape(cookieValue);
}


function parseQueryString(){
   var query = location.search.substring(1);
   var paramPairs = query.split('&');
   var params = new Array();
   for(i=0; i<paramPairs.length; i++){
      var result = paramPairs[i].match(/(.+)\=(.+)/);
      if(result){               
         if(result.length == 3){
            params[result[1]] = result[2];
         }
      }
   }
   return params;
}





