function getElementsByClassName(stringElementType, stringClassName) {
	d = document.getElementsByTagName(stringElementType);
	j=0;
	var cl = new Array()
	for(i=0;i<d.length;i++){
		if(d[i].className == stringClassName){
			cl[j] = d[i];
			j++
		}
	}
	return cl
}

function focusinput(id){
	el = document.getElementById(id);
	if(id == 'email'){
		if(el.value == 'email'){
			el.value = "";
			el.style.color = "#000000";
		}
	} else if(id == 'pass'){
		if(el.value == 'password'){
			el.value = "";
			el.style.color = "#000000";
		}
	} else if(id == 'search'){
		if(el.value == 'search by product code, name or type'){
			el.value = "";
			el.style.color = "#000000";
		}
	}
}

function blurinput(id){
	el = document.getElementById(id);
	col = "#b2b2b2"
	if(id == 'email'){
		if(el.value == ''){
			el.value = "email";
			el.style.color = col;
		}
	} else if(id == 'pass'){
		if(el.value == ''){
			el.value = "password";
			el.style.color = col;
		}
	} else if(id == 'search'){
		if(el.value == ''){
			el.value = "search by product code, name or type";
			el.style.color = col;
		}
	}
}

function submittradelogin(){
	el1 = document.getElementById('email');
	el2 = document.getElementById('pass');
	if((el1.value == 'email' && el2.value == 'password')||(el1.value == '' && el2.value == '')){
		return false;
	} else {
		return true;
	}
}

function decrease(div){
	countDiv = document.getElementById(div);
	if(countDiv.value >= 1){
		countDiv.value = parseInt(countDiv.value) - 1;
	} else {
		countDiv.value = 0;
	}
	document.getElementById(div+'_tot').innerHTML = parseFloat(document.getElementById(div+'_pack').innerHTML) * document.getElementById(div).value;
}

function increase(div){
	countDiv = document.getElementById(div);
	if((countDiv.value < 999)&&(countDiv.value >= 0)){
		countDiv.value = parseInt(countDiv.value) + 1;
	} else if(countDiv.value < 0) {
		countDiv.value = 1;
	} else {
		countDiv.value = 999;
	}
	document.getElementById(div+'_tot').innerHTML = parseFloat(document.getElementById(div+'_pack').innerHTML) * document.getElementById(div).value;
}

function subprice(div,price){
	subTotal = document.getElementById(div).value * price * parseInt(document.getElementById(div+'_pack').innerHTML);
	document.getElementById(div+'_tot').innerHTML = parseInt(document.getElementById(div+'_pack').innerHTML * document.getElementById(div).value);
    document.getElementById(div+'_grandtot').innerHTML = subTotal.toFixed(2);
}

function recalculate(customer,id){
	tot = document.getElementById(id+'[total]');
	qty = parseInt(document.getElementById(id+'[quantity]').value);
	pak = parseInt(document.getElementById(id+'[quantity]_pack').innerHTML);
	qtot = parseInt(document.getElementById(id+'[quantity]_tot').innerHTML);
	pri = parseFloat(document.getElementById(id+'[price]').innerHTML);
	dispri = document.getElementById(id+'[discount_price]').value;
	dis = document.getElementById('d');

        if(qty > 0){
            subtotal = Math.round(  ( ((qty*pak)*(pri)) ) * 100 ) / 100;
            discountSubtotal =   ( ((qty*pak)*((pri)*(dis.value/100))) );
        } else {
            subtotal = 0;
            discountSubtotal = 0;
            qty = 0;
        }
        
        document.getElementById(id+'[quantity]_tot').innerHTML = pak * qty;
	tot.innerHTML = number_format(subtotal.toFixed(2),2,'.',',');
        //alert(tot);

        discountSubtotal = (parseInt(discountSubtotal*100))/100;
        dispri = number_format(discountSubtotal.toFixed(2),2,'.');
	d = getElementsByClassName( 'input', 'discountSubtotal' );
	var discountGrandTotal = 0;
	for(i=0;i<d.length;i++){
            var string = d[i].value;
            discountGrandTotal = discountGrandTotal + parseFloat(string);
	}

	d = getElementsByClassName( 'span', 'subtotal' );
	var grandTotal = 0;
	var vatTotal = 0;
	var fullTotal = 0;
	for(i=0;i<d.length;i++){
            str = d[i].innerHTML;
            var stringNum = str.replace(/,/gi,"");
            grandTotal = grandTotal + parseFloat(stringNum);
	}
	//set the grand total
	grandTotal = Math.round(  ( grandTotal ) * 100 ) / 100;
	grandTotal = grandTotal.toFixed(2);
        
	vatTotal = (parseInt((grandTotal-discountGrandTotal)*(document.getElementById('vat').value/100)*100))/100;
	fullTotal = (parseInt((grandTotal-discountGrandTotal)*(document.getElementById('vat').value/100+1)*100))/100;

	document.getElementById('grandTotal').innerHTML = number_format(grandTotal, 2, '.', ',');
        if((discountGrandTotal > 0)&&(document.getElementById('discountGrandTotal'))){
            document.getElementById('discountGrandTotal').innerHTML = number_format(discountGrandTotal, 2, '.', ',');
        }
	document.getElementById('vatTotal').innerHTML = number_format(vatTotal, 2, '.', ',');
	document.getElementById('fullTotal').innerHTML = number_format(fullTotal, 2, '.', ',');
	//update the basket using ajax
	keys = customer + '-' + id + '-' + qty;
	ajaxDb('updateBasket',keys);
}

