﻿/****The following is used to auto tab to the next text box, used for phone *****/

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) 
{
    var keyCode = (isNN) ? e.which : e.keyCode; 
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

    if(input.value.length >= len && !containsElement(filter,keyCode)) 


    {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }


function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
else
    index++;
    return found;
}

function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
    }

return true;
}

/*********/



/************SITEMAP Functions start**************/
/************SITEMAP Functions start**************/
function hideSiteMapVehicleYears()
{
	var vehicleContainers = $('newvehicles').getElementsByClassName('vehicleyear');
	
	for (curr = 0; curr < vehicleContainers.length; curr++)
	{
		vehicleContainers[curr].hide();
	}
}

function showSiteMapVehiclesYear(year)
{
	$('vehicles_' + year).show();
}
function changeSiteMapYear(year)
{
	hideSiteMapVehicleYears();
	showSiteMapVehiclesYear(year);
	unselectYears();
	selectYear(year);
	setCookie(ModelYearCookie,year,365);
}

function unselectYears()
{
	var years = $('newvehicles').getElementsByClassName('year_selected');
	var yearsLength = years.length;
	curr=0;
	while (curr < yearsLength)
	{
		years[curr].className='year_notselected';
		curr=curr + 1;
	}			
}
function selectYear(year)
{
	$('year_' + year).className = 'year_selected';
}
/************SITEMAP Functions end**************/
/************SITEMAP Functions end**************/

/****************** PreOwned Record Start**************************/
function activatePreOwnedThumb(thumb)
{
    deactivateThumbs('preOwnedRecordImageGallery');//first deactivate all other thumbs
    //now activate the thumb selected 
    activateThumb(thumb,'/Images/PreOwnedRecord/SelectedImage.gif');//active the thumbnail
    changePreOwnedMainImage(thumb);//swap the main image with selected
		
}
function changePreOwnedMainImage(thumb)
{
     var thumbImg = $(thumb.id.replace('thumb_','thumbimage_'));
    $('mainimage').src =  thumbImg.src.replace('_thumb/','');
}
function openPDF(guid,lang,retailer,useSave)
{
    var date = new Date()
    var ticks = date.getTime()
    var url = '/handlers/PreOwnedPDF.ashx?id=' + guid + '&retailer=' + retailer + '&lang=' + lang + '&SaveAs=' + useSave + '&ticks=' + ticks;
    document.location.href=url;
}

//This function will be obselete once the in page vehicle record page is launched
function openSimilarVehicle(vehicleGuid,thisDiv)
{
    document.body.style.cursor = 'wait';
    thisDiv.style.cursor ='wait';
    window.location='/PreOwned/PreOwnedRecord.aspx?lng=' + langid + '&id=' + vehicleGuid;
    thisDiv.style.cursor ='default';
    document.body.style.cursor = 'default';
}
//This function does a form submit as appose to a redirect so it 
//retains the search criteria
function openSimilarVehicles(vehicleGuid,thisDiv,frm)
{
    document.body.style.cursor = 'wait';
    thisDiv.style.cursor ='wait';
    frm.action='/PreOwned/PreOwnedVehicle.aspx?lng=' + langid + '&id=' + vehicleGuid;
    frm.submit();
    thisDiv.style.cursor ='default';
    document.body.style.cursor = 'default';
}
/******************PreOwned Record End *******************************/


/*********** SHOWROOM AND NATIONAL OFFERS START ****************/
/*********** SHOWROOM AND NATIONAL OFFERS START ****************/
/*********** SHOWROOM AND NATIONAL OFFERS START ****************/ 

function showModelSelector(yearSwitch,ContainerID,year)
{
    
	setCookie(ModelYearCookie,year,365);
	var showing = $(ContainerID).getElementsByClassName('year_selected');
	var numOfShowing = showing.length;
	while (numOfShowing > 0)
	{
		showing[numOfShowing-1].className = 'year_notselected';
		numOfShowing = numOfShowing - 1;
	}
	
	yearSwitch.className='year_selected';
	
	
	var showing = $(ContainerID).getElementsByClassName('showModels');
	 
	var numOfShowing = showing.length;
	while (numOfShowing > 0)
	{
		showing[numOfShowing-1].className='hideModels';
		numOfShowing = numOfShowing - 1;
		
	}
	
	modelContainer = $(yearSwitch.id + '_container');
	modelContainer.className='showModels';
	modelContainer.show();
}

