﻿// ** Global Constants
var LeftPosition = (screen.width) ? (screen.width-1024)/2 : 0;
var TopPosition = (screen.height) ? (screen.height-768)/2 : 0;
var success = true;
// ** Global Functions **

function LaunchWindow(url, features) 
{
	var docFrm = document.Form1;
	
	//window.external.AutoCompleteSaveForm(docFrm);
	window.open(url, "AdminWindow", features);
}

function Login(controlId)
{
	var docFrm = document.Form1;
	
    var newParm = docFrm.Username.value + "|" + docFrm.Password.value;
    
    docFrm.Username.value = "";
    docFrm.Password.value = "";

    controlId.Callback(newParm); 
}

function Redirect(path)
{
	if(path == null || path == "")
	    path = "Admin/Default.aspx"
	location.href = path;    
}

function ExpandDetails(srcElem, targetElem)
{

	var doc = document;

	targetElem = doc.getElementById(targetElem);
	var parentElem = srcElem;

	while(parentElem && parentElem.tagName != "TR")
		parentElem = parentElem.parentElement;


	if(targetElem.style.display == "none")
	{
		targetElem.style.display = "block";
		srcElem.src = "Images/GridImages/topItem_col.gif";
		//parentElem.className = "GridExpandedItem";
		//class="GridExpandedItem"
	}
	else
	{
		targetElem.style.display = "none";
		srcElem.src = "Images/GridImages/topItem_exp.gif";
	//	parentElem.className = "GridRow";
	}
} 
function ShowPopup(path, title, width, height, top, left)
{
	var leftPosition;
	var topPosition;
	
	height = typeof height != "undefined" ? height : 400;
	width = typeof width != "undefined" ? width : 400;
	
	if(typeof top == "undefined")
		topPosition = (screen.height) ? (screen.height-height)/2 : 0;
	else
		topPosition = top;
		

	if(typeof left == "undefined")
		leftPosition = (screen.width) ? (screen.width-width)/2 : 0;
	else
		leftPosition = left;

	window.open(path, title, "scrollbars=yes,height="+ height +",width="+ width +",status=no,toolbar=no,menubar=no,location=no,resizable=no, top=" + topPosition + ", left=" + leftPosition);
}

function hidediv(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}

function showdiv(id) {
	//safe function to show an element with a specified id
		  
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}
// ** Email Validation **
function SubmitEnquiry(validate, pathAbove)
{
	var doc = document;
	var docFrm = doc.forms[0];
	
	if(typeof validate != "undefined" && validate == true)
		var valid = ValidateForm();
	
	if(!valid) return;
	
	docFrm.submit();
}

// Validates an email and returns true/false.
function IsEmail(email)
{
	var re = /^(([^<>()[\]\\.,;:\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,}))$/
	return re.test(email)
}

// Validates the input from a contact form page.
function ValidateForm()
{
var doc = document;
var docFrm = doc.forms[0];
success = true;
	for(var i=0; i < docFrm.length; i++)
	{
		if(docFrm[i].name == null || docFrm[i].name.substring(0, 1) != "z")continue;

		if(docFrm[i].getAttribute("validate") != "undefined" && docFrm[i].getAttribute("validate") != "" && docFrm[i].getAttribute("validate") != null)
		{
			switch(docFrm[i].getAttribute("validate"))
			{
				case "Required":
					if(docFrm[i].value.length < 1)
						InvalidateElement(docFrm[i]);
					else if(docFrm[i].value == "-1")
						InvalidateElement(docFrm[i]);
					else
						ValidateElement(docFrm[i]);
				break;
				case "Required,Number":
					if(docFrm[i].value.length < 1)
						InvalidateElement(docFrm[i]);
					else if(isNaN(docFrm[i].value))
						InvalidateElement(docFrm[i]);
					else
						ValidateElement(docFrm[i]);
				break;
				case "Required,Email":
					if(docFrm[i].value.length < 1)
						InvalidateElement(docFrm[i]);
					else if(!IsEmail(docFrm[i].value))
						InvalidateElement(docFrm[i]);
					else
						ValidateElement(docFrm[i]);
				break;
				case "Required,Dropdown":
					if(docFrm[i].selectedIndex < 1)
						InvalidateElement(docFrm[i]);
					else
						ValidateElement(docFrm[i]);
				break;
				case "Number":
					if(isNaN(docFrm[i].value) && docFrm[i].value.length > 0)
						InvalidateElement(docFrm[i]);
					else
						ValidateElement(docFrm[i]);
				break;
				case "Email":
					if(!IsEmail(docFrm[i].value) && docFrm[i].value.length > 0)
						InvalidateElement(docFrm[i]);
					else
						ValidateElement(docFrm[i]);
				break;
			}
//			alert(docFrm[i].id + " " + success);
		}
	}
	return success;
}

