// Cantidad de 'unidades de latitud/longitud' que se permiten alejadas de las coordenadas del destino para que se considere correcta
var jscte_LatDelta = 1;
var jscte_LongDelta = 1;

//-------------------------------
// Preview Image
//-------------------------------
function jsPreviewImage(id)
{
    var varImagen = $('txtImagen'+id)
    var imgImagen = $('previewImagen'+id)
    imgImagen.src = varImagen.value;
    imgImagen.style.display = 'block';
}
//-------------------------------
//-------------------------------
// Insert Form
//-------------------------------
//function jsSubmitInsertForm(pstrType)
function jsSubmitFormNew(idBtn, idForm, pstrType)
{
    //tinyMCE.triggerSave();
    
    oForm = document.forms[idForm];
    oBtn = document.getElementsByName(idBtn);  
    oStrType = pstrType;     
    
    DownForm();

    var oElem = Form.findFirstElement(oForm);
    //--- Verifica si está habilitado el formulario
    if (oElem==undefined)
    {
        ClearForm();
        jsGbl_MsgBox("Ya se ha realizado el alta de la Sugerencia","Mensaje",jscteGbl_Icon_Exclamation);
        return;
    }
    //
    //--- Valida el Formulario
    if (!jsValidateInsertForm(pstrType))
    {
        ClearForm();
        return;
    }
    //
    //--- Setea el tipo de Usuario que ingreso
    document.getElementById("hidUserType").value = pstrType;
    //--- Envia a procesar el Alta
    var hidWorkType = document.getElementById("hidWorkType");
    if (hidWorkType==undefined || hidWorkType.value!='IFRAME')
    {
        new Ajax.Request(oForm.action, { onSuccess : jsHandleInsertResponse,
                                         onFailure : jsGbl_AJAX_HandleError,
                                         parameters : Form.serialize(oForm)
                                       });
    }
    else
    {
        var ifrmResponse = $('ifrmResponse')
        jsGbl_addEvent(ifrmResponse,'load',jsSubmitInsertForm_OnLoadCallback);
        
                            
        //--- Envía el Formulario
        oForm.target = 'ifrmResponse';
        oForm.submit();
    }
    if (document.getElementById("processOk"))
    {
        document.getElementById("processOk").value = '1';
    } 
}
function jsSubmitInsertForm_OnLoadCallback()
{
    var ifrmResponse = $('ifrmResponse')
    jsGbl_removeEvent(ifrmResponse,'load',jsSubmitInsertForm_OnLoadCallback);
    //

    //var wstrContent = ifrmResponse.contentWindow.document.body.innerText;
    //MLM (10/12/2007)
    var wstrContent;
    if (navigator.appName == "Microsoft Internet Explorer")
	wstrContent = ifrmResponse.contentWindow.document.body.innerText;
    else
	wstrContent = ifrmResponse.contentDocument.body.textContent;
    //----------------
	 wstrContent = wstrContent.replace(/-/g,"");
    wstrContent = wstrContent.replace(/^ /, "");
    wstrContent = wstrContent.replace(/^ /, "");
    var wResponse = jsGbl_Text2Response(wstrContent);
    jsHandleInsertResponse(wResponse);
}
function jsHandleInsertResponse(pobjResponse)
{
    //function ShowModal(divID) {
    var divID = 'iframemodal';
    var thanksID = 'fThanks';
    var responseText = 'hidResponseText';
    document.getElementById(divID).style.top = document.body.scrollTop;
    document.getElementById(responseText).value = jsGetResponseText(pobjResponse.responseXML);
    if (document.getElementById(responseText).value != "")
    {	      
         document.getElementById(divID).style.display = "block";
	      if (document.getElementById(responseText).value != "ANTIFLOOD")
	      {
	         document.getElementById(thanksID).src = "/gracias2.html?sugerencias";
	      }
	      else
	         document.getElementById(thanksID).src = "/Captcha.html";
    }	
    else
    {
         ClearForm();
         ClosePopUp();
	      jsGbl_AJAX_HandleResponseForOneSubmit(pobjResponse,true,oForm.id)
    }
        scroll(0,0); 
    //if (jsGbl_AJAX_ExecuteOK)
    //{
        //--- Deshabilita el Editor
        //tinyMCE.execCommand('mceRemoveControl', true, 'txtTexto');
//        var varTexto = $('txtTexto')
//        var lblTexto = $('lblTexto')
//        //--- Muestra el contenido como HTML
//        lblTexto.innerHTML = varTexto.value;

    //}
}

