/**
 * Encargado de empezar a procesar el xml recibido.
 * @param object el xml recibido
 * @param object el elemento en donde será cargado el xml procesado
**/

function processGenericModalXml(xml) {
	var section = AJAX_PANEL.getActive();
	processModalXml(xml,section);
}

function processModalXml(xml,element) {
	var result = false;
	if (element == null && AJAX_PANEL.hasActive()) element = AJAX_PANEL.getActive();
	if (xml != null && xml.getElementsByTagName("load").length != 0) {
		var toLoad		= xml.getElementsByTagName("load").item(0);
		var toLoadType	= toLoad.getAttribute("type");
		var canClose	= toBoolean(toLoad.getAttribute("canClose"));
		
		if (LOAD_TEXT == toLoadType) {
			AJAX_PANEL.showingLoading = false;
			processModalXmlText(xml,element,canClose);
			result = true;
		
		} else if (LOAD_FORM == toLoadType) {
			AJAX_PANEL.showingLoading = false;
			processModalXmlForm(xml,element,canClose);
			result = true;
		
		} else if (LOAD_FUNCTION == toLoadType) {
			AJAX_PANEL.showingLoading = false;
			processModalXmlFunction(xml,element,canClose);
			result = true;
		}
	}
	
	if (xml != null && xml.getElementsByTagName("actions").length != 0) {
		result = processXmlActions(xml.getElementsByTagName("actions").item(0));
	}
	
	if (result == true) {
		AJAX_PANEL.refresh();
		return result;
	}
	
	alert("Ops! Nothing to load from the response asdasdas");
	AJAX_PANEL.closeAll();
	return false;
}

var lastFunctionAjaxCall = null;
function processModalXmlFunction(xml,element,canClose) {
	var toLoad				= xml.getElementsByTagName("load").item(0);
	lastFunctionAjaxCall	= toLoad.getElementsByTagName("function").item(0);
	
	var functionName = lastFunctionAjaxCall.getAttribute("name");
	
	window.setTimeout(functionName + "()",10);
	return true;
}

/** Encargado de procesar una tabla y sus elementos. Crea una tabla en función
 * de la información recibida.<b>
 * @param object xml de la tabla
**/
function processModalXmlFormTable(xmlTable) {
	var html = "";

	if (xmlTable != null && xmlTable.length > 0) {
		var aTable	= xmlTable.item(0);
		var rows	= aTable.getElementsByTagName("row");
		
		html += "<table width=\"100%\" " + processXmlTagAttributes(aTable) + ">";

		for (var i = 0; rows != null && i < rows.length; i++) {
			var row		= rows.item(i);
			var cells	= row.getElementsByTagName("cell");
			
			html += "<tr " + processXmlTagAttributes(row) + ">";
			
			for (var j = 0; cells != null && j < cells.length; j++) {
				var cell	= cells.item(j);
				var value	= (cell.childNodes.length > 0)?cell.firstChild.nodeValue:"";
				
				html += "<td " + processXmlTagAttributes(cell) + ">" + value + "</td>";
			}
			
			html += "</tr>";
		}
		
		html += "</table>";
	}

	return html;
}

