function onLogon() {
	
	if (document.frmLogon.UID.value == "") {
		alert("The Username is missing. Please check it and try again.");
		document.frmLogon.UID.focus();
		return false;
	}

	if (document.frmLogon.PWD.value == "") {
		alert("The Password is missing. Please check it and try again.");
		document.frmLogon.PWD.focus();
		return false;
	}

	
	$.cookie('username', document.frmLogon.UID.value, { path: '/', expires: 90, domain: document.domain, secure: false });
	$.cookie('password', document.frmLogon.PWD.value, { path: '/', expires: 90, domain: document.domain, secure: false });


	document.frmLogon.hdnAction.value="logon";
	document.frmLogon.submit();
}

function defaultKeypressLogon(e){ 
	var characterCode; 
	
	if(e && e.which){  
		e = e;
		characterCode = e.which;
	}else{
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		onLogon();
		return false;
	}else{
		return true;
	}
}


function onLogoff() {
	document.frmLogoff.submit();
}

function defaultKeypressNewUser(e){ 
	var characterCode; 
	
	if(e && e.which){ 
		e = e;
		characterCode = e.which;
	}else{
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		newUser();
		return false;
	}else{
		return true;
	}
}

function newUser() {

	if (document.frmLogon.sFirstNm.value == "") {
		alert("The First Name is missing. Please check it and try again.");
		document.frmLogon.sFirstNm.focus();
		return false;
	}

	if (document.frmLogon.sLastNm.value == "") {
		alert("The Last Name is missing. Please check it and try again.");
		document.frmLogon.sLastNm.focus();
		return false;
	}

	if (emailCheck(document.frmLogon.sEmail.value) == false) {
		alert("The email address provided is not valid. Please check it and try again.");
		document.frmLogon.sEmail.focus();
		return false;
	}

	document.frmLogon.hdnAction.value="newuser";
	document.frmLogon.submit();

}

function defaultKeypressChangePassword(e){ 
	var characterCode; 
	
	if(e && e.which){ 
		e = e;
		characterCode = e.which;
	}else{
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		changePassword();
		return false;
	}else{
		return true;
	}
}

function changePassword() {

	if (document.frmLogon.sUsername.value == "") {
		alert("The User Name provided is not valid. Please check it and try again.");
		document.frmLogon.sUsername.focus();
		return false;
	}

	if (document.frmLogon.sCurrentpassword.value == "") {
		alert("The current password provided is not valid. Please check it and try again.");
		document.frmLogon.sCurrentpassword.focus();
		return false;
	}

	if (document.frmLogon.sNewpassword.value == "") {
		alert("The new password provided is not valid. Please check it and try again.");
		document.frmLogon.sNewpassword.focus();
		return false;
	}

	if (document.frmLogon.sNewpassword.value != document.frmLogon.sConfirmNewpassword.value) {
		alert("The new password does not match the confirmation password. Please check it and try again.");
		document.frmLogon.sNewpassword.focus();
		return false;
	}
	
	if (document.frmLogon.sNewpassword.value == document.frmLogon.sCurrentpassword.value) {
		alert("The new password is the same as the current password supplied. You can not change your password to the current password.");
		document.frmLogon.sNewpassword.focus();
		return false;
	}

	document.frmLogon.hdnAction.value="changepassword";
	document.frmLogon.submit();
}

function defaultKeypressForgotPassword(e){ 
	var characterCode; 
	
	if(e && e.which){ 
		e = e;
		characterCode = e.which;
	}else{
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		forgotPassword();
		return false;
	}else{
		return true;
	}
}

function forgotPassword() {

	if (emailCheck(document.frmLogon.sEmailaddress.value) == false) {
		alert("The email address provided is not valid. Please check it and try again.");
		document.frmLogon.sEmailaddress.focus();
		return false;
	}

	document.frmLogon.hdnAction.value="forgotpassword";
	document.frmLogon.submit();
}

function onSubmit() {
	var searchboxValue=document.frmMain.keyword.value;
	document.frmMain.sKeywordSearch.value=document.frmMain.searchbox.value;
	if(document.frmMain.searchbox.value=="Search"){
		searchboxValue="";
		document.frmMain.searchbox.value="";
		document.frmMain.sKeywordSearch.value="";
	}
	document.frmMain.sSearchTerms.value=getSearchTerms();
	document.frmMain.action = document.frmMain.action + "?keyword=" +searchboxValue+ document.frmMain.sSearchTerms.value;
	//alert(document.frmMain.action);
	document.frmMain.submit();
}

