var shouldSwapImagesFlag = false;

function changePreview(imagename, filename)
{
	if (filename.length >= 7) {
		if (filename.substring(filename.length - 7, filename.length) == "invalid") {
			filename = "/images/admin/spacer.gif";
		}
	}
	document.getElementById(imagename).src = filename;
}

function submitForm()
{
	//when submitting form via link, call form onsubmitter
	if(document.form1.onsubmit())
	{
		//do the actual submission
		document.form1.submit();
	}
}

function fixToTwo(inputValue) {
	return (Math.floor(inputValue * 100)) / 100;
}

function openCenteredWindow(url, height, width, name, parms) {
   var left = Math.floor( (screen.width - width) / 2);
   var top = Math.floor( (screen.height - height) / 2);
   var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   if (parms) 
   { 
     winParms += "," + parms; 
   }
   var win = window.open(url, name, winParms);
   if (parseInt(navigator.appVersion) >= 4) 
   { 
     win.window.focus(); 
   }
   return win;
}

function calcPerIncome()
{
	var percentage = Math.round(document.form1.dblTotalWages.value / (document.form1.dblRevenue.value / 1.1) * 100)
	if(percentage > 38)
	{
		document.getElementById("percentage").innerHTML = "<font color=\"red\">" + percentage + "%</font>";
	}
	else
	{
		document.getElementById("percentage").innerHTML = "<font color=\"green\">" + percentage + "%</font>";
	}
}

function closeParentRefresh()
{
	if (window.opener) 
	{
		window.opener.location.reload();
		window.close();
	}
	else
	{
		alert("You have closed the main booking window, or are using an older browser. Please close this window and logon again to verify your booking.");
	}
	window.parent.opener
}

function setToday()
{
	var now = new Date();
	var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
	var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
	document.form1.dtDate.value = now.getDate() + " " + months[now.getMonth()] + " " + now.getFullYear();
	//document.form1.dtDate.value = now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear();
	getDay();
	return true;
}

function setTodaySansYear(formElement)
{
	var now = new Date();
	var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
	var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
	formElement.value = now.getDate() + " " + months[now.getMonth()]
	return true;
}

function getDay()
{
	var now = new Date(document.form1.dtDate.value);
	var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
	document.form1.strDay.value = days[now.getDay()];
	alert(document.form1.strDay.value);
	return true;
}

//amount is a decimal, e.g. 0.4 which is the %
function getBonusMessage(rateType, performance, cost)
{
	var amount
	amount = cost / performance;
	if (rateType == 1)
	{
		if (amount <= 0.18)
			return "<font color=#D9D919>Fantastic! (Gold Day)</font>";
		else if (amount <= 0.23)
			return "<font color=#C0C0C0>Great! (Silver Day)</font>";
		else if (amount <= 0.28)
			return "<font color=#8C7853>Good! (Bronze Day)</font>";
		else if (amount <= 0.35)
			return "<font color=green>OK (Green Day)</font>";
		else
			return "<font color=red>Bad Day</font>";
	}
	else if(rateType == 2)
	{
		if (performance <= 40) 
			return "<font color=red>Bad Day</font>";
		else if (performance <= 80)
			return "<font color=green>OK (Green Day)</font>";
		else if (performance <= 170)
			return "<font color=#8C7853>Good! (Bronze Day)</font>";
		else if (performance <= 260)
			return "<font color=#AAAAAA>Great! (Silver Day)</font>";
		else
			return "<font color=#D9D919>Fantastic! (Gold Day)</font>";
	}
	// rateType == 3
	else 
	{
		if (performance < 100) 
			return "<font color=red>Bad Day</font>";
		else if (performance < 200)
			return "<font color=green>OK (Green Day)</font>";
		else if (performance < 300)
			return "<font color=#8C7853>Good! (Bronze Day)</font>";
		else if (performance < 400)
			return "<font color=#AAAAAA>Great! (Silver Day)</font>";
		else
			return "<font color=#D9D919>Fantastic! (Gold Day)</font>";
	}	
}

