﻿
/**
  * FUNCIONES DE AYUDA PARA LOS FORMULARIOS
  * 
*/


// Realiza un post a la página principal del site
// con los parámetros "pdf" con el HTML
// El site debe tener un Global.asax tipo JuniperGlobalAsax
// procesar esta petición.
function printMeAs(key, id) {
    
    var htmlCode;
    if (typeof (id) == 'undefined') {
        htmlCode = document.getElementsByTagName('html')[0].innerHTML
    } else {
        htmlCode = find_innerHTML(document.getElementById(id).parentNode)
    }
     
    htmlCode = escape(htmlCode)
    // Creamos un formulario para hacer el form
    createFormAndSubmit("/default.aspx", key, htmlCode) 
}
//helper function to create the form
function getNewSubmitForm() {
    var submitForm = document.createElement("FORM");
    document.body.appendChild(submitForm);
    submitForm.method = "POST";
    return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue) {
    // var newElement = document.createElement("<input name='" + elementName + "' type='hidden'>");
    var newElement = document.createElement('input');
    newElement.setAttribute('type', 'hidden');
    newElement.setAttribute('name', elementName);
    newElement.setAttribute('value', elementValue);
    inputForm.appendChild(newElement);
    return inputForm;
}

//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(url, key, value) {
    var submitForm = getNewSubmitForm();
    createNewFormElement(submitForm, key, value);
    submitForm.action = url;
    submitForm.submit();
}

// Busca el primer nodo que contenga la propiedad innerHTML
function find_innerHTML(obj) {
    while (obj.innerHTML == undefined) {
        obj = obj.parentNode;
    }
    return obj.innerHTML;
}

// Carga una url en el elemento que se le pasa via id
// Parámetros:
// id:  Id del elemento que contendrá el html resultante
// url: Página a cargar, ojo con cross-domain!
function loadHTMLUrlIn(id, url) {
    $("#" + id).load(url);
}

// Comprueba si se ha llegado el scroll al final
// si llega, llama a la función callback
function chkDivScrollBottom(id, eventCall) {
    // Nos enganchamos al evento scroll!
    $("#" + id).scroll(function() {
        var elem = $("#" + id);
        var inner = $("#" + id + " > .inner");
        if ((elem[0].scrollHeight > elem.outerHeight()) && // Comprobamos que haya scroll!
            (elem[0].scrollHeight - elem.scrollTop() < elem.outerHeight())) {
            if (eventCall)
                eventCall();
        }
    })
}


/*  Gestión de listas de elementos con capacidad para
    añadir nuevos, editar seleccionado y eliminar seleccionado
    La función se engancha a los enventos on click de los id de botones
    indicados como idAdd, idDel, idEdit y realiza las siguintes funciones
    on click idAdd:         Añade el contenido de idControlValue a la lista
    on click idDel:         Quita de la lista el elemento seleccionado
    on click idEdit:        Llama a la función onEditCallBack con el índice del elemento seleccionado
    PARAMETROS              
        idControlValue      : Id del control que genera el evento click que contiene los datos a añadir
		idList              : Id del control que muestra la lista (tipo lista o dropdown)
        idAdd               : Id del control que genera el evento click para añadir
        idDel               : Id del control que genera el evento click para eliminar
		' opcionales !
		idEdit              : Id del control que genera el evento click para editar
        onEditCallback      : Función a llamar cuando se edita un valor, se pasa el nuevo valor y debe devolver true para confirmar
		onDelCallBack		: Función a llamar antes de eliminar, devuelve true si se debe eliminar
		
		' Si no se pasa valor, poner null

*/
function manageItemList(idControlValue, idList, idAdd, idDel, idEdit, onEditCallback, onDelCallBack) {

	var oThis = this
	// PROTECTED 
	this.checkSelecteds = function(){
		if($("#"+idList + " :selected").length){
			 $("#" + idDel).css("display", "block");
			 if(idEdit != null)
				 $("#" + idEdit).css("display", "block");
			 // Mostramos el seleccionado
			 $("#" + idControlValue).val($($("#"+idList + " :selected")[0]).text());
		}else{
			 $("#" + idDel).css("display", "none");
			 if(idEdit != null)
				 $("#" + idEdit).css("display", "none");
		}
	}
	

	this.setValue = function(value){
		$("#" + idControlValue).val(value)
	}
	this.clearValue = function(){
		$("#" + idControlValue).val('')
	}

	this.getValue = function(){
		return  $("#" + idControlValue).val()
	}

    // Nos enganchamos al click add
    $("#" + idAdd).click(function() {
        // Obtenemos el valor y lo insertamos
        var value = oThis.getValue();
		if(value != ""){
			// Quitamos los seleccionados
			$("#"+idList + " :selected").each(function(){ $(this).attr("selected", false)});
			$("#"+idList).append($("<option></option>").val("0").html(value));
			oThis.clearValue();
		}
		oThis.checkSelecteds();
		return false;
    });
	
    // Nos enganchamos al click Del
    $("#" + idDel).click(function() {
		if(typeof(onDelCallBack) == 'undefined' 
				|| onDelCallBack() == false){
			// Eliminamos
			$("#"+idList + " :selected").remove()
			oThis.clearValue();
		}
		oThis.checkSelecteds();
		return false;
    });
	
    if (idEdit != null) {
        // Nos enganchamos al click Edit
        $("#" + idEdit).click(function() {
       		var value = oThis.getValue();
			if(onEditCallback == null || onEditCallback(value)){
				// Obtenemos el valor y lo insertamos
				if(value == "") return
				// Pedimos confirmación al usuario
				$("#"+idList + " :selected").text(value);
				oThis.clearValue();
				$("#"+idList + " :selected").each(function(){ this.selected = false;});
				
			}
			return false;
        });
    }
	
	// Cambio de selección en la lista
	$("#"+idList).change(function(){
		oThis.checkSelecteds();
	});
	
	// Deshabilitamos los edit y cancel hasta que selecciones
	 oThis.checkSelecteds();
}