// client side check of if values are adequate to satisfy login
function testLogin(){
	var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if( !emailFilter.test( document.getElementById('lognName').value ) ){
		alert('Please ensure Username is your email address.');
		return false;
	}
	if( document.getElementById('lognPass').value.length <6 ){
		alert('Please ensure your password is at least 6 characters in length.');
		return false;
	}
	return true;
}

// set the iframe to the correct height
function iframeLoaded(id){
	var framePageHeight = 0;
	var theFrame=document.getElementById(id);
	if(theFrame.Document){
		framePageHeight = theFrame.Document.body.scrollHeight;
	} else {
		framePageHeight = theFrame.contentDocument.body.scrollHeight;
	}
	theFrame.style.height=framePageHeight+'px';
}

// remove an iframe form the page
function removeFromPage(id){
	var e = document.getElementById(id);
	e.parentNode.removeChild( e );
}

// ajax call to add a new address
function addAddress(){
	var newAddress = document.getElementById('newAddress').value;
	ajax('adminAddAddress.aspx','action=addAddress&address='+newAddress,addressAdded);
}

// ajax reply with the new address
function addressAdded( response ){

	// parse the xml response document
	var xmlDoc;
	try{ //Internet Explorer
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async="false";
	  xmlDoc.loadXML(response);
	} catch(e) {
		try{ //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(response,"text/xml");
		} catch(e) {
			alert(e.message)
		}
	}

	// get the 2 values wanted from the respone xml
	var id = xmlDoc.getElementsByTagName("id")[0].childNodes[0].nodeValue;
	var address = xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;
	xmlDoc = null;

	// add to the page an iframe for editing the new address
	var node = document.getElementById('maintainAddresses');
	var elem=document.createElement('DIV');
	elem.innerHTML='<iframe frameborder="0" marginheight="0" marginwidth="0" id="addrFrame'+id+'" name="addrFrame'+id+'" scrolling="no" src="adminAddress.aspx?id='+id+'&amp;address='+escape(address)+'" width="440"></iframe>';
	node.appendChild(elem);
	document.getElementById('newAddress').value=''; // reset the new address box value to empty
}

// Provide the XMLHttpRequest class for IE 5.x-6.x:
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};

function ajax(url, vars, callbackFunction) {
  var request =  new XMLHttpRequest();
  request.open("POST", url, true);
  request.setRequestHeader("Content-Type",
                           "application/x-www-form-urlencoded");
 
  request.onreadystatechange = function() {
    var done = 4, ok = 200;
    if (request.readyState == done && request.status == ok) {
      if (request.responseText) {
        callbackFunction(request.responseText);
      }
    }
  };
  request.send(vars);
}

// check that the my cart page can post
function doCheckout(){
	var hasError = false; // track if form data has an error

	if( document.getElementById('placedby').value.length <2 ){
		document.getElementById('placedbyErr').style.display='block';
		document.getElementById('placedby').style.border='solid 1px #890103';
		hasError = true;
	} else {
		document.getElementById('placedbyErr').style.display='none';
		document.getElementById('placedby').style.borderColor='#7F9DB9';
	}

	var hasAddress = false;
	var adds = document.getElementsByName('addressId');
	for( var i=0; i < adds.length; i++){
		if(adds[i].checked){
			hasAddress = true;
			document.getElementById('address').value = document.getElementById('s'+adds[i].id).innerHTML;
			break;
		}
	}
	if(!hasAddress){
		document.getElementById('addressErr').style.display='block';
		document.getElementById('addressCont').style.border='solid 1px #890103';
		hasError = true;
	} else {
		document.getElementById('addressErr').style.display='none';
		document.getElementById('addressCont').style.border='none';
	}
	
	if(!document.getElementById('regTerms').checked){
		document.getElementById('regTermsErr').style.display='block';
		hasError = true;
	} else {
		document.getElementById('regTermsErr').style.display='none';
	}

	if(!hasError){
		document.getElementById('frmCheckout').submit();
	}
}

