// start cookie functions used on homepage to store tab open states

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function isText(strString) {
	if (strString.length <1) {
		return false;
	} else {
		return true;
	}
}

function isNumeric(strString) {
   var strValidChars = " 0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;
   for (i = 0; i < strString.length && blnResult == true; i++) {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1) {
		 blnResult = false;
	  }
   }
   return blnResult;
}

function isEmail(strString) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(strString)){
		return true;
	}
	return false;
}

function isDate(strString) {
	if (/^([0-3][0-9])\/([0-1][0-9])\/([0-9]{2,4})$/.test(strString)){
		return true;
	}
	return false;
}

function isDateTime(strString) {
	if (/^([0-3][0-9])\/([0-1][0-9])\/([0-9]{2,4}) ([0-2][0-9]):([0-5][0-9])$/.test(strString)){
		return true;
	}
	return false;
}

function isTime(strString) {
	if (/^([0-2][0-9]):([0-5][0-9])$/.test(strString)){
		return true;
	}
	return false;
}

function chkForm(form) {

	var errMessage = "";
	
	// check any required fields
	var fieldList = $(form.name).getElementsByClassName('req');

	for (var i = 0, j = fieldList.length; i < j; i++) {
		fieldList[i].removeClassName('checkFld');

		if(thisField = fieldList[i].hasClassName('text')) {
			if(!isText(fieldList[i].value)) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}			
		}
		if(thisField = fieldList[i].hasClassName('numeric')) {
			if(!isNumeric(fieldList[i].value)) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('email')) {
			if(!isEmail(fieldList[i].value)) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('datetime')) {
			if(!isDateTime(fieldList[i].value)) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('date')) {
			if(!isDate(fieldList[i].value)) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('time')) {
			if(!isTime(fieldList[i].value)) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
	}

	// check any optional fields
	var fieldList = $(form.name).getElementsByClassName('opt');

	for (var i = 0, j = fieldList.length; i < j; i++) {
		fieldList[i].removeClassName('checkFld');

		if(thisField = fieldList[i].hasClassName('text')) {
			if( (fieldList[i].value != '') && (!isText(fieldList[i].value)) ) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}			
		}
		if(thisField = fieldList[i].hasClassName('numeric')) {
			if( (fieldList[i].value != '') && (!isNumeric(fieldList[i].value)) ) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('email')) {
			if((fieldList[i].value != '') && (!isEmail(fieldList[i].value))) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('datetime')) {
			if((fieldList[i].value != '') && (!isDateTime(fieldList[i].value))) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('date')) {
			if((fieldList[i].value != '') && (!isDate(fieldList[i].value))) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
		if(thisField = fieldList[i].hasClassName('time')) {
			if((fieldList[i].value != '') && (!isTime(fieldList[i].value))) {
				errMessage += fieldList[i].title + "\n";
				fieldList[i].addClassName('checkFld');
			}
		}
	}
		
	if (errMessage != "") {
		alert(errMessage);
		return false;
	} else {
		if (form.submit.value != null) {
			form.submit.disabled = true;
			form.submit.value = 'Submitting';
		}
		return true;
	}

}

// Compares 2 password values and checks they are the same
function comparePasswords(box1, box2) {

	if(box1.value != box2.value) {
		alert('The passwords entered do not match.');
		return false;
	}
	return true;
}

function chkPostcode(postcode) {
	
	test = postcode.value; 
	size = test.length;
	
	if (size == 0) {
		return true;
	}
	
	test = test.toUpperCase(); //Change to uppercase
	
	while (test.slice(0,1) == " ") //Strip leading spaces
	{
		test = test.substr(1,size-1);
		size = test.length;
	}
	
	while(test.slice(size-1,size)== " ") //Strip trailing spaces
	{
		test = test.substr(0,size-1);
		size = test.length;
	}
	
	//document.find_venue_form.search_postcode.value = test; //write back to form field
	if ((size < 6 || size > 8)
	|| (!(isNaN(test.charAt(0))))
	|| (isNaN(test.charAt(size-3)))
	|| (!(isNaN(test.charAt(size-2))))
	|| (!(isNaN(test.charAt(size-1))))
	|| (!(test.charAt(size-4) == " ")))
	{ //Code length rule
		alert(test + " is not a valid postcode");
		//postcode.addClassName('checkFld');
		postcode.focus();
		return false;
	}
	 
	count1 = test.indexOf(" ");
	count2 = test.lastIndexOf(" ");
	if (count1 != count2){//only one space rule
		alert(test + " is not a valid postcode");
		//postcode.addClassName('checkFld');
		postcode.focus();
		return false;
	}
	
	return true;

}