function onSubmitCategories(category_id) {
	sCategory   = formatCriteriaList("category",category_id+",");
	sCatalog	= formatCriteriaList("catalog", "8,");
    document.frmMain.sSearchTerms.value=sCategory+sCatalog
	document.frmMain.searchbox.value="";
	document.frmMain.sKeywordSearch.value="";
	document.frmMain.action = document.frmMain.action + "?keyword=" + document.frmMain.sSearchTerms.value;
	document.frmMain.submit();
}

function defaultKeypressSearch(e){ 
	var characterCode; 
       if(document.getElementById("searchbox").value == "Search")
		document.getElementById("searchbox").value = "";
	if(e && e.which){ 
		e = e;
		characterCode = e.which;
	}else{
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		onSubmit();
		return false;
	}else{
		return true;
	}
}


function emailCheck (emailStr) {
var checkTLD=1;
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/i;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);

if (matchArray==null) {
//	alert("Email address seems incorrect (check @ and .'s)");
	return false;
}

var user=matchArray[1];
var domain=matchArray[2];

for (i=0; i<user.length; i++) {
	if (user.charCodeAt(i)>127) {
//		alert("The email username contains invalid characters.");
		return false;
   }
}

for (i=0; i<domain.length; i++) {
	if (domain.charCodeAt(i)>127) {
//		alert("The email domain name contains invalid characters.");
		return false;
   }
}

if (user.match(userPat)==null) {
//	alert("The email username doesn't seem to be valid.");
	return false;
}

var IPArray=domain.match(ipDomainPat);

