var req;
var checkbox;
var page = "";
var className = "";
var baseDir = 'http://www.illsean.com/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'});
	var requestUrl = baseDir + 'req/reorder.php?table='+table+'&'+order;
//	alert(theList);
	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';
}

//RESIZE DIV********************
function resizeDiv(width, height, target){
	target = document.getElementById(target);
	newWidth = width;
	newHeight = height + 65;
	screenHeight = document.documentElement.clientHeight;
	if(screenHeight < (newHeight + 100))
	{
		newHeight = (screenHeight - 120);
		//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);
	callBackFunction = "resolveSaveSelect()";
	updateStatus('Saving...', 'block');
	loadXMLDoc(requestUrl);
}
function resolveSaveSelect() {
	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);
	}
}

