var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE

function xhrRequest(type) {
	if (!type) {
		type = 'html';
	}

	// xhrsend IS THE xi POSITION THAT GETS PASSED BACK
	// INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
	// IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
	var xhrsend = xi.length;

	// GO THROUGH AVAILABLE xi VALUES
	for (var i=0; i<xi.length; i++) {

		// IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
		if (xi[i] == 1) {
			xi[i] = 0;
			xhrsend = i;
			break;
		}
	}

	// SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
	xi[xhrsend] = 0;

	// SET UP THE REQUEST
	if (window.XMLHttpRequest) {
		xhr[xhrsend] = new XMLHttpRequest();
		if (xhr[xhrsend].overrideMimeType) {
			xhr[xhrsend].overrideMimeType('text/' + type);
		}
	} else if (window.ActiveXObject) {
		try {
			xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return (xhrsend);
}

function showSubject(subject_id) {
	showFbox(300, 400);
	var xhri = xhrRequest('html');
	var qry = 'js=yes&sid=' + subject_id;
	var url = '/php/show_subject.php';
	xhr[xhri].open('POST', url, true);
	xhr[xhri].onreadystatechange = function () {
			if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
				document.getElementById('fbox').innerHTML = closeCode() + xhr[xhri].responseText;
				resetFboxPos();
				//alert("done");
			} else {
				try {
					var alertStr = "xhr[xhri].readyState=" + xhr[xhri].readyState + " xhr[xhri].status=" + xhr[xhri].status;
					//alert(alertStr);
				}
				catch (e) {
					var alertStr = "error getting xhr[xhri].readyState and xhr[xhri].status";
					//alert(alertStr);
				}
			}
		};
	xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr[xhri].send(qry);
}

function showShipping(pid) {
	document.getElementById("shipcalc_" + pid).style.display = "block";
	document.getElementById("shipcalc_" + pid).style.visibility = "visible";
	document.getElementById("shipcalcbut_" + pid).style.display = "none";
	document.getElementById("shipcalcbut_" + pid).style.visibility = "hidden";
	resetFboxPos();
}

function calcShipping(pid) {
	document.getElementById('shipcost_' + pid).innerHTML = "";
	document.getElementById('atcbutton_' + pid).innerHTML = "";
	var xhri = xhrRequest('html');
	var ship_zone = document.getElementById('shipselect_' + pid).value;
	var qry = 'js=yes&pid=' + pid + '&ship=' + ship_zone;
	var url = '/php/calc_shipping.php';
	xhr[xhri].open('POST', url, true);
	xhr[xhri].onreadystatechange = function () {
			if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
				document.getElementById('shipcost_' + pid).innerHTML = "&euro;" + xhr[xhri].responseText;
				resetFboxPos();
				makeATCbutton(pid);
				//alert("done");
			} else {
				try {
					var alertStr = "xhr[xhri].readyState=" + xhr[xhri].readyState + " xhr[xhri].status=" + xhr[xhri].status;
					//alert(alertStr);
				}
				catch (e) {
					var alertStr = "error getting xhr[xhri].readyState and xhr[xhri].status";
					//alert(alertStr);
				}
			}
		};
	xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr[xhri].send(qry);
}

function makeATCbutton(pid) {
	var xhri = xhrRequest('html');
	var ship_zone = document.getElementById('shipselect_' + pid).value;
	var qry = 'js=yes&pid=' + pid + '&ship=' + ship_zone;
	var url = '/php/make_atcbutton.php';
	xhr[xhri].open('POST', url, true);
	xhr[xhri].onreadystatechange = function () {
			if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
				document.getElementById('atcbutton_' + pid).innerHTML = xhr[xhri].responseText;
				document.getElementById('atcbutton_' + pid).style.display = "block";
				document.getElementById('atcbutton_' + pid).style.visibility = "visible";
				//alert("done");
			} else {
				try {
					var alertStr = "xhr[xhri].readyState=" + xhr[xhri].readyState + " xhr[xhri].status=" + xhr[xhri].status;
					//alert(alertStr);
				}
				catch (e) {
					var alertStr = "error getting xhr[xhri].readyState and xhr[xhri].status";
					//alert(alertStr);
				}
			}
		};
	xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr[xhri].send(qry);
}