function jsValidateSugerencias(cantSugerencias, varMsgs)
{
           
    for( var i = 1; i <= cantSugerencias; i++)
    {
        var varTitulo = $('txtTitulo' + i);
        var varTexto = $('txtTexto' + i);
        var varMapContent = $('mapContent' + i);
        var varLat = $('txtLat' + i);
        var varLong = $('txtLong' + i);
        var varCategSugerencia = $('hidCategoriaId' + i);
        var varDestLat = $('hidDestLat');
        var varDestLong = $('hidDestLong');
        var cantFotos = $('hidCountdivSugerencia' + i + 'Foto').value;
    //    varTexto.value = varTexto.value.unescapeHTML().stripScripts().escapeHTML();
        
        
        if (jsGbl_IsEmpty(varCategSugerencia.value))
            varMsgs.AddMsg("Categoría de la sugerencia " + i );
        if (jsGbl_IsEmpty(varTitulo.value))
            varMsgs.AddMsg("Título de la Sugerencia " + i );
        if (jsGbl_IsEmpty(varTexto.value))
            varMsgs.AddMsg("Texto de la Sugerencia " + i);
                       
        if (!varMapContent.disabled)
        {
            if (jsGbl_IsEmpty(varLat.value))
                varMsgs.AddMsg("Latitud.");
            else
            {
                if ((varDestLat.value*1 + jscte_LatDelta*1 < varLat.value*1) || (varDestLat.value*1 - jscte_LatDelta*1 > varLat.value*1))
                    varMsgs.AddMsg("La latitud de la sugerencia " + i + " es incorrecta para el destino seleccionado");
            }
                
            if (jsGbl_IsEmpty(varLong.value))
                varMsgs.AddMsg("Longitud.");
            else
            {
                if ((varDestLong.value*1 + jscte_LongDelta*1 < varLong.value*1) || (varDestLong.value*1 - jscte_LongDelta*1 > varLong.value*1))
                    varMsgs.AddMsg("La longitud de la sugerencia " + i + " es incorrecta para el destino seleccionado.");
            }
        }
        
        for (var j=1 ; j<=cantFotos ; j++)
        {   
            var varTituloImagen = $('txtTituloImagen' + i + '_' + j);
            var varImagen = $('txtImagen' + i + '_' + j);
            
            if (jsGbl_IsEmpty(varImagen.value) && !jsGbl_IsEmpty(varTituloImagen.value))
                varMsgs.AddMsg("Ruta de la foto " + j + " de la sugerencia " + i );
            
            if (!jsGbl_IsEmpty(varImagen.value) && jsGbl_IsEmpty(varTituloImagen.value))
                varMsgs.AddMsg("Título de la foto " + j + " de la sugerencia " + i );
        }
    }
    
    return varMsgs;
}


function jsValidateInsertForm(pstrType)
{
    var varMsgs = new jsGbl_MsgSummary();
    varMsgs.AddMsgTitle("Por favor, ingrese el/los siguiente/s datos:")
    var cantSugerencias = document.getElementById('hidCountSugerencias').value;
    var validarSugerencias = $('hidValidarSugerencias');

    if (validarSugerencias == null || validarSugerencias.value == 'true')
        varMsgs = jsValidateSugerencias(cantSugerencias,varMsgs);
        
    jsGbl_ValidateUserInfo(pstrType,varMsgs);
    if (!varMsgs.IsEmpty())
    {
        varMsgs.ShowSummary();
        return false;
    }
        
    return true;
}
//-------------------------------



