// Standard JavaScript Document - Volvo AB

// ========================  ======================== 
// ------------------------  ------------------------ 
// ........................  ........................


/* 
........................ STRUCTURE ........................

- general
- window.onload
- TEST

*/


// ======================== general ========================


// ------------------------ get next sibling (DOM traversal) ------------------------ 

function getNextSibling(startBrother){
	endBrother=startBrother.nextSibling;
	while(endBrother.nodeType!=1){
		endBrother = endBrother.nextSibling;
	}
	return endBrother;
}


// ------------------------ find position of objects (courtesy of Peter-Paul Koch) ------------------------ 

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}



// ------------------------ Get the scrolled distance (in an array) ------------------------ 

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}


// ------------------------ Rounded corner code for images ------------------------ 

var imgRcStart = '<span class="imgRc"><span class="imgRc_top"><span class="imgRc_topLeft"></span><span class="imgRc_topRight"></span></span>';
var imgRcEnd = '<span class="imgRc_bottom"><span class="imgRc_bottomLeft"></span><span class="imgRc_bottomRight"></span></span></span>';


// ------------------------ flash check ------------------------ 

// This script will test up to the following version.
flash_versions = 20;

// Initialize variables and arrays
var flash = new Object();
flash.installed=false;
flash.version='0.0';

// Dig through Netscape-compatible plug-ins first.
if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x < navigator.plugins.length; x++) {
		if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
			flash.version = navigator.plugins[x].description.split('Shockwave Flash ')[1];
			flash.installed = true;
			break;
		}
	}
}

// Then, dig through ActiveX-style plug-ins afterwords
else if (window.ActiveXObject) {
	for (x = 2; x <= flash_versions; x++) {
		try {
			oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
			if(oFlash) {
				flash.installed = true;
				flash.version = x + '.0';
			}
		}
		catch(e) {}
	}
}

// Create sniffing variables in the following style: flash.ver[x]
// Modified by mjac
flash.ver = Array();
for(i = 4; i <= flash_versions; i++) {
	eval("flash.ver[" + i + "] = (flash.installed && parseInt(flash.version) >= " + i + ") ? true : false;");
}

var flashVersion = parseInt(String(flash.version).substring(0,1));

//very simple IE check
var ua = window.navigator.userAgent
var msie = ua.indexOf ( "MSIE " )
//use syntax if(msie>0) { do something IF msie }  


// ------------------------ "contains" - for checking relations on mouseout of nested objects ------------------------ 

function contains(a, b) { // Return true if node a contains node b.
	if ((a && b)) {
	  while (b.parentNode)
	    if ((b = b.parentNode) == a)
	      return true;
	  return false;
	}
}


// ------------------------ URL query string retriever ------------------------ 

function retrieveQueryStringFromURL(name) {
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}

// ------------------------ clear the value of a text field ------------------------

function clearFieldValue(me) {
	if (me.value == me.title) {
		me.value = '';
	}
}


// ------------------------ restore the value of an empty text field ------------------------

function restoreFieldValue(me) {
	if (me.value == '') {
		me.value = me.title;
	}
}

// ------------------------ flash loader ------------------------

