// identify explorer - not as easy as it sounds (opera likes to pretend it's IE)
var MSIE = /^ms_/.test(document.documentElement.uniqueID);
var ieVersion = (MSIE) ? navigator.appVersion.match(/MSIE (\d\.\d)/)[1] : 0;

/**
 * Adds a counter to a textarea and limits its number of charaters to maxLength.
 */
function addTextAreaCounter(textareaName, maxLength, alertMessage) {
	var textarea = document.getElementById(textareaName);
	var textareaCounterName = textareaName + 'Counter';
	function updateCounter() {
		var value = maxLength - textarea.value.length;
		var counter = textarea.form[textareaCounterName];
		counter.value = value;
	}
	function onKeyPressHandler(evt) {
		if (!evt) {
		    evt = window.event;
        }
		//return checkTextareaMaxLength(textarea, evt, maxLength);
	}
	function onBlurHandler() {
		if (textarea.value.length>maxLength && alertMessage) {
			alert(alertMessage);
			if (textarea.focus) {
			    textarea.focus();
            }
		}
	}

	if (!textarea.form[textareaCounterName]) {
		if (MSIE) {
			// margin top -1px cos IE likes to be annoying
			document.writeln('<div id="character_count" style="float: left; margin: -1px 0px 0px 3px;display:inline;"><input type="text" name="' + textareaCounterName + '" size="4" maxlength="4" value="" disabled="disabled" style="margin: 0px;padding:0px;" /> characters left</div>');
		} else {
			document.writeln('<div id="character_count" style="float: left; margin: 0px 0px 0px 3px;"><input type="text" name="' + textareaCounterName + '" size="4" maxlength="4" value="" disabled="disabled" style="margin: 0px;padding:0px;" /> characters left</div>');
		}
		
		updateCounter();
		textarea.onkeypress = onKeyPressHandler;
		textarea.onkeyup = textarea.onkeydown = updateCounter;
		textarea.onblur = onBlurHandler;
	} else {
		alert('Error in addTextAreaCounter(): Form already contains a child node named "' + textareaCounterName + '".');
	}
}

function _addEventListener(element, eventName, func) {
	if (element.addEventListener) element.addEventListener(eventName, func, false); // W3C
	else if (element.attachEvent) element.attachEvent('on' + eventName, func); // IE
	else element['on' + eventName] = func;
}

function submitForm(formName) {
	document[formName].submit()
};

function setFormAction(formName, actionValue) {
	document[formName].action = actionValue;
};

function openWindow(url, width, height){
	var win = window.open(url, "", "toolbar=no,location=no,directories=no,status=no,menubar=0,resizable=0,copyhistory=no,width=" + width + ",height=" + height + ",scrollbars=1");
	if (win.focus) win.focus();
};

function getWindowHeight() {
	return window.innerHeight || document.documentElement.offsetHeight;
};

// convert text to HTML so we can update innerHTML safely
function encodeHTML(text) {
	return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
};

function adSetup() {
	if (window.adDrop) adDrop();
	resize();
	if (window.roundedCorners) roundedCorners.recalc();
};

// ensure that page content expands to fill the height of the screen
var MIN_HEIGHT = (MSIE) ? "height" : "minHeight";
function resize() {
	var content = document.getElementById("pagecontent");
	var footer = document.getElementById("footer");
	if (content && footer) {
		//content.style[MIN_HEIGHT] = getWindowHeight() - content.offsetTop - footer.offsetHeight;
	}
};

// event handling

function addEventHandler(element, event, handler) {
	if (element.attachEvent) element.attachEvent(event, handler);
	else if (element.addEventListener)	element.addEventListener(event.slice(2), handler, null);
};

if (!MSIE || ieVersion > 5) addEventHandler(window, "onresize", resize);
addEventHandler(window, "onload", adSetup);

//admin site functions

function setUserAction(formName, actionField, actionValue) {
    document[formName].elements[actionField].value = actionValue;
}

function setNextStep(formName, value) {
    document[formName].nextStep.value = value;
}

// script to target parent of pop-up window

function targetopener(mylink, closeme, closeonly){
	if (! (window.focus && window.opener))return true;
	window.opener.focus();
	if (! closeonly)window.opener.location.href=mylink.href;
	if (closeme)window.close();
	return false;
	}

//car finance price-poster
function constructURL(url,formName){
	amount=document.finance.borrow.value;
	newURL = url+'?amount='+amount;
	//removed opener functionality
	//window.opener.focus();
	//window.opener.location.href=newURL;
	//window.location.href=newURL;
	raw_popup(newURL,'_blank','location=0,resizable=yes,statusbar=0,scrollbars=1, menubar=0, width=780, height=500');
	//self.resizeTo(780,500);
	return false;
}

/* popup window stuff */

function isUndefined(v) {
    var undef;
    return v===undef;
}

