// Works in BOTH IE & Mozilla
//alert("Works in BOTH IE & Mozilla");
var isWorking = false;
var http_request = getHTTPObject();

var templateContainerForm;
var destinationContainerForm;

var lastRadioCheck;

// Create the HTTP XML Object
function getHTTPObject() {
	var xmlhttp;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
    	xmlhttp = new XMLHttpRequest();
		if (xmlhttp.overrideMimeType) {
        	xmlhttp.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
    	try {
        	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
            	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
    	}
    }
      
	if (!xmlhttp) {
        alert('Cannot create XMLHTTP instance');
    	return false;
	}
      
	return xmlhttp;
}


// Find an object on the page
function findObj(objName) {
	var theObj = document.getElementById(objName);
	
	if (!theObj) {
		// Commented out because it was breaking on Mozilla but worked in IE
		// Now it works in both with this commented out. Who knows!
		//theObj = document.all[objName];
	}
	
	return theObj;
}


// Find an object that is contained within an object
function findContainedObj(objName, objContainer) {
	var theObj = objContainer.elements[objName];
	
	if ((!theObj) && (objContainer.all)) {
		theObj = objContainer.all[objName];
	}
	
	// If no object found, search through layers
	if ((!theObj) && (objContainer.getElementsByTagName)) {
		var tmpObj = objContainer.getElementsByTagName("div");
		for (var i = 0; i < tmpObj.length; i++) {
			if ((tmpObj[i].name == objName) || (tmpObj[i].id == objName)) {
				theObj = tmpObj[i];
			}
		}
	}
	
	// If we still haven't found the object, look for table cells
	if ((!theObj) && (objContainer.getElementsByTagName)) {
		var tmpObj = objContainer.getElementsByTagName("td");		
		for (var i = 0; i < tmpObj.length; i++) {
			if ((tmpObj[i].name == objName) || (tmpObj[i].id == objName)) {
				theObj = tmpObj[i];
			}
		}
	}
		
	// If we still haven't found the object, look for spans
	if ((!theObj) && (objContainer.getElementsByTagName)) {
		var tmpObj = objContainer.getElementsByTagName("span");		
		for (var i = 0; i < tmpObj.length; i++) {
			if ((tmpObj[i].name == objName) || (tmpObj[i].id == objName)) {
				theObj = tmpObj[i];
			}
		}
	}
	
	return theObj;	
}


// Replaces text with by in string
function replace(string, text, by) {
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}


// Process the Return Response from the HTTP XML Object
function handleHttpResponse() {
	if ((http_request.readyState == 4) && (http_request.status == 200)) {
				
		// we're done executing
		isWorking = false;
		
		// Copy template form to destination form (if we're in that situation)
		if ((templateContainerForm) && (destinationContainerForm)) {
			var tmpStr = templateContainerForm.innerHTML;
			
			// Replace hardcoded variables in the template form html
			tmpStr = replace(tmpStr, '{form_id}', destinationContainerForm.id);
			tmpStr = replace(tmpStr, '{form_name}', destinationContainerForm.name);

			// Assign the destination form innerHTML			
			destinationContainerForm.innerHTML = tmpStr;
		}
		
		// Use the XML DOM to unpack the variables and values
		//alert(http_request.responseText);
		var xmlObj = http_request.responseXML.documentElement;
		
		if (!xmlObj) { return false; }
		
		// If we have child nodes
		if (xmlObj.hasChildNodes()) {
			// Loop through each sub-child node
			for (i = 0; i < xmlObj.childNodes.length; i++) {
				// If the node type is text
				if (xmlObj.childNodes[i].nodeType == 1) {
					
					// Assign var names and values
					var itemName = xmlObj.childNodes[i].nodeName;
					var itemValue = xmlObj.childNodes[i].firstChild.nodeValue;
					//alert(itemName + ' = ' + itemValue);

					// Check to see if we're using a template to destination form situation
					if ((templateContainerForm) && (destinationContainerForm)) {				
						var pageElem = findContainedObj(itemName, destinationContainerForm);

					// Otherwise, just find the element on the page					
					} else {					
						var pageElem = findObj(itemName);
					}

					// If the page element exists on the page
					if ((pageElem) && (itemValue != '')) {						
						// Determine the page element type to know what value to update
						switch (pageElem.type) {
							// Standard form elements
							case 'text':
							case 'password':
							case 'file':
							case 'hidden':
							case 'submit':
							case 'button':
							case 'reset':
							case 'select-one':
							case 'textarea':
										if (itemValue == '_null_') {
											pageElem.value = '';
										} else {
											pageElem.value = itemValue;												
										}
										break;

							case 'checkbox':
							case 'radio':							
										if (itemValue == pageElem.value) {
											pageElem.checked = true;
										} else {
											pageElem.checked = false;
										}
										break;
										
							//TODO: Create alternate rule for DIVs with specified nid or cid
							case 'span':
							case 'div':
								var classActionName = "action::className(";
								if (itemValue == "action::hide()") {
									pageElem.style.display = "none";	
								} else 
								if (itemValue.indexOf(classActionName) == 0) {
                                                                        var classArgs = itemValue.substring(itemValue.indexOf(classActionName)+ classActionName.length, itemValue.lastIndexOf(")"));
                                                                        pageElem.className=classArgs;
								} else {
									//alert(itemValue);
									if (itemValue == '_null_') {
										pageElem.innerHTML = '';
									} else {
										pageElem.innerHTML = itemValue;											
									}
								}
								break;
							// Assume it's a display object (table, form, div..etc)
							default:
								//alert(pageElem.type);
								var classActionName = "action::className(";
								if (itemValue == "action::hide()") {
									pageElem.style.display = "none";
								} else 
								if (itemValue.indexOf(classActionName) == 0) {
									var classArgs = itemValue.substring(itemValue.indexOf(classActionName)+ classActionName.length, itemValue.lastIndexOf(")"));
									pageElem.className=classArgs;
								} else
								if (itemValue == '_null_') {
									pageElem.innerHTML = '';
								} else {
									pageElem.innerHTML = itemValue;											
								}
								break;
						}
					}					
				}
			}
						
		} else {
			// Invalid XML type -- no nodes found
			alert('\'' + xmlObj.tagName + '\' is an Invalid XML Object -- No Nodes Found!');
		}
	}
}