//retailIncome + salesIncome = income
function calculateTotal()
{
	var i, itemIndex, rate, wageid, total, grandTotal, hours, performance, percentage, bonusType, retailIncome, salesIncome;

	grandTotal = 0.0;
	for (i = 0; i < document.form1.elements.length; i++)
	{
		if (document.form1.elements[i].value.length != "" && document.form1.elements[i].name.indexOf("hours") > -1)
		{
			itemIndex = document.form1.elements[i].name.charAt(5);
			wageid = eval("document.form1.rate" + itemIndex + ".options[document.form1.rate" + itemIndex + ".selectedIndex].value");
			hours = document.form1.elements[i].value;
			rate = wagesArray[wageid];
			bonusType = bonusesArray[wageid];
			total = fixToTwo(rate * hours);

			//new form fields with auto calculate
			retailIncome = parseFloat(eval("document.form1.retailIncome" + itemIndex + ".value"));
			salesIncome = parseFloat(eval("document.form1.salesIncome" + itemIndex + ".value"));
			if(!isNaN(retailIncome) && !isNaN(salesIncome)) {
				//alert("Total is " + (retailIncome + salesIncome))
				eval("document.form1.income" + itemIndex + ".value = " + (retailIncome + salesIncome));
			}		
			
			if (isNaN(total))
			{
				eval("document.form1.total" + itemIndex + ".value = \"\"");
			}
			else	
			{
				eval("document.form1.total" + itemIndex + ".value = " + total);
				grandTotal += total;
				performance = eval("document.form1.income" + itemIndex + ".value");
				//alert(drawWarnings[wageid]);
				if (drawWarnings[wageid] == 1 && !isNaN(performance))
				{
					eval("window.document.getElementById(\"message" + itemIndex + "\").innerHTML = \"" + getBonusMessage(bonusType, performance, total) + "\";");
				}
				else
				{
					eval("window.document.getElementById(\"message" + itemIndex + "\").innerHTML = \"\";");
				}
			}
		}
		else
		{
		}
	}
	document.form1.dblTotalWages.value = Math.round(100 * grandTotal) / 100;
	calcPerIncome();
}

//this is the event handler for the on change event for the drop downs
function calculateThisTotal(currentInput)
{
	var i, itemIndex, rate, wageid, total, hours;
	itemIndex = currentInput.name.charAt(4);
	wageid = currentInput.options[currentInput.selectedIndex].value;
	hours = eval("document.form1.hours" + itemIndex + ".value");
	rate = wagesArray[wageid];
	total = rate * hours;
	if (isNaN(total))
	{
		eval("document.form1.total" + itemIndex + ".value = \"\"");
	}
	else	
	{
		eval("document.form1.total" + itemIndex + ".value = " + total);
	}
}

