/* 
 * misc.js
 *
 * Content: Various Javascript odds and ends such as error handling and specific functions that
 * 			do not warrant seperate libraries. 
 * Notes:	More documentation is needed.
 *
 * Status:	UP TO DATE
 *
 * Author:	Matt Adair
 *
 */


// Function for clearing a target field based on data entry in the source. Used for
// mutually exclusive data entry because I simply do not have time to write a 
// comprehensive validation package at the moment.
function blankIt(target) {
	var targetNode = document.getElementById(target);
	var newValue = targetNode.getAttribute('defaultValue');
	if(targetNode) {
		if(newValue) {
			targetNode.value = newValue;
		}
		else {
			targetNode.value = '';
		}
	}
}

// Generic activate/deactivate response handler used throughout the app. Currently does not
// work in IE6, IE7, or Safari.
function actIt(node) {
	var obj = new xobj();
    obj.requestFile = node.getAttribute('my_url');
	obj.URLString = 'status=' + node.getAttribute('my_status') + '&id=' + node.getAttribute('my_id') + '&xhttp=true';
    obj.oncompletion = function() {
        var statusNode = obj.responseXML.getElementsByTagName('status');
		if(statusNode[0].firstChild.nodeValue != '0') {
			errorHandler(obj.responseText);
		}
		else {
			if(node.className == 'active') {
				node.className = 'inactive';
				node.setAttribute('my_status', '1');
				node.setAttribute('src', '/images/pi_diagonal/03/16/01.png');
				node.setAttribute('title', 'Click to activate');
			}
			else if(node.className == 'inactive') {
                node.className = 'active';
				node.setAttribute('my_status', '0');
				node.setAttribute('src', '/images/pi_diagonal/03/16/02.png');
				node.setAttribute('title', 'Click to deactivate');
			} 
		}
	}
	obj.runXObj();
}

// Generic activate/deactivate response handler used throughout the app. Currently does not
// work in IE6, IE7, or Safari.
function actIt2(node, url, attr) {
	var obj = new xobj();
    obj.requestFile = url;
	for (a in attr) {
		obj.URLString += a + '=' + attr[a] + '&';
	}
	obj.URLString += '&xhttp=true';
    obj.oncompletion = function() {
        var statusNode = obj.responseXML.getElementsByTagName('status');
		if (statusNode[0].firstChild.nodeValue != '0') {
			errorHandler(obj.responseText);
		} else {
			if(node.className == 'active') {
				node.className = 'inactive';
				node.setAttribute('src', '/images/pi_diagonal/03/16/01.png');
				node.setAttribute('title', 'Click to activate');
			}
			else if(node.className == 'inactive') {
                node.className = 'active';
				node.setAttribute('src', '/images/pi_diagonal/03/16/02.png');
				node.setAttribute('title', 'Click to deactivate');
			} 
		}
	}
	obj.runXObj();
}

function systemCall(node) {
    var obj = new xobj();
    obj.requestFile = '/esadmin/main.php?menu=misc^system';
    obj.URLString = 'what=' + node.getAttribute('my_task') + '&xhttp=true';
	if(node.getAttribute('my_params')) {
		obj.URLString = obj.URLString + node.getAttribute('my_params');
	}
    obj.oncompletion = function() {
        var statusNode = obj.responseXML.getElementsByTagName('status');
        if(statusNode[0].firstChild.nodeValue != '0') {
            errorHandler(obj.responseText);
        }
        else {
			var helpList = document.getElementsByTagName('a');
//			alert(helpList[1].firstChild);
			for(i = 0; i < helpList.length; i++) {
				var aNode = helpList[i].firstChild;
//				alert(aNode.getAttribute('class'));
			}
            if(node.className == 'hactive') {
                node.className = 'hinactive';
                node.innerHTML = 'Off';
            }
            else if(node.className == 'hinactive') {
                node.className = 'hactive';
                node.innerHTML = 'On';
			}
        }
    }
    obj.runXObj();
}


// This needs to be developed. Current planned codes:
// 0	Success
// 1	Access denied
// 2	Missing data
// 3	Database error
function errorHandler(responseXML) {
	console.log(responseXML);
}