//-------------------------------
// Ranking Form
//-------------------------------
function jsSubmitRankingForm(pstrType)
{
    var oForm = document.forms['frmMain'];
    var oElem = Form.findFirstElement(oForm);
    //--- Verifica si está habilitado el formulario
    if (oElem==undefined)
    {
        jsGbl_MsgBox("Ya se ha calificado la Sugerencia","Mensaje",jscteGbl_Icon_Exclamation);
        return;
    }
    //
    //--- Valida el Formulario
    if (!jsValidateRankingForm())
        return;
    //
    //--- Envia a procesar el Ranking
    new Ajax.Request(oForm.action, { onSuccess : jsHandleRankingResponse,
                                     onFailure : jsGbl_AJAX_HandleError,
                                     parameters : Form.serialize(oForm)
                                   });
                                   
    if (document.getElementById("processOk"))
    {
        document.getElementById("processOk").value = '1';
    }                                    
}
function jsHandleRankingResponse(pobjResponse)
{
    jsGbl_AJAX_HandleResponseForOneSubmit(pobjResponse,true,'frmMain');
}
function jsValidateRankingForm(pstrType)
{
    var varMsgs = new jsGbl_MsgSummary();

	var wValue = null;
	var oCol = document.getElementsByName("optCalificacion");
	var wCount = oCol.length;
    for (var i = 0; i < wCount; i++)
	{
		if (oCol[i].checked)
			wValue = oCol[i].value;
	}

    if (jsGbl_IsEmpty(wValue))
        varMsgs.AddMsg("Calificación sobre la Sugerencia.");
        
    if (!varMsgs.IsEmpty())
    {
        varMsgs.ShowSummary();
        return false;
    }
        
    return true;
}
//-------------------------------
function jsSubmitForm()
{
    var oForm = document.forms['frmComentariosUsuarios'];

    
    new Ajax.Request(oForm.action, { onSuccess : jsHandleCategIdealResponse,
                                     onLoading : $('divComentariosUsuariosContent').innerHTML = jscteGbl_Images_AjaxLoaderImgTag,
                                     onFailure : jsGbl_AJAX_HandleError,
                                     parameters : Form.serialize(oForm)
                                   });
}

function jsChangeCategoriaSugerencia()
{
    jsLoadComentariosUsuarios();
}
//-----------------------------------
// Comentarios Usuarios
//-----------------------------------
function jsLoadComentariosUsuarios()
{
    //jsCloseCalifPanel('divCalifDestinoIdeales');
    
    var oForm = document.forms['frmComentariosUsuarios'];
    var selCategSugerencia = oForm['selCategSugerencia'];
    var hidCategSugerenciaId = oForm['hidCategSugerenciaId'];
    var hidCategSugerenciaNombre = oForm['hidCategSugerenciaNombre'];
//    var hrefRankingIdeales = $('hrefRankingIdeales');

    var sValues = selCategSugerencia.value.split("|");
    hidCategSugerenciaId.value = sValues[0];
    hidCategSugerenciaNombre.value = selCategSugerencia.options[selCategSugerencia.selectedIndex].text;
//    if (hrefRankingIdeales!=null)
//    {
//        hrefRankingIdeales.href = "ranking-destinos-ideales-"+sValues[1]+".html";
//    }
    new Ajax.Request(oForm.action, { onSuccess : jsHandleCategIdealResponse,
                                     onFailure : jsGbl_AJAX_HandleError,
                                     parameters : Form.serialize(oForm)
                                   });
}

