/* --------------------------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
/* ------------------------------------------ COMPONENTE --------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
function JSObj_content_search_adv()
{
	this.posId = 1;
	this.compId = 1;
	this.lngId = 'es'; 

	this.searchId;
	this.session_search_id = '';
	this.cat_var_name = '';
	this.input_tags = ''; //Input que servirá para filtrar resultados por tags
	this.query_tag_var = '_content_tag';//Nombre de variable para pasar la tag por url
	this.filter_action;
	this.att_filter_joiner = 'AND';
	this.att_filters = new Array();	// Filters, nombres de los campos que participan en el filtro */
	this.att_filter_fields = new Array();
	this.att_filter_fields_op = new Array();
	this.att_filter_fields_type = new Array();
	this.att_filter_relation_search = new Array(); // Para cada campo, indicamos si buscar en contenidos relacionados

	this.att_order = new Array();	// Order by , nombres de los campos con que se ordernará */
	this.att_order_type = new Array();	// Order by , tipo de datos */
	this.att_order_dir = new Array();	// Order by , ASC | DESC */

	this.parentIdField = null;		// Identificador del campo que marca el padre que queremos buscar.
	
	//Parta búsquedas por múltiples contenidos
	this.contentTypeIDs = null;		// Identificadores de los tipos de contenido sobre los que queremos buscar.
	
	/*	Recarga de la posición	*/
	this.reload = function () {
		var objReloader = new WbePositionReloader();
		objReloader.posId = this.posId;
		objReloader.reload();
	};
	
	/* Añade una nueva definición de filtro
		Argumentos:
		- códigos de atributos separados por coma.
		- Operador like, eq (equals), bet (between), year_eq, dist
		- Tipo : int, float, decimal, text, date
	 */
	this.addAttFilter = function (sHtmlField, sFilterFields, sFieldsOp, sFieldsType) {
		this.att_filters[this.att_filters.length]  = sHtmlField;
		this.att_filter_fields[this.att_filter_fields.length] = sFilterFields;
		this.att_filter_fields_op[this.att_filter_fields_op.length] = sFieldsOp;
		this.att_filter_fields_type[this.att_filter_fields_type.length] = sFieldsType;
		this.att_filter_relation_search[this.att_filter_relation_search.length] = '0'; // Por defecto solo buscamos en el contenido
	}
	
	/* Añade una nueva definición de filtro
		Argumentos:
		- códigos de atributos separados por coma.
		- Operador like, eq (equals), bet (between), year_eq, dist
		- Tipo : int, float, decimal, text, date
		- joinner --> 'or'
	 */
	this.addAttFilterOr = function(sHtmlField, sHtmlField2, sFilterFields, sFilterFields2, sFieldsOp, sFieldsOp2, sFieldsType, sFieldsType2) {
	    this.att_filters[0] = sHtmlField;
	    this.att_filters[1] = sHtmlField2;
	    this.att_filter_fields[0] = sFilterFields;
	    this.att_filter_fields[1] = sFilterFields2;
	    this.att_filter_fields_op[0] = sFieldsOp;
	    this.att_filter_fields_op[1] = sFieldsOp2;
	    this.att_filter_fields_type[0] = sFieldsType;
	    this.att_filter_fields_type[1] = sFieldsType2;
	    this.att_filter_joiner = 'OR';
	    this.att_filter_relation_search[0] = '0'; // Por defecto solo buscamos en el contenido
	    this.att_filter_relation_search[1] = '0';
	}
	
	/* Sobrecarga para indicar si se busca en contenidos relacionados o no
		0 : Solo en el contenido
		1 : Buscamos en contenidos padres como hijos
		2 : Buscamos en los padres
		3 : Buscamos en los hijos
	*/
	this.addAttFilter = function (sHtmlField, sFilterFields, sFieldsOp, sFieldsType, sRelationSearch) {
		this.att_filters[this.att_filters.length]  = sHtmlField;
		this.att_filter_fields[this.att_filter_fields.length] = sFilterFields;
		this.att_filter_fields_op[this.att_filter_fields_op.length] = sFieldsOp;
		this.att_filter_fields_type[this.att_filter_fields_type.length] = sFieldsType;
		this.att_filter_relation_search[this.att_filter_relation_search.length] = sRelationSearch;
	}

	/* Añade una nueva definición de filtro de ordenación
		Argumentos:
		- atributo para ordenar
		- Tipo : int, float, decimal, text, date
		- ASC | DESC
	 */
	this.addAttOrderByField = function (sHtmlField, sFieldsType, sFieldsDir) {
		this.att_order[this.att_order.length]  = sHtmlField;
		this.att_order_type[this.att_order_type.length] = sFieldsType;
		this.att_order_dir[this.att_order_dir.length] = (sFieldsDir) ? sFieldsDir : "asc";
	}

	/*
	* Devuelve el nombre de un campo de búsqueda.
	*/
	this.getFormFieldValue = function (sFieldName) {
		var oElem = eval('document.forms[0].' + sFieldName);
   		var sValue = '';
   		if (!oElem) return "";
		if (oElem.length) { // n campos con el mismo nombre o un select
			for (var i = 0; i < oElem.length; i++) {
				if (oElem[i].checked) {
					if (sValue != '') sValue += ',';
					sValue += oElem[i].value;
				} else {
					if (oElem[i].selected) {
						if (sValue != '') sValue += ',';
						sValue += oElem[i].value;
					}
				}
			}
		} else {  // un solo campo
			if (oElem.type == "checkbox" || oElem.type == "radio") sValue = (oElem.checked) ? oElem.value : "";
			else if (oElem.tagName == "SELECT") sValue = oElem[oElem.selectedIndex];
			else sValue = oElem.value;
		}
		return sValue;
	}

	/* 
	 * Crea el filtro XML para generar filtro.
	 */
	this.createXmlFilter = function() {
	    var oDivFields, oINPUTField;
	    var i, sV1, sV2, sXML = "";
	    sXML = '<filter joiner="' + this.att_filter_joiner + '">';

	    // Padres asociados
	    var sParents = this.getFormFieldValue(this.parentIdField + "_" + this.posId);
	    if (sParents != null && sParents != '')
	        sXML += "<pids>" + sParents + "</pids>";

	    if (this.contentTypeIDs != null && this.contentTypeIDs != '')
	        sXML += "<ctids>" + this.contentTypeIDs + "</ctids>";

	    for (i = 0; i < this.att_filter_fields.length; i++) {
	        sV1 = this.getFormFieldValue(this.att_filters[i] + '_v1_' + this.posId);
	        sV2 = this.getFormFieldValue(this.att_filters[i] + '_v2_' + this.posId);
	        if (sV1 != '' || sV2 != '') {	// Añade el filtro.
	            sXML += "<sf id='" + this.att_filters[i] + "' op='" + this.att_filter_fields_op[i] + "' type='" + this.att_filter_fields_type[i] + "' relation='" + this.att_filter_relation_search[i] + "'>";
	            sXML += "<fields>" + this.att_filter_fields[i] + "</fields>";
	            if (sV1) sXML += "<v1><![CDATA[" + sV1 + "]]></v1>";
	            if (sV2) sXML += "<v2><![CDATA[" + sV2 + "]]></v2>";
	            sXML += "</sf>";
	        }
	    }

	    // Fecha de la versión
	    if (this.getFormFieldValue('f_ver_date_start_' + this.posId) != '') {
	        sXML += '<ver_date_start>' + this.getFormFieldValue('f_ver_date_start_' + this.posId) + '</ver_date_start>';
	    }
	    if (this.getFormFieldValue('f_ver_date_end_' + this.posId) != '') {
	        sXML += '<ver_date_end>' + this.getFormFieldValue('f_ver_date_end_' + this.posId) + '</ver_date_end>';
	    }

	    sXML += this.createOrderXmlFilter();
	    sXML += "</filter>";
	    return sXML;
	}

	/* 
	 * Crea el filtro XML para ordenar.
	 */
	this.createOrderXmlFilter = function() {
		var oDivFields, oINPUTField;
		var iOrderByIdx, sXML = "";
		
		iOrderByIdx = this.getFormFieldValue('order_by_' + this.posId);
		if (iOrderByIdx==null || iOrderByIdx=='') return '';
		sXML = "<order ";
		sXML += "type='" + this.att_order_type[iOrderByIdx] + "' dir='" + this.att_order_dir[iOrderByIdx] + "'>";
		sXML += this.att_order[iOrderByIdx];
		sXML += "</order>";
		return sXML;
	}

	/*
	* Crea una caja INPUT de tipo hidden para enviar la configuración del buscador 
	*/
	this.createINPUT = function (name, value) {
		var elem = document.createElement("INPUT");
	    elem.type="hidden";
	    elem.value=value;
	    elem.name=name;
	    return elem;
	}

	/*
	* Aplica el filtro y realiza la búsqueda.
	*/
	this.applyAttributeFilter = function () {
	
		var sXml;
		var oDivFields;

		sXml = this.createXmlFilter()
		if (!this.searchId || this.searchId=='') this.searchId = this.posId;
	    oDivFields = document.getElementById("att_filter_form_" + this.posId);
	    oDivFields.innerHTML = '';
	    oDivFields.appendChild(this.createINPUT("session_search_id", this.session_search_id));
	    oDivFields.appendChild(this.createINPUT("new_filter_" + this.searchId, this.posId));
	    oDivFields.appendChild(this.createINPUT("filter_xml_" + this.posId, sXml));

		if (this.filter_action && this.filter_action!='') {
			// Limpiamos los filter_action que acaban con un '&'
			if ( this.filter_action.substring(this.filter_action.length - 1, this.filter_action.length) == "&" ) {
				this.filter_action = this.filter_action.substring(0, this.filter_action.length - 1);
			}
			
			// quitamos este parametro para no ponerlo 2 veces
			if ( this.filter_action.indexOf('session_search_id') > 1 ) { 
				//todo: Detectar si hay mas parametros después del session_search y no cortarlos
				this.filter_action = this.filter_action.substring(0, this.filter_action.indexOf('session_search_id')-1);
			}

			document.forms[0].action = process_submit_url(this.filter_action);
		}

		if (document.forms[0].action.indexOf('?') > 0) document.forms[0].action += '&';	else document.forms[0].action += '?';
		document.forms[0].action += 'session_search_id=' + this.session_search_id;
		
		if (this.cat_var_name != '') {
			var oCatElem = eval('document.forms[0].' + this.cat_var_name + '_' + this.posId);
			if (oCatElem && (oCatElem.value != ''))
				document.forms[0].action += '&' + this.cat_var_name + '=' + oCatElem.value;
		}

		if (this.input_tags != '')
		{
		    var oTagElem = eval('document.forms[0].' + this.input_tags);
		    if (oTagElem && oTagElem.value != '')
		        document.forms[0].action += '&' + this.query_tag_var + '=' + oTagElem[oTagElem.selectedIndex].text + '&_content_type_tag=all';		        
		}

		if (document.getElementById('month_hidden') && document.getElementById('year_hidden')) document.forms[0].action = document.forms[0].action + '&month=' + document.getElementById('month_hidden').value + '&year=' + document.getElementById('year_hidden').value;
		document.forms[0].submit();
	}
	

	/*
	* Aplica el filtro y realiza la búsqueda (concatena el concepto de búsqueda en la URL mediante la variable q)
	*/
	this.applyAttributeFilterQ = function () {
		var sXml;
		var oDivFields;

		sXml = this.createXmlFilter()
		if (!this.searchId || this.searchId=='') this.searchId = this.posId;
	    oDivFields = document.getElementById("att_filter_form_" + this.posId);
	    oDivFields.innerHTML = '';
	    oDivFields.appendChild(this.createINPUT("session_search_id", this.session_search_id));
	    oDivFields.appendChild(this.createINPUT("new_filter_" + this.searchId, this.posId));
	    oDivFields.appendChild(this.createINPUT("filter_xml_" + this.posId, sXml));
		
		if (this.filter_action && this.filter_action!='') {
			// Limpiamos los filter_action que acaban con un '&'
			if ( this.filter_action.substring(this.filter_action.length - 1, this.filter_action.length) == "&" ) {
				this.filter_action = this.filter_action.substring(0, this.filter_action.length - 1);
			}
			
			// quitamos este parametro para no ponerlo 2 veces
			if ( this.filter_action.indexOf('session_search_id') > 1 ) { 
				//todo: Detectar si hay mas parametros después del session_search y no cortarlos
				this.filter_action = this.filter_action.substring(0, this.filter_action.indexOf('session_search_id')-1);
			}


			// quitamos este parametro para no ponerlo 2 veces
			if ( this.filter_action.indexOf('q=') >= 0 ) { 
				//todo: Detectar si hay mas parametros después del session_search y no cortarlos
				this.filter_action = this.filter_action.substring(0, this.filter_action.indexOf('q=')-1);
			}			
						
			if (this.filter_action.indexOf('?') > 0)  this.filter_action += '&q=' + this.getFormFieldValue(this.att_filters[0] + '_v1_' + this.posId).replace(/ /g,'+'); else this.filter_action += '?q=' + this.getFormFieldValue(this.att_filters[0] + '_v1_' + this.posId).replace(/ /g,'+');
				
			document.forms[0].action = this.filter_action;
		}

		
		if (document.forms[0].action.indexOf('?') > 0) document.forms[0].action += '&';	else document.forms[0].action += '?';
		document.forms[0].action += 'session_search_id=' + this.session_search_id;
		
		if (!this.filter_action || this.filter_action==''){
			// quitamos este parametro para no ponerlo 2 veces
			if ( document.forms[0].action.indexOf('q=') >= 0 ) { 
				//todo: Detectar si hay mas parametros después del session_search y no cortarlos
				document.forms[0].action = document.forms[0].action.substring(0, this.filter_action.indexOf('q=')-1);
			}						
			
			if (document.forms[0].action.indexOf('?') >= 0) document.forms[0].action += '&q=' + this.getFormFieldValue(this.att_filters[0] + '_v1_' + this.posId).replace(/ /g,'+'); else document.forms[0].action += '?q=' + this.getFormFieldValue(this.att_filters[0] + '_v1_' + this.posId).replace(/ /g,'+');
		}
		
		if (this.cat_var_name != '') {
			var oCatElem = eval('document.forms[0].' + this.cat_var_name + '_' + this.posId);
			if (oCatElem && (oCatElem.value != ''))
				document.forms[0].action += '&' + this.cat_var_name + '=' + oCatElem.value;
		}
		if (document.getElementById('month_hidden') && document.getElementById('year_hidden')) document.forms[0].action = document.forms[0].action + '&month=' + document.getElementById('month_hidden').value + '&year=' + document.getElementById('year_hidden').value;
		document.forms[0].submit();
	}		
	
	
	
	/*
	* Va a la fecha de calendario.
	*/
	this.calendarGoToDay = function (sFieldValue, sDay) {
		var oField = eval('document.forms[0].' + sFieldValue + '_' + this.posId);
		if (oField) {
			oField.value = sDay;
			this.applyAttributeFilter();
		} else {
			alert('Campo mal configurado. No se puede lanzar la búsqueda');
		}
	}
	
	this.calendarNavMonth = function(iMonth, iYear, iPageId) {
			
		var objReloader = new WbePositionReloader();
		if(iMonth<=0) {
			iMonth=12;iYear--;
		}
		if(iMonth>12) {
			iMonth=1;iYear++;
		}
		objReloader.pageId = iPageId;
		objReloader.Ajax.addPostParameter("goto_month_" + this.posId, iMonth);
		objReloader.Ajax.addPostParameter("goto_year_" + this.posId, iYear);
		objReloader.posId = this.posId;
		objReloader.reload();
	}
	
}


