/**
* special alert message stuff
*/
function showSpecialAlertMessage(alertText)
{
	var newText = '';
	while (newText != alertText) {
		newText = alertText;
		if (alertText == null)
			alertText = '';
		alertText = alertText.replace("\r\n", "<br />");
		alertText = alertText.replace("\n", "<br />");
		alertText = alertText.replace("\r", "<br />");
	}
	document.getElementById('alertTextSpecial').innerHTML = alertText;	
	document.getElementById('alertBoxLayerSpecial').style.display='block';
	document.getElementById('alertButtonSpecial').style.display='block';
	document.getElementById('alertButtonSpecial2').style.display='block';	
	var h = document.getElementById('alertTextSpecial').clientHeight;
	if (h != 0) {
		document.getElementById('alertBoxSpecial').style.height = (h+75)+"px";
		var h1 = document.getElementById('alertBoxSpecial').clientHeight;
	}
	if (window.reDisplaySelectboxes)
	{
		reDisplaySelectboxes();
	}
}
function hideSpecialAlertMessage()
{
	document.getElementById('alertBoxLayerSpecial').style.display='none';
	document.getElementById('alertButtonSpecial').style.display='none';
	document.getElementById('alertButtonSpecial2').style.display='none';	
	document.getElementById('confirmButtonSpecial').style.display='none';
	if (window.reDisplaySelectboxes)
	{
		reDisplaySelectboxes();
	}
}
function conflictWithSpecialAlertLayer(left, width, top, height)
{
	var layerLeft = document.getElementById('alertBoxSpecial').offsetLeft;
	var layerTop = document.getElementById('alertBoxSpecial').offsetTop + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	var layerWidth = document.getElementById('alertBoxSpecial').offsetWidth;

	var layerHeight = document.getElementById('alertBoxSpecial').offsetHeight;
	//window.status = ((layerLeft < left && layerTop < top && layerLeft + layerWidth > left && layerTop + layerHeight > top) 				 + " " + 				(layerLeft < left + width && layerTop < top && layerLeft + layerWidth > left + width && layerTop + layerHeight > top) 				 + " " + 				(layerLeft < left + width && layerTop < top + height && layerLeft + layerWidth > left + width && layerTop + layerHeight > top + height) 				 + " " +  (layerLeft < left && layerTop < top + height && layerLeft + layerWidth > left && layerTop + layerHeight > top + height) + " " + layerTop+ " " + top + " "  + height);

	return (layerLeft < left && layerTop < top && layerLeft + layerWidth > left && layerTop + layerHeight > top
			||
			layerLeft < left + width && layerTop < top && layerLeft + layerWidth > left + width && layerTop + layerHeight > top
			||
			layerLeft < left + width && layerTop - 18 < top + height && layerLeft + layerWidth > left + width && layerTop + layerHeight > top + height
			||
			layerLeft < left && layerTop - 18 < top + height && layerLeft + layerWidth > left && layerTop + layerHeight > top + height
			);
	//return document.getElementById('alertBoxLayer').style.display == 'block';
}

var timeoutShow = 45;
var timeoutHide = 25;
var resizeableAnimDiff = 25;
var timeoutResizeable = 10;

var openedControlLines = {};

var remoteFields = new Array();
var searchInfoBoxTop = 283;
var searchButtonsHeight1 = 20;
var searchButtonsHeight2 = 48;

var openedSelectByLevel = {};
var timeoutTodo = new Array();
var timeoutId = false;
var controlEnabled = false;
var selectValuesMap = {};
var otherValuesMap = {};
var colourValuesMap = {};
var checkboxValuesMap = {};
var colorsNotForAllModel = {};
var colourNames = new Array();
var packageNames = new Array();
var selectedColours = {};

var searchForAll = true;

var adTimeout = false;

var callJsOnChangeTimeoutSecs = 0;

var showSearchingTimeoutSecs = 0.6;
var showSearchingTimer = false;

var initialized = false;

function registerTimeout(func, time) {
	timeoutTodo.push(new Array(func + '; doTimeout();', time));
}

function startTimeout(time) {
	registerTimeout('', time);
	if (!timeoutId) {
		doTimeout();
	}
}