/*********** SHOWROOM AND NATIONAL OFFERS END ****************/
/*********** SHOWROOM AND NATIONAL OFFERS END ****************/
/*********** SHOWROOM AND NATIONAL OFFERS END ****************/


/***********FIND US PAGE START*********************/
/***********FIND US PAGE START*********************/

function initializeFindUsMap(latitude,longitude) {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(latitude, longitude), 13);
    map.setUIToDefault();

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    //baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(35, 32);
   // baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 32);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    // Creates a marker whose info window displays the letter corresponding
    // to the given index.
    function createMarker(point) {
      // Create a lettered icon for this point using our icon class
      //var letter = String.fromCharCode("A".charCodeAt(0) + index);
      var letteredIcon = new GIcon(baseIcon);
      letteredIcon.image = "/Images/FindUs/Logo_VW_GoogleMaps.png";

      // Set up our GMarkerOptions object
      markerOptions = { icon:letteredIcon };
      var marker = new GMarker(point, markerOptions);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml($('dealerPopUpInfo').innerHTML);
      });
      return marker;
    }

    // Add 10 markers to the map at random locations
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    var latlng = new GLatLng(latitude,longitude);
    map.addOverlay(createMarker(latlng));
    //for (var i = 0; i < 10; i++) {
    //  var latlng = new GLatLng(southWest.lat() + latSpan * Math.random(),
    //    southWest.lng() + lngSpan * Math.random());
    //  map.addOverlay(createMarker(latlng, i));
    //}
    
  }
}
/***********FIND US PAGE END*********************/
/***********FIND US PAGE END*********************/


/************************* Model Gallery Page START*******************************/
/************************* Model Gallery Page START*******************************/
/************************* Model Gallery Page START*******************************/
function activatePhotoGalleryThumb(thumb)
{
    deactivateThumbs('thumbGallery');//first deactivate all other thumbs
    //now activate the thumb selected 
    activateThumb(thumb,'/Images/Gallery/ActiveThumbnail.gif');//active the thumbnail
    //changeActionImage(thumb);//the little image to the left of the main one
    changePhotoGalleryMainImage(thumb);//swap the main image with selected
}

function deactivateThumbs(GalleryID)
{
	var thumbs = $(GalleryID).getElementsByClassName('thumb');
	var currThumb;
	for (currThumb=0;currThumb < thumbs.length; currThumb ++)
	{
	    var currOutline = $(thumbs[currThumb].id).getElementsByClassName('outline')[0];
	    currOutline.style.backgroundImage = '';
	    thumbs[currThumb].style.opacity = '.5';
	    thumbs[currThumb].style.filter="alpha(opacity=50)";
	}
}

function activateThumb(thumb,activeImagePath)
{
	var outline = $(thumb.id).getElementsByClassName('outline')[0];
    var thumbImg = $(thumb.id.replace('thumb_','thumbimage_'));
	outline.style.backgroundImage = 'url(' + activeImagePath + ')';
	thumb.style.opacity = '1';
	thumb.style.filter="alpha(opacity=100)";
}
function changePhotoGalleryMainImage(thumb)
{
    var thumbImg = $(thumb.id.replace('thumb_','thumbimage_'));
    $('mainimage').src =  thumbImg.src.replace('Tn_','Large_');
}
/*function changeActionImage(thumb)
{
    var thumbImg = $(thumb.id.replace('thumb_','thumbimage_'));
	$('actionImage').style.backgroundImage = 'url(' + thumbImg.src.replace('Tn_','ActionsBackground_') + ')';
    
}*/
function hoverThumb(thumb)
{
	thumb.style.opacity = '1';
	thumb.style.filter="alpha(opacity=100)";
}
function unhoverThumb(thumb)
{
	//first check to make sure it's not active
	var outline = $(thumb.id).getElementsByClassName('outline')[0];
	if (outline.style.backgroundImage =='')
	{
		thumb.style.opacity = '.5';
		thumb.style.filter="alpha(opacity=50)";
	}					
}
function openGalleryImage(size,retailer)
{
    var url = '/handlers/addtexttoimage.ashx?size=' + size + '&imagepath='+ $('mainimage').src.replace('Large_',size + '_') + '&RetailerID=' + retailer;
    window.open(url,'_parent','');
}