/**
 * Encargado de procesar los elementos recibidos en el xml. Crea
 * el código HTML para cada uno de los elementos recibidos.
 * @param object xml de los elementos
**/
function processModalXmlFormElements(xmlElements) {
	var html = "";

	if (xmlElements != null && xmlElements.length > 0) {
		var elements = xmlElements.item(0).getElementsByTagName("element");
	
		html += "<table>";
		htmlHidden = "";
	
		for (var i = 0; elements != null && i < elements.length; i++) {
			var element = elements.item(i);
			if (element != null) {
				var type		= element.getAttribute("type");
				var name		= element.getAttribute("name");
				var text		= element.getAttribute("text");
				var title		= element.getAttribute("title");
				var value		= element.getAttribute("value");
				var isHtml		= element.getAttribute("html");
				var selected	= element.getAttribute("selected");
	
				if (title == null) title = "";
				if (title != "") title = " title=\"" + title + "\" ";
				
				var htmlOptions = "";
				if (type == "select" || type == "radio" || type == "list") {
					htmlOptions = processModalXmlFormElementOptions(element.getElementsByTagName("options").item(0),value,type,name);
				} else if (type == "selectMultiple") {
					type = "selectMultiple";
					htmlOptions = processModalXmlFormElementOptionsValues(element.getElementsByTagName("options").item(0),element.getElementsByTagName("values").item(0),type,name);
				}

				if (isHtml == "false") value = value.replace("<","&lt;").replace(">","&gt;");
	
				if (type == "select") {
					html += "<tr><td class=\"text\"" + title + ">" + text + ":</td><td class=\"content\"><select name=\"" + name + "\">" + htmlOptions + "</select></td></tr>";
				
				} else if (type == "selectMultiple") {
					html += "<tr><td class=\"text\"" + title + ">" + text + ":</td><td class=\"content\"><select name=\"" + name + "\" multiple size=\"5\">" + htmlOptions + "</select></td></tr>";
				
				} else if (type == "textarea") {
					html += "<tr><td class=\"text\"" + title + ">" + text + ":</td><td class=\"content\"><textarea name=\"" + name + "\" rows=\"5\" cols=\"80\">" + value + "</textarea></td></tr>";
				
				} else if (type == "fixed") {
					html += "<tr><td class=\"text\"" + title + ">" + text + ":</td><td class=\"content\">" + value + "</td></tr>";
				
				} else if (type == "2column") {
					html += "<tr><td colspan=\"2\">" + value + "</td></tr>";
				
				} else if (type == "checkbox") {
					if (toBoolean(selected)) { 
						selected = "checked";
					} else {
						selected = "";
					}
					html += "<tr><td colspan=\"2\"" + title + "><input type=\"checkbox\" class=\"default\" value=\"" + value + "\" " + selected + " name=\"" + name + "\">" + text + "</td></tr>";
				
				} else if (type == "2columnTitle") {
					html += "<tr><td colspan=\"2\"" + title + "><b>" + text + "</b></td></tr>";
				
				} else if (type == "radio") {
					if (text == "") {
						html += "<tr><td colspan=\"2\"" + title + ">" + htmlOptions + "</td></tr>";
					} else {
						html += "<tr><td class=\"text\"" + title + ">" + text + ":</td><td class=\"content\">" + htmlOptions + "</td></tr>";
					}
				
				} else if (type == "list") {
					html += "<tr><td class=\"text\">" + text + ":</td><td class=\"content\">" + htmlOptions + "</td></tr>";
				
				} else if (type == "hidden") {
					htmlHidden += "<input type=\"" + type + "\"  class=\"default\" name=\"" + name + "\" value=\"" + value + "\">";
				
				} else if (type == "image") {
					html += "<tr><td colspan=\"2\"><img onload=\"AJAX_PANEL.refresh();\" src=\"" + value + "\" alt=\"" + text + "\" name=\"" + name + "\" id=\"" + name + "\"></td></tr>";
				
				} else if (type == "flash") {
					html += "<tr><td colspan=\"2\"><object width=550 height=300 modalFlash=true><param name=\"movie\" value=\"" + value + "\"><embed width=550 height=300 src=\"" + value + "\"></embed></object></td></tr>";
				
				} else if (type == "flashVideo") {
					value = value + ".flv";
					
					var htmlVar = "";
					htmlVar += "file=" + SITE_CONTEXT + "/" + value;
					htmlVar += "&autostart=true";
					htmlVar += "&controlbar=over";
					htmlVar += "&fullscreen=true";
					htmlVar += "&stretching=fill";
					
					html += "<tr><td colspan=\"2\" align=\"cener\">";
					html += "<object modalFlash=true classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" ";
					html += "	codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\""; 
					html += "	width=\"500\" ";
					html += "	height=\"380\" ";
					html += "	id=\"player\" ";
					html += "	align=\"middle\">";
					html += "	<param name=\"allowFullScreen\" value=\"true\" />";
					html += "	<param name=\"flashvars\" value=\"" + htmlVar + "\" />";
					html += "	<param name=\"swliveconnect\" value=\"true\">";
					html += "	<param name=\"movie\" value=\"" + SITE_CONTEXT + "/pages/player/player.swf" + "\" />";
					html += "	<param name=\"quality\" value=\"high\" />";
					html += "	<param name=\"bgcolor\" value=\"#000000\" />";
					html += "	<embed ";
					html += "		src=\"" + SITE_CONTEXT + "/pages/player/player.swf" + "\""; 
					html += "		quality=\"high\" ";
					html += "		swliveconnect=\"true\""; 
					html += "		bgcolor=\"#000000\" ";
					html += "		width=\"500\" ";
					html += "		height=\"380\" ";
					html += "		name=\"player\" ";
					html += "		align=\"middle\" ";
					html += "		allowFullScreen=\"true\""; 
					html += "		type=\"application/x-shockwave-flash\""; 
					html += "		pluginspage=\"http://www.macromedia.com/go/getflashplayer\""; 
					html += "		flashvars=\"" + htmlVar + "\" />";
					html += "</object>";
					html += "</td></tr>";
				
				} else if (type == "empty") {
					html += "<tr><td colspan=\"2\">&nbsp;</td></tr>";
				
				} else {
					if (text != null && text != "") text += ":";
					html += "<tr><td class=\"text\"" + title + ">" + text + "</td><td class=\"content\"><input type=\"" + type + "\" name=\"" + name + "\" value=\"" + value + "\"></td></tr>";
				}
			}
		}
		
		if (htmlHidden != "") {
			html += "<tr><td colspan=\"2\">" + htmlHidden + "</td></tr>";
		}
		
		html += "</table>";
	}

	return html;
}

