/*GLOBALS*/
var _invalid_input_img_html="<img src='img/wrong.gif' style='vertical-align:middle' title='Invalid Input' alt='invalid input'/>&nbsp;";
var _ajax_loading_img_html="<img src='img/ajax-loader.gif' ><img src='img/ajax-loader-text.gif'/>";

/* space savers */
function getEl(id){
	return document.getElementById(id);
}
/*
 AJAX
*/
//e.g call setAjaxHTML('GET','panelbody/form_login.html','body_div')

function getAjaxHttpObject() {
	var xmlHttp=null;
	// Firefox, Opera 8.0+, Safari
	if(window.XMLHttpRequest){
		xmlHttp=new XMLHttpRequest();
	} else {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function setAjaxHTML(method,url,divid,imgid,imgsrc) {
	
	if(imgid){
		startAjaxImage(imgid);
	}
	//unique id to prevent avoid cached file usage
	var uid = Math.random();
	url.indexOf('?') > -1 ? url+=("&uid="+uid) : url+=("?uid="+uid);
	
	ajaxReq = getAjaxHttpObject();
	ajaxReq.onreadystatechange = function(){
		if(ajaxReq.readyState == "4" || ajaxReq.readyState == "complete"){
			if(ajaxReq.status == 200) {
				if(divid){
					getEl(divid).innerHTML = ajaxReq.responseText;	
				}
			} else {
				//TODO add some kind of warning?
			}
			if(imgid) stopAjaxImage(imgid);
		}		
	};
	ajaxReq.open(method,url,true);
	ajaxReq.send(null);
}

function startAjaxImage(id,img){
	if(!img) img = "img/ajax-loader.gif";
	obj = getEl(id);
	obj.src = img;
}
function stopAjaxImage(id,img){
	if(!img) img = "img/blank.gif";
	obj = getEl(id);
	obj.src = img;
}

/*
 * AJAX UI METHODS
 */
function showHideContent(control,showLabel,hideLabel,contentDivId,uri){
	
	var cItem = getEl(contentDivId);
	
	if(cItem.innerHTML == ""){
		//display
		cItem.style.display="";
		setAjaxHTML("GET",uri,contentDivId);
		control.innerHTML = hideLabel;
	} else {
		//hide
		cItem.innerHTML = "";
		cItem.style.display="none";
		control.innerHTML = showLabel;
	}
}

function showContent(contentDivId,uri,imgid,imgsrc){
	var cItem = getEl(contentDivId);
	cItem.style.display="";
	setAjaxHTML("GET",uri,contentDivId,imgid,imgsrc);
}
/*
 * NON AJAX
 */
function showItem(id){
	var el = getEl(id)
	if(el){
		el.style.display="";	
	}
}

function hideItem(id){
	var el = getEl(id)
	if(el){
		el.style.display="none";	
	}
	
}

function setFocus(id){
	var el = getEl(id)
	if(el){
		el.focus()
	}
}

/*
INPUT VALIDATION METHODS
*/
function validateInputLength(input,minlength,maxlength,errorblockid,errmsg){
	var len = input.value.length;
	var block = getEl(errorblockid);
	block.style.display='none';
	if(minlength){
		if(len < minlength){
			block.style.display='';
			if(!errmsg) errmsg = 'Value too short. Requires at least ' + minlength + ' characters.';
			if(len > 0){
				block.innerHTML=_invalid_input_img_html + errmsg;
			} else {
				block.innerHTML=_invalid_input_img_html + errmsg;
			}
			return false;
		}
	}
	if(maxlength){
		if(len > maxlength){
			block.style.display='';
			block.innerHTML=_invalid_input_img_html + "Value too long, maximum length is " + maxlength + ",you have entered " + len ;
			return false;
		}
	}
	return true;
}

function validateFileUploadName(input,extarray,errorblockid){
	//for now hardcoding just to allow jpeg and gif files
	var block = getEl(errorblockid);
	block.style.display='none';
	var fname = input.value;
	if(fname && fname.length > 0){
		var x = fname.lastIndexOf(".");
		var suffix;
		if(x < 0){
			suffix='xxx';
		} else {
			suffix = fname.substr(x+1,fname.length);
		}
		var valid = false;
		for(var i = 0;i < extarray.length;i++){
		  if(suffix == extarray[i]){
		      valid = true;
		      break;
		  }
		}
		
		if(!valid) {
			block.style.display='';
			block.innerHTML=_invalid_input_img_html + "This file type is not accepted.";
			return false;
		}
		
	}
	return true;
	
}

function validateCharacterRange(input,validchars,errorblockid,errmsg){
	if(!errmsg){
		errmsg = "Invalid Value."
	}
	var block = getEl(errorblockid);
	block.style.display='none';
	var val = input.value;
	var valid = true;
	for(i = 0;i < val.length;i++){
		if(validchars.indexOf(val.charAt(i)) == -1){
			valid = false;
			break;
		}
	}
	if(!valid){
		block.style.display='';
		block.innerHTML=_invalid_input_img_html + errmsg;
	}
	return valid;
}

function validateSelect(select,errorblockid,errmsg){
	
	if(!errmsg){
		errmsg = "No option selected.";
	}
		
	var block = getEl(errorblockid);
	block.style.display = 'none';
	if(select.selectedIndex < 1 || select.options[select.selectedIndex].value == 'none'){
		block.style.display = '';
		block.innerHTML=_invalid_input_img_html + errmsg;
		return false;
	}
	return true;
}

function validateCheckboxSelected(cbname,errorblockid,errmsg){
	var cbs = document.getElementsByName(cbname);
	var valid = false;
	for(var i = 0;i < cbs.length;i++){
		if(cbs[i].checked){
			valid = true;
			break;
		}
	}
	var block = getEl(errorblockid);
	block.style.display = 'none';
	if(!valid){
		block.style.display = '';
		if(!errmsg) errmsg = 'Required option not selected.';
		block.innerHTML=_invalid_input_img_html + errmsg;
	}	
	return valid;
}

function validateCurrencyValue(input,errorblockid){
	var valid = true;
	var val = input.value;
	var errmsg = "";
	
	var c = '';
	var dec = 0;
	//validate chars
	for(var i=0;i < val.length;i++){
		c = val.charAt(i);
		if((c >= 0 && c <= 9) || c == '.'){
			if(c == '.'){
				if(dec > 0){
					//too many points
					valid = false;
					errmsg = "Should be only one decimal point.";
					break;
				}
				++dec;
			}
		} else {
			valid = false;
			errmsg = "Invalid Character";
			break;
		}
	}
	if(valid && dec > 0){
		//only 2 decimal places allowed
		var ind = val.indexOf('.');
		if(val.length > ind + 3){
			//keep 2 dec places only
			input.value = val.substring(0,ind + 3)
		} 
		else if(val.length == ind + 1){
			//add 00
			input.value = val + "00";
		}
		else if(val.length == ind + 2){
			//add 0
			input.value = val + "0";
		}
		//add 0 prefix if less than 1
		if(ind == 0){
			input.value = "0" + input.value;
		}
	} else if(valid) {
		input.value = val + ".00";
	}
	if(!valid){
		var block = getEl(errorblockid);
		block.style.display = '';
		if(!errmsg) errmsg = 'Invalid value.';
		block.innerHTML=_invalid_input_img_html + errmsg;
		
	}
	return valid;
}

function validateUsername(input,errorblockid){
	var block = getEl(errorblockid);
	block.style.display='none';
	var valid = true;
	if(!input.value.match(/^[a-zA-Z0-9_-]+$/)){
		valid = false;
	}
	if(!valid){
		block.style.display='';
		block.innerHTML=_invalid_input_img_html + "Only letters, numbers, underscores and hyphens allowed for username.";
	}
	return valid;
}
/*
APPLICATION'S INVIDUAL FORM VALIDATION
*/
var ok = true;
var imageExtArray = ['jpg','JPG','jpeg','JPEG','gif','GIF'];



function validateAccountForm(update){
	ok = true;
	var x = validateInputLength(getEl('register_business'),4,null,'register_business_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('register_firstname'),1,null,'register_firstname_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('register_surname'),2,null,'register_surname_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('register_email'),4,null,'register_email_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('register_address1'),4,null,'register_address1_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('register_address2'),4,null,'register_address2_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('register_county'),4,null,'register_county_error');
	(ok && !x)?ok = false:ok;
	
	
	
	//values that may not be included in the user form e.g. password update is optional
	if(getEl('register_username')){
		x = validateInputLength(getEl('register_username'),6,null,'register_username_error');
		(ok && !x)?ok = false:ok;
		if(x){
			x = validateUsername(getEl('register_username'),'register_username_error');
			(ok && !x)?ok = false:ok;
		}
	}
	
	if(getEl('register_password')){
		x = validateInputLength(getEl('register_password'),8,null,'register_password_error');
		(ok && !x)?ok = false:ok;
	}
	
	if(getEl('register_password_check')){
		x = validateInputLength(getEl('register_password_check'),8,null,'register_password_check_error');
		(ok && !x)?ok = false:ok;
		
		//password check if ok still true
		if(ok){
			var a = getEl('register_password').value;
			var b = getEl('register_password_check').value;
			block = getEl('register_password_check_error');
			block.style.display = 'none';
			if(a != b){
				ok = false;
				block.style.display = '';
				block.innerHTML = _invalid_input_img_html + "Mismatch, please enter passwords again.";
			}
		}
	}

	return ok;
}

function validateItemForm(update){
	ok = true;
	var x;
	//main category input
	if(getEl("catmaindiv").style.display != "none"){
		var cmSel = getEl("catmain");
		x = validateSelect(cmSel,"catmain_error","No Main Category Selected.");
	} else {
		//new main cat field div shown
		x = validateInputLength(getEl('new_catmain'),4,null,'catmain_error')
	}
	//sub category input
	if(x){
		if(getEl("catsubdiv").style.display != "none"){
			var cmSel = getEl("catsub");
			x = validateSelect(cmSel,"catsub_error","No Category Selected.");
		} else {
			//new main cat field div shown
			x = validateInputLength(getEl('new_catsub'),4,null,'catsub_error')
		}	
	}
	(ok && !x)?ok = false:ok;
	//item_id - not checked with an update - can't be updated
	if(!update){
		var idel = getEl('item_reference');
		x = validateInputLength(idel,4,null,'item_reference_error')
		if(x){
			//check item id is alphanumeric with no spaces, hyphens allowed, then convert to uppercase
			var val = idel.value;
			idel.value = val.toUpperCase();
			x = validateCharacterRange(idel,"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-","item_id_error","Product Code cotains invalid character.");
		}
		(ok && !x)?ok = false:ok;	
	}
	
	x = validateInputLength(getEl('item_title'),4,null,'item_title_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('item_description'),4,null,'item_description_error');
	(ok && !x)?ok = false:ok;
	x = validateInputLength(getEl('item_price'),1,null,'item_price_error','Price Required.');
	if(x){
		x = validateCurrencyValue(getEl('item_price'),'item_price_error');
	}
	(ok && !x)?ok = false:ok;
	//handle special offer
	var spv = getEl("item_special_price").value;
	var errblock = getEl('item_special_price_error');
	errblock.style.display='none';
	if(getEl("item_special_option").checked && (spv.length < 1 || spv < 0.01)){
		errblock.style.display = '';
		errblock.innerHTML=_invalid_input_img_html + "Valid special offer price required.";
		ok = false;
	}
	if(ok){
		//check special price is lower
		if(spv >= getEl('item_price').value){
			errblock.style.display = '';
			errblock.innerHTML=_invalid_input_img_html + "Special offer price is not lower than normal price.";
			ok = false;
		}
	}
	if(getEl("item_special_price").value.length > 0){
		x = validateCurrencyValue(getEl('item_special_price'),'item_special_price_error');
		(ok && !x)?ok = false:ok;
	}
	
	if(ok){
		if(getEl('item_image').value.length > 0){
			//image progress
			getEl('item_image').style.display = 'none';
			getEl('item_image_ip').style.display = '';	
		}
	}
	return ok;
}

function validateNewsForm(update){
	ok = true;
	var x = validateInputLength(getEl('news_headline'),1,null,'news_headline_error');
	(ok && !x)?ok = false:ok;
	var x = validateInputLength(getEl('news_article'),1,2000,'news_article_error');
	(ok && !x)?ok = false:ok;
	x = validateFileUploadName(getEl('news_image'),imageExtArray,'news_image_error');
	(ok && !x)?ok = false:ok;
	if(ok){
		if(getEl('news_image').value.length > 0){
			getEl('news_image').style.display = 'none';
			getEl('news_image_ip').style.display = '';	
		}
		
	}
	return ok;
}

function validatePlaceOrder(){
	var x = validateInputLength(getEl('order_comment'),null,1000,'order_comment_error');
	return x
}

/* GENERAL FUNCTIONS */
function charCounter(inputEl, outid, max){

	var output = getEl(outid);
	
	if (inputEl && output) {
		var len = inputEl.value.length;
		if (len == 0) {
			output.innerHTML = "";
		}
		var left = max - (len);
		
		if (left > 0) {
			output.innerHTML = "Room for " + left + " more";
		}
		else {
			output.innerHTML = "Sorry, this is as much as you can enter.";
			inputEl.value = inputEl.value.substring(0, max);
		}
	}
}

function checkQtyChar(e){
	var kc;
	var c;
	if(window.event){ //IE
		kc = e.keyCode;
	} else if(e.which) { //other browsers
		kc = e.which;
	}
	//left right del bs
	if(kc==37||kc==39||kc==46||kc==8){
		return true;
	}
	c = String.fromCharCode(kc);
	if("0123456789".indexOf(c) > -1){
		return true;
	} else {
		return false;
	}
}

function checkQtyInStock(input,max,min){
    (min != 0)? min = 1 : min = "";
    if(input.value > max)
        input.value = max;
    else if(input.value == "")
        input.value = min;
}

function catmainSelection(sel){
	//alert(sel.options[sel.selectedIndex].value);
	var id = sel.options[sel.selectedIndex].value;
	if(id != "none"){
		getEl("catsubdiv").innerHTML = _ajax_loading_img_html;
		setAjaxHTML("GET","do.php?f=panelbody&p=form_item_catsub&id=" + id,"catsubdiv");
	} else {
		getEl("catsubdiv").innerHTML = "<span>First select or create a new Main Category.</span>";
	}
}

function newCatsub(){
	showItem("newcatsubdiv");
	hideItem("catsubdiv");
	setFocus("new_catsub")
}

function updateCart(itemid,qtyFieldIdPrefix,updateType,outdiv,reqsrc){
	qtyFieldId = qtyFieldIdPrefix + "_" + itemid;
	qty = getEl(qtyFieldId).value;
	url = "do.php?f=phpscript&p=action_updatecart&itemid=" + itemid + "&qty=" + qty + "&type=" + updateType + "&src=" + reqsrc;
	setAjaxHTML("GET",url,outdiv);
}

function addOrderToCart(orderid,outdiv){
	url = "do.php?f=phpscript&p=action_addordertocart&orderid=" + orderid;
	setAjaxHTML("GET",url,outdiv);
}

function emptyCart(outdiv){
	if(confirm("Are you sure sure you want to empty you cart?")){
		url = "do.php?f=phpscript&p=action_emptycart";
		setAjaxHTML("GET",url,outdiv);
	}
}

function showSubCat(subDivId){
	if(getEl(subDivId).style.display == "none"){
		showItem(subDivId);
		getEl(subDivId + "title").style.backgroundColor="#D5F38D";
		getEl(subDivId + "main").style.borderWidth="1px";
		getEl(subDivId + "main").style.margin="2px 0px 2px 0px";
	} else {
		hideItem(subDivId);
		getEl(subDivId + "title").style.backgroundColor="#F1FBDB";
		getEl(subDivId + "main").style.borderWidth="0px";
		getEl(subDivId + "main").style.margin="0px 0px 0px 0px";
	}
}
function showOrderDetail(orderid,manage){
	var script = "action_showorderdetails";
	if(manage){
		script =  "action_showmanageorderdetails";
	}
	var detailDiv = getEl("orderDetail" + orderid);
	url = "do.php?f=phpscript&p=" + script + "&orderid=" + orderid;
	setAjaxHTML("GET",url,detailDiv.id);
	detailDiv.style.display = "";
	detailDiv.innerHTML = _ajax_loading_img_html;
}

function updateOrderDetail(orderid,elementid,updatefield,value,itemid){
	var el = getEl(elementid);
	url = "do.php?f=phpscript&p=action_updateorder&orderid=" + orderid + "&field=" + updatefield + "&value=" + value;
	if(itemid){
		url+="&itemid=" + itemid;
	}
	setAjaxHTML("GET",url,el.id);
	el.style.display = "";
	el.innerHTML = _ajax_loading_img_html;
}

function editItem(itemtype,itemid,outdiv){
	if(itemid && itemtype){
		var url;
		if (itemtype == 'product') {
			url = "do.php?f=phpscript&p=action_item&edit_mode=true&item_id=" + itemid;
		} else if(itemtype == 'loginreminder'){
			url = "do.php?f=phpscript&p=action_login_reminder&email=" + escape(itemid);
		} else if(itemtype=='news'){
			url = "do.php?f=phpscript&p=action_news&edit_mode=true&news_id=" + itemid;
		} else if(itemtype=='account'){
			url = "do.php?f=phpscript&p=action_account&register_edit_mode=true&register_id=" + itemid;
		}
		var el = getEl(outdiv);
		setAjaxHTML("GET",url,el.id);
		el.style.display = "";
		el.innerHTML = _ajax_loading_img_html;
	}
}
function showProducts(showtype,outdiv){
	var url = null;
	if(showtype=='allspecials') url = "do.php?f=panelbody&p=catalogue_items&allspecials=true";
	if(url){
		var el = getEl(outdiv);
		setAjaxHTML("GET",url,el.id);
		el.style.display = "";
		el.innerHTML = _ajax_loading_img_html;
	}
}
function showNews(show,outdiv){
	var el = getEl(outdiv);
	url = "do.php?f=panelbody&p=catalogue_news_show&show=" + show;
	setAjaxHTML("GET",url,el.id);
	el.style.display = "";
	el.innerHTML = _ajax_loading_img_html;
}