function loadFlash(loadFlash_link,loadFlash_width,loadFlash_height,loadFlash_placeHolder,loadFlash_vars,loadFlash_bgCol,loadFlash_wMode,loadFlash_alt) {
	// loadFlash_vars is reserved for future use
	var placeHolder = document.getElementById(loadFlash_placeHolder);  // find placeholder by ID
	if (!(placeHolder)) {
		placeHolder = document.getElementsByClassName(loadFlash_placeHolder); // if no ID, find the first item with className
		placeHolder = placeHolder[0];
	}
	if ((flashVersion > 7 && loadFlash_link != '')) {
		// write flash	
		if (loadFlash_width == '') {
			loadFlash_width = 350; // default width
		}
		if (loadFlash_height == '') {
			loadFlash_height = 200; // default height
		}
		if (loadFlash_bgCol == '') {
			loadFlash_bgCol = '#FFFFFF'; // default background
		}
		var loadFlash_id = loadFlash_placeHolder + '_flash'; // gives the flash content a unique ID
		var loadFlashObject = new SWFObject(loadFlash_link, loadFlash_id, loadFlash_width, loadFlash_height, "8", loadFlash_bgCol);
		if (loadFlash_wMode == 'alpha') {
			loadFlashObject.addParam("wmode", "transparent"); // if stated, background is transparent
		}
		loadFlashObject.write(placeHolder);
		
		//placeHolder.innerHTML = imgRcStart + placeHolder.innerHTML + imgRcEnd; // TEST
		
	} else {
		if (loadFlash_alt != '') {
			placeHolder.innerHTML = loadFlash_alt; // if no flash link, orn wrong flash version; show alt content, if any
		}
	}
}

/*
example: loadFlash('_flash/promo_dummy02.swf','400','200','main01_contentMain_mediaBlock01','','#FF0000','alpha','This is <em>alternative content</em>');
*/


// ------------------------ rcbItem mouse over / out ------------------------

function rcbMOver(me) {
	var theClicker = me.getElementsByTagName('a');
	if(theClicker[0].rel != 'marked'){
		me.className = 'rcbItem_pad01_marked';
		me.onmouseout = rcbMOut;
	}
}

function rcbMOut(event) {
	var theClicker = this.getElementsByTagName('a');
	var container = this.getElementsByClassName('rcbItem_pad02');
	var containerStripe = this.parentNode;
	var current, related;
	if (window.event) {
		current = this;
		related = window.event.toElement;
	} else {
		current = event.currentTarget;
		related = event.relatedTarget;
	}
	if (current != related && !contains(current, related)) {
		if(theClicker[0].rel != 'marked'){
			this.className = 'rcbItem_pad01';
		}
	}
}


// ------------------------ selectFlipper ------------------------

function selectFlipper(switchMe) { // hides <select> elements, for IE6
	var selects = document.getElementsByTagName('select');
	if (switchMe == 'hide') {
		for (var i = 0; i < selects.length; i++){	
			selects[i].style.visibility = 'hidden';
		}
	} else if (switchMe == 'show') {
		for (var i = 0; i < selects.length; i++){	
			selects[i].style.visibility = 'visible';
		}
	}
}

function flashFlipper(switchMe) { // Should be used to hide Flash from Safari, because of flicker bug
	var appVersion = 0;
	var appVersionChk = navigator.appVersion;
	appVersionChk = appVersionChk.split('/');
	if (appVersionChk.length > 1) {
		for (var i = 0; i < appVersionChk.length; i++){
			var strChk = appVersionChk[i].match('Safari');
			if (strChk != null) {
				var pickThis = i;
				pickThis++;
				appVersion = appVersionChk[pickThis];
			}
		}
	}
	if (appVersion != 0) {
		appVersion = parseFloat(appVersion);
		if (appVersion < 419.3) { // apply flash fix on Safari versions earlier than this number
			var embed = document.getElementsByTagName('embed');
			if ((switchMe == 'hide' && embed.length > 0)) {
				for (var i = 0; i < embed.length; i++){	
					embed[i].style.visibility = 'hidden';
				}
			} else if ((switchMe == 'show' && embed.length > 0)) {
				for (var i = 0; i < embed.length; i++){	
					embed[i].style.visibility = 'visible';
				}
			} else if (switchMe == 'hidePromo') {
				var theBigFlasher = document.getElementById("main01_promoPh");
				theBigFlasher.style.visibility = 'hidden';
			} else if (switchMe == 'showPromo') {
				var theBigFlasher = document.getElementById("main01_promoPh");
				theBigFlasher.style.visibility = 'visible';
			}
		}
	}
}

// ------------------------ voidAllJSLinks ------------------------