// Function that clears any altered styles if the input is valid
function ValidateElement(elem)
{
	var ErrMessage = document.getElementById(elem.name + "ErrorMessage");

	if(typeof elem.errormessage != "undefined" && elem.errormessage != "")
	{
		if(typeof ErrMessage != "undefined" && ErrMessage != "")
		{
			ErrMessage.innerHTML = " ";
		}
	}
	//success = true;
	elem.style.backgroundColor = "";
	elem.style.color = "";
	elem.style.fontWeight = "";
}

// Function that changes the style of an input if it's invalid or missing
function InvalidateElement(elem)
{
	var ErrMessage = document.getElementById(elem.name + "ErrorMessage");
	
	if(typeof elem.errormessage != "undefined" && elem.errormessage != "")
	{
		if(typeof ErrMessage != "undefined" && ErrMessage != "")
		{
			ErrMessage.innerHTML = elem.errormessage;
		}
	}
	success = false;
	elem.style.backgroundColor = "#f8f7de";
	elem.style.color = "#000000";
	elem.style.fontWeight = "";
}

// ** Site Specific Functions **

// Makes a button a default button
/*function ClickButton(e, buttonId)
{ 
	var button = document.getElementById(buttonId); 
	
	if (typeof(button) == 'object')
	{ 
		if(navigator.appName.indexOf("Netscape")>(-1))
		{ 
            if(e.keyCode == 13)
            { 
                button.click(); 
                return false; 
            } 
		}
    } 
    
    if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
    { 
		if (event.keyCode == 13)
		{ 
			button.click(); 
			window.event.returnValue=false;
			return false; 
        } 
    } 
} 
*/
function SubmitToSearch(Page, ClientID) {
   	location.href = Page + "?Make=" + document.getElementById(ClientID + '_SearchMake').value + "&Model=" + document.getElementById(ClientID + '_SearchModel').value + "&MinPrice=" + document.getElementById('SearchMinPrice').value + "&MaxPrice=" + document.getElementById('SearchMaxPrice').value + "&Transmission=" + getRadioValue('Transmission') + "&Age=" + document.getElementById('SearchAge').value + "&Colour=" + document.getElementById(ClientID + '_SearchColour').value;
}

 function getRadioValue(radioGroupName) {
        radios = document.getElementsByName(radioGroupName);
        for (i = 0; i < radios.length; i++) {
            if (radios[i].checked) return radios[i].value;
        }
    }
    
function PrintPage(StockNumber)
{
	if(StockNumber.length <1)
		return false;
	path = "PrintPage.aspx?StockNumber=" + StockNumber;
	ShowPopup(path, "PrintPage", 615, 765);
}

function ActionPrint()
{
	if(PrintButton == null || typeof(PrintButton) == "undefined")return;
	
	PrintButton.style.visibility = "hidden";
	window.print();
	PrintButton.style.visibility = "visible";
}

function ChangeSearchOrder(CurrentPageUrl, ClientID)
{
    location.href=CurrentPageUrl + "&Sort=" + document.getElementById(ClientID + '_Sort').value;
}


// Global Callback Function
function InitiateAsyncRequest(AjaxManager, arguments)
{
   var ajaxManager = AjaxManager;
   ajaxManager.AjaxRequest(arguments);
}


function SiteSearchEvent(elemID, resultsPage, theEvent)
{
    if (window.event)
    {
        if(window.event.keyCode == 13)
        {
            window.event.returnValue = false;
            SiteSearch(elemID, resultsPage);
        }
    } else {
        if(theEvent.keyCode == 13)
        {
            theEvent.preventDefault();
            SiteSearch(elemID, resultsPage);
        }
    }
}

