var flagCaptcha = false;
var flagFields = true;

var bustcachevar = 1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var bustcacheparameter = '';

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function createRequestObject() {
	try	{
		xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
	}
	
	return xmlhttp;
}

function ajaxpage(url, containerid, requesttype) {
	var page_request = createRequestObject();
	
	if (requesttype == 'get'){
		if (bustcachevar) bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		page_request.open('GET', url+bustcacheparameter, true)
		page_request.send(null)
	} else if (requesttype == 'post') {
		page_request.open('POST', url, true);
		page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		page_request.setRequestHeader("Content-length", poststr.length);
		page_request.setRequestHeader("Connection", "close");
		page_request.send(poststr);
	}

	page_request.onreadystatechange = function() {
		loadpage(page_request, containerid);
	}
}

function hasClassName (objElement, strClass) {
	// if there is a class
	if ( objElement.className ) {
		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');
		
		// get uppercase class for comparison purposes
		var strClassUpper = strClass.toUpperCase();
		
		// find all instances and remove them
		for ( var i = 0; i < arrList.length; i++ ) {
			// if class found
			if ( arrList[i].toUpperCase() == strClassUpper ) {
				// we found it
				return true;
			}
		}
	}
	
	// if we got here then the class name is not there
	return false;

}

function addClassName (objElement, strClass, blnMayAlreadyExist) {
	// if there is a class
	if ( objElement.className ) {
		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// if the new class name may already exist in list
		if ( blnMayAlreadyExist ) {
			// get uppercase class for comparison purposes
			var strClassUpper = strClass.toUpperCase();

			// find all instances and remove them
			for ( var i = 0; i < arrList.length; i++ ) {
				// if class found
				if ( arrList[i].toUpperCase() == strClassUpper ) {
					// remove array item
					arrList.splice(i, 1);

					// decrement loop counter as we have adjusted the array's contents
					i--;
				}
			}
		}

		// add the new class to end of list
		arrList[arrList.length] = strClass;

		// add the new class to beginning of list
		//arrList.splice(0, 0, strClass);

		// assign modified class name attribute
		objElement.className = arrList.join(' ');
	} else { // if there was no class
		// assign modified class name attribute      
		objElement.className = strClass;
	}
}

function removeClassName (objElement, strClass) {
	// if there is a class
	if ( objElement.className ) {
		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// get uppercase class for comparison purposes
		var strClassUpper = strClass.toUpperCase();

		// find all instances and remove them
		for ( var i = 0; i < arrList.length; i++ ) {
			// if class found
			if ( arrList[i].toUpperCase() == strClassUpper ) {
				// remove array item
				arrList.splice(i, 1);

				// decrement loop counter as we have adjusted the array's contents
				i--;
			}
		}

		// assign modified class name attribute
		objElement.className = arrList.join(' ');
	}
	
	// if there was no class
	// there is nothing to remove
}

function loadpage(page_request, containerid) {
	if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) {
		document.getElementById(containerid).innerHTML = page_request.responseText;
	}
}

function ajaxpagePrice(url, containerid, productId, requesttype) {
	var page_request = createRequestObject();
	
	if (requesttype == 'get'){
		if (bustcachevar) bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		page_request.open('GET', url+bustcacheparameter, true)
		page_request.send(null)
	} else if (requesttype == 'post') {
		page_request.open('POST', url, true);
		page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		page_request.setRequestHeader("Content-length", poststr.length);
		page_request.setRequestHeader("Connection", "close");
		page_request.send(poststr);
	}

	page_request.onreadystatechange = function() {
		loadpagePrice(page_request, containerid, productId);
	}
}

function loadpagePrice(page_request, containerid, productId) {
	if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) {
		var response = page_request.responseText;
		
		document.getElementById(containerid).innerHTML = response;
		
		var btn = document.getElementById('productSubmit_'+productId);
		
		if (btn) {
			if (response == 'N/A') {
//				btn.style.backgroundImage = 'url("img/btn_buy_off.png")';
//				btn.style.cursor = 'default';
				removeClassName(btn, 'btnBuyOn');
				addClassName(btn, 'btnBuy', true);
				btn.setAttribute('disabled', 'disabled');
			} else {
//				btn.style.backgroundImage = 'url("img/btn_buy_on.png")';
				removeClassName(btn, 'btnBuy');
				addClassName(btn, 'btnBuyOn');
				btn.removeAttribute('disabled');
			}
		}
	}
}

function getElementsByClass(searchClass, node, tag) {
	var classElements = new Array();
	
	if ( node == null ) {
		node = document;
	}
	
	if ( tag == null ) {
		tag = '*';
	}
	
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	
	return classElements;
}

function getFormElementsByType(frm, field_type) {
	var elems = frm.elements;
	var result = new Array;
	
	for (var i = 0; i < elems.length; i++) {
		if (elems[i].type == field_type) {
			result[i] = elems[i];
		}
	}
	
	return result;
}

function getPrice(frm, selectClass, url) {
	var postStr = '?1=1';
	var product_id = frm.id.value;
	var attributes = getElementsByClass(selectClass);
	
	postStr += '&id='+product_id;
	
	for (var i = 0; i < attributes.length; i++) {
		postStr += '&pav['+i+']='+attributes[i].options[attributes[i].selectedIndex].value;
	}
	
	ajaxpagePrice(url+postStr, 'price_'+product_id, product_id, 'get');
}

function replaceImage(imageThumbUrl, imageResizedUrl, currentImageWrapper) {
	var dest = document.getElementById(currentImageWrapper);
	var html = '';
	
	html += '<img alt="Product Preview" src="'+imageThumbUrl+'" id="imagePreview" onload="vZoom.add(this, \''+imageResizedUrl+'\');" />';
	
	dest.innerHTML = html;
}

function calculateShipping(val, obj, id, frm) {
	val = parseFloat(val).toFixed(2);
	var viewShipping = document.getElementById(id);
	
	viewShipping.innerHTML = val;
	obj.value = val;
	
	updatePrice(frm);
}

function calculateTax(val, obj, id, basePrice, frm) {
	val = parseFloat(val).toFixed(2);
	var viewTax = document.getElementById(id);
	var tax = basePrice*val/100;
	tax = tax.toFixed(2);
	
	viewTax.innerHTML = tax;
	obj.value = tax;
	
	updatePrice(frm);
}

function updatePrice(frm) {
	var viewPrice = document.getElementById('price');
	var basePrice = parseFloat(frm.base_price.value);
	var shipping = parseFloat(frm.shipping_cost.value);
	var tax = parseFloat(frm.tax_cost.value);
	var total = basePrice + shipping + tax;
	
	viewPrice.innerHTML = CommaFormatted(total.toFixed(2));
	//frm.price.value = total.toFixed(2);
}

function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.', 2);
	var d = a[1];
	var i = parseInt(a[0]);
	
	if(isNaN(i)) {
		return '';
	}
	
	var minus = '';
	
	if(i < 0) { 
		minus = '-';
	}
	
	i = Math.abs(i);
	
	var n = new String(i);
	var a = [];
	
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	
	if(n.length > 0) {
		a.unshift(n);
	}
	
	n = a.join(delimiter);
	
	if(d.length < 1) {
		amount = n;
	} else {
		amount = n + '.' + d;
	}
	
	amount = minus + amount;
	
	return amount;
}

function getFieldValue(obj) {
	switch (obj.type) {
		case 'select-one':
			return obj.options[obj.selectedIndex].value;
			break;
		case 'text':
			return obj.value;
			break;
		case 'textarea':
			return obj.value;
			break;
		default:
			return obj.value;
			break;
	}
	
	return false;
}