function showFbox(width, height) {
	document.getElementById('wrapper').style.opacity = '0.3';
	document.getElementById('wrapper').style.filter = 'alpha(opacity=30)';
	document.getElementById('fbox').style.visibility = 'visible';
	document.getElementById('fbox').style.display = 'block';
	document.getElementById('fbox').style.width = width + 'px';
	document.getElementById('fbox').style.height = height + 'px';
	var fbheight = (((Geometry.getViewportHeight() - (height))/2) > 0)?((Geometry.getViewportHeight() - (height))/2):0;
	//alert(fbheight);
	document.getElementById('fbox').style.top = fbheight + 'px';
	var fbwidth = (((Geometry.getViewportWidth() - (width))/2) > 0)?((Geometry.getViewportWidth() - (width))/2):0;
	//alert(fbwidth);
	document.getElementById('fbox').style.left = fbwidth + 'px';
	document.getElementById('fbox').innerHTML = closeCode() + busyImage();
	document.getElementById('fbox').style.height = 'auto';
}

function resetFboxPos() {
	document.getElementById('fbox').style.width = 'auto';
	document.getElementById('fbox').style.height = 'auto';
	if (document.getElementById('fbox_img').complete) {
		var widthImg = document.getElementById('fbox_img').offsetWidth;
		document.getElementById('fbox').style.width = widthImg + 'px';
		var heightFbox = document.getElementById('fbox').offsetHeight;
		var fbheight = (((Geometry.getViewportHeight() - (heightFbox))/2) > 0)?((Geometry.getViewportHeight() - (heightFbox))/2):0;
		document.getElementById('fbox').style.top = fbheight + 'px';
		var widthFbox = document.getElementById('fbox').offsetWidth;
		var fbwidth = (((Geometry.getViewportWidth() - (widthFbox))/2) > 0)?((Geometry.getViewportWidth() - (widthFbox))/2):0;
		document.getElementById('fbox').style.left = fbwidth + 'px';
	} else {
		var t = setTimeout("resetFboxPos()",500);
	}
}

function closeFbox() {
	document.getElementById('wrapper').style.opacity = '1.0';
	document.getElementById('wrapper').style.filter = 'alpha(opacity=100)';
	document.getElementById('fbox').style.visibility = 'hidden';
	document.getElementById('fbox').style.display = 'none';
}

function closeCode() {
	return "<div class='fbox_close_code'><a href='#' onclick='closeFbox()'>close</a></div>";
}

function busyImage() {
	return "<div align='center'><img src='/images/common/busy.gif' alt='busy...' title='busy...' /></div>";
}

function validate_contact(form)
{
	if (form.username.value == "") {
		alert("Please enter your name");
		form.username.focus();
		form.username.select();
		return false;
	}
	if (check_email(form) == false) {
		return false
	}
	if (form.subject.value == "") {
		alert("Please enter a subject");
		form.subject.focus();
		form.subject.select();
		return false;
	}
	if (form.message.value == "") {
		alert("Please enter a message");
		form.message.focus();
		form.message.select();
		return false;
	}
	if (!filter_html(form.message)) {
		alert("Your message appears to contain HTML or other tags or web addresses which have been removed. Please check it and try again.");
		form.message.focus();
		form.message.select();
		return false;
	}
	//if (form.captcha_code.value == "") {
	//	alert("Please enter the code");
	//	form.captcha_code.focus();
	//	form.captcha_code.select();
	//	return false;
	//}
	//if (!check_captcha(form)) {
	//	return false;
	//}
	//alert("return true");
	return true;
}

function check_email(form) {
	if (form.email.value == "") {
		alert("Please enter your email address");
		form.email.focus();
		form.email.select();
		return false;
	}
	if (form.email.value.indexOf(" ") != -1) {
		alert("Your email address appears to be invalid (it contains 1 or more spaces)");
		form.email.focus();
		form.email.select();
		return false;
	}
	if (form.email.value.indexOf("@") != -1) {
		var email_array = form.email.value.split("@");
		if (email_array[1].indexOf(".") != -1) {
			var domain_array = email_array[1].split(".");
			for (i=0; i<=domain_array.length; i++) {
				if (domain_array[i] == "") {
					alert("Your email address appears to be invalid; please check it");
					form.email.focus();
					form.email.select();
					return false;
				}
			}
		} else {
			alert("Your email address appears to be invalid; please check it");
			form.email.focus();
			form.email.select();
			return false;
		}
	} else {
		alert("Your email address appears to be invalid (there is no @ symbol)");
		form.email.focus();
		form.email.select();
		return false;
	}
}