// Perform the ajax function with the specify values
function performAjax(requestVars, url, templateForm, destinationForm) {	
	// If we're not already performing an XML request, and we have a valid HTTP XML object
	if (!isWorking && http_request) {
		
		var isForm = false;
				
		// generate a random number (1 - 100000) so IE wont cache the results
		var randomnumber = Math.floor(Math.random() * 100001);
		var postString = randomnumber + '=' + randomnumber;

		if (requestVars.length) {
			
			// if the reqest vars has a name/id assume it's a form
			if ((requestVars.id) || (requestVars.name)) { isForm = true; }
			
			// If we have a form obj loop through each element and add it to the post string
			if (isForm) {
				for (i = 0; i < requestVars.length; i ++) {
					// Dont overwrite the action
					if (requestVars[i].name != 'action') {
						
						// If we're dealing with a checkbox or a radio button -- make sure they are checked before passing the value
						if ((requestVars[i].type == 'checkbox') || (requestVars[i].type == 'radio')) {							
							if (requestVars[i].checked == true) {
								postString += "&" + escape(requestVars[i].name) + "=" + escape(requestVars[i].value);								
							}
							
						// Just a normal form element -- pass the value
						} else {
							postString += "&" + escape(requestVars[i].name) + "=" + escape(requestVars[i].value);
						}
					}
				}
				
			// Loop through all the request vars and add it to the post string
			} else {
				for (var i in requestVars) {
					// Dont overwrite the action
					if (requestVars[i].name != 'action') {
						postString += "&" + escape(i) + "=" + escape(requestVars[i]);
					}
				}
			}
		}
	
		// Set the template and destination forms (if they're passed in)
		if (templateForm != '') {
			templateContainerForm = document.getElementById(templateForm);
		}
		
		if (destinationForm != '') {
			destinationContainerForm = document.getElementById(destinationForm);
		}
		
		// Perform the XML GET request
		//alert(postString);
		http_request.open("POST", url, true);
		http_request.onreadystatechange = handleHttpResponse;
		
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", postString.length);
		http_request.setRequestHeader("Connection", "close");
		
		isWorking = true;		
		http_request.send(postString);
	}
}


// Clear all the error labels for a form submission
// Must be be called before onClick="clearFormErrors(this.form); performAjax(....);
function clearFormErrors(containerObj) {
	
	if (containerObj.getElementsByTagName) {
		// Clear all errors that are within a table cell
		var tmpObj = containerObj.getElementsByTagName("td");
		for (var i = 0; i < tmpObj.length; i++) {			
			if (tmpObj[i].id.indexOf('_error') > 0) {
				tmpObj[i].innerHTML = '';
			}
		}
		
		// Clear all errors that are within a div
		var tmpObj = containerObj.getElementsByTagName("div");
		for (var i = 0; i < tmpObj.length; i++) {			
			if (tmpObj[i].id.indexOf('_error') > 0) {
				tmpObj[i].innerHTML = '';
			}
		}
		
		// Clear all errors that are within a span
		var tmpObj = containerObj.getElementsByTagName("span");
		for (var i = 0; i < tmpObj.length; i++) {			
			if (tmpObj[i].id.indexOf('_error') > 0) {
				tmpObj[i].innerHTML = '';
			}
		}		
		
	}			
}


function goodKarmaNode(oDom, nid) {
	performAjax(oDom, "/karma.php?q=karma/good/node/" + nid + "/" + g_solo, '', '');
}

function badKarmaNode(oDom, nid) {
	performAjax(oDom, "/karma.php?q=karma/bad/node/" + nid + "/" + g_solo, '', '');
}

function goodKarmaComment(oDom, cid) {
	performAjax(oDom, "/karma.php?q=karma/good/comment/" + cid + "/" + g_solo, '', '');
}

function badKarmaComment(oDom, cid) {
	performAjax(oDom, "/karma.php?q=karma/bad/comment/" + cid + "/" + g_solo, '', '');
}

function showHideElement(sType, oAnchor, nCommentId, forceState) {
	var sShow = '';
	if (oAnchor.isContentVisible != null && oAnchor.isContentVisible == true) {
		sShow = 'none'; 
		oAnchor.isContentVisible = false;
	} else {
		sShow = '';
		oAnchor.isContentVisible = true;
	}
	if (forceState != null) {
		sShow = forceState;
	}
	document.getElementById(sType + '-content-' + nCommentId).style.display = sShow;
	document.getElementById(sType + '-links-' + nCommentId).style.display = sShow;
	document.getElementById(sType + '-author-' + nCommentId).style.display = sShow;
}