function hasTimeout() {
	return timeoutTodo.length > 0;
}

function doTimeout() {
	var funcTime = timeoutTodo.shift();
	if (funcTime) {
		func = funcTime[0];
		timeoutId = setTimeout(func, funcTime[1]);
	} else {
		timeoutId = false;
	}

}

function canControl() {
	return controlEnabled && !hasTimeout();
}

function clickOnControlSelect(id) {
	clickOnParentSelect(id, 0);
}

function clickOnParentSelect(id, level) {
	if (canControl()) {
		clickOnParentSelectGo(id, level);
	}
}

function clickOnParentSelectGo(id, level) {
	var opened = openedControlLines[id];
	if (opened) {
		openedSelectByLevel[level] = false;
		registerHideControlLine(id, opened);
	} else {
		opened = openedSelectByLevel[level];
		if (opened) {
			var openedline = openedControlLines[opened];
			if (openedline) {
				registerHideControlLine(opened, openedline);
			} else {
				openedSelectByLevel[level] = false;
			}
		}
		openedSelectByLevel[level] = id;
		registerShowControlLine(id);
	}
}

function registerShowControlLine(prefix) {
	var index = 1;
	while (index > 0) {
		var line = document.getElementById(prefix + '-' + index);
		if (line) {
			if (controlEnabled && (index == 1)) {
				registerTimeout('controlEnabled = false;', 0);
			}
			var isLineToHide = false;
			var modelIdField = document.getElementById('input-modelId');
			if (modelIdField) {
				isLineToHide = (modelIdField.value == 'MF92') && (prefix == 'transmission') && (index == 1 || index == 3);
			}
			if (!isLineToHide) {
				registerTimeout('showControlLine(\'' + prefix + '\', ' + index + ')', timeoutShow);
			}

			index++;
		} else {
			if (controlEnabled && (index != 1)) {
				registerTimeout('controlEnabled = true;', 0);
			}
			index = 0;
		}
	}
	if (window.showScrollAdv) {
		registerTimeout('showScrollAdv();', 0);
	}
	startTimeout(timeoutShow);
}

function showControlLine(prefix, index) {
	var line = document.getElementById(prefix + '-' + index);
	if (line) {
		line.style.display = '';
		openedControlLines[prefix] = index;
	}
}

function registerHideControlLine(prefix, index, recursive) {
	while (index > 0) {
		var id = prefix + '-' + index;
		var opened = openedControlLines[id];
		if (opened) {
			registerHideControlLine(id, opened, true);
		}
		var line = document.getElementById(id);
		if (line) {
			registerTimeout('hideControlLine(\'' + prefix + '\', ' + index + ')', timeoutHide);
		}
		index--;
	}
	if (window.showScrollAdv) {
		registerTimeout('showScrollAdv();', 0);
	}
	if (!recursive) {
		startTimeout(timeoutHide);
	}
}

function hideControlLine(prefix, index) {
	var id = prefix + '-' + index;
	var line = document.getElementById(id);
	if (line) {
		line.style.display = 'none';
		openedControlLines[prefix] = index-1;
	} else {
		openedControlLines[prefix] = false;
	}
}