/************************* Model Gallery Page END*******************************/
/************************* Model Gallery Page END*******************************/
/************************* Model Gallery Page END*******************************/	


//**************PREOWNED PAGE STARTS***********************************
//**************PREOWNED PAGE STARTS***********************************
//**************PREOWNED PAGE STARTS***********************************

//used in the search preowned page to update the price and slider
function checkPriceRangeValues(values,slider,lng)
{
    var first = values[0]*1000;
    var second = values[1]*1000;
    
    if (first < second)
    {
        $('fromPrice').value = first;//input to be sent to server
        $('toPrice').value = second;//input to be sent to server    
        if (values[1]==slider.maximum)
        {
            second=priceMaxMessage;
            $('toPrice').value = 1000000;
        }
        else
            second=formatCurrency(second,lng);    
        $('minval').update(formatCurrency(first,lng));//label on page to display price
        $('maxval').update(second);//label on page to display price

        $('coloredbar').style.left = $('firstslider').offsetLeft + $('firstslider').clientWidth/2 + 'px';
        $('coloredbar').style.width = $('secondslider').offsetLeft -$('firstslider').offsetLeft + 'px';
    }
    else
    {
        $('fromPrice').value = second;//input to be sent to server
        $('toPrice').value = first;//input to be sent to server     
        if (values[0]==slider.maximum)
        {
            first=priceMaxMessage; 
            $('toPrice').value = 1000000;   
        }
        else
            first = formatCurrency(first,lng);    
        $('minval').update(formatCurrency(second,lng));//label on page to display price
        $('maxval').update(first);  //label on page to display price
       
        $('coloredbar').style.left = $('secondslider').offsetLeft + $('secondslider').clientWidth/2 + 'px';
        $('coloredbar').style.width = $('firstslider').offsetLeft -$('secondslider').offsetLeft + 'px';
    }
}


function updateMileage(mileage,slider,lng)
{
    
    if (mileage==slider.maximum)
    {
        mileage=mileageMaxMessage;
        $('mileage').value = 1000000;
    }    
    else
    {
        $('mileage').value = mileage*10000;
        mileage = formatNumber(mileage*10000,lng) + mileageMessage;
	}
	$('mileagecoloredbar').style.width = $('mileagehandle').offsetLeft + 'px';       
	$('currmileage').update(mileage); 
}

function checkYearBox(input,min,max,fromYear,toYear) 
{
    var num = input.value;
    var valid;
    if(isNaN(num))
        num = 0;
    else if(num.length >= 4)
    {
        if(num < min || num > max)
            valid = false
        else 
            valid = true;
    }
    else
    {
        if (isNaN(fromYear.value) && isNan(toYear.value))
        {
            if (fromYear.value <= toYear.value)
                valid = true;
            else    
                valid = false
        }
        else
        {
            valid = true;
        }
    }            
    if (!valid)
    {
        input.value='';
    }
}

function formatCurrency(num, lng)
{
    if (lng==2)
        return(formatEnglishCurrency(num)) 
    else if (lng==3)
        return(formatFrenchCurrency(num))     
}

function formatEnglishCurrency(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
    
    return (((sign)?'':'-') + '$' + num);
}

function formatFrenchCurrency(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+' '+ num.substring(num.length-(4*i+3));
    
    return (((sign)?'':'-') + num + ' $');
}
function formatNumber(num,lng)
{
    if(lng==2)
        return formatEnglishNumber(num);
    else if(lng==3)
        return formatFrenchNumber(num);
}
function formatEnglishNumber(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
    
    return (((sign)?'':'-') + num);
}

function formatFrenchNumber(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+' '+ num.substring(num.length-(4*i+3));
    
    return (((sign)?'':'-') + num);
}
//**************PREOWNED PAGE ENDS***********************************
//**************PREOWNED PAGE ENDS***********************************
//**************PREOWNED PAGE ENDS***********************************

