/*
Strip whitespace from the beginning and end of a string
Input : a string
*/


function CurrFormatOnly(Curr){
    //var regexp = /^\d{1,3}(,\d\d\d)*\.\d\d$/;
    //return regexp.test(el.value);
    return /^\d{1,3}(,\d{3})*\.\d\d$|^\d+\.\d\d$/.test(Curr);
}

function IsInteger(St) {
    return !/\D/.test(St);
}

function numbersonly(e){
     var unicode=e.charCode? e.charCode : e.keyCode
     // if (unicode!=8||unicode!=9)
     if (unicode<8||unicode>9)
        {
        //if the key isn't the backspace key or tab key (which we should allow)
        if (unicode<48||unicode>57) //if not a number
        return false //disable key press
     }
}

function trim(str)
{
	return str.replace(/^\s+|\s+$/g,'');
}

function checkNumber(textBox)
{
		while (textBox.value.length > 0 && isNaN(textBox.value)) {
		textBox.value = textBox.value.substring(0, textBox.value.length - 1)
	}
	
	textBox.value = trim(textBox.value);
/*	if (textBox.value.length == 0) {
		textBox.value = 0;		
	} else {
		textBox.value = parseInt(textBox.value);
	}*/
}



function get_timestamp()
{
	dummyDate = new Date() ; 
	dummyParameter = dummyDate.getTime()
	return dummyParameter;

	}
/*
	Check if a form element is empty.
	If it is display an alert box and focus
	on the element
*/
function isEmpty(formElement, message) {
	formElement.value = trim(formElement.value);
	
	_isEmpty = false;
	if (formElement.value == '') {
		_isEmpty = true;
		alert(message);
		formElement.focus();
	}
	
	return _isEmpty;
}

/*
	Set one value in combo box as the selected value
*/
function setSelect(listElement, listValue)
{
	for (i=0; i < listElement.options.length; i++) {
		if (listElement.options[i].value == listValue)	{
			listElement.selectedIndex = i;
		}
	}	
}

function checkSearchString()
{
	

	 with (window.document.frmSearch) {
		 if (isEmpty(searchstr, 'Enter Search text')) {
			return;
		} else if ( searchstr.value !='') {
			//alert(searchstr.value);
			submit();
			//window.location.href = 'index.php?page_request=search&searchstr=' + searchstr.value;
		}
	 }
}

function checkEnter(e){ //e is event object passed from function invocation
	var characterCode; //literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	} else {
		e = event;
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		//document.forms[0].submit() //submit the form
		return false
	} else {
		return true
	}

}

function viewProduct()
{
	with (window.document.frmSearchProdByItem) {
		if (cboCategory.selectedIndex == 0) {
			window.location.href = 'index.php';
		} else {
			window.location.href = 'index.php?page_request=product&c=' + cboCategory.options[cboCategory.selectedIndex].value;
		}
	}
}

function AddToCart(Id){
	alert ('Not yet implemented.');
	//if(Id) window.location.href = 'cart.php?action=add&p='+Id;
}

/* this will cancel the Invoice from Invoice page list */
function cancelInvoice(Id){
	if (confirm('Are you sure you want to cancel this invoice? Invoice#'+Id)){
		var pars = 'items=' + Id;
		new Ajax.Request('library/HttpdPostRequest.php?action=cancelInvoice',
			{   asynchronous:true, //Set async when looping
				parameters:pars,
				onSuccess: showResult,
				onException: function(req,exception) {
					alert("The request had a fatal exception thrown.\n\n" +
					exception);
					return true;
				},
				onFailure:reportError 
			}
		);
	}//end if
}
//Show result from previous request
function showResult(ServerResponse) {
	if(ServerResponse.responseText=='SUCCESS'){
		window.location.href = 'index.php?page_request=invoice&action=view';
	}else{
	//leave blank. for debugging purposes only
	alert(ServerResponse.responseText);}
}

function printInvoiceEx(orderId){
	var c = parseInt(Math.random()*99999999);
	window.open ('admin/order/invoice.php?orderId='+orderId+'&secId='+c,'&mywindow'+c,'menubar=1,resizable=1,width=640,height=480,scrollbars=1');
}

//Get customer data from user_signup
function fetchCustomerData(Id){
	var input = 'userID='+ Id;
	var pars = input;
	new Ajax.Request(
	'admin/order/HttpdPostRequest.php?action=userinfo',
	   {   asynchronous:true,
		  parameters:pars,
		  onComplete: ShowData
	   }
	);
}
	