function ajaxDelete ( operation, divChange, keys, customMessage ) {
	if ( !customMessage ){
		customMessage = 'Are you sure you want to delete this item?';
	}
	if ( confirm( customMessage )){
		ajax( operation, divChange, keys );
//		return true;
	} else {
//		return false;
	}
}

//LOADING DIV AND REPLACING INNERHTML
function ajax(operation,divChange,keys){
	//loading(divChange,'show');
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var ajaxDisplay = document.getElementById(divChange);
			ajaxDisplay.innerHTML = ajaxRequest.responseText;
			//loading(divChange,'hide');
		}
	}
	var queryString = "?operation=" + operation + "&keys=" + keys;
	ajaxRequest.open("GET", "ajax.php" + queryString, true);
	ajaxRequest.send(null);
}

function loading(divChange,action){
	if(action == 'hide'){
		document.getElementById(divChange).style.backgroundImage = "";
	} else {
		document.getElementById(divChange).innerHTML = "";
		document.getElementById(divChange).style.backgroundImage = "url(img/preload.gif)";
	}
}


//NO LOADING DIV AND NOTHING TO REPLACE - SIMPLY UPDATING THE DB
function ajaxDb(operation,keys){
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	var queryString = "?operation=" + operation + "&keys=" + keys;
	ajaxRequest.open("GET", "ajax.php" + queryString, true);
	ajaxRequest.send(null);
}

function check(currency){
	var cost = document.getElementById('fullTotal').innerHTML;
	if(parseFloat(cost) > 0){
		if ( confirm( 'Are you sure you want to purchase these items?' )){
			return true;
		} else {
			return false;
		}
	} else {
		alert('Please select at least one item to continue.')
		return false;
	}
}

function addToBasket(id){
	var products = new Array();
	var quantity = 0;
	var totquantity = 0;
	d = getElementsByClassName( 'input', 'items' );
	for(i=0;i<d.length;i++){
		products[i] = d[i].id + ';' + d[i].value;
		quantity = parseFloat(quantity)+parseFloat(d[i].value);
		totquantity = totquantity + quantity;
	}
	products = products.join('|');
	if(totquantity > 0){
		if ( confirm( 'Are you sure you want to add ' + quantity + ' ' + document.getElementById('product').innerHTML + '(s) to your basket.\r\nIf you already have any ' + document.getElementById('product').innerHTML + '\'s in your basket, they will be replaced.' )){
			keys = id + '-' + products;
			ajax('addToBasket','basketCount',keys);
		}
	} else {
		alert('Please select at least one item to add to your basket.');
	}
}

function isNumberKey(evt){
	var charCode=evt.keyCode? evt.keyCode : evt.charCode;
	if (charCode > 31 && (charCode < 48 || charCode > 57)){
		return false;
	} else {
		return true;
	}
}

function chkSearch(id){
	div = document.getElementById(id);
	if((div.value != '')&&(div.value != 'search by product code, name or type')){
		return true;
	} else {
		return false;
	}
}

function validateOrder(form){
	document.getElementById("error_address").innerHTML="";
	var deliveryError = "";
	//var billingError = "";
	//var chosen1 = "";
	blnReturn=true;
	if(form.delivery){
//		var len = form.delivery.length;
//		for (i = 0; i <len; i++) {
//			if (form.delivery[i].checked) {
//				chosen1 = form.delivery[i].value;
//			}
//		}
//		if (chosen1 == "") {
//			blnReturn=false;
//			deliveryError="<li>Please select a Delivery Address</li>";
//		}
		
//		var chosen2 = "";
//		var len = form.billing.length;
//		for (i = 0; i <len; i++) {
//			if (form.billing[i].checked) {
//				chosen2 = form.billing[i].value;
//			}
//		}
//		if (chosen2 == "") {
//			blnReturn=false;
//			billingError="<li>Please select a Billing Address</li>";
//		}
		
	} else {
		blnReturn=false;
		deliveryError="<li>Please contact the administrator - you need an address to deliver to.</li>";
	}
	if (blnReturn==false) {
		document.getElementById("error_address").innerHTML="<div id='error'><p>The following errors occured:</p><ul>" + deliveryError + "</ul>";
		//window.scrollTo(0,0);
	}
	return blnReturn;
}

function number_format(a, b, c, d) {
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if (!f[0]) {
		f[0] = '0';
	}
	if (!f[1]) {
		f[1] = '';
	}
	if (f[1].length < b) {
		g = f[1];
		for (i=f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j+=3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '' : c;
	return f[0] + c + f[1];
}

function emptyBasket(globalid){
	if ( confirm( 'Are you sure you want to empty your basket?' )){
		window.location='basket.php?action=empty&q='+globalid;
	}
}

function LimitText(fieldObj,maxChars) {
    var result = true;
    var text = document.getElementById(fieldObj);
    if (text.value.length >= maxChars) {
        result = false;
    }

    if (window.event) {
        window.event.returnValue = result;
        return result;
    }
}