// change the order history view from last 10 to date search
function showOrderHistory(){
	if(document.getElementById('ordersLast10').checked){
		document.getElementById('orderHistoryAction').value = 'last10';
		document.getElementById('orderHistoryForm').submit();
		return;
	}

	// get the start date
	var startDay = parseInt(document.getElementById('orderStartDay').value);
	var startMonth = parseInt(document.getElementById('orderStartMonth').value);
	var startYear = parseInt(document.getElementById('orderStartYear').value);

	// get the end date
	var endDay = parseInt(document.getElementById('orderEndDay').value);
	var endMonth = parseInt(document.getElementById('orderEndMonth').value);
	var endYear = parseInt(document.getElementById('orderEndYear').value);

	// check the start date
	if( startDay > getDaysInMonth(startMonth,startYear) ){
		alert('START DATE ERROR: There are only '+getDaysInMonth(startMonth,startYear)+' days in '+ getMonthName(startMonth) +' ' + startYear);
		return;
	}

	// check the end date
	if( endDay > getDaysInMonth(endMonth,endYear) ){
		alert('END DATE ERROR: There are only '+getDaysInMonth(endMonth,endYear)+' days in '+ getMonthName(endMonth) +' ' + endYear);
		return;
	}
	
	// check start date is after end
	var startDate=new Date();
	startDate.setFullYear(startYear,startMonth-1,startDay);
	var endDate=new Date();
	endDate.setFullYear(endYear,endMonth-1,endDay);
	
	if(startDate > endDate){
		alert('DATE ERROR: Start date must be before end date');
		return;
	}

	// can post the form knowing the dates are good
	document.getElementById('orderHistoryAction').value = 'setOrderHistoryDates';
	document.getElementById('orderHistoryForm').submit();
}

function getMonthName( month ){
	switch(month){
		case 1: return 'Jan';
		case 2: return 'Feb';
		case 3: return 'Mar';
		case 4: return 'Apr';
		case 5: return 'May';
		case 6: return 'Jun';
		case 7: return 'Jul';
		case 8: return 'Aug';
		case 9: return 'Sep';
		case 10: return 'Oct';
		case 11: return 'Nov';
		case 12: return 'Dec';
	}
}

function getDaysInMonth( month, year ){
	switch(month){
		case 1: return 31;
		case 2: return 28+isLeapYear(year);
		case 3: return 31;
		case 4: return 30;
		case 5: return 31;
		case 6: return 30;
		case 7: return 31;
		case 8: return 31;
		case 9: return 30;
		case 10: return 31;
		case 11: return 30;
		case 12: return 31;
	}
}

function isLeapYear( year ){
	var retval = 0;
	if( year % 4 == 0 ){ // is leap year if divisible by 4
		retval = 1;
	}
	if( year % 100 == 0 && year % 400 != 0 ){ // extra rule, if divisible by 100, then only if not divisible by 400
		retval = 0;
	}
	return retval;
}

// when user sets a date, assume this means they want to search between dates
function setSearchOn(){
	document.getElementById('ordersByDate').checked=true;
}

// POPOUT MENU ON PRODUCT PAGES !!!
var curMenuId = '';
var curMenuIds = new Array();
var menuDelay = 300; // delay after hover in menu (ms)

