/* addEvent: simplified event attachment */
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
	
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

/* window 'load' attachment */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function empty(value) {
	var regexpWhitespace = /^\s+$/;
	return  ((value == null) || (value.length == 0) || regexpWhitespace.test(value));
}

/* quick getElement reference */
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

//same as in PHP
function in_array (variable, array) {

	var is_in_array  = false;

	for (var i in array) {
	
		if(array[i] == variable) {
						
			is_in_array = true;
			break;
		
		}
	
	}

	return is_in_array;
	
}//end function in_array

//************** BEGIN OLD ORDER PAGES FUNCTIONS ******************//
function get_product_value() {
	for (var i=0; i < document.forms[0].product_id.length; i++)
	{

		if (document.forms[0].product_id[i].checked)
		{
			var v = document.forms[0].product_id[i].value;
		}
	}

	if(typeof(v) == 'undefined') {
		v = document.forms[0].product_id.value;
	}

	return v;
}

function get_ship_value() {
    return getCheckedValue(document.forms[0].ship);
}

function bb_ce() {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.forms[0].email.value)){
		return (true);
	}
	return (false);
}

function setValue(theElement,val) {
	if(!val) return false;
	var select = theElement;

	for (var i = 0; i < select.options.length; i ++) {

		if (select.options[i].value == val){
			select.selectedIndex=i;
			return true;
		}
	}
	return false;
}

function getCheckedValue(radioObj) {
	if(!radioObj)
	return '';
	var radioLength = radioObj.length;
	if(radioLength == undefined)
	if(radioObj.checked)
	return radioObj.value;
	else
	return '';
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return '';
}

function setCheckedValue2(radioObj, newValue) {
	if(!newValue) return false;
	if(!radioObj)
	return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function show_inum(){
	box1 = document.forms[0].CardType;
	ct = box1.options[box1.selectedIndex].value;
	if(ct == 'SOLO' || ct == 'SWITCH')
	document.getElementById('dinum').style.visibility = 'visible';
	else
	document.getElementById('dinum').style.visibility = 'hidden';
}
//************** END OLD ORDER PAGES FUNCTIONS ******************//

function track_visit(field, field_value){

	var track_id;
	
	if(typeof(TRACK_VISIT_ID) != 'undefined' && !empty(TRACK_VISIT_ID) && TRACK_VISIT_ID != 0) {
		//use global JS variable
		track_id = TRACK_VISIT_ID;	
	} else if($('track_visit_id') != null) {
		track_id = $('track_visit_id').value;	
	}	

	var url_pramaters = '?track_id='+track_id;
	if(typeof(field) != 'undefined' && typeof('field_value') != 'undefined' && !empty(field_value)) {
		//add single field	
		url_pramaters += '&'+field+'='+escape(field_value);
	} else {
		//insrt the form
		var fname = '';
		var lname = '';
		var username  = '';
		var password  = '';
		var split_name = true;

		var fields_array = new Array('track_visit_form', 'step', 'name', 'fname', 'lname', 'email', 'phone', 'address', 'city', 'state', 'zip', 'country', 'cc_name', 'cc_num', 'cc_cvv', 'terms', 'username', 'password', 'webmaster');

		for(field_num = 0; field_num < fields_array.length; field_num++) {
			//------create commmon url request parameter-------
			var current_field = document.getElementById(fields_array[field_num]);
			if(current_field != null && !empty(current_field.value)){
				switch(current_field.name)
				{
					//case for specific field parameter and value
					case 'fname':
					case 'lname':
					url_pramaters += '&'+fields_array[field_num]+'='+escape(current_field.value);
					split_name = false;
					break
					case 'cc_num':
					url_pramaters += '&cc=1';
					break
					case 'cc_cvv':
					url_pramaters += '&'+fields_array[field_num]+'=1';
					break						
					case 'terms':
					if(current_field.checked){
						url_pramaters += '&'+fields_array[field_num]+'=1';	
					}
					break
					default:
					url_pramaters += '&'+fields_array[field_num]+'='+escape(current_field.value);
				}
			}
			//--end--create common url request parameter-------
		}
		
		//get first and last name -- Look for fname and last name input elemtnts - if not found uses name input element
		if(split_name && $('name') != null && !empty($('name').value)) {
			var full_name = $('name').value.split(' ', 2);
			fname = escape(full_name[0]);
			url_pramaters += '&fname='+fname;
			if(typeof(full_name[1]) != 'undefined') {
				lname = escape(full_name[1]);	
				url_pramaters += '&lname='+lname;
			}
		}//end get frist and last name
		
	}
	
	img_src = 'track_visit/input.php'+url_pramaters;
	if($('track_gif') != null) {
		//prompt('0',img_src);
		$('track_gif').src = img_src;	
	}
	/*document['bb'].src=img_src;*/
}

function createRequestObject() {

    var A;
    try {
        A=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            A=new ActiveXObject("Microsoft.XMLHTTP");
        } catch (oc) {
            A=null;
        }
    }
    if(!A && typeof XMLHttpRequest != "undefined")
        A = new XMLHttpRequest();
    if (!A)
        alert("Could not create connection object.");
    return A;
}