if (IPArray!=null) {
	for (var i=1;i<=4;i++) {
		if (IPArray[i]>255) {
//			alert("Destination email IP address is invalid!");
			return false;
	   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The email domain name does not seem to be valid.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The email address must end in a well-known domain or two letter " + "country.");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("The email address is missing a hostname!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}



function formatCriteriaList(sLabel, sList) {
	if (sList.length > 0){
		return "&" + sLabel + "=" + sList.substring(0, sList.length - 1);
    }else {
		return "";
	}

}

function getSearchTerms() {
var sSearch		= "";
var sCategory	= "";
var sMaterial	= "";
var sDateAdded	= "";
var sFormat		= "";
var sRight		= "";
var sLength		= "";
var sLanguage	= "";
var sSupplier	= "";
var sYear		= "";
var sBrand		= "";
var sCatalog	= "";

	$("#nav .selected1").each(function(index){

		switch ($(this).attr('type'))
		{
			case 'category':
				sCategory += $(this).attr('ref') + ",";
				break;
			case 'material':
				sMaterial += $(this).attr('ref') + ",";
				break;
			case 'dateAdded':
				sDateAdded += $(this).attr('ref') + ",";
				break;
			case 'format':
				sFormat += $(this).attr('ref') + ",";
				break;
			case 'right':
				sRight += $(this).attr('ref') + ",";
				break;
			case 'length':
				sLength += $(this).attr('ref') + ",";
				break;
			case 'language':
				sLanguage += $(this).attr('ref') + ",";
				break;
			case 'supplier':
				sSupplier += $(this).attr('ref') + ",";
				break;
			case 'year':
				sYear += $(this).attr('ref') + ",";
				break;
			case 'brand':
				sBrand += $(this).attr('ref') + ",";
				break;
			case 'catalog':
				sCatalog += $(this).attr('ref') + ",";
				break;
			default:
				break;
		}
	});

	sCategory	= formatCriteriaList("category",	sCategory);
	sMaterial	= formatCriteriaList("material",	sMaterial);
	sDateAdded	= formatCriteriaList("dateAdded",	sDateAdded);
	sFormat		= formatCriteriaList("format",		sFormat);
	sRight		= formatCriteriaList("right",		sRight);
	sLength		= formatCriteriaList("length",		sLength);
	sLanguage	= formatCriteriaList("language",	sLanguage);
	sSupplier	= formatCriteriaList("supplier",	sSupplier);
	sYear		= formatCriteriaList("year",		sYear);
	sBrand		= formatCriteriaList("brand",		sBrand);
	sCatalog	= formatCriteriaList("catalog",		sCatalog);

	sSearch = sCategory + sMaterial + sDateAdded + sFormat + sRight + sLength + sLanguage + sSupplier + sYear + sBrand + sCatalog;
	//alert(sSearch);
	return sSearch;
}


function toggleLogonNav(sSelector, sField, sFilter, sHide, nSelector) {

	$(sSelector).click(function() {
		if ($(this).hasClass("closed") == true){
			$(this).removeClass("closed");
			$(this).addClass("open");
			$(sField).slideDown("medium");

			if ($(sFilter).hasClass("open")) {
				$(sFilter).removeClass("open");
				$(sFilter).addClass("closed");
				$(sHide).slideUp("medium");
			}
		} else {
			$(this).removeClass("open");
			$(this).addClass("closed");
			$(sField).slideUp("medium");
		}
	});

	$(nSelector).click(function() {
		if ($(sSelector).hasClass("closed") == true){
			$(sSelector).removeClass("closed");
			$(sSelector).addClass("open");
			$(sField).slideDown("medium");

			if ($(sFilter).hasClass("open")) {
				$(sFilter).removeClass("open");
				$(sFilter).addClass("closed");
				$(sHide).slideUp("medium");
			}
		} else {
			$(sSelector).removeClass("open");
			$(sSelector).addClass("closed");
			$(sField).slideUp("medium");
		}
	});
}


function toggleSearchNav(sSelector, nSelector) {

	$(sSelector).click(function() {

		if ($(this).hasClass("closed") == true){

			$("#nav #searchoptions .level1 .arrow").removeClass("open");
			$("#nav #searchoptions .level1 .arrow").addClass("closed");
            if ($(this).attr("type") == "supplier") {
				$(".level3").hide();
				$(this).parent().parent().find(".level3").show();
			} else {
				$(".level3").slideUp("medium");
				$(this).parent().parent().find(".level3").slideDown("medium");
			}

			$(this).removeClass("closed");
			$(this).addClass("open");
			

		} else {
		    $(this).removeClass("open");
		    $(this).addClass("closed");
			if ($(this).attr("type") == "supplier")  {
			  $(this).parent().parent().find(".level3").hide();
			} else{
			 $(this).parent().parent().find(".level3").slideUp("medium");
			}
		}
	
	});

	$(nSelector).click(function() {
		if ($(sSelector).hasClass("closed") == true){

			$("#nav #searchoptions .level1 .arrow").removeClass("open");
			$("#nav #searchoptions .level1 .arrow").addClass("closed");
            if ($(sSelector).attr("type") == "supplier") {
				$(".level3").hide();
				$(sSelector).parent().parent().find(".level3").show();
			} else {
				$(".level3").slideUp("medium");
				$(sSelector).parent().parent().find(".level3").slideDown("medium");
			}

			$(sSelector).removeClass("closed");
			$(sSelector).addClass("open");
			

		} else {
		    $(sSelector).removeClass("open");
		    $(sSelector).addClass("closed");
			if ($(sSelector).attr("type") == "supplier")  {
			  $(sSelector).parent().parent().find(".level3").hide();
			} else{
			 $(sSelector).parent().parent().find(".level3").slideUp("medium");
			}
		}
		
	});
}



function toggleNav() {


	$(".hidenav").click(function() {
		$("#nav li:hover ul").css("display","none"); 
	});



	$("#searchtop").mouseover(function() {
	    $("#searchoptions").slideDown("slow");
		$("#nav li:hover ul").css("position","absolute");

	});


	$("#nav").mouseleave(function() {
		$("#searchoptions").slideUp("slow");
	

	});

       
	$(".clear").click(function() {
		$(this).parent().children().remove("img");
		$(this).parent().parent().parent().find(".level2>.level3>div[type!=catalog]").removeClass("selected1").children().remove("img");
		$(this).parent().parent().parent().find(".level1 >div[type!=catalog]").children().remove("img");
		
	});



	//New User Stuff
	$("#searchoptions,.newuserfields, .changepasswordfields, .forgotpasswordfields").hide();
	
	/*Login expand Collapse */
	toggleLogonNav(".logon", ".logonfields", ".newuser, .changepassword, .forgotpassword",".newuserfields, .changepasswordfields, .forgotpasswordfields",".rightLogon");
	toggleLogonNav(".newuser", ".newuserfields", ".logon, .changepassword, .forgotpassword",".logonfields, .changepasswordfields, .forgotpasswordfields",".rightNewuser");
	toggleLogonNav(".changepassword", ".changepasswordfields", ".newuser, .logon, .forgotpassword",".newuserfields, .logonfields, .forgotpasswordfields",".rightChangePassword");
	toggleLogonNav(".forgotpassword", ".forgotpasswordfields", ".newuser, .changepassword, .logon",".newuserfields, .changepasswordfields, .logonfields",".rightForgot");
	

	$(".level3").hide();

	$("div.searchWrapper>div.level1>div.box[ers]").click(function() {
		$(this).children().remove("img");
		$(this).parent().parent().find(".level2>.level3>div[type]").removeClass("selected1").children().remove("img");
	});
	
	/* Search Expand Collapse */
	toggleSearchNav(".category", ".rightCategory");
	toggleSearchNav(".materials", ".rightMaterials");
	toggleSearchNav(".date", ".rightDate");
	toggleSearchNav(".format", ".rightFormat");
	toggleSearchNav(".rights", ".rightRights");
	toggleSearchNav(".length", ".rightLength");
	toggleSearchNav(".language", ".rightLanguage");
	toggleSearchNav(".supplier", ".rightSupplier");
	toggleSearchNav(".year", ".rightYear");
	toggleSearchNav(".brand", ".rightBrand");
	toggleSearchNav(".catalog", ".rightCatalog");

		

	//All filters except the catalog:
	$("#nav div[class='searchWrapper'] div > div[ref][type!=catalog]").click(function() {

		if ($(this).hasClass("selected1") == true){
			$(this).removeClass("selected1");
			$(this).children().remove("img");

			if ($(this).parent().parent().find("div").hasClass(".selected1") == false) 
				$(this).parent().parent().parent().find(".level1 > .box").children().remove("img");

		} else {
			$(this).addClass("selected1");
			$(this).append("<img class='selectAllIcon' src='images/icons/add_black.png'/>");		

			$(this).parent().parent().parent().find(".level1 > .box").children().remove("img");
			$(this).parent().parent().parent().find(".level1 > .box").append("<img class='selectAllIcon' src='images/icons/add_grey.png'/>");
		}
	});

	//Catalog filter:
	$("#nav div[class='searchWrapper'] div > div[ref][type=catalog]").click(function() {

		if ($(this).hasClass("selected1") == true){
			// Do Nothing
		} else {
			$(this).parent().children().remove("img");
			$(this).parent().parent().parent().find(".level2>.level3>div[type]").removeClass("selected1").children().remove("img");
			$(this).addClass("selected1");
			$(this).append("<img class='selectAllIcon' src='images/icons/add_black.png'/>");		
			$(this).parent().parent().parent().find(".level1 > .box").children().remove("img");
			$(this).parent().parent().parent().find(".level1 > .box").append("<img class='selectAllIcon' src='images/icons/add_grey.png'/>");
		}
	});

	// Causes the items with 'val=1' to get the plus sign:
	$("#nav div[class='searchWrapper'] div > div[val=1]").click();
}		

	function replace(string,text,by) {
	// Replaces text with by in string
			var i = string.indexOf(text);
			var newstr = '';
			if ((!i) || (i == -1)) return string;
			newstr += string.substring(0,i) + by;

			if (i+text.length < string.length)
					newstr += replace(string.substring(i+text.length,string.length),text,by);
			
			return newstr;
	}

	function onCheck(string) { if (string == "on") return true; return false; }

	function getValue(string,elementName,object,elementType) {
	// gets value of elementName from string and populates object of elementType

			var startPos = string.indexOf(elementName + "=")
			
			if (startPos > -1) {
					startPos = startPos + elementName.length + 1;
					var endPos = string.indexOf("&",startPos);
					if (endPos == -1) endPos = string.length;

					var elementValue = unescape(string.substring(startPos,endPos));
					
					if (elementType == "text")     object.value = elementValue;
					if (elementType == "password") object.value = elementValue;
					if (elementType == "select")   object.selectedIndex = elementValue;
					if (elementType == "checkbox") object.checked = onCheck(elementValue);
					if (elementType == "radio")    object[elementValue].checked = true;
			}
	}
$(document).ready(function() {toggleNav();});