// flag that a menu should be opened. flag can be overriden by a hide command for 300 ms
function openMenu(rootId){
	curMenuIds[rootId]=true;
	setTimeout('showMenu("'+rootId+'")',menuDelay);
}
// optn a menu if the corresponding flag is true to show opening
function showMenu(rootId){
	if(rootId==curMenuId){
		return; // get out if are already displaying the menu to show
	}
	if(curMenuIds[rootId]==true){
		curMenuId = rootId;
		document.getElementById(rootId+'-stub').className+='Exp';
		var mpcont = document.getElementById(rootId+'-mpcont');
		mpcont.style.display='block';
		var mTop = findTop(mpcont.parentNode); // start trying to make the popout menu top line up with the calling link
		var mBot = mTop + mpcont.offsetHeight; // get how low this will make the base of the menu
		var yScroll = getScrollY();
		var wBot = windowHeight() + yScroll; // get how low in the document is shown in the browser window
		//alert('w:'+wBot+', m:'+mBot);
		if(mBot > wBot){ // if menu goes lower than the end of the window
			mTop -= (mBot-wBot); // push the menu up so that it fits to the bottom of the window
		}
		var topLimit = (yScroll>234)?yScroll:234;
		if(mTop < topLimit){
			mTop = topLimit; // ensure top of the popout menu does not go up into the headers, or out of the top of the window
		}
		mpcont.style.top = mTop+'px'; // assign the top of the menu
	}
}
// flag that a menu should be shut. flag can be overriden by a show command for 300 ms
function closeMenu(rootId){
	curMenuIds[rootId]=false;
	setTimeout('hideMenu("'+rootId+'")',menuDelay);
}
// shut a menu if the corresponding flag is false to show closure
function hideMenu(rootId){
	if(curMenuIds[rootId]==false){
		if(curMenuId==rootId){
			curMenuId = '';
		}
		var cn = document.getElementById(rootId+'-stub').className;
		if( RegExp(".*Exp$").test(cn) ){
			document.getElementById(rootId+'-stub').className=cn.substring(0,cn.length-3);
		}
		document.getElementById(rootId+'-mpcont').style.display='none';
	}
}

function findTop(obj) {
	if(obj.offsetParent){
		return obj.offsetTop + findTop(obj.offsetParent);
	}
	return 0;
}

function windowHeight() {
	if( document.documentElement && document.documentElement.clientHeight ){ // tested on win32: ie6,7 and firefox2,3 and safari 3
		return document.documentElement.clientHeight;
	}
	if( typeof( window.innerHeight ) == 'number' ){ // Non-IE
		return window.innerHeight;
	}
	if( document.body && document.body.clientHeight ){ //IE 4 compatible
		return document.body.clientHeight;
	}
}

function getScrollY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ){ // Netscape compliant
    return window.pageYOffset;
  }
  if( document.body && document.body.scrollTop ){ // DOM compliant
    return document.body.scrollTop;
  }
  if( document.documentElement && document.documentElement.scrollTop ){  // IE6 standards compliant mode
    return document.documentElement.scrollTop;
  }
  //alert('ie6');
  return 0;
}

var highlightId = '';
var highlightNum=0;
function highlightProd(){
	var url = window.document.URL.toString();
	var urlFp = url.indexOf("#");
	if(urlFp==-1){ return; }
	var pid = url.substring(urlFp+1);
	doHighlight(pid+'-cont');
}

function highlightProdInPage( pid ){
	if( doHighlight('prod'+pid+'-cont') ){
		curMenuIds[curMenuId]=false;
		hideMenu(curMenuId);
	}
}

function doHighlight(pid){
	if(highlightId != ''){
		var oldpCont = document.getElementById(highlightId);
		if(oldpCont != null){
			oldpCont.style.backgroundColor='';
		}
	}
	var pcont = document.getElementById(pid);
	if(pcont != null){
		highlightId = pid;
		highlightNum=11;
		doFade();
		return true;
	}
	return false;
}

 function doFade(){
 	var pcont = document.getElementById(highlightId);
	if(pcont != null){
		switch(highlightNum){
			case 11: pcont.style.backgroundColor='#FFE788'; break;
			case 10: pcont.style.backgroundColor='#FFE994'; break;
			case 9: pcont.style.backgroundColor='#FFECA0'; break;
			case 8: pcont.style.backgroundColor='#FFEEAC'; break;
			case 7: pcont.style.backgroundColor='#FFF1B8'; break;
			case 6: pcont.style.backgroundColor='#FFF3C4'; break;
			case 5: pcont.style.backgroundColor='#FFF5D0'; break;
			case 4: pcont.style.backgroundColor='#FFF8DC'; break;
			case 3: pcont.style.backgroundColor='#FFFAE8'; break;
			case 2: pcont.style.backgroundColor='#FFFDF4'; break;
			case 1: pcont.style.backgroundColor='#FFFEFC'; break;
			case 0: pcont.style.backgroundColor='#FFFFFF'; break;
		}
		if(highlightNum >0){
			highlightNum--;
			setTimeout("doFade()",350);
		}
	}
}