var _POPUP_FEATURES = 'location=0,resizable=yes, statusbar=0,scrollbars=1, menubar=0, width=680, height=500';

function raw_popup(url, target, features) {
    // pops up a window containing url optionally named target, optionally having features
    if (isUndefined(features)) features = _POPUP_FEATURES;
    if (isUndefined(target  )) target   = '_blank';
    var theWindow = window.open(url, target, features);
    theWindow.focus();
    return theWindow;
}

function link_popup(src, features) {
    // to be used in an html event handler as in: <a href="..." onclick="link_popup(this,...)" ...
    // pops up a window grabbing the url from the event source's href
    return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', features);
}

function fillChilds(form,name1,name2,allchilds,allparents) {
	emptySelectBox(form, name1, allchilds);
	var childid = 0;
	var start = 1;
	var name2Length = document[form][name2].length;
	if (allchilds == true) {
		childid = 1;
	}
	if (allparents == false) {
		start = 0;
	}
    var selectedvalue = 0;
	for (var i=start;i<name2Length;i++) {
		if (document[form][name2][i].selected) {

            selectedvalue = parentArr[i-start].split(";")[0];
			var tmpArr = childArr[i-start].split("|");
			for (var j=0;j<tmpArr.length;j++) {
				var tmpArr2 = tmpArr[j].split(";");
			    document[form].elements[name1].options[childid] = new Option(tmpArr2[1],tmpArr2[0]);
                childid++;
			}
		}
	}
    if (allchilds) {
        document[form].elements[name1].options[0].value = '0';
    }
}

function emptySelectBox(form, boxname, allchilds){
	var length = Number(document.forms[form].elements[boxname].options.length);

	if (navigator.appName.indexOf("Netscape") != -1) {
		for (var i=(length); i > 0; i--) {
			document.forms[form].elements[boxname].options[i]=null;
		}
	} else if (navigator.userAgent.indexOf("Opera") != -1) {
		for(var i=(length); i > 0; i--) {
			document.forms[form].elements[boxname].options.remove(i);
		}
	} else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4)) {
		for(var i=(length); i > 0; i--) {
			document.forms[form].elements[boxname].options.remove(i);
		}
	} else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) < 4)) {
		for (var i=(length-1); i > 0; i--) {
			document.forms[form].elements[boxname].options[i].selected = false;
		}
	} else {
		for (var i=(length-1); i > 0; i--) {
			document.forms[form].elements[boxname].options[i].selected = false;
		}
	}
	if (navigator.appName.indexOf("Netscape") == -1) {
		if (allchilds) {
			document.forms[form].elements[boxname].options[0] = new Option("All","0",true,true);
		} else {
			document.forms[form].elements[boxname].options[0] = new Option("","0",true,true);
		}
		document.forms[form].elements[boxname].options[0].selected = true;
	}
}

var numb = '0123456789';

function isValid(parm,val) {
  if (parm == "") return true;
  for (i=0; i<parm.length; i++) {
    if (val.indexOf(parm.charAt(i),0) == -1) return false;
  }
  return true;
}

function isNum(parm) {return isValid(parm,numb);}

function openLocationWindow(formName, fieldName, parameterName, url){
    url = url + '?' + parameterName + '=' + document[formName].elements[fieldName].value + '&locationfield=' + fieldName;
	openWindow(url, '700','400');
};

function returnValueToOpener(formName, fieldName, localFormName, localFieldName, multiple) {
    if (formName != null && fieldName != null && localFormName != null && localFieldName != null) {
        var returnValue = this.document.forms[localFormName].elements[localFieldName].value;
        if (multiple) {
            var array = new Array();
            array = this.document.forms[localFormName].elements[localFieldName];
            var finished = false;
            var index = 0;
            while(!finished || index < array.length) {
                if (array[index].checked == true) {
                    returnValue = array[index].value;
                    finished = true;
                }
                index++;
            }
        }
        window.opener.document[formName].elements[fieldName].value = returnValue;        
    }
};

function closeLocationWindow(formName) {
    window.close();
    window.opener.document[formName].submit();
    window.opener.focus();
};

// Used by the <input:select> tag to remember options when the user navigates back in history
function rememberoptions_load(inputSelect) {
	if (inputSelect && inputSelect.form && inputSelect.options) {
		var hValues = inputSelect.form[inputSelect.name + '_values'];
		var hText = inputSelect.form[inputSelect.name + '_text'];
		var hSelected = inputSelect.form[inputSelect.name + '_selected'];
		if (hValues && hText && hSelected && hValues.value.length > 0) {
			// deserialize the arrays from the hidden fields
			var optionValues = hValues.value.split(';');
			var optionText = hText.value.split(';');
			var optionSelected = hSelected.value.split(';');

			// Delete all existing options.
			while (inputSelect.options.length>0) inputSelect.options.remove(0);

			for (var i=0; i<optionValues.length; ++i) {
				// Create a new option
				var option = new Option(optionText[i], optionValues[i]);
				// Add the option to the select tag
				inputSelect.options[i] = option;
				// Mark the option as selected if it should be
				for (var j=0; j<optionSelected.length; ++j) if (option.value == optionSelected[j]) {
					option.selected = true;
				}
			}
		}
	}
}