/**
 * Encargado de procesar los options de un element SELECT recibidos en el xml. Crea
 * el código HTML para cada uno de los options recibidos.
 * @param object xml de los options de un element
 * @param string valor seleccionado en el select
 * @param string tipo de elemento para el cual son las opciones
 * @param string nombre del elemento si es necesario (solo para radio buttons)
**/
function processModalXmlFormElementOptions(xmlOptions,selectedValue,type,name) {
	var html = "";
	
	if (xmlOptions == null) return html;
	var options = xmlOptions.getElementsByTagName("option");

	for (var i = 0; i < options.length; i++) {
		var option = options.item(i);
		if (option != null) {
			var value		= option.getAttribute("value");
			var text		= (option.firstChild != null)?option.firstChild.nodeValue:"";
			var selected	= (value == selectedValue)?((type == "radio")?"checked":"selected"):"";

			if (type == "radio") {
				html += "<input type=\"radio\" class=\"default\" name=\"" + name + "\" value=\"" + value + "\" " + selected + ">" + text + "</option>";
				html += "<br>";
			
			} else if (type == "list") {
				html += text;
				html += "<br>";
			
			} else {
				html += "<option value=\"" + value + "\" " + selected + ">" + text + "</option>";
			}
		}
	}
	return html;
}
/**
 * Encargado de procesar los options y values de un element SELECT MULTIPLE recibidos en el 
 * xml. Crea el código HTML para cada uno de los options recibidos.
 * @param object xml de los options de un element
 * @param object xml de los valores seleccionado en el select
 * @param string tipo de elemento para el cual son las opciones
 * @param string nombre del elemento si es necesario (solo para radio buttons)
 **/