function filter_html(field) {
	if (field.value.match(/<a|href=|url=|link=|<\/a>|\/url|\/link|\/http|http\:\/\/|\/href/g) != null) {
	//if (field.value.match(/<a|href=|url=|link=|www.|.com|.net|.org|<\/a>|\/url|\/link|\/http|http:\/\/|\/href/g) != null) {
		//field.value = field.value.replace(/<a|href=|url=|link=|www.|.com|.net|.org|<\/a>|\/url|\/link|\/http|http:\/\/|\/href/g, "");
		field.value = field.value.replace(/<a|href=|url=|link=|<\/a>|\/url|\/link|\/http|http\:\/\/|\/href/g, "");
		return false;
	}
	return true;
}

function refresh_captcha() {
	document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random();
}

function check_captcha(form) {
	document.getElementById('captcha_busy').style.visibility = "visible";
	document.getElementById('captcha_busy').style.display = "block";
	document.getElementById('bad_captcha').style.visibility = "hidden";
	document.getElementById('bad_captcha').style.display = "none";
	var xhri = xhrRequest('html');
	var qry = 'captcha_code=' + form.captcha_code.value;
	var url = '/php/captcha.php';
	xhr[xhri].open('POST', url, true);
	xhr[xhri].onreadystatechange = function () {
			if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
				//alert(xhr[xhri].responseText);
				if (xhr[xhri].responseText == "pass") {
					form.captcha_valid.value = "true";
					document.getElementById('contact_form').style.visibility = "visible";
					document.getElementById('contact_form').style.display = "block";
					document.getElementById('contact_captcha').style.visibility = "hidden";
					document.getElementById('contact_captcha').style.display = "none";
					document.getElementById('captcha_busy').style.visibility = "hidden";
					document.getElementById('captcha_busy').style.display = "none";
					//document.getElementById('contact').submit();
					//return true;
				} else {
					form.captcha_valid.value = "false";
					document.getElementById('contact_form').style.visibility = "hidden";
					document.getElementById('contact_form').style.display = "none";
					document.getElementById('bad_captcha').style.visibility = "visible";
					document.getElementById('bad_captcha').style.display = "block";
					document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random();
					document.getElementById('captcha_busy').style.visibility = "hidden";
					document.getElementById('captcha_busy').style.display = "none";
					//return false;
				}
			} else {
				try {
					var alertStr = "xhr[xhri].readyState=" + xhr[xhri].readyState + " xhr[xhri].status=" + xhr[xhri].status;
				}
				catch (e) {
					var alertStr = "error getting xhr[xhri].readyState and xhr[xhri].status";
				}
				//alert(alertStr);
			}
		};
	xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr[xhri].send(qry);
}

//
// Admin (backoffice) functions
//

function editSubject(id) {
	var $hostname = window.location.hostname;
	window.location.assign("http://" + $hostname + "/adminedit.php?type=subject&id=" + id);
}

function editProduct(id) {
	var $hostname = window.location.hostname;
	window.location.assign("http://" + $hostname + "/adminedit.php?type=product&id=" + id);
}

function duplicateProduct(id) {
	var $hostname = window.location.hostname;
	window.location.assign("http://" + $hostname + "/admin.php?type=duplicateproduct&id=" + id);
}

function deleteProduct(id) {
	var userResponse = confirm("Are you sure you want to delete this product? (deletions cannot be undone)");
	if (userResponse == true) {
		var $hostname = window.location.hostname;
		window.location.assign("http://" + $hostname + "/admin.php?type=deleteproduct&id=" + id);
	}
}

function addProduct(subjectId) {
	var $hostname = window.location.hostname;
	window.location.assign("http://" + $hostname + "/admin.php?type=addproduct&subjectId=" + subjectId);
}