// Used by the <input:select> tag to remember options when the user navigates back in history
function rememberoptions_save(inputSelect) {
	if (inputSelect && inputSelect.form && inputSelect.options) {
		var options = inputSelect.options;
		var optionValues = new Array(), optionText = new Array(), optionSelected = new Array();

		// Store options to arrays
		for (var i=0; i<options.length; ++i) {
			var option = options[i];
			optionValues.push(option.value);
			optionText.push(option.text);
			if (option.selected) optionSelected.push(option.value);
		}

		// Serialize the arrays to hidden fields
		inputSelect.form[inputSelect.name + '_values'].value = optionValues.join(';');
		inputSelect.form[inputSelect.name + '_text'].value = optionText.join(';');
		inputSelect.form[inputSelect.name + '_selected'].value = optionSelected.join(';');
	}
}

// Used by the <input:select> tag to remember options when the user navigates back in history
function rememberoptions_registerEventHandlers(formName, selectTagName) {
	// Find formName if it's missing.
	if (!formName || formName.length==0) {
		var tags = document.getElementsByName(selectTagName);
		if (tags.length>0 && tags[0] && tags[0].form && tags[0].form.name) formName = tags[0].form.name;
	}
	var form = document.forms[formName];
	if (form) {
		var selectTag = form[selectTagName];
		if (selectTag) {
			_addEventListener(form, 'submit', function() { rememberoptions_save(selectTag); });
			_addEventListener(window, 'load', function() { rememberoptions_load(selectTag); });
		}
	}
}

function emptySelectBox(form, boxname, allchilds){
	var length = Number(document.forms[form].elements[boxname].options.length);

	if (navigator.appName.indexOf("Netscape") != -1) {
		for (var i=(length); i > 0; i--) {
			document.forms[form].elements[boxname].options[i]=null;
		}
	} else if (navigator.userAgent.indexOf("Opera") != -1) {
		for(var i=(length); i > 0; i--) {
			document.forms[form].elements[boxname].options.remove(i);
		}
	} else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4)) {
		for(var i=(length); i > 0; i--) {
			document.forms[form].elements[boxname].options.remove(i);
		}
	} else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) < 4)) {
		for (var i=(length-1); i > 0; i--) {
			document.forms[form].elements[boxname].options[i].selected = false;
		}
	} else {
		for (var i=(length-1); i > 0; i--) {
			document.forms[form].elements[boxname].options[i].selected = false;
		}
	}
	if (navigator.appName.indexOf("Netscape") == -1) {
		if (allchilds) {
			document.forms[form].elements[boxname].options[0] = new Option("All","0",true,true);
		} else {
			document.forms[form].elements[boxname].options[0] = new Option("","0",true,true);
		}
		document.forms[form].elements[boxname].options[0].selected = true;
	}
}


/*create request object to allow data interrogation
  without page reloads*/
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) oldonload();
			func();
		}
	}
}

//toggle divs
function blockToggle(nr,link)
{
	if (link) {openclose = link;}
	else {openclose = null;}
	if (document.layers)
	{
		current = (document.layers[nr].display == 'block') ? 'none' : 'block';
		document.layers[nr].display = current;
	}
	else if (document.all)
	{
		current = (document.all[nr].style.display == 'block') ? 'none' : 'block';
		if (openclose) {
		    if ((openclose.className=='minus') || (openclose.className=='open')) {
		        current = 'none';
		    } else {
		        current = 'block';
		    }
		}
		document.all[nr].style.display = current;
	}
	else if (document.getElementById)
	{
		current = (document.getElementById(nr).style.display == 'block') ? 'none' : 'block';
		if (openclose) {
		    if ((openclose.className=='minus') || (openclose.className=='open')) {
		        current = 'none';
		    } else {
		        current = 'block';
		    }
		}
		document.getElementById(nr).style.display = current;
	}
            if (openclose) {
                if((openclose.className=='open') || (openclose.className=='closed')) {
                    if (current=='block') {openclose.className='open'} else {openclose.className='closed'};
                } else {
                    if (current=='block') {openclose.className='minus'} else {openclose.className='plus'};
                }
            }

}

// virtual tours for ie6 and below
function virtual_tours(anchor, ul_id, action)
{
	if (MSIE && ieVersion <= 6) {
		var list = document.getElementById(ul_id);
		list.style.display = action;
		
	};
}