function processModalXmlFormElementOptionsValues(xmlOptions,xmlSelectedValues,type,name) {
	var options = xmlOptions.getElementsByTagName("option");
	var values = (xmlSelectedValues != null) ? xmlSelectedValues.getElementsByTagName("text") : null;
	var html = "";

	var theValues = new Array();
	
	if (values != null) {
			for (var i = 0; i < values.length; i++) {
			var value = values.item(i);
			if (value != null) {
				theValues[theValues.length] = (value.firstChild != null) ? value.firstChild.nodeValue : "";
			}
		}
	}
	
	for (var i = 0; i < options.length; i++) {
		var option = options.item(i);
		if (option != null) {
			var value		= option.getAttribute("value");
			var text		= (option.firstChild != null)?option.firstChild.nodeValue:"";
			var selected	= (isInArray(theValues,value)) ? "selected" : "";
			
			html += "<option value=\"" + value + "\" " + selected + ">" + text + "</option>";
		}
	}
	return html;
}

function processModalXmlFormButtons(xmlButtons,element) {
	var html = "";

	if (xmlButtons != null && xmlButtons.length > 0) {
		var buttons = xmlButtons.item(0).getElementsByTagName("button");
	
		for(var i = 0; i < buttons.length; i++) {
			var button = buttons.item(i);
			if (button != null) {
				var value	= button.getAttribute("text");
				var onclick	= button.getAttribute("onclick");
				var type	= button.getAttribute("type");
				
				if (onclick == "hiddeElement") {
					onclick = "AJAX_PANEL.hiddeActive()";
				}
				
				if (type == "showAjax") {
					type	= "button";
					onclick	= "AJAX_PANEL.newPanel(); doModalAjax('" + onclick + "',event);";
				} else if (type == "url") {
					type = "button";
					onclick = "AJAX_PANEL.showLoading(); doLink('" + onclick + "');";
				}
				
				html += "<input type=\"" + type + "\" value=\"" + value + "\" onClick=\"" + onclick + "\">";
			}
		}
	}
	
	return html;
}

function processModalXmlText(xml,element,canClose) {
	var toLoad		= xml.getElementsByTagName("load").item(0);
	var theText		= toLoad.getElementsByTagName("text").item(0);
	var closeAll	= theText.getAttribute("closeAll");
	
	var html = theText.firstChild.nodeValue;
	
	var formClose = canClose? ("<div class=\"ajaxResultFooter\">" + generateModalCloseAjax(false,true,closeAll) + "</div>") : "";

	if (element == null && html != null && html.length > 0) element = AJAX_PANEL.getActive();
	if (element != null) element.innerHTML = "<div class=\"ajaxResultContent\">" + html + "</div>" + formClose;
}