function jsHandleCategIdealResponse(pobjResponse)
{
    jsGbl_AJAX_HandleResponse(pobjResponse,false);
    
    if (jsGbl_AJAX_ExecuteOK)
    {
        var divComentariosUsuariosContent = $('divComentariosUsuariosContent')
        //--- Muestra el contenido como HTML
        divComentariosUsuariosContent.innerHTML = jsGbl_AJAX_Body_Content();

        map.clearOverlays();

        var sugerencias = document.getElementsByName("hidSugerenciaId");
            
        for (var i=0; i<=sugerencias.length-1; i++)
        {
            var id = sugerencias[i].innerHTML;
            var latitud = document.getElementById("hidLatitud" + id).innerHTML;
            var longitud = document.getElementById("hidLongitud" + id).innerHTML;
            var categ = document.getElementById("hidCategoriaPrefijo" + id).innerHTML;
            var nombre = document.getElementById("hidNombre" + id).innerHTML;
            var titulo = document.getElementById("hidTitulo" + id).innerHTML;
            var texto = document.getElementById("hidTexto" + id).innerHTML;
            var icono = document.getElementById("hidIcono" + id).innerHTML;
            var usuarioIngreso = document.getElementById("hidUsuarioIngreso" + id).innerHTML;
            var fechaIngreso = document.getElementById("hidFechaIngreso" + id).innerHTML;
            var cantidadFotos = document.getElementById("hidCantidadFotos" + id).innerHTML;
            
            GSetMarker(latitud, longitud, icono, categ, id, nombre, titulo, texto, usuarioIngreso, fechaIngreso, cantidadFotos);
        }
        
//        var oForm = document.forms['frmCategIdeal'];
//        var selCategIdealId = oForm['selCategIdealId'];
//        var hrefRankingIdeales = $('hrefRankingIdeales');

//        var sValues = selCategIdealId.value.split("|");
//        hrefRankingIdeales.href = "ranking-destinos-ideales-"+sValues[1]+".html";
    }
}


function sugerenciaEvaluationFixImages()
{
    var itemID = null;
    var containerID = null;
    for(var photoIndex=0; photoIndex<3; photoIndex++)
    {
        containerID = 'PhotoItem' + photoIndex.toString();
        itemID = 'PhotoItemImageControl' + photoIndex.toString();
        
        if ($(itemID) != null)
        {
            sugerenciaEvaluationFixImage(containerID, itemID, 
                200, 148);
        }
    }
}


function sugerenciaEvaluationFixImage(photoContainerControlID, photoControlID, newWidth, newHeight)
{
	var x = document.getElementById(photoControlID);
	var containerControl = document.getElementById(photoContainerControlID);
	
    var topWidth = newWidth;
    var topHeight = newHeight;
    var factor; 
    var ratio = x.width - x.height;

    if (!(x.width <= newWidth && x.height <= newHeight))
    {   

        if (ratio > 0)
        {
            factor = (x.width / newWidth);

            if ((x.height / factor) > newHeight) // si el alto calculado con el factor del ancho es mayor que el maximo, recalculo el factor con este alto.
            {
                factor = (x.height / newHeight);
                newWidth = (x.width / factor);
                newHeight = (x.height / factor);
            }
            else
            {
                newHeight = (x.height / factor);
            }
        }
        else if (ratio < 0)
        {
            factor = (x.height / newHeight);
            
            if ((x.width / factor) > newWidth) // idem anterior pero al reves
            {
                factor = (x.height / newHeight);
                newWidth = (x.width / factor);
                newHeight = (x.height / factor);
            }
            else
            {
                newWidth = (x.width / factor);
            }
        }

        if (Math.abs(topWidth - newWidth) < parseFloat('10'))
            newWidth = topWidth;

        if (Math.abs(topHeight - newHeight) < parseFloat('10'))
            newHeight = topHeight;

	    x.width = newWidth;
	    x.height = newHeight;
    }	
		
	if (x.width < topWidth)
	{
	    x.style.marginLeft = ((topWidth - x.width) / 2) + 'px';
	}
	else
	{
	    x.style.marginLeft = '0px';	
	}

	if (x.height < topHeight)
	{
	    x.style.marginTop = ((topHeight - x.height) / 2) + 'px';
	}
	else
	{
	    x.style.marginTop = '0px';	
	}

}
