var req;
var checkbox;
var page = "";
var className = "";
var baseDir = 'http://www.thebutchershop.com.au/admin/';

/////////////////////////////////////////////////////////////////////////////////////////
//XMLHTTPREQUEST FUNCTIONS_______________________________________________________________
function loadXMLDoc(url) {
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open('GET', url, true);
		req.send(null);
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		req = new ActiveXObject('Microsoft.XMLHTTP');
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open('GET', url, true);
			req.send();
		}
	}
}

//callBackFunction is set (as a string) as you send XML request and is called on response
var callBackFunction = "";

//processes request
function processReqChange() {
	// only if req shows 'loaded'
	if (req.readyState == 4) {
		// only if 'OK'
		if (req.status == 200) {
			eval(callBackFunction);
			req.stuff = "ee";
		}else{
			alert(req.statusText);
		}
	}
}

//sets the content and vis of ajax_status
function updateStatus(content, vis){
	document.getElementById('ajax_status').innerHTML = content;
	document.getElementById('screen_dimmer').style.display = vis;
}

/////////////////////////////////////////////////////////////////////////////////////////
//TO KEEP FUNCTIONS_______________________________________________________________

//REORDER LIST***************
function reorder(table,theList){
	var order = Sortable.serialize(theList, {name:'rl'});
	order = order.replace(/&rl\[\]=/g, '|');
	order = order.replace(/rl\[\]=/g, '');
	var requestUrl = baseDir + 'req/reorder.php?table='+table+'&order='+order;
//	alert(requestUrl);
	callBackFunction = "resolveReorder()";
	updateStatus('Saving...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveReorder() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
		checkbox.checked = !checkbox.checked;
	} else {
		//cool
	}
}

//MOVE/COPY SECTION***************
function moveSection(element, droppableElement, e)
{
	var altDown = e.altKey;
	if(altDown)
	{
		//then we want to copy the fucker to a new category
		var requestUrl = baseDir + 'req/move_section.php?copy=1&page_id='+droppableElement.id+'&section_id='+element.id;
	}else{
		var requestUrl = baseDir + 'req/move_section.php?page_id='+droppableElement.id+'&section_id='+element.id;
	}
//	alert(requestUrl);
	callBackFunction = "resolveMoveSection()";
	updateStatus('Saving...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveMoveSection() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
//		checkbox.checked = !checkbox.checked;
	} else if(req.responseText == 'no change') {
		//no need to delete it
	} else {
		//then we need to update the section list
		var splitContent = req.responseText.split("\n");
		document.getElementById('reorder_list_' + splitContent[2]).style.display = 'none';
		var  theUrl = "req/get_sections.php?id=" + splitContent[0] + "&pages_title=" + splitContent[1];
		getContent(theUrl, 'sections');
	}
}

//SHOW HIDE AN ELEMENT***************
function toggleVis(elementId, theButton){
	if(document.getElementById(elementId).style.display == 'none' || document.getElementById(elementId).style.display == '')
	{
		document.getElementById(elementId).style.display = 'block';
		theButton.innerHTML = 'HIDE';
	}else{
		document.getElementById(elementId).style.display = 'none';
		theButton.innerHTML = 'SHOW';
	}
}

//CANCEL/SUBMIT PROMPT******************************************
function cancelPrompt(){
	document.getElementById(theTargetId).innerHTML = '';
	document.getElementById(theTargetId).style.display = 'none';
}
function submitPrompt(callFunction){
	if(event.keyCode == 13){
		eval(callFunction);
	}
}

//XMLHTTPREQUEST CONTENT, INSERT INTO AN ELEMENT***************
var theTargetId = '';
function getContent(theUrl, target){
	var requestUrl = baseDir + theUrl;
	theTargetId = target;
	callBackFunction = "resolveGetContent()";
	updateStatus('Loading...', 'block');
	loadXMLDoc(requestUrl);
//	alert(requestUrl);
}
function resolveGetContent() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
		checkbox.checked = !checkbox.checked;
	} else {
		//first, seperate the javascript
		var splitContent = req.responseText.split("END THE JAVASCRIPT BIT");
		var javascriptContent = splitContent[0];
		var content = splitContent[1];
		//then insert the content
		document.getElementById(theTargetId).innerHTML = '';
		document.getElementById(theTargetId).innerHTML = content;
		document.getElementById(theTargetId).style.display = 'block';
		//then run the javascript
		eval (javascriptContent);
	}
}

