// ** 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,Username, Password)
{
	var docFrm = document.Form1;
	
    var newParm = document.getElementById(Username).value + "|" + document.getElementById(Password).value;
    
    document.getElementById(Username).value = "";
    document.getElementById(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();
}

function SwapImage1() {
  document.image1.src="/Images/Nav1_On.png"
}
function SwapImage1Back() {
  document.image1.src="/Images/Nav1_Off.png"
}

function SwapImage2() {
  document.image2.src="/Images/Nav2_On.png"
}
function SwapImage2Back() {
  document.image2.src="/Images/Nav2_Off.png"
}

function SwapImage3() {
  document.image3.src="/Images/Nav3_On.png"
}
function SwapImage3Back() {
  document.image3.src="/Images/Nav3_Off.png"
}

function SwapImage4() {
  document.image4.src="/Images/Nav4_On.png"
}
function SwapImage4Back() {
  document.image4.src="/Images/Nav4_Off.png"
}

// 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(navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
		e = window.event;

	// Check for Enter key
	if(e.keyCode == 13)
	{
		// Check to see if button or image.
		if(button.tagName.toUpperCase() == "INPUT" || button.tagName.toUpperCase() == "BUTTON")
			button.click();
		else if(button.tagName.toUpperCase() == "IMG")
			button.onclick();

		return false;
	}
} 

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);
}

// NewsLetter
function Subscribe(reqvalidator, regvalidator, emailaddress, ajaxBlock)
{
    ValidatorValidate(document.getElementById(reqvalidator));
    ValidatorValidate(document.getElementById(regvalidator));
    if(document.getElementById(reqvalidator).isvalid && document.getElementById(regvalidator).isvalid && document.getElementById(emailaddress).value.length >0)
    {
        var EmailAddress = document.getElementById(emailaddress).value;
        InitiateAsyncRequest(ajaxBlock,'email|' + EmailAddress);
    }
}      

function NewsletterEvent(e,EmailValidatorReq,EmailValidatorReg, emailaddress, AjaxBlock)
{
	if (document.all){ // Handle IE
	   if(event.keyCode == 13)
            { 
                Subscribe(EmailValidatorReq,EmailValidatorReg,emailaddress,AjaxBlock);
                return false; 
            } 
	} else { // Handle the Fox
	    if (e.keyCode == 13)
		    { 
                Subscribe(EmailValidatorReq,EmailValidatorReg,emailaddress,AjaxBlock);
			    return false; 
            } 
	}
}  

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;
    window.location.href = resultsPage + '?SearchTerms=' + searchTerms;
}


function ChangePassword(ajaxBlock, tPassword, tPasswordConfirm)
{
    Page_ClientValidate();
    
    var Password = document.getElementById(tPassword);
    var PasswordConfirm = document.getElementById(tPasswordConfirm);
    if((Password.value == PasswordConfirm.value) && (Password.value.length>0))
    {
        var NewPassword = Password.value;
        InitiateAsyncRequest(ajaxBlock,'password|' + NewPassword);
        document.getElementById('PassMatch').innerText = "";
    } else {
        if (Password.value != '' && PasswordConfirm.value != '')
        {
            document.getElementById('PassMatch').innerText = "* Passwords must match";
        } else {
            document.getElementById('PassMatch').innerText = "";
        }
    }
}

function QuickSearchClear(KeywordControl)
{
    var Keywords = KeywordControl.value;
    
    if (Keywords == 'Enter keyword(s) here...')
        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;
    }    
}