function clickOnNodeSelect(prefixRoot, value, textContainer) {
	var indexPimlico  =  textContainer.childNodes[0].nodeValue.indexOf("Pimlico", 0);
	var indexHampton  =  textContainer.childNodes[0].nodeValue.indexOf("Hampton", 0);
	if (indexPimlico != -1){
		var searchButton  =  document.getElementById("show-colors-button");
		if( searchButton != null){
			searchButton.style.display = "none";
		}
		
		var contentChild  =  document.getElementById("contentChild_0");
		contentChild.style.top =  "0px";
		var scrollChild  =  document.getElementById("scrollChild_0");
		scrollChild.style.top =  "0px";
	}else{
		if (indexHampton != -1){
			var searchButton  =  document.getElementById("show-colors-button");
			if( searchButton != null){
				searchButton.style.display = "none";
			}
			var contentChild  =  document.getElementById("contentChild_0");
			contentChild.style.top =  "0px";
			var scrollChild  =  document.getElementById("scrollChild_0");
			scrollChild.style.top =  "0px";
		}else{
			var searchButton  =  document.getElementById("show-colors-button");
			if( searchButton != null){
				searchButton.style.display = "";
			}
		}
	}
	if (canControl()) {
		if (false && value == 'MF92') {
			var as = document.getElementById('transmission-2').getElementsByTagName('a');
			var firstA = as[0];
			clickOnNodeSelect('transmission', 'M', firstA);
			clickOnNodeSelect('transmission', 'M', firstA);
		}
		var callRemoteValues = false;
		var canChange = true;
		if (window.validateControls) {
			canChange = validateControls(prefixRoot, value, textContainer);
		}
		if (canChange) {
			copyNodeValue(prefixRoot, value, textContainer);
			clickOnControlSelect(prefixRoot);
			callRemoteValues = new Array( prefixRoot, value );
			callRemote(callRemoteValues);
		}
	}
}

function copyNodeValue(prefixRoot, value, textContainer) {
	var text = document.getElementById('text-' + prefixRoot);
	if (text) {
		var textValue = textContainer.innerHTML;
		text.innerHTML = textValue;
		callRemoteValues = new Array(prefixRoot, textValue);
		callJsOnChange(prefixRoot, textValue);
	}
	var hidden = document.getElementById("input-" + prefixRoot);
	if (hidden) {
		hidden.value = value;
	}
}

function closeAllSelect() {
	clickOnControlSelect(false);
}

function showHideInputText(id, show, hide) {
	if (canControl()) {
		closeAllSelect();
		var textInput = document.getElementById('input-' + id);
		var text = document.getElementById('text-' + id);
		if (textInput && text) {
			var needToShow = show || (!hide && textInput.style.display == 'none');
			var canChange = true;
			if (!needToShow && window.validateControls) {
				canChange = validateControls(id, textInput.value);
			}
			if (canChange) {
				var callRemoteValues = false;
				if (needToShow) {
					textInput.style.display = '';
					text.style.display = 'none';
					textInput.focus();
				} else {
					textInput.style.display = 'none';
					var textValue = textInput.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
					text.innerHTML = textValue;
					text.style.display = '';
					callRemoteValues = new Array(id, textValue);
				}
				callRemote(callRemoteValues);
			}  else {
				textInput.focus();
			}
		}
	}
}

function clickOnControlInputText(id) {
	showHideInputText(id, false, false);
}

function hideInputText(id) {
	showHideInputText(id, false, true);
}

function resizeContent(fromY, toY, titleShow, buttonShow, fullHeight) {
	showHidePostcodeError(false);
	var button = document.getElementById('resizeable-' + titleShow + '-button');
	if (button) {
		button.style.display = 'none';
	}
	var title = document.getElementById('resizeable-' + titleShow + '-title');
	if (title) {
		title.style.display = '';
	}
	resizeContentAnim(fromY, toY, buttonShow, fullHeight);
}

function resizeContentAnim(y, toY, buttonShow, fullHeight) {
	var div = document.getElementById('resizeable-content');
	if (div) {
		if (toY > y) {
			y += resizeableAnimDiff;
			if (y > toY) {
				y = toY;
			}
		} else {
			y -= resizeableAnimDiff;
			if (y < toY) {
				y = toY;
			}
		}
		div.style.marginTop = y + 'px';
		div.style.height = (fullHeight - y) + 'px';
		if (y == toY) {
			var title = document.getElementById('resizeable-' + buttonShow + '-title');
			if (title) {
				title.style.display = 'none';
			}
			var button = document.getElementById('resizeable-' + buttonShow + '-button');
			if (button) {
				button.style.display = '';
			}
		} else {
			setTimeout('resizeContentAnim(' + y + ', ' + toY + ', \'' + buttonShow + '\', ' + fullHeight + ')', timeoutResizeable);
		}
	}
}