/**
 * Encargado de procesar el xml y generar un formulario con la distinta información recibida.
 * @param object el xml recibido
 * @param object el elemento en donde será cargado el xml procesado
**/
function processModalXmlForm(xml,element,canClose) {
	var toLoad = xml.getElementsByTagName("load").item(0);
	var theForm = toLoad.getElementsByTagName("form").item(0);
	
	var formAction			= theForm.getAttribute("action");
	var multiPartForm		= toBoolean(theForm.getAttribute("multiPart"));
	var formAjaxSumbit		= theForm.getAttribute("ajaxsubmit");
	var formAjaxNewPanel	= toBoolean(theForm.getAttribute("ajaxNewPanel"));
	var formTitle 			= theForm.getAttribute("title");
	var formAutoExpand 		= theForm.getAttribute("autoExpand");
	var closeAll 			= theForm.getAttribute("closeAll");
	var formMethod 			= "post";
	
	var showErrors = toBoolean(theForm.getAttribute("showErrors"));
	
	var formClose = canClose?generateModalCloseAjax(false,true,closeAll):"";

	if (formAjaxSumbit == "true") {
		formAjaxSumbit = "onsubmit=\"return doAjaxSubmit(this," + formAjaxNewPanel + ");\"";
//	} else {
//		formAjaxSumbit = "onsubmit=\"return validateForm(this);\"";
	}
	
	if (formTitle == null) {
		formTitle = "";
	} else if (formTitle != "") {
		formTitle = "<div class=\"ajaxResultTitle\">" + formTitle + "</div>";
	}
	
	var formStart = "";
	var formEnd = "";
	
	if (formAction != null && formAction != "") {
		var htmlMultipart = "";
		if (multiPartForm) {
			htmlMultipart = " enctype=\"multipart/form-data\" target=\"iframeUpload\"";
		}
		
		formStart = "<form action=\"" + formAction + "\" method=\"" + formMethod + "\" " + formAjaxSumbit + htmlMultipart + ">";
		formEnd = "</form>";
		
		if (multiPartForm) {
			formStart = "<iframe name=\"iframeUpload\" id=\"iframeUpload\" style=\"display:none;\"></iframe>" + formStart;
		}
	}
	
	var formElements	= processModalXmlFormElements(theForm.getElementsByTagName("elements"));
	var formTable		= processModalXmlFormTable(theForm.getElementsByTagName("table"));
	var formButtons		= processModalXmlFormButtons(theForm.getElementsByTagName("buttons"),element);
	
	var formFooter = "<div class=\"ajaxResultFooter\">" + formClose + formButtons + "</div>";
	
	var htmlForm = formStart + formTitle + "<div id=\"ajaxResultContent\" class=\"ajaxResultContent\">" + formTable + formElements + "</div>" + formFooter + formEnd;

	if (element == null) element = AJAX_PANEL.newPanel();
	
	element.innerHTML = htmlForm;
	
	var ajaxResultContent = getElementById("ajaxResultContent");

	if (ajaxResultContent != null) {
		if (document.all && typeof document.body.style.maxHeight == "undefined") {
			var height = ajaxResultContent.offsetHeight;
			ajaxResultContent.style.height = "100%";
			if (ajaxResultContent.offsetHeight > height) {
				ajaxResultContent.style.height = height + "px";
			}
		} else { 
			ajaxResultContent.style.height = "100%";
		}
	}
	
	AJAX_PANEL.refresh(toBoolean(formAutoExpand));
	if (showErrors) showAjaxErrors();
}

/**
 * Process the xml actions and creates the corresponding timeout functions to be executed. Call 
 * cancelAjaxHidde to cancel all the timeout functions.
 */
function processXmlActions(xmlActions) {
	var actions = xmlActions.getElementsByTagName("action");
	var result = false;
	
	for (var i = 0; i < actions.length; i++) {
		var action = actions.item(i);
		result = true;
		
		if (action != null) {
			var toDo = action.getAttribute("toDo");
			
			if (toDo == "ajaxTimed") {
				var paramTime	= action.getElementsByTagName("param").item(0).firstChild.nodeValue;
				var paramUrl	= action.getElementsByTagName("param").item(1).firstChild.nodeValue;
				
				ajaxTimeout1 = setTimeout("doModalAjaxTimed('" + paramUrl + "')",paramTime);
			} else if (toDo == "linkTimed") {
				var paramTime	= action.getElementsByTagName("param").item(0).firstChild.nodeValue;
				var paramUrl	= action.getElementsByTagName("param").item(1).firstChild.nodeValue;

				ajaxTimeout1	= setTimeout("doLink('" + paramUrl + "')",paramTime);
				
			} else if (toDo == "ajaxHidde") {
				var paramTime	= action.getElementsByTagName("param").item(0).firstChild.nodeValue;
				ajaxTimeout2	= setTimeout("AJAX_PANEL.closeActive()",paramTime);
				
			} else if (toDo == "ajaxHiddeAll") {
				var paramTime	= action.getElementsByTagName("param").item(0).firstChild.nodeValue;
				ajaxTimeout2	= setTimeout("AJAX_PANEL.closeAll()",paramTime);
			}
		}
	}
	
	return result;
}