/* 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 show(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)
{
//  alert("swapImage RefName:"+refName+" imgName:"+imgName+" imgState:"+imgState);
	var imgRef = eval(docRef + refName);
    imgRef.src = "images/" + imgName + imgState + ".gif";


//newpic = '<img id=chosenPhotoIMG src="./photos/cars/'+d+i+p+'.jpg" name=chosenPhotoIMG>'
//document.getElementById("mainpic").innerHTML= newpic;


}

/*
 * 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] ;
                preloadArray[i++].src = imgFiles[j];
            }
    }
}



function DeletePhoto(p)
{
var x;
var xp1;

//alert("in DeletePhoto for "+p);

 try
 {
  if (document.images)
  {
    if (document.chosenPhotos!=null && document.chosenPhotos.length>0)
    {
   if(p<document.chosenPhotos.length) show(p);
if(p<document.chosenPhotos.length)
	{
	for(x=p-1;x<document.chosenPhotos.length-1;x++) 
		{
		    xp1=x + 1;
			document.chosenPhotos[x].src = document.chosenPhotos[xp1].src;
		}
	}
	}
  }
   var photosf = document.getElementById('rfields[photos]');
   photosf.value = photosf.value - 1;
 }
 catch (error)
 {
document.write(error.description);
 }


}





/*
 * ScanPics FUNCTION
 * @param imageFile an image filename to put into the chosenPhotos array of Image objects
   example: ScanPics('/stock/386x258/225885.jpg');
*/
function ScanPics(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(" ", "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 += " &nbsp;";
        }
        return caption;
    }
}
var selectedpic;
function show(n) {
//	alert("in show with n:"+n);
    var imgRef = eval(docRef + chosenPhotoIMGobjectName);
    if (null != imgRef && n < document.chosenPhotos.length) {
		selectedpic=n+1;
        imgRef.src = document.chosenPhotos[n].src;
        document.getElementById('largephoto').title = n+1;
		updateChosenPhotoCaption(n);
        //imgRef.className = "photo";
        //imgRef.border = 2;
        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;
    }
////khalid	alert(highlightedPhoto.src);
}

/* 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);
        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(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");
}


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 popMultiPhotoWindow(urlToPopup) {
   urlToPopup +=  '&currentPhoto='+ lastChosenPhotoIndex;
  makeLarge(urlToPopup,'popup','width=440,height=400,top=100,left=100,resize,scrollbars=yes');
}




function refreshphoto(path,dx,ix,x)
{
var photolocation;
if(path=="") path = "./photos/items/";
var xminus1=x + 1;
var imgRef = eval(docRef + 'tnImg' + xminus1);
photolocation=path+eval(dx)+"."+eval(ix)+"."+eval(x)+".jpg";
//alert("refreshing image "+x+" at path: "+photolocation);
imgRef.src = photolocation;

}

function RefreshImages(path,dx,ix,n)
{
var x;
for(x=0;x<n;x++) {
refreshphoto(path,dx,ix,x);
}
}