function checker(strMode)
{
	return confirm("Are you sure you want to " + strMode + " this item?");
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function openCenteredWindow(url, height, width, name, parms) {
   var left = Math.floor( (screen.width - width) / 2);
   var top = Math.floor( (screen.height - height) / 2);
   var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   if (parms) 
   { 
     winParms += "," + parms; 
   }
   var win = window.open(url, name, winParms);
   if (parseInt(navigator.appVersion) >= 4) 
   { 
     win.window.focus(); 
   }
   return win;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0

  if (document.MM_sr != null)
  {
  	var i,x,a=document.MM_sr; 
	for(i=0; a && i<a.length && (x=a[i]) && x.oSrc; i++)
	{
  		x.src=x.oSrc;
	}
  }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  shouldSwapImagesFlag = false;
  MM_swapImgRestore();
  var i,j=0,x,a=MM_swapImage.arguments; 
  document.MM_sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
  if ((x=MM_findObj(a[i]))!=null)
  {
  	document.MM_sr[j++]=x; 
  	if(!x.oSrc) 
  		x.oSrc=x.src; 
  	x.src=a[i+2];
  }
}

function isEmail(emailToCheck)
{
	if (emailToCheck.length > 8)
	{
		if (emailToCheck.indexOf("@") > 0 && emailToCheck.indexOf(".") > 0)
			return true;
		else
			return false;
	}
	else
		return false;
}

function isEmailGVFeedback(emailToCheck)
{
	if (emailToCheck.length > 0)
	{
		if (emailToCheck.indexOf("@") > 0 && emailToCheck.indexOf(".") > 0)
			return true;
		else
			return false;
	}
	else
		return true;
}

function checkForm(fieldsToCheck) 
{
	var errorCount = 0;
	var emailErrorCount = 0;
	var errorMessage = "The form could not be submitted because of the following error(s): \n\n";
	var i;
	var invalidField;
	
	for (i = 0; i < document.form1.elements.length; i++)
	{
		if (document.form1.elements[i].type != "hidden" && fieldsToCheck.indexOf(document.form1.elements[i].name) > -1 && (document.form1.elements[i].value == "" || document.form1.elements[i].value == "invalid")) 
		{
			errorCount++;
			invalidField = document.form1.elements[i];
		}
		if (document.form1.elements[i].name.toUpperCase().indexOf("EMAIL") > -1 && fieldsToCheck.indexOf(document.form1.elements[i].name) > -1 && !isEmail(document.form1.elements[i].value))
		{
			emailErrorCount++;
			invalidField = document.form1.elements[i];
		}
		//is B'day required?
		if(document.form1.elements[i].name.toUpperCase().indexOf("BIRTHDAY") > -1 && fieldsToCheck.indexOf(document.form1.elements[i].name) > -1 && !isDate(document.form1.elements[i].value))
		{
			document.form1.elements[i].focus();
			return false;
		}
		//even if B'day not required, make sure the data is valid if entered
		if(document.form1.elements[i].name.toUpperCase().indexOf("BIRTHDAY") > -1 && document.form1.elements[i].value.length > 0 && !isDate(document.form1.elements[i].value))
		{
			document.form1.elements[i].focus();
			return false;
		}		
	}
	if (errorCount > 1)
		errorMessage += "* There were " + errorCount + " fields left empty.\n";
	else if (errorCount == 1)
		errorMessage += "* There was " + errorCount + " field left empty.\n";
	if (emailErrorCount > 1)
		errorMessage += "* All email addresses must be valid. There were " + emailErrorCount + " email fields invalid.\n";	
	else if (emailErrorCount == 1)		
		errorMessage += "* All email addresses must be valid. There was " + emailErrorCount + " email field invalid.\n";		
	if (errorCount > 0 || emailErrorCount > 0)
	{
		alert(errorMessage + "\nPlease click OK to try again.");
		invalidField.focus();
		return false;
	}
	else
		return true;
}

function checkGVForm() 
{
	var errorCount = 0;
	var emailErrorCount = 0;
	var errorMessage = "The form could not be submitted because of the following error(s): \n\n";
	var i;
	var invalidField;

	if (document.getElementById("fullname").value == "")
	{
		errorMessage += "* Please enter your name.\n";
		errorCount++;
	}
	if (document.getElementById("daytime_phone").value == "")
	{
		errorMessage += "* Please enter your phone number.\n";
		errorCount++;
	}
	if (document.getElementById("emailaddress").value == "")
	{
		errorMessage += "* Please enter your email address.\n";
		errorCount++;
	}


	if (!isEmailGVFeedback(document.getElementById("emailaddress").value))
	{
		errorMessage += "* Email address is invalid.\n";
		emailErrorCount++;
	}

	if (errorCount > 0)
	if (emailErrorCount > 1)
		errorMessage += "* All email addresses must be valid. There were " + emailErrorCount + " email fields invalid.\n";	
	else if (emailErrorCount == 1)		
		errorMessage += "* All email addresses must be valid. There was " + emailErrorCount + " email field invalid.\n";		
	if (errorCount > 0 || emailErrorCount > 0)
	{
		alert(errorMessage + "\nPlease click OK to try again.");
		return false;
	}
	else
		return true;
}


function checkFeedbackForm() 
{
	var errorCount = 0;
	var emailErrorCount = 0;
	var errorMessage = "The form could not be submitted because of the following error(s): \n\n";
	var i;
	var invalidField;

	if (document.getElementById("phonenumber").value == "" && document.getElementById("emailaddress").value == "")
	{
		errorCount++;
	}

	if (!isEmailGVFeedback(document.getElementById("emailaddress").value))
	{
		emailErrorCount++;
	}

	if (errorCount > 0)
		errorMessage += "* Please enter some contact details.\n";
	else if (errorCount == 1)
		errorMessage += "* There was " + errorCount + " field left empty.\n";
	if (emailErrorCount > 1)
		errorMessage += "* All email addresses must be valid. There were " + emailErrorCount + " email fields invalid.\n";	
	else if (emailErrorCount == 1)		
		errorMessage += "* All email addresses must be valid. There was " + emailErrorCount + " email field invalid.\n";		
	if (errorCount > 0 || emailErrorCount > 0)
	{
		alert(errorMessage + "\nPlease click OK to try again.");
		return false;
	}
	else
		return true;
}

// Declare valid date character, minimum year and maximum year
var dtCh= "-";
var now = new Date();
var minYear=now.getYear() - 90;
var maxYear=now.getYear() - 1;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this
}
function MonthStr() {
	return "JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC";
}

function isDate(dtStr){
	var monthsInYear = MonthStr();
	var daysInMonth = DaysArray(12);
	var pos1 = dtStr.indexOf(dtCh);
	var pos2 = dtStr.indexOf(dtCh,pos1+1);
	var strDay = dtStr.substring(0,pos1);
	var strMonth = dtStr.substring(pos1+1,pos2).toUpperCase();
	var strYear = dtStr.substring(pos2+1);
	strYr = strYear;
	//if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	//if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	//for (var i = 1; i <= 3; i++) {
	//	if (strYr.charAt(0)=="0" && strYr.length>1) 
	//		strYr=strYr.substring(1);
	//}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("Please ensure you enter your birthday correctly: \n* The date format should be dd-mmm-yyyy. \n    For example, 1-Jan-1990 or 23-Aug-1985.");
		return false;
	}
	if (monthsInYear.indexOf(strMonth.toUpperCase()) <= -1){
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (day + "" != strDay)
	{
		alert("Please enter a valid day");
		return false;
	}
	return true;
}