function callRemote(callRemoteValues) {
	if (callRemoteValues) {
		if (remoteFields.length == 0) {
			if (window.buildRemoteFields) {
				buildRemoteFields();
			}
		}
		var length = remoteFields.length;
		if (length != 0) {
			var myForm = document.callRemoteForm;
			if (myForm) {
				var field = callRemoteValues[0];
				var found = field == '*';
				var i;
				for (i = 0; i < length; i++) {
					var remoteField = remoteFields[i];
					var myField = eval('myForm.' + remoteField);
					var myText = document.getElementById('input-' + remoteField);
					if (myField && myText) {
						myField.value = myText.value;
					}
					if (field == remoteField) {
						found = true;
					}
				}
				var input = document.getElementById('input-colorCodes');
				if (input) {
					var colorValues = '';
					var colourNamesLenght = colourNames.length;
					for (i = 0; i < colourNamesLenght; i++) {
						var colourName = colourNames[i];
						var colourValue = colourValuesMap['color-' + colourName][0];
						if (selectedColours['color-' + colourValue]) {
							colorValues += ' ' + colourValue;
						}
					}
					if (colorValues.length > 0) {
						colorValues = colorValues.substr(1);
					}
					input.value = colorValues.replace(/-/g, ' ');
				}
				if (found) {
					if (!showSearchingTimer) {
						showSearchingTimer = setTimeout('showCountResultsSearching(true);', showSearchingTimeoutSecs * 1000);
					}
					myForm.submit();
				}
			}
		}
	}
}

function callRemoteNow() {
    callRemote(new Array('*'));
}

function changeCountResuls(value, hasCount, canSearch, postcodeError) {
	if( value == 0 && !postcodeError )
	{
		showSpecialAlertMessage('Your search returned no matches, click below and we will let you know when your perfect MINI is in stock.');
	}
	showCountResultsSearching(false);
	var text = document.getElementById('countResults');
	if (text) {
		text.innerHTML = value;
	}
	var box = document.getElementById('search-info-box');
	if (box) {
		var top = searchInfoBoxTop;
		if (hasCount) {
			top -= searchButtonsHeight1;
			var searchButtons = document.getElementById('search-buttons');
			if (searchButtons) {
				searchButtons.style.display = canSearch ? '' : 'none';
			}
			if (canSearch) {
				top -= searchButtonsHeight2;
			}
		}
		box.style.marginTop = top + 'px';
	}
	if (postcodeError) {
		showHidePostcodeError(true);
	}
}

function showSearchInfoBox() {
	var box = document.getElementById('search-info-box');
	if (box) {
		var searchButtons = document.getElementById('search-buttons');
		if (searchButtons) {
			searchButtons.style.display = '';
		}
		var top = searchInfoBoxTop - searchButtonsHeight1 - searchButtonsHeight2;
		box.style.marginTop = top + 'px';
	}
}

function showHidePostcodeError(show) {
	var errorDiv;
	errorDiv = document.getElementById('postcode-error-container');
	if (errorDiv) {
		errorDiv.style.display = show ? '' : 'none';
	}
	errorDiv = document.getElementById('postcode-error');
	if (errorDiv) {
		errorDiv.style.display = show ? '' : 'none';
	}
}

function clickOnControlCheckbox(id) {
	if (canControl()) {
		closeAllSelect();
		var callRemoteValues = false;
		var check = document.getElementById('check-' + id);
		if (check) {
			var checked = check.className == '';
			check.className = checked ? 'checked' : '';
			var textValue = checked ? '1' : '';
			callRemoteValues = new Array(id, textValue);
			var hidden = document.getElementById("input-" + id);
			if (hidden) {
				hidden.value = textValue;
			}
		}
		callRemote(callRemoteValues);
	}
}

function clickOnControlColor(id) {
	var selected = selectedColours['color-' + id] ? false : true;
	setColor(id, selected, true);
	callRemoteNow();
}

function setSelect(id, value, valueToShow) {
	var textInput = document.getElementById('input-' + id);
	if (textInput) {
		textInput.value = value;
	}
	var text = document.getElementById('text-' + id);
	if (text) {
		text.innerHTML = valueToShow;
	}
}

function clearSelect(id) {
	setSelect(id, '', '');
}