//CLOSE ANYTHING******************************
function ungetContent(target){
	document.getElementById(target).innerHTML = '';
	document.getElementById(target).style.display = 'none';
}

//USE SCRIPTACULOUS To APPEAR/DISAPPEAR AN ELLEMENT********************
function toggleElementInOut(target){
	if(document.getElementById(target).style.display == 'none')
	{
		Effect.BlindDown(target, {duration:	0.2});
	}else{
		Effect.BlindUp(target, {duration:	0.2});
	}
}

//RESIZE DIV********************
function killBubbles(e)
{
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
function resizeDiv(width, height, target){
	target = document.getElementById(target);
	newWidth = width;
	newHeight = height + 100;
	screenHeight = document.documentElement.clientHeight;
	if(screenHeight < newHeight + 40)
	{
		newHeight = (screenHeight - 40);
		newWidth = newWidth;
		//target.style.margin = "10px auto 0 auto";
	}
	target.style.width = newWidth + 'px';
	target.style.height = newHeight + 'px';
	//target.style.left = Math.round((screenWidth - newWidth) / 2);
}

//CONFIRM DELETE***************
/*function confirmDelete(theUrl){
	var confirmString = "Yeah? You sure you want to DELETE that?";
	if(window.confirm(confirmString))
	{
		window.location = baseDir + theUrl;
	}
}*/

//ACTIVATE / DEACTIVATE A SECTION***************
function toggleCheckbox(theId, theTable, theColumn, theCheckbox){
	var requestUrl = baseDir + "req/toggle_checkbox.php?id=" +theId+"&table="+theTable+"&column="+theColumn+"&the_checkbox="+theCheckbox;
	callBackFunction = "resolveToggleCheckbox()";
	updateStatus('Saving Status...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveToggleCheckbox() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
		checkbox.checked = !checkbox.checked;
	} else {
		//first, seperate the javascript
		var splitContent = req.responseText.split("::::");
		var theId = splitContent[0];
		var status = splitContent[1];
		var theCheckbox = splitContent[2];
		//set the checked on the element
		document.getElementById(theCheckbox).checked = eval(status);
	}
}

//ACTIVATE / DEACTIVATE A SECTION***************
function toggleActive(theId, theTable){
	var requestUrl = baseDir + "req/toggle_active.php?id=" +theId+"&table="+theTable;
	callBackFunction = "resolveToggleActive()";
	updateStatus('Saving Active Status...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveToggleActive() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
		checkbox.checked = !checkbox.checked;
	} else {
		//first, seperate the javascript
		var splitContent = req.responseText.split("::::");
		var theId = splitContent[0];
		var status = splitContent[1];
		//set the checked on the element
		document.getElementById('active_' + theId).checked = eval(status);
	}
}

//SAVE A DROPDOWN SELECTION TO A TABLE***************
function saveSelect(theId, theTable, theColumn, theSelect){
	if(theTable == 'carts'){
		//then we on the cart page and need to disable the proceed button
		document.getElementById('proceed_to_pp').disabled = true;
	}
	var theSelectIndex = document.getElementById(theSelect).options.selectedIndex;
	var theValue = document.getElementById(theSelect).options[theSelectIndex].value;
	var requestUrl = baseDir + "req/set_val.php?table=" + theTable + "&column=" + theColumn + "&id=" + theId + "&value=" + escape(theValue);
	//alert(requestUrl);
	callBackFunction = "resolveSaveSelect()";
	updateStatus('Saving...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveSaveSelect() {
	if(req.responseText.substr(0,7) != 'refresh'){
		updateStatus('', 'none');
	}
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed')
	{
		alert(req.responseText.substr(8));
	}else if(req.responseText.substr(0,7) == 'refresh'){
		window.location.href = location.href;
	}else if(req.responseText.substr(0,15) == 'postcode prompt'){
		var message = "Please enter the postcode where this order will be shipped.";
		var cartId = req.responseText.substr(16,req.responseText.length);
		getContent("req/prompt.php?prompt=" + message + "&prompt_button=Submit&call_function=savePostcode&args=" + cartId + "&no_cancel=1", 'prompt');
	}
}
//SAVE THE POSTCODE ON AEROSOL SHIPPING
function savePostcode(cartId){
	var thePostcode = document.getElementById('value').value;
	if(thePostcode)
	{
		var requestUrl = baseDir + "req/set_val.php?table=carts&column=zip&id=" + cartId + "&value=" + escape(thePostcode);
		callBackFunction = "resolveSavePostcode()";
		document.getElementById('prompt').style.display = 'none';
		updateStatus('Saving Postcode...', 'block');
		loadXMLDoc(requestUrl);
	}
}
function resolveSavePostcode() {
	window.location.href = location.href;
}

//SAVE A RADIO BUTTON CLICK TO A TABLE***************
function saveRadio(theId, theTable, theColumn, theValue){
	if(theTable == 'carts'){
		//then we on the cart page and need to disable the proceed button
		document.getElementById('proceed_to_pp').disabled = true;
	}
	var requestUrl = baseDir + "req/set_val.php?table=" + theTable + "&column=" + theColumn + "&id=" + theId + "&value=" + escape(theValue);
	callBackFunction = "resolveSaveRadio()";
	updateStatus('Saving...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveSaveRadio() {
	if(req.responseText.substr(0,7) != 'refresh'){
		updateStatus('', 'none');
	}
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
	}else if(req.responseText.substr(0,7) == 'refresh'){
		window.location.href = location.href;
	}
}

//INSERT CONTENT INTO A TEXTAREA***************
function insertImage(insertInto){
	imageIndex = document.getElementById('image_select').options.selectedIndex;
	formatIndex = document.getElementById('image_format').options.selectedIndex;
	if(formatIndex == 0){
		alert('Please select an image format before inserting an image.');
	}else{
		if(imageIndex != 0){
		var imageCode = '[' + document.getElementById('image_format').options[formatIndex].value + ' ' +document.getElementById('image_select').options[imageIndex].value;
		insertAtCaret(insertInto, imageCode)
		}
	}
	document.getElementById('image_select').options.selectedIndex=0;
}
function insertFile(insertInto){
	fileIndex = document.getElementById('file_select').options.selectedIndex;
	if(fileIndex != 0){
		insertAtCaret(insertInto, document.getElementById('file_select').options[fileIndex].value)
	}
	document.getElementById('file_select').options.selectedIndex=0;
}
function insertSectionLink(insertInto, selectFrom){
	sectIndex = document.getElementById(selectFrom).options.selectedIndex;
	if(sectIndex != 0){
		if(document.getElementById(selectFrom).options[sectIndex].value != 'none'){
			insertAtCaret(insertInto, document.getElementById(selectFrom).options[sectIndex].value)
		}
	}
	document.getElementById(selectFrom).options.selectedIndex=0;
}
function insertAtCaret(obj, text) {
	obj = document.getElementById(obj).elements[0];
	if(document.selection) {
		obj.focus();
		var orig = obj.value.replace(/\r\n/g, "\n");
		var range = document.selection.createRange();

		if(range.parentElement() != obj) {
			return false;
		}

		range.text = text;
		
		var actual = tmp = obj.value.replace(/\r\n/g, "\n");

		for(var diff = 0; diff < orig.length; diff++) {
			if(orig.charAt(diff) != actual.charAt(diff)) break;
		}

		for(var index = 0, start = 0; 
			tmp.match(text) 
				&& (tmp = tmp.replace(text, "")) 
				&& index <= diff; 
			index = start + text.length
		) {
			start = actual.indexOf(text, index);
		}
	} else if(obj.selectionStart) {
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;

		obj.value = obj.value.substr(0, start) 
			+ text 
			+ obj.value.substr(end, obj.value.length);
	}
	
	if(start != null) {
		setCaretTo(obj, start + text.length);
	} else {
		obj.value += text;
	}
}

function setCaretTo(obj, pos) {
	if(obj.createTextRange) {
		var range = obj.createTextRange();
		range.move('character', pos);
		range.select();
	} else if(obj.selectionStart) {
		obj.focus();
		obj.setSelectionRange(pos, pos);
	}
}

//ADD PRODUCT TO CART***************
function addToCart(productId){
	var quantity = document.getElementById('value').value;
	if(quantity)
	{
		var requestUrl = baseDir + "req/add_to_cart.php?product_var_id=" + productId + "&quantity=" + escape(quantity);
		callBackFunction = "resolveAddToCart()";
		document.getElementById('prompt').style.display = 'none';
		updateStatus('Adding To Cart...', 'block');
		loadXMLDoc(requestUrl);
	}
}
function resolveAddToCart() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
	}else{
		updateStatus('Added To Cart.', 'block');
		setTimeout(updateStatus('', 'none'), 2000);
	}
}
//UPDATE CART ITEM QUANTITY***************
var redirectURL = '';
function updateQuantity(cartItemsId, table, column, redirect){
	var quantity = document.getElementById('value').value;
	if(quantity)
	{
		var requestUrl = baseDir + "req/set_val.php?table=" + table + "&column=" + column + "&id=" + cartItemsId + "&value=" + escape(quantity);
		callBackFunction = "resolveUpdateQuantity()";
		redirectURL = redirect;
		loadXMLDoc(requestUrl);
	}
}
function resolveUpdateQuantity() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
	}else{
		window.location.href = redirectURL;
	}
}
//UPDATE SHIPPING METHOD AND CALCULATE SHIPPING***************
function updateShipping(cartId){
	var theSelectIndex = document.getElementById('shipping_selct').options.selectedIndex;
	var theValue = document.getElementById(theSelect).options[theSelectIndex].value;
	var requestUrl = baseDir + "req/set_val.php?table=carts&column=shipping_method&id=" + cartId + "&value=" + escape(theValue);
	callBackFunction = "resolveUpdateShipping()";
	updateStatus('Saving...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveUpdateShipping() {
	updateStatus('', 'none');
	//***************** check for failed at start and print error string
	if (req.responseText.substr(0,6) == 'failed') {
		alert(req.responseText.substr(8));
	}else{
		window.location.href = baseDir + '../cart/';
	}
}

//GENERATE COMMA SEPERATED NUMBER FROM A RANGE***************
function getRange(theValues, theRange){
	if(event.keyCode == 13){
		var range = document.getElementById(theValues).value;
		range = range.split('-');
		var low = range[0];
		var high = range[1];
		var numRange = '';
		for(var i = low; i <= high; i++)
		{
			numRange = numRange + i +',';
		}
		numRange = numRange.substring(0, (numRange.length -1));
		document.getElementById(theRange).value = numRange;
		document.getElementById(theRange).focus();
		document.getElementById(theRange).select();
	}
}



/*//PROMPT TO RUN DATABSE BACKUP***************
function runBackup(){
	var doBackUp = window.confirm("Would you like to backup the database now?");
	if(doBackUp)
	{
		window.location = baseDir + "mysqldump/";
	}
}*/

//FUNCTIONS TO HANDLE FIELD SUGGESTION***************
/*
var input='';
var regExp = '';
var oldSelectedResult = 0;
var selectedResult = 0;
var endResult = 0;
var row = '';
var safariToggle = 0;

function predict() {
	switch(event.keyCode){
		case 9://tab
			break;
		case 13://return
			if(selectedResult > 0 ){
				document.getElementById('input_text').value = document.getElementById(selectedResult).innerHTML;
			}
			break;
		case 40://dn arrow
			if(navigator.userAgent == 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'){
				if(safariToggle == 1){
					if(selectedResult < endResult){
						selectedResult++;
					}
					safariToggle = 0;
				}else{
					safariToggle = 1;
				}
			}else{
				if(selectedResult < endResult){
					selectedResult++;
				}
			}
			break;
		case 38://up arrow
			if(navigator.userAgent == 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'){
				if(safariToggle == 1){
					if(selectedResult > 0){
						selectedResult--;
					}
					safariToggle = 0;
				}else{
					safariToggle = 1;
				}
			}else{
				if(selectedResult > 0){
					selectedResult--;
				}
			}
			break;
		default:
			document.getElementById('results').innerHTML = '';
			selectedResult = 0;
			endResult = 0;

			putput = document.getElementById('input_text').value;
			if(putput != ''){
				putput = putput.toLowerCase();
				putLen = putput.length;
				
				for(var i = 0; i < matchArray.length; i ++){
					match = matchArray[i].slice(0, putLen);
					match = match.toLowerCase();
					if(putput == match){
						endResult ++;
						document.getElementById('results').innerHTML += "<a style='background:#FFF' href='#' id='" + endResult + "'>" + matchArray[i] + "</a><br />";
					}
				}
			}
			
			break;
	}

colourResults();
}

function colourResults(){
	for(i = 0; i < endResult; i ++){
		if(selectedResult == (i + 1)){
			row = '' + selectedResult;
			document.getElementById(row).style.background = '#AAA';
		}else{
			row = '' + (i + 1);
			document.getElementById(row).style.background = '#FFF';
		}
	}
}

function blockReturn(){
	return false;
}
*/
//END FUNCTIONS TO HANDLE FIELD SUGGESTION***************