var http = createRequestObject();

function sndPageCheck(value)
{
    var date = new Date();
    http.open("get","track_visit/ajax_check.php?a=set_otp&value=" + value + "&t=" + date.getTime());
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function jsVoucherCheck(obj, product_id, calc_total)
{
	
	var error_container = document.getElementById('bonus_code-E');
	var success_container = document.getElementById('bonus_code-S');
	
	//function local product_id
	var flproduct_id;
	if(typeof(product_id) != 'undefined') {
		flproduct_id = product_id;
	} else {
		flproduct_id = get_product_value();
	}
	
	var flbonus_code = hex_md5(obj.value.toUpperCase());
	var flprice      = 0.00;
	if(bonus_array[flbonus_code] && (bonus_array[flbonus_code][flproduct_id] || bonus_array[flbonus_code][0]) ) {
		
		if(bonus_array[flbonus_code][flproduct_id]) {
			flprice = bonus_array[flbonus_code][flproduct_id];
		} else {
			flprice = bonus_array[flbonus_code][0];
		}
		
		success_container.className = 'successMsg';
		error_container.className = 'errMsgHidden';
	} else {
		success_container.className = 'successMsgHidden';
		error_container.className = 'errMsg';		
	}

	if(typeof(calc_total) != 'undefined' && calc_total == false) {
		return true;
	}
	
	var newTotalPrice = parseFloat($('price_no_discount').value) - parseFloat(flprice);
	$('tvprice').value = newTotalPrice;
		
	return true;
}

function handleResponse()
{
	if(http.readyState == 4) {
		var response = http.responseText;
		var value = new Array();
		if(response.indexOf('@')!= -1) {
			
			var error_container = document.getElementById('bonus_code-E');
			var success_container = document.getElementById('bonus_code-S');
			
			value = response.split("@");
			document.getElementById('bonus_value').value = value[0];
			total(0);
			if(value[0] != 0){
				success_container.className = 'successMsg';
				error_container.className = 'errMsgHidden';				
			} else {
				success_container.className = 'successMsgHidden';
				error_container.className = 'errMsg';
			}
		}
	}
}


function on_the_page()
{
    sndPageCheck($('track_visit_id').value);
    setTimeout("on_the_page()",20000);
}

function calc_cross_product(obj) {
	
	if(obj.checked){
/*		alert(obj.value);
		alert(cross_products[obj.value]);*/
		if(obj.value == 0) {
			document.getElementById('cross_products_total').value = 0;
		} else {
			document.getElementById('cross_products_total').value = cross_products[obj.value];
		}

	} else {
		//case for checkbox cross product
		document.getElementById('cross_products_total').value -= cross_products[obj.value];
	}
	
	total();
}



function show_common_errors( error_type, check_error_obj ) {
	
	if(typeof(check_error_obj) != 'undefined') {
		var show_message = true;
		var error_obj = document.getElementById(check_error_obj);
		if(error_obj != null) {
			show_message = (
								(error_obj.className == 'errMsgHidden errMsg')
								|| (error_obj.className == 'allrequired errFld')
								|| (error_obj.className == 'required errFld')
								|| (error_obj.className == 'errMsg')
								|| (error_obj.className == ' errMsg')
							);
		}
		if(!show_message) {
			return true;
		}
	}
	
	var message = '';
	switch(error_type)
	{
		case 'required':
			message = 'This field is required.';
		break
		case 'name':
			message = 'You must have a first and last name, e.g. John Smith';
		break
		case 'email':
			message = 'We do not recognize this as a valid email address, it should look something like this yourname@email.com';
		break
		case 'address':
			message = 'You must have at least one address line here.';
		break
		case 'city':
			message = 'You must include your city here.';
		break
		case 'zip':
			message = 'You must include your post/zip code here.';
		break
		case 'phone':
			message = 'We do not recognize this as a valid phone number, please only use numbers and spaces, no letters are allowed for example 666 039 928, country code is optional.';
		break
		case 'cc_name':
			message = 'This should match the name on your credit card exactly e.g. John Smith.';
		break
		case 'cc_num':
			message = 'Our system does not recognize your card number, please double check your credit card number, this should be the long number across the front of your credit card, if you require assistance please call %GEOIP_PHONE%.';
		break
		case 'cc_cvv':
			message = 'You should check to make sure that only numbers have been entered and that it is no less than 3 digits and no more than 4 digits.';
		break
		case 'bonus_code':
			message = 'This E-Voucher code is incorrect or no longer valid.';
		break
		case 'terms':
			message = 'You must read and agree to the terms and conditions of sale.';
		break
		case 'exp_date':
			message = 'The date seems to be incorrect, either this card has expired or you have made a mistake. Please recheck your entry.';
		break
		case 'cross_products':
			message = 'You must choose at least one option. If you do not wish to add this item to your order, please choose No Thanks.';
		break		
		case 'state':
			if(typeof(__country_check) != 'undefined') {
				message = 'State is required if you live in either ' + __country_check.join('/');	
			} else {
				message = 'State is required if you live in either US/CA/AU';	
			}
		break		
		default:
	}

	return overlib(message, FGCOLOR, '#F8FBFC', BGCOLOR, '#7FB1C8', TEXTCOLOR, 'black');
}


function make_shipping() {
	
    var is_online=0;
    
    pv = get_product_value();
	
    var shippers = ship_options.split(',');
    var has_shipping = false;    
    for(i=0;i<shippers.length;i++) {
    	
    	var shipping_id;
    	var default_shipping_id;

    	if(shipping[pv] && shipping[pv][shippers[i]]) {
    		shipping_id = pv;
    		if(!has_shipping) {
    			has_shipping = true;
    			default_shipping = shippers[i];
    		}    		    		
    	} else if(shipping[0] && shipping[0][shippers[i]]){
    		shipping_id = 0;
    		if(!has_shipping) {
    			has_shipping = true;
    			default_shipping = shippers[i];
    		}    		    		
    	} else {
    		if($('td_ship_'+shippers[i]) != null) $('td_ship_'+shippers[i]).style.display="none";
    		continue;
    	}
		
		if(typeof(shipping[shipping_id]) != 'undefined') {
    		var ship_price = shipping[shipping_id][shippers[i]]['price'].toFixed(2);
    		var ship_desc  = shipping[shipping_id][shippers[i]]['description'];
    
    		eval("document.forms[0]."+shippers[i]+"_price.value=ship_price;");
    		eval("$('"+shippers[i]+"_desc').innerHTML=ship_desc;");
    
    		if($("td_ship_"+shippers[i]) != null) {
    			document.getElementById("td_ship_"+shippers[i]).style.display="";
    		}
    
    		$("tbl_noship").style.display="none";
    		$("tbl_ship").style.display="";
    		if(get_ship_value()==shippers[i]) document.forms[0].ship_price.value=ship_price;
    		if(getCheckedValue(document.forms[0].ship)=="online") setCheckedValue2(document.forms[0].ship,shippers[i]);			
		}
    		
    }
    
    if(!has_shipping) {
    	document.forms[0].ship_price.value = "0";
		$("tbl_noship").style.display = "";
		$("tbl_ship").style.display = "none";
		document.forms[0].ship_price.value = "0";
		setCheckedValue2(document.forms[0].ship, "online");    	
    }
    
    var checked_sv = get_ship_value();
    /*alert($('td_ship_'+checked_sv));*/
    if($('td_ship_'+checked_sv) != null) {
        /*alert($('td_ship_'+checked_sv).style.display);*/
        if($('td_ship_'+checked_sv).style.display == 'none') {
        	document.forms[0].ship_price.value = "0";
        	setCheckedValue2(document.forms[0].ship, default_shipping);
        }
        
    }
}

function make_no_free_shipping() {
	
    var is_online=0;
    
    pv = get_product_value();
	
    var shippers = ship_options.split(',');
    
    var has_shipping = false;
    
    for(i=0;i<shippers.length;i++) {
    	
    	var shipping_id;
    	var default_shipping_id;
    	
    	if(shipping[0] && shipping[0][shippers[i]] && shipping[pv] && shipping[pv][shippers[i]]) {
    		
    		if(shipping[0][shippers[i]]['orders'] < shipping[pv][shippers[i]]['orders']) {
    			shipping_id = 0;
    		} else {
    			shipping_id = pv;
    		}
    		
    		if(!has_shipping) {
    			has_shipping = true;
    			default_shipping = shippers[i];
    		}    		
    		
    	} else if(shipping[pv] && shipping[pv][shippers[i]]) {
    		
    		shipping_id = pv;
    		
    		if(!has_shipping) {
    			has_shipping = true;
    			default_shipping = shippers[i];
    		}    		    		
    		
    	} else if(shipping[0] && shipping[0][shippers[i]]){
    		
    		shipping_id = 0;

    		if(!has_shipping) {
    			has_shipping = true;
    			default_shipping = shippers[i];
    		}    		    		

    	} else {
    		
    		if($('td_ship_'+shippers[i]) != null) $('td_ship_'+shippers[i]).style.display="none";
    		
    		continue;
    	}
    	
		
		if(shipping[shipping_id]['online']) {

			$("tbl_noship").style.display = "";
			$("tbl_ship").style.display = "none";
			document.forms[0].ship_price.value = "0";
			setCheckedValue2(document.forms[0].ship, "online");

		} else {

			var ship_price = shipping[shipping_id][shippers[i]]['price'].toFixed(2);
			var ship_desc  = shipping[shipping_id][shippers[i]]['description'];

			if(ship_price>0)
			{
    			eval("document.forms[0]."+shippers[i]+"_price.value=ship_price;");
    			eval("$('"+shippers[i]+"_desc').innerHTML=ship_desc;");
    
    			if($("td_ship_"+shippers[i]) != null) {
    				document.getElementById("td_ship_"+shippers[i]).style.display="";
    			}
    
    			$("tbl_noship").style.display="none";
    			$("tbl_ship").style.display="";
    			if(get_ship_value()==shippers[i]) document.forms[0].ship_price.value=ship_price;
    			if(getCheckedValue(document.forms[0].ship)=="online") setCheckedValue2(document.forms[0].ship,shippers[i]);			
			}
			else
			{
			    if($("td_ship_"+shippers[i]) != null) {
    				document.getElementById("td_ship_"+shippers[i]).style.display="none";
    			}
			}
		}
    		
    }
    
    if(!has_shipping) {
    	document.forms[0].ship_price.value = "0";
    }
    
    var checked_sv = get_ship_value();
    /*alert($('td_ship_'+checked_sv));*/
    if($('td_ship_'+checked_sv) != null) {
        /*alert($('td_ship_'+checked_sv).style.display);*/
        if($('td_ship_'+checked_sv).style.display == 'none') {
        	document.forms[0].ship_price.value = "0";
        	setCheckedValue2(document.forms[0].ship, default_shipping);
        }
        
    }
  
}

function hide_free_shipping( product_id ) {
	
    var selected_product = get_product_value();
    var selected_ship    = get_ship_value();
    var change_selected  = false;
    
    if(typeof(product_id) != 'undefined' && !in_array(selected_product, product_id)) {
    	return;
    }
    
    if(typeof(product_id) == 'undefined' || selected_product == product_id) {
    	
    	var shippers = ship_options.split(',');

    	var has_shipping = false;

    	for(i=0;i<shippers.length;i++) {
			if( (shipping[0] && shipping[0][shippers[i]]['price'] == 0) || (shipping[selected_product] && shipping[selected_product][shippers[i]]['price']) ) {
				if($('td_ship_'+shippers[i]) != null) $('td_ship_'+shippers[i]).style.display="none";
				if(change_selected == false && selected_ship == shippers[i]) {
					change_selected = true;
				}
			} else {
				var new_ship = shippers[i];
			}
    	}
    	
    }
    
    if(change_selected && typeof(new_ship) != 'undefined') {
    	//change selected shipping and recalcluate total amount
    	setCheckedValue2(document.forms[0].ship, new_ship);
    	total();
    }
    
}

function calc_charity() {
	var charitybox = $('charity');
	
	if(charitybox == null) {
		return false;
	}
	
	var total = parseFloat($('tvprice').value);
	var charity_amount = parseFloat(charitybox.value);
	if(charitybox.checked) {
		total += charity_amount;
	} else {
		total -= charity_amount;
	}
	
	$('tvprice').value = Math.round(total*100)/100;
}

function total() {
    if(window.checkbox_event) checkbox_event();

    var vat = 0;
    if(typeof(VAT) != 'undefined') vat = VAT;
    
    var crossp = 0;
    pv = get_product_value();
    sv = get_ship_value();
    
    products[pv] = parseFloat(products[pv]);

    if($('cross_products_total') != null) crossp = parseFloat($('cross_products_total').value);
    ts = parseFloat($('ship_price').value);
    tv = parseFloat(products[pv]*vat/100);
    
    $('tprice').value  = Math.round((products[pv] + crossp)*100)/100;
    $('tsprice').value = Math.round(ts*100)/100;
    $('tv').value      = Math.round(tv*100)/100;
	/*alert(pv);alert(products[pv]);alert(ts);alert(crossp);alert(products[pv]*vat/100);*/
    tp = parseFloat(products[pv] + ts + crossp + products[pv]*vat/100);
        
    $('tvprice').value = Math.round(tp*100)/100;
    if($('price_no_discount')) $('price_no_discount').value = Math.round(tp*100)/100;
}