function setInputText(id, value) {
	var textInput = document.getElementById('input-' + id);
	var text = document.getElementById('text-' + id);
	if (textInput && text) {
		textInput.value = value;
		var textValue = textInput.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
		text.innerHTML = textValue;
	}
}

function clearInputText(id) {
	setInputText(id, '');
}

function changeInputText(id, concurrentBoxes, idShowHide, minLength, onlyShow) {
	if (canControl()) {
		var textInput = document.getElementById('input-' + id);
		if (textInput) {
			if (textInput.style.display != 'none') {
				var lengthConcurrentBoxes = concurrentBoxes ? concurrentBoxes.length : 0;
				var i;
				var textInputValues;
				if (textInput.value == '') {
					textInputValues = '';
					for (i = 0; i < lengthConcurrentBoxes; i++) {
						var textInputOther = document.getElementById('input-' + concurrentBoxes[i]);
						if (textInputOther) {
							textInputValues += textInputOther.value;
						}
					}
				} else {
					for (i = 0; i < lengthConcurrentBoxes; i++) {
						var concurrentBoxId = concurrentBoxes[i];
						if (concurrentBoxId != id) {
							clearInputText(concurrentBoxId);
						}
					}
					textInputValues = textInput.value;
				}
				if (idShowHide) {
					var divShowHide = document.getElementById(idShowHide);
					if (divShowHide) {
						if (textInputValues.length < minLength) {
							if (!onlyShow) {
								divShowHide.style.display = 'none';
							}
						} else {
							if (idShowHide == 'search-info-box') {
								showSearchInfoBox();
							} else {
								divShowHide.style.display = '';
							}
						}
					}
				}
			}
		}
	}
}

function setCheckbox(id, checked) {
	var hidden = document.getElementById('input-' + id);
	if (hidden) {
		hidden.value = checked ? '1' : '';
	}
	var check = document.getElementById('check-' + id);
	if (check) {
		check.className = checked ? 'checked' : '';
	}
}

function setColor(id, selected, click) {
	selectedColours['color-' + id] = selected;
	var isNotForAllModel = colorsNotForAllModel['color-' + id];
	var div = document.getElementById('color-selector-' + id);
	if (div) {
		div.className = selected ? 'selected' : '';
	}
	var postfix = searchForAll && isNotForAllModel ? '-only' : '';
	var divText;
	divText = document.getElementById('color-your-selected-' + id + postfix);
	if (divText) {
		divText.style.display = selected ? '' : 'none';
	}
	postfix = postfix == '' ? '-only' : '';
	divText = document.getElementById('color-your-selected-' + id + postfix);
	if (divText) {
		divText.style.display = 'none';
	}
	if (div) {
		if (click && !(searchForAll && isNotForAllModel)) {
			changeCarColor(selected ? id : false);
		}
	}
}

function changeCarColor(colorIds) {
	if (!colorIds) {
		div = document.getElementById('color-your-colors');
		if (div) {
			var nodes = div.childNodes;
			var more = true;
			var nodeIndex;
			for (nodeIndex = nodes.length - 1; more && (nodeIndex >= 0); nodeIndex--) {
				var node = nodes.item(nodeIndex);
				if (node.style.display != 'none') {
					colorIds = node.id;
					if (colorIds.substring(0, 20) == 'color-your-selected-') {
						colorIds = colorIds.substring(20);
						var length = colorIds.length;
						if ((length > 5) && (colorIds.substring(length - 5) == '-only')) {
//							colorIds = colorIds.substring(0, length - 5);
						} else {
							more = false;
						}
					}
				}
			}
		}
	}
	if (colorIds) {
		colorIds = colorIds.replace(/-/g, ' ');
		callJsOnChange('color', colorIds);
	}
}

function setDefaultValueSelect(id, defaultValue) {
	var valueToShow = selectValuesMap[id + ':' + defaultValue];
	if (valueToShow == undefined) {
		valueToShow = '';
	}
	setSelect(id, defaultValue, valueToShow);
	if (callJsOnChangeTimeoutSecs == 0) {
		callJsOnChange(id, valueToShow, true);
	} else {
		setTimeout('callJsOnChange(\'' + id + '\', \'' +  valueToShow + '\', true)', callJsOnChangeTimeoutSecs * 1000);
	}
	if ((id == 'modelId') && window.getColorsForModel) {
		getColorsForModel(defaultValue);
	}
}