/* --------------------------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
/* ------------------------------------------ EDICIÓN DEL COMPONENTE --------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */

function JSObj_content_search_edit_adv()
{
	this.posId = 1;
	this.compId = 1;
	this.parentPosId = 1;
	this.varName = '';
	this.lngId = 'es';
	this.config_xml_process = 'xml_process';

	// Oculta todos los campos de formulario SELECT por el problema que tiene el IE. (como en el back azul)
	this.hideSelectBoxes = function () {
		for(var i = 0; i < document.forms.length; i++) {
			for(var e = 0; e < document.forms[i].length; e++){
				if(document.forms[i].elements[e].tagName == "SELECT")
					document.forms[i].elements[e].style.visibility="hidden";
			} // for e
		} // for i
	};
	
	// Muestra todos los campos de formulario SELECT por el problema que tiene el IE. (como en el back azul)
	this.displaySelectBoxes = function () {
		for(var i = 0; i < document.forms.length; i++) {
			for(var e = 0; e < document.forms[i].length; e++){
				if(document.forms[i].elements[e].tagName == "SELECT")
					document.forms[i].elements[e].style.visibility="visible";
			} // for e
		} // for i
	};
	
	// Mustra la ruta de la xsl al seleccionar algún proceso
	this.changeProcess = function () {
		var dest_div = document.getElementById('xsl_path_' + this.posId);
		var elem_sel = eval('document.WBForm.config_' + this.config_xml_process + '_' + this.posId);
		var from_div = document.getElementById('xsl_path_' + this.posId + '_' + elem_sel.selectedIndex);
		dest_div.innerHTML = from_div.innerHTML;
	};
	
	this.save = function () {
		var objConfig = new WBEConfigMgr();

		window.parent.objLoading.showWindow();
		this.hideSelectBoxes();
		
		objConfig.posId = this.posId;
		objConfig.compId = this.compId;
		objConfig.cache_delete_prefix = '|wbe/xsl.content_search_adv.' + this.posId + '|';
		
		objConfig.saveConfig();
	
		var objReloader = new WbePositionReloader();
		objReloader.posId = this.parentPosId;
		objReloader.reload();

		window.parent.___wbeADMIN.hidePopUp();
		window.parent.objLoading.hideWindow();
		this.displaySelectBoxes();
	};

};