function addSubject() {
	var $hostname = window.location.hostname;
	window.location.assign("http://" + $hostname + "/admin.php?type=addsubject");
}

function selectGenre(thisSelect) {
	if (thisSelect.options[thisSelect.selectedIndex].value == '_new') {
		var newGenre = prompt("Enter a new Genre:","");
		if (newGenre!=null && newGenre!="") {
			var xhri = xhrRequest('html');
			var qry = 'js=yes&genre='+newGenre;
			var url = 'php/validate_genre.php';
			xhr[xhri].open('POST', url, true);
			xhr[xhri].onreadystatechange = function () {
					if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
						var response = xhr[xhri].responseText;
						//alert(response);
						if (response.search("ok") >= 0) {
							var newOption = document.createElement('option');
							newOption.value = newGenre;
							newOption.text = newGenre;
							var newGenreBefore = thisSelect.options[thisSelect.options.length - 1];
							thisSelect.add(newOption,newGenreBefore);
							thisSelect.selectedIndex = thisSelect.options.length - 2;
						} else if (response.search("exists") >= 0) {
							for (var i=0; i<thisSelect.options.length; i++) {
								if (thisSelect.options[i].value == newGenre) {
									var genreIndex = i;
								}
							}
							thisSelect.selectedIndex = genreIndex;
							thisSelect.options[genreIndex].selected = true;
						} else if (response.search("no") >= 0) {
							alert('You entered an invalid genre ('+newGenre+')');
							thisSelect.selectedIndex = 0;
							thisSelect.options[0].selected = true;
						} else {
							alert('unable to process response ('+response+')');
							thisSelect.selectedIndex = 0;
							thisSelect.options[0].selected = true;
						}
						xi[xhri] = 1;
						xhr[xhri] = null;
					} else {
						try {
							var alertStr = "xhr[xhri].readyState=" + xhr[xhri].readyState + " xhr[xhri].status=" + xhr[xhri].status;
							//alert(alertStr);
						}
						catch (e) {
							var alertStr = "error getting xhr[xhri].readyState and xhr[xhri].status";
							//alert(alertStr);
						}
					}
				};
			xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr[xhri].send(qry);
		} else {
			thisSelect.selectedIndex = 0;
			thisSelect.options[0].selected = true;
		}
	}
}

function selectCategory(thisSelect) {
	if (thisSelect.options[thisSelect.selectedIndex].value == '_new') {
		var newCat = prompt("Enter a new Category:","");
		if (newCat!=null && newCat!="") {
			var xhri = xhrRequest('html');
			var qry = 'js=yes&category='+newCat;
			var url = 'php/validate_category.php';
			xhr[xhri].open('POST', url, true);
			xhr[xhri].onreadystatechange = function () {
					if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
						var response = xhr[xhri].responseText;
						if (response.search("ok") >= 0) {
							var newOption = document.createElement('option');
							newOption.value = newCat;
							newOption.text = newCat;
							var newCatBefore = thisSelect.options[thisSelect.options.length - 1];
							thisSelect.add(newOption,newCatBefore);
							thisSelect.selectedIndex = thisSelect.options.length - 2;
						} else if (response.search("exists") >= 0) {
							for (var i=0; i<thisSelect.options.length; i++) {
								if (thisSelect.options[i].value == newCat) {
									var catIndex = i;
								}
							}
							thisSelect.selectedIndex = catIndex;
							thisSelect.options[catIndex].selected = true;
						} else if (response.search("no") >= 0) {
							alert('You entered an invalid category ('+newCat+')');
							thisSelect.selectedIndex = 0;
							thisSelect.options[0].selected = true;
						} else {
							alert('unable to process response ('+response+')');
						}
						xi[xhri] = 1;
						xhr[xhri] = null;
					} else {
						try {
							var alertStr = "xhr[xhri].readyState=" + xhr[xhri].readyState + " xhr[xhri].status=" + xhr[xhri].status;
							//alert(alertStr);
						}
						catch (e) {
							var alertStr = "error getting xhr[xhri].readyState and xhr[xhri].status";
							//alert(alertStr);
						}
					}
				};
			xhr[xhri].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr[xhri].send(qry);
		} else {
			thisSelect.selectedIndex = 0;
			thisSelect.options[0].selected = true;
		}
	}
}