function setDefaultValueInputText(id, defaultValue) {
	setInputText(id, defaultValue);
}

function setDefaultValueCheckbox(id, defaultValue) {
	setCheckbox(id, defaultValue == 'true');
}

function setDefaultValueColor(id, defaultValue) {
	if (defaultValue == 'true') {
		setColor(id, true, false);
	}
}

function switchColors(show) {
	showHidePostcodeError(false);
	var buttonShow = document.getElementById('show-colors-button');
	if (buttonShow) {
		buttonShow.style.display = show ? 'none' : '';
	}
	var buttonHide = document.getElementById('show-details-button');
	if (buttonHide) {
		buttonHide.style.display = show ? '' : 'none';
	}
	var tabShow = document.getElementById('search-details');
	if (tabShow) {
		tabShow.style.display = show ? 'none' : '';
	}
	var tabHide = document.getElementById('search-colors');
	if (tabHide) {
		tabHide.style.display = show ? '' : 'none';
	}
}

function initControls() {
	if (window.initControlValues) {
		initControlValues();
	}
	initialized = true;
	controlEnabled = true;
}

function doSearch(url, waitSecs) {
	hideAd();
	showHidePostcodeError(false);
	var myForm = document.callRemoteForm;
	if (myForm) {
		callRemote(new Array('-'));
		if (myForm.postcode.value == '') {
			showHidePostcodeError(true);
		} else {
			if (waitSecs > 0) {
				var divAd = document.getElementById('search-ad-box');
				if (divAd) {
					var text1 = document.getElementById('countResults');
					var text2 = document.getElementById('countResults-ad');
					if (text1 && text2) {
						text2.innerHTML = text1.innerHTML;
					}
					divAd.style.display = '';
				}
				adTimeout = setTimeout('goSearch(\'' + url + '\')', waitSecs * 1000);
			} else {
				goSearch(url);
			}
		}
	}
}

function goSearch(url) {
	var refineButton = document.getElementById('refine-button');
	if (refineButton) {
		refineButton.style.display = 'none';
	}
	var myForm = document.callRemoteForm;
	if (myForm) {
		myForm.action = url;
		myForm.target = '_self';
		myForm.submit();
	}
}

function hideAd() {
	if (adTimeout) {
		clearTimeout(adTimeout);
		adTimeout = false;
	}
	var divAd = document.getElementById('search-ad-box');
	if (divAd) {
		divAd.style.display = 'none';
	}
}

function callJsOnChange(id, value, replace) {
	var otherValue = otherValuesMap[id + ':' + value];
	if (otherValue) {
		if (replace && window.replaceOtherValue) {
			otherValue = replaceOtherValue(otherValue);
		}
		eval(otherValue);
	}
}

function showCountResultsSearching(show) {
	var div;
	if (showSearchingTimer && !show) {
		clearTimeout(showSearchingTimer);
		showSearchingTimer = false;
	}
	div = document.getElementById(show ? 'count-results' : 'count-results-searching');
	if (div) {
		div.style.display = 'none';
	}
	div = document.getElementById(show ? 'count-results-searching' : 'count-results');
	if (div) {
		div.style.display = '';
	}
}

function validateControlsPrice(id, value) {
	var ok = true;
	var minPrice = id == 'minPrice' ? value : document.getElementById('input-minPrice').value;
	var maxPrice = id == 'maxPrice' ? value : document.getElementById('input-maxPrice').value;
	if (minPrice == '') {
		minPrice = 0;
	}
	if (maxPrice == '') {
		maxPrice = 100000;
	}
    if (Number(maxPrice) < Number(minPrice)) {
        alert('The minimum price is larger than the maximum price.');
        ok = false;
    }
	return ok;
}

function validateControlsPostcode(id, value) {
	var ok = true;
    if (value.length < 1) {
        alert('Please enter your postcode.');
        ok = false;
    }
	return ok;
}