function windopen(id,source) {
	window.open("/includes/global_confirm_delete.php?id="+id+"&source="+source);
}

function DisableButton(b) {
	b.disabled = true;
	b.value = 'Submitting';
	return chkForm(b.form);
	b.disabled = false;
	b.value = 'Add';
}

// called by popups to close the window
function closeWindow() {
window.close();
}

function loadPage(page_title) {
	if((page_title.indexOf("Proposed Details") != -1) || (page_title.indexOf("Initial Contact E-Mails") != -1) || (page_title.indexOf("Actual Details") != -1)) {
		window.moveTo(0,0);window.resizeTo(window.screen.availWidth,window.screen.availHeight/2);window.moveTo(0,window.screen.availHeight/2);
	}
}


Date.prototype.lastday = function() {
    var d = new Date(this.getFullYear(), this.getMonth() + 1, 0);
    return d.getDate();
};


Date.prototype.getMonthsBetween2 = function(d) {
    var sDate, eDate;   
    var d1 = this.getFullYear() * 12 + this.getMonth();
    var d2 = d.getFullYear() * 12 + d.getMonth();
    var sign;
    var months = 0;

    if (this == d) {
        months = 0;
    } else if (d1 == d2) {      //same year and month
        months = (d.getDate() - this.getDate())/this.lastday();
    } else {
        if (d1 <  d2) {
            sDate = this;
            eDate = d;
            sign = 1;
        } else {
            sDate = d;
            eDate = this;
            sign = -1;
        }

        var sAdj = sDate.lastday() - sDate.getDate();
        var eAdj = eDate.getDate();
        var adj = (sAdj + eAdj)/sDate.lastday() -1;
        months = Math.abs(d2 - d1) + adj;
        months = (months * sign)
    }
    return months;
  };
  
function copyTableToData() {
	var r  = 0;
	numofRows = report_results_table.rows.length-1;
	numofCells =  report_results_table.rows[0].cells.length-1    //
	var row= [numofRows];
	var cntrows = 0;
	for ( r == 0; r <= numofRows; r++) {
		var c =0;
		tempdata = "";
		for (c == 0; c<=numofCells; c++) {
			if (c != numofCells) {
				var innerText = report_results_table.rows[r].cells[c].innerText;
				if (r == 0) {
					// remove '6' from first row (downward facing arrow if sorted)
					innerText = innerText.replace(" 6", "");
				}
				tempdata+= innerText + "\t";
			} else {
				var innerText = report_results_table.rows[r].cells[c].innerText;
				if (r == 0) {
					// remove '6' from first row (downward facing arrow if sorted)
					innerText = innerText.replace(" 6", "");
				}
				tempdata+= innerText + "\n";
			}
		}
		row[r] = tempdata
	}
	var rowcnt = 0;
	var data ='';
	for (rowcnt == 0; rowcnt<= row.length-1; rowcnt++) {
		data = data + row[rowcnt];
	} 
	downloadform.data.value=data;
}

function confirmDelete() {
	return confirm ("Are you sure you want to delete?");
}

function applyMarkup($percentage) {
	var numberForms = document.forms.length;
	var formIndex;
	for (formIndex = 0; formIndex < numberForms; formIndex++) {
		if((document.forms[formIndex].name == "update_order_item_product") || (document.forms[formIndex].name == "update_order_item_additional")) {
			var OriginalPrice = parseFloat(document.forms[formIndex].OrderItemSellPrice.value);
			AddPrice = (OriginalPrice/100) * parseFloat($percentage);
			NewPrice = OriginalPrice + AddPrice;
			document.forms[formIndex].OrderItemSellPrice.value = NewPrice.toFixed(2);
		}
	}
	alert('Markup Applied');
}

function discountCount(box1, box2, box3) {
	cnt = 0;
	if(box1.value != "") {
		alert("here");
		cnt = cnt +1;
	}
	if(box2.value != "") {
		alert("here");
		cnt = cnt +1;
	}
	if(box3.value != "") {
		alert("here");
		cnt = cnt +1;
	}
}