function voidAllJSLinks() { // makes sure that swfObject doesn't bug in IE. May not be neccessary on live site.
 	var links = document.getElementsByTagName('a');
	for (i = 0; i < links.length; i++) {
       var s = links[i].href;
		if (s.match(/#+$/)) {
			links[i].href = 'javascript:void(0);';
		}
	}
} 


// ------------------------ giveFocus ------------------------

function giveFocus(me_id,me_className) {
	var me;
	if (me_id != '') {
		me = document.getElementById(me_id);
		me.focus();
	} else {
		me = document.getElementsByClassName(me_className);
		me[0].focus();
	}
}

// ------------------------ submitOnEnter ------------------------

function handleSubmitOnEnter(className) {
	var inputs = document.getElementsByClassName(className);
	for (i = 0; i < inputs.length; i++) {
		var currentInput = inputs[i];
		currentInput.onkeypress = submitOnEnter;
	}
}

function submitOnEnter(event) {
	var key;
	if (window.event) {
		key = window.event.keyCode;
	} else {
		key = event.keyCode;
	}
	if (key == 13) {
		document.forms[0].submit();
	}
}

// ------------------------ contact form module handling -----------------------

var VCEDL_errorMsg_search = false;
var VCEDL_errorMsg_direction = false;

function initErrorMsg_search(content) {
	if (content != false) {
		var container = content;
		VCEDL_errorMsg_search = container.innerHTML;
	}
}

function validateSearch(me) {
	var form = document.forms[0];
	var locationSelector = document.getElementById('vcedl_location_wrap01').getElementsByTagName('select')[0]; 

	if (!locationSelector.value) {
		if (VCEDL_errorMsg_search != false) {
			alert(VCEDL_errorMsg_search);
		}
		return false;
	} else {
		return true;
	}
}



function initErrorMsg_direction(content) {
	if (content != false) {
		var container = content;
		VCEDL_errorMsg_direction = container.innerHTML;
	}
}

function validateDirection(me) {
	var form = document.forms[0];
	var directionField = document.getElementById('vcedl_direction_wrap01').getElementsByTagName('input')[0]; 
	
	if (!directionField.value) {
		if (VCEDL_errorMsg_direction != false) {
			alert(VCEDL_errorMsg_direction);
		}
		return false;
	} else {
		return true;
	}
}


function initErrorMsg_sendDetails(content) {
	if (content != false) {
		var container = content;
		VCEDL_errorMsg_direction = container.innerHTML;
	}
}

function validateSendDetails(me) {
	var form = document.forms[0];
	var sendDetails_fields = document.getElementById('sendDetails').getElementsByTagName('input'); 
	var sendDetails_errorMsg = document.getElementById('sendDetails_errorMsg');
	var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	var errorLevel = 0;
	
	for (var i = 0; i < sendDetails_fields.length; i++){
		var theLabel = sendDetails_fields[i].parentNode.getElementsByTagName('label')[0];
		theLabel.style.color = '#000';
		theLabel.getElementsByTagName('span')[0].style.display = 'none';
		if ((!sendDetails_fields[i].value) || (!emailFilter.test(sendDetails_fields[i].value))) {
			errorLevel++;
			theLabel.style.color = '#f00';
			theLabel.getElementsByTagName('span')[0].style.display = 'inline';
		}
	}
	
	if (errorLevel != 0) {
		sendDetails_errorMsg.style.display = 'block';
		return false;
	} else {
		return true;
	}
}





// ------------------------ handle active content ------------------------

function handleActiveContent(contentType) {
	// rcb_banner - activeContent_flash
	var ac_links = document.getElementsByClassName('rcb_banner');
	var thisLink;
	if (contentType == 'activeContent_flash') {
		for (i = 0; i < ac_links.length; i++) {
			if (ac_links[i].rel == contentType) {
				thisLink = ac_links[i];
				thisSrc = thisLink.getElementsByClassName('rcbe_main_end');
				thisLink.onclick = function () {
					showPopupLayer('actContent_flash',thisSrc[0].title,'294','222','350')
				}
			}
		}
	}
}

// ======================== help popup ========================


function openNewWindow(url,winWidth,winHeight) {
	var screenWidth = screen.availWidth / 2;
	var screenHeight = screen.availHeight / 2;
	var winLeft = winWidth / 2;
	var winTop = winHeight / 2;
	winLeft = screenWidth - winLeft;
	winTop = screenHeight - winTop;
	var ctrlString = 'left=' + winLeft + ',top=' + winTop + ',height=' + winHeight + ',width=' + winWidth + ',resizable=yes,scrollbars=yes';
	var newwindow = window.open(url,'blankPopup',ctrlString);	
}

// ======================== print popup ========================


function openPrintWindow(url,winWidth,winHeight) {
	var screenWidth = screen.availWidth / 2;
	var screenHeight = screen.availHeight / 2;
	var winLeft = winWidth / 2;
	var winTop = winHeight / 2;
	winLeft = screenWidth - winLeft;
	winTop = screenHeight - winTop;
	var ctrlString = 'left=' + winLeft + ',top=' + winTop + ',height=' + winHeight + ',width=' + winWidth + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes';
	var newwindow = window.open(url,'printPopup',ctrlString);	
}


// ........................ selector module ........................


function selector_gotoSelected(showThis) {
	if(showThis != '') {
		document.forms[0].submit();
	}
}


function selector_SelectOnchange_init(checkMe) {
	var theSelect = document.getElementById(checkMe);
	
	var userAgent = navigator.userAgent;
	var uACheck = userAgent.match('AppleWebKit');
	
	if (uACheck != null) {
		theSelect.onchange = selector_selectChangedSafari;
	} else {
		theSelect.changed = false;
		theSelect.onfocus = selector_selectFocused;
		theSelect.onchange = selector_selectChanged;
		theSelect.onkeydown = selector_selectKeyed;
		theSelect.onclick = selector_selectClicked;
	}
	
	return true;
}


function selector_selectChangedSafari() {
	var theSelect = document.getElementById(this.id);
	selector_gotoSelected(theSelect.value);
}


function selector_selectChanged(theElement) {
	var theSelect;
	
	if (theElement && theElement.value) {
		theSelect = theElement;
	}
	else {
		theSelect = this;
	}
	
	if (!theSelect.changed) {
		return false;
	}
	
	selector_gotoSelected(theSelect.value);
	return true;
}


function selector_selectClicked() {
	this.changed = true;
}




function selector_selectFocused() {
	this.initValue = this.value;
	
	return true;
}




function selector_selectKeyed(e) {
	var theEvent;
	var keyCodeTab = "9";
	var keyCodeEnter = "13";
	var keyCodeEsc = "27";
	
	if (e) {
		theEvent = e;
	}
	else {
		theEvent = event;
	}

	if ((theEvent.keyCode == keyCodeEnter || theEvent.keyCode == keyCodeTab) && this.value != this.initValue) {
		this.changed = true;
		selector_selectChanged(this);
	}
	else if (theEvent.keyCode == keyCodeEsc) {
		this.value = this.initValue;
	}
	else {
		this.changed = false;
	}
	
	return true;
}

// ======================== iframe contractor ========================

var iframeContr_container = '';
var iframeContr_element = '';
var iframeContr_height = '';

function iframeContractor(container,matchElement,addHeight) {
	if (container || (iframeContr_container != '')) {
		if (addHeight === '') addHeight = 40;
		
		if (iframeContr_container == '') {
			if (container.getElementsByTagName('iframe').length > 0) {
				container = container.getElementsByTagName('iframe')[0];
			} else {
				container = container.getElementsByTagName('object')[0];
			}
			iframeContr_container = container;
		} else {
			container = iframeContr_container;
		}
		
		if (iframeContr_element == '') {
			iframeContr_element = matchElement;
		} else {
			matchElement = iframeContr_element;
		}
		
		if (iframeContr_height == '') {
			iframeContr_height = addHeight;
		} else {
			addHeight = iframeContr_height;
		}
		
		var appContainer = container;

		var appHeight = parseInt(matchElement.offsetHeight);
		var keepHght = appHeight;
		appHeight = appHeight + addHeight;
		appContainer.style.height = appHeight + 'px';
	}
}




function flipDirectionMap(me) {
	thisRow = me.parentNode.parentNode.parentNode;
	thisMap = getNextSibling(thisRow);
	thisMap = thisMap.getElementsByTagName('td')[0];
	if (thisMap.className != 'hideMap') {
		thisMap.className = 'hideMap';
	} else {
		thisMap.className = '';
	}
	
	iframeContractor();
}


// ======================== map marker mouse over box ========================


function initMapMarkerInfoBox(mapHolder) {
	/* create elements */
	var infobox_container = document.createElement('div');
	var infobox_containerPad = document.createElement('div');
	var infobox_top = document.createElement('div');
	var infobox_bottom = document.createElement('div');
	var infobox_arrow = document.createElement('div');
	
	/* assemble elements */
	infobox_container.appendChild(infobox_top);
	infobox_container.appendChild(infobox_containerPad);
	infobox_container.appendChild(infobox_bottom);
	infobox_bottom.appendChild(infobox_arrow);
	
	/* assign id's */
	infobox_container.id = 'mapMarker_infobox';
	var infobox_nodelist = infobox_container.getElementsByTagName('div');
	infobox_nodelist[0].id = 'mapMarker_infobox_top';
	infobox_nodelist[1].id = 'mapMarker_infobox_pad01';
	infobox_nodelist[2].id = 'mapMarker_infobox_bottom';
	infobox_nodelist[3].id = 'mapMarker_infobox_arrow';

	/* place infoBox */
	mapHolder.appendChild(infobox_container);
}



function mapMarkerInfoBox(me){
	var mapHolder = document.getElementById('map01');
	if (!document.getElementById('mapMarker_infobox')) {
		initMapMarkerInfoBox(mapHolder);
	}
	var infoBox = document.getElementById('mapMarker_infobox');
	infoBox.style.display = 'block';
	
	// clear existing content, if any
	var infoBox_content = document.getElementById('mapMarker_infobox_pad01');
	infoBox_content.innerHTML = '';
	
	
	var boxID = parseInt(me.innerHTML);
	boxID--; // remove if dealer address ID's are listed from 1 instead of zero
	
	// transfer content from list
	infoBox_content.innerHTML = document.getElementById('mapMarker_' + boxID).innerHTML;
	
	// assign the <a href> to the box click, and clear the <a>-tag
	var infoBox_link = infoBox_content.getElementsByTagName('a')[0];
	var infoBox_href = infoBox_link.href;
	if (infoBox_link.href != 'javascript:void(0);') {
		infoBox.onclick = function() {
			window.location.href = infoBox_href;
		}
	}
	infoBox_link.href = 'javascript:void(0);';
	
	// position box
	infoBox.style.left = findPos(me)[0] + 'px';
	infoBox.style.top = findPos(me)[1] + 'px';
	var goLeft = parseInt(infoBox.offsetWidth);
	var goTop = parseInt(infoBox.offsetHeight);
	goLeft = goLeft - 46;
	goTop = goTop - 5;
	infoBox.style.marginLeft = '-' + goLeft + 'px';
	infoBox.style.marginTop = '-' + goTop + 'px';
	
	// assign hiding on map click
	if (!mapHolder.onclick) {
		mapHolder.onclick = hidemapMarkerInfoBox;
	} else {
	}
}

function hidemapMarkerInfoBox() {
	var infoBox = document.getElementById('mapMarker_infobox');
	infoBox.style.display = 'none';
}

// ======================== TEST ========================