function SiteSearch(elemID, resultsPage)
{
    var searchTerms = document.getElementById(elemID).value;
    if (searchTerms == 'Enter Keywords...')
        searchTerms = '';
    window.location.href = resultsPage + '?SearchTerms=' + searchTerms;
}

function ChangePassword(ajaxBlock, Password, PasswordConfirm)
{

    Page_ClientValidate();
    if((Password.value == PasswordConfirm.value) && (Password.value.length>0))
    {
        var NewPassword = Password.value;
        InitiateAsyncRequest(ajaxBlock,'password|' + NewPassword);
    }
}

function QuickSearchClear(KeywordControl)
{
    var Keywords = KeywordControl.value;

    if (Keywords == 'Enter Keywords...')
        KeywordControl.value = '';
}

// Gets all the checkboxes for the section specified.
function GetElementsForSection(section)
{
    var docFrm = document.Form1;
    var chkBoxes = new Array();
    var x = 0;
    
    // Loop through all elements in the form
    for(i = 0; i < docFrm.elements.length; i++)
    {
        // Check elements to see if they are checkboxes and are part of the section required.
        if(docFrm.elements[i].tagName.toLowerCase() == "input" && docFrm.elements[i].type.toLowerCase() == "checkbox" && docFrm.elements[i].name.indexOf(section, docFrm.elements[i].name.lastIndexOf('$')) > -1)
        {
            // Add to array
            chkBoxes[x] = docFrm.elements[i];
            x++;
        }
    }
    
    return chkBoxes;
}

// Clear the 'any' box when the user clicks on a 'specific' box.
function ClearAnyBoxes(section, elem)
{
    if(!elem.checked)return;

    var chkBoxes = GetElementsForSection(section);
    
    // Loop through array and check for value of 0 for the 'any' checkbox.
    // NB: not used the first one, just in case it moves.
    for(i = 0; i < chkBoxes.length; i++)
    {
        if(chkBoxes[i].value == "0")
        {
            chkBoxes[i].checked = false;
            // Only one 'any' box will exist at any one time for that section.
            return;
        }
    }  
}

// Clear the 'specific' boxes when the user clicks on a 'any' box.
function ClearSpecificBoxes(section, elem)
{
    if(!elem.checked)return;

    var chkBoxes = GetElementsForSection(section);
    
    // Loop through array and check for value of not 0 for the 'specific' checkboxes.
    for(i = 0; i < chkBoxes.length; i++)
    {
        if(chkBoxes[i].value != "0")
            chkBoxes[i].checked = false;
    }    
}

function SwapImage(imageRef, mainImage)
{
	if(imageRef.src.substring(imageRef.src.length-16,imageRef.src.length) == "NoImageSmall.jpg")
		return false;

	var mainImage = document.getElementById(mainImage);	
	var newImagePath = imageRef.src.substring(0,imageRef.src.lastIndexOf('/'));
	var newImageFilename = imageRef.src.substring(imageRef.src.lastIndexOf('/')+1);
	var oldImagePath = mainImage.src.substring(0,imageRef.src.lastIndexOf('/'));
	var oldImageFilename = mainImage.src.substring(imageRef.src.lastIndexOf('/')+1);

	var mainImageSrc = newImagePath + "/" + newImageFilename.replace("_S", "");
	var thumbImageSrc = oldImagePath + "/" + oldImageFilename.replace(".jpg", "_S.jpg");
	//var thumbImageSrc = oldImagePath + "_S" + oldImageFilename;
	
	if (document.all) {
	    mainImage.style.filter="blendTrans(duration=0.25)";

	    if (mainImage.filters.blendTrans.status == 2)return;
	    mainImage.filters.blendTrans.apply();
	    mainImage.src = mainImageSrc;	
	    mainImage.filters.blendTrans.play();
	    imageRef.src = thumbImageSrc;
	} else {
	    mainImage.src = mainImageSrc;
	    imageRef.src = thumbImageSrc;
	}
	
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}