function ShowData(originalRequest) {
	   var xmlDoc = originalRequest.responseXML.documentElement;
	   var lname = xmlDoc.getElementsByTagName("lastName")[0]. 
				   childNodes[0].nodeValue;
	   var fname = xmlDoc.getElementsByTagName("firstName")[0]. 
				   childNodes[0].nodeValue;
	   var address = xmlDoc.getElementsByTagName("address")[0]. 
				   childNodes[0].nodeValue;
		$('lastName').value=lname;
		$('firstName').value=fname;
		$('email').value=address;
	
}



//print pdf invoice from botht the storefront and admin page
function printPDFInvoice(orderId){
	if (orderId!=''){
		 with (window.document.frmInvoice) submit();
	}
	//window.location.href = 'processOrder.php?action=print2PDF&tempFile='+tempFile+'&orderId='+orderId;
}

function processPayment(orderId){
	var c = parseInt(Math.random()*99999999);
	window.location.href = 'index.php?page_request=processpayment&step=1&orderId='+orderId+'&c='+c;
}

function backToInvoiceList(){
	var c = parseInt(Math.random()*99999999);
	window.location.href = 'index.php?page_request=invoice&action=view&c='+c;
}

function validatePaymentInfo(){
		
	if (($('optPaypal').checked==true || $('optCod').checked==true) && $('chkAddress').checked == false ){
		//Validate all
		if (!goodChar(document.payment.firstName,"Firstname is a required field. Please input a readable firstname.")){return false;}
		if (!goodChar(document.payment.lastName,"Lastname is a required field. Please input a readable lastname.")){return false;}
		if (!goodChar(document.payment.Address1,"Adress line1 is a required field. Please input a readable Address.")){return false;}
		if (!goodPhone("(ddd) ddd-dddd",document.payment.phoneNumber,"Please input a valid phone number in format of (604) 123-1234")){return false;}
		if (!goodInt(document.payment.zip,"Please input numbers only.")){return false;}
	}

	if ($('optPaypal').checked==true || $('optCod').checked==true){
		//Validate only city, country and email
		if (document.payment.country.selectedIndex == 0){
			alert('Please select country of origin');
			document.payment.country.select();
			return false;
		}
		if (!goodEMail(document.payment.email, "Please input a valid email address.")){return false;}
		
	}
	//if all is good then submit
}

function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
		var element = document.getElementById (expandCollapse.arguments[i]);
		element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}

function reportError(request)
{
	alert('Sorry. There was an error. '+request.status);
}
	
function checkPaymentType(formName){
	
	if ($('optPaypal').checked==true){
		Field.enable('chkAddress');
		//enableFields(true);
	}else if($('optCod').checked==true) {
		$('chkAddress').checked = false;
		Field.disable('chkAddress');
	}
	checkAddressState();


}

function enableFields(state){
	if (state){
		Field.enable('firstName');
		Field.enable('lastName');
		Field.enable('Address1');
		Field.enable('Address2');
		Field.enable('phoneNumber');
		Field.enable('city');
		Field.enable('zip');
		$('firstName').activate();
	}else{
		Field.disable('firstName');
		Field.disable('lastName');
		Field.disable('Address1');
		Field.disable('Address2');
		Field.disable('phoneNumber');
		Field.disable('city');
		Field.disable('zip');
		
		
	}
}

function checkAddressState(){
	if ($('chkAddress').checked==true){
		enableFields(false);
	}else{ 
		enableFields(true);
	}
}

function loadCity(){
	
	document.getElementById('state').options.length = 0;
	if ($('country').value==242){
	var stateList = new Array("Alaska","Alabama","Arkansas","Arizona","California","Colorado","Connecticut","District of Columbia","Delaware","Florida","Georgia","Hawaii","Iowa","Idaho","Illinois","Indiana","Kansas","Kentucky","Louisiana","Massachusetts","Maryland","Maine","Michigan","Minnesota","Missouri","Mississippi","Montana","North Carolina","North Dakota","Nebraska","New Hampshire","New Jersey","New Mexico","Nevada","New York","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Virginia","Vermont","Washington","Wisconsin","West Virginia","Wyoming");


	for(j=0;j<stateList.size();j++)
      	{
        	document.payment.state.options[j]=new Option(eval(stateList)[j],eval(stateList)[j])
      	}

		
	}else{
		document.payment.state.options[0]=new Option("N.A.","NA")
	}
}