// Sucker Fish Menus
sfHover = function() {
	var sfEls = document.getElementById("es_nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" hover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" hover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);


//browser testing
ie=window.navigator.appName.indexOf('Internet')!=-1;
ie7=ie && (window.navigator.appVersion.indexOf('MSIE 7')!=-1);
opera=window.navigator.appName.indexOf('Opera')!=-1;
safari=window.navigator.userAgent.toLowerCase().indexOf('safari')!=-1;


var startFuncs=new Array();

function chain(funcs, eve) {
	while (func=funcs.shift()) {
		if (typeof(func)=='string') {
			//if (!eval(func+'(eve);')) alert(func+' failed');
			eval(func+'(eve);');
		} else if (func.length) {
			//if (!eval(func[0]+'("'+func[1]+'");')) alert(func+' failed');
			eval(func[0]+'("'+func[1]+'");');
		}
	}
}


startFuncs.push('prepForms')

//Search for parent element == form
function findForm(ele) {
	if (ele.tagName=='FORM') return ele;
	if (ele.parentNode) return findForm(ele.parentNode);
	return false;
}

//onclick handler for submittable buttons
formOnClick = function() {
	if (ie) {
		var tar=event.srcElement;
		event.returnValue=false;
	} else if (arguments[0].target) {
		var tar=arguments[0].target;
	} else {
		var tar=arguments[0];
	}
	var frm=tar.form;
	if (!frm) frm=findForm(tar);
	if (!frm) alert("No Form found.");
//	alert(tar+' '+tar.name+' '+tar.type);
	if (tar.name && (tar.type.toLowerCase()=='submit')) {
		frm.setAttribute('submitValue', tar.value);
		frm.setAttribute('submitName', tar.name);
		// tar.disabled=true;
	} else if (tar.type.toLowerCase()!='submit') {
		frm.setAttribute('submitValue', frm.submit.value);
		frm.setAttribute('submitName', frm.submit.name);
		// frm.submit.disabled=true;
	}

	//if (!processing && !ie) processing=popAlert('Processing...', false, true);
	if (ie7) {
		frm.onsubmit(tar);
	} else if (ie || opera) {
		frm.onsubmit.call(frm, tar);
	}
	return true;
}

//Builds the POST data
function getFormData(frm) {
	var postData='';
	for (var x=0; x<frm.elements.length; x++) {
		if (ie) {
			if (frm.elements(x)) {
				it=frm.elements(x);
			} else {
				continue;
			}
		} else {
			it=frm.elements.item(x);
		}

		if ((it.type!='submit') && (it.name != undefined) && (it.name)) {
			if ((it.type=='checkbox') || (it.type=='radio')) {
				if (it.checked) postData+=it.name+'='+utf8_encode(it.value)+'&';
			} else if ((it.tagName.toLowerCase()=='select')) {
				for (var y=0; y<it.childNodes.length; y++) {
					if (it.childNodes.item(y).selected) {
						if (it.multiple) {
							postData+=it.name+'[]='+encodeURIComponent(it.childNodes.item(y).value)+'&';
						} else {
							postData+=it.name+'='+encodeURIComponent(it.childNodes.item(y).value)+'&';
						}
					}
				}
			} else {
				postData+=it.name+'='+encodeURIComponent(it.value)+'&';
			}
		}
	}
	return postData;
}

function utf8_encode(str) {
	str = str.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < str.length; n++) {
		var c = str.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		} else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		} else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}

	return utftext;
}

function submitForm(args) {
	if (ie) {
		var eve=args;
		eve.target=eve.srcElement;
		eve.returnValue=false;
	} else if (window.event) {
		var eve=window.event;
		if (eve.preventDefault) eve.preventDefault();
	} else if (args.target) {
		var eve=args;
		if (eve.preventDefault) eve.preventDefault();
	} else if (args[0].target)  {
		var eve=args[0];
		if (eve.preventDefault) eve.preventDefault();
	} else {
		alert("Can't find event");
	}
	eve.cancelBubble=true;
	if (eve.target.form) {
		var frm=eve.target.form
	} else if (eve.target){
		var frm=eve.target
	} else {
		alert("error");
		throw "error";
	}

	var postData=getFormData(frm);
	if (frm.getAttribute('submitValue') || frm.getAttribute('submitName')) {
		var submitData=frm.getAttribute('submitName')+'='+(frm.getAttribute('submitValue'))+'&';
		postData+=submitData;
	}
	postData += '&isXHR=1';

    var obj = new xobj(frm.getAttribute('action'));
    obj.URLString = postData;
    obj.oncompletion = function() {
		if (obj.responseXML) {
			xmlDoc=obj.responseXML;
			if (ele = xmlDoc.getElementsByTagName('response').item(0)) {

				switch (ele.getAttribute('code')) {
					case '0':
						if (ele.getAttribute('redir')) {
							window.location.assign(ele.getAttribute('redir'));
						}
					break;
					default:
						console.log(ele);
						var errorMsg = ele.getElementsByTagName('message');
						var errorDiv = document.getElementById('errorDiv');
						var errorList = new Array();;

						if (errorMsg.length == 0) {
							errorList.push('Unspecified error.');
						} else {
							for (var i=0; i < errorMsg.length; i++) {
								errorList.push(errorMsg[i].textContent);
							}
						}

						if (errorDiv) {
							errorDiv.innerHTML = 'Error: <ul><li>' + errorList.join('</li><li>') + '</li></ul>';
							errorDiv.style.textAlign = 'left';
							errorDiv.style.display = '';
						} else {
							console.log(ele);
							alert("Error:\n\t" + errorList.join("\n\t"));
						}
					break;
				}
			} else {
				console.log(obj);
				alert('XML: '+obj.responseText);
			}
		} else {
			alert('TXT: '+obj.responseText);
		}
    }
    obj.runXObj();
	return false;
}

//
function prepForms() {
	formList = document.getElementsByTagName('FORM');
	for (i=0; i<formList.length; i++) {
		if ((ele=formList.item(i)) && (ele.getAttribute('method').toLowerCase()=='post')) {
			inputs=ele.getElementsByTagName('input');
			for (var x=0; x<inputs.length; x++) {
				if (inputs[x].type.toLowerCase() == 'submit') {
					inputs[x].onclick = formOnClick;
				}
				
			}
		}
	}
}