/*
**************START of SPECIFICATIONS FUNCTIONS**************
**************START of SPECIFICATIONS FUNCTIONS**************
**************START of SPECIFICATIONS FUNCTIONS**************
*/

function toggleTrim(id,checkbox)
{
    var checkedTrims=0;
    var trims = document.trimForm.trimBox;
    var trimsSelected= new Array();
    for (i = 0; i < trims.length; i++)
    {
	    if (trims[i].checked == true)
	    {
	        trimsSelected[checkedTrims] = trims[i].value;
	        checkedTrims=checkedTrims+1;
	    } 
	}
	if (checkedTrims > 3)
	{
	    checkbox.checked = false;
	   
	    var dialog = $('specContainer').getElementsByClassName('WarningDialogBox')[0];
	    showDialog(dialog);
	   
	}
	else
	{
	   
	   var specItems = $('specContainer').getElementsBySelector('span.trim_'+id);
	   
	   for (x=0; x < specItems.length;x++)
	   {
	        specItems[x].toggle();
	   }
	}
}
function toggleSpec(header)
{
   var toggleItems = $(header.id).getElementsByClassName('toggle'); 
    
   for (ti=0; ti < toggleItems.length;ti++)
   {
        toggleItems[ti].toggle();
   }  
    $(header.id + '_collapse').toggle();
    if (header.className == 'headeron')
    {
        header.className = 'headeroff';
    }
    else
    {    
        
        header.className = 'headeron';
        
        
    }    
    
}
function openAllSpecs()
{
   var specItems = $('specContainer').getElementsByClassName('headeroff');
   var si;
   var len = specItems.length;
   
   while (len > 0)
   {
        toggleSpec(specItems[len-1]);
        len= len-1;
    }
}
function closeAllSpecs()
{
   var specItems = $('specContainer').getElementsByClassName('headeron');
   var si;
   var len = specItems.length;

   while (len > 0)
   {
        toggleSpec(specItems[len-1]);
        len= len-1;        
   }   
}

/*
**************END of SPECIFICATIONS FUNCTIONS**************
**************END of SPECIFICATIONS FUNCTIONS**************
**************END of SPECIFICATIONS FUNCTIONS**************
*/


/*
Function:showDialog
Paramters: the element which contains the dialog that you want to show
Assumptions:The element must be set to display:none with inline css **not in a css file**, 
            so the toggle function can work 
-This function places the div directly below the body tag so that the dialog can be placed above 
all other elements on the page using fixed positioning (fix for IE)
*/
function showDialog(dialog)
{
    dialog.toggle();
    $('topDiv').innerHTML = dialog.outerHTML;
    $('shadedBackground').toggle();
    $('topDiv').toggle();
}

function closeDialog(dialog)
{
   // var dialog = $('specContainer').getElementsByClassName('WarningDialogBox')[0];
    dialog.toggle();
    $('shadedBackground').toggle();
    $('topDiv').toggle();   
    
}

/*
**************HOURS AND OPERATIONS PAGE START **************
**************HOURS AND OPERATIONS PAGE START **************
**************HOURS AND OPERATIONS PAGE START **************
*/
function showHoursContent(id,tab)
{
	z_index = z_index + 1;
	$(id).style.zIndex = z_index;
	for (x = 0; x < tabCount;x++)
	{
	    if ($(tabs[x] + '_tab') != undefined)
	    {
	        if ($(tabs[x] + '_tab').className.include('first'))
	            $(tabs[x] + '_tab').className = 'tab first';
	        else
    		    $(tabs[x] + '_tab').className = 'tab';
	    }
	}
	if (tab.className.include('first'))	
	    tab.className = 'tab first_selected';
	else
	    tab.className = 'tab selected';

}
/*
**************HOURS AND OPERATIONS PAGE END************** 
**************HOURS AND OPERATIONS PAGE END **************
**************HOURS AND OPERATIONS PAGE END **************
*/

function validateEmail(strValue){
	
	if(strValue=='') {return true;}
	var regularExpression = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	//source:http://www.breakingpar.com/bkp/home.nsf/Doc!OpenNavigator&amp;87256B280015193F87256C40004CC8C6
	
	return regularExpression.test(strValue);
}