﻿/// <changes>
/// 2008-07-04  IC      Added function ProcessError for handled ajax error
/// 2008-07-08  IC      Added logic for generate LOW images.
/// 2008-08-13  SS      Prevent bad data
/// 2008-09-09  SS      Added logic to show count avisos in Tab   
/// 2008-09-12  SS      Added alert msg when is only one or less than advertisement selected
/// 2008-09-16  AP      Added ControlText function to control the format of the text.
/// 2008-09-17  SS      Changed no-picture image source
/// 2008-09-19  SS      Resize column with to 170 px and padding right of 10 px
/// 2008-10-06  SS      Increment index of search string added area geof
/// 2008-10-14	EF		Remove the "searchTextValues" and related parameters.
/// 2008-10-28  DSF     Buscar_Callback method: Add functionality to return divCategoriasHijas data when the 
///                     user search data using the right panel
/// 2008-10-30  EF      Add ApplicationPath to image URLs
/// 2008-10-30  SS      Added logic to put '...' at end of text in control text
/// 2008-11-18	SS		Added var to nTotal
/// 2008-12-05	SS		To keep filter options when use lateral search
///	2008-12-11	EF		Add and remove a non visible iframe to render certifica control in ajax calls when paging
///                     or when refining search filter.
/// 2009-01-28	EF		Consider printed advertisements comparison
/// 2009-01-29	SS	    Added logic to execute the specific search given the selected tab
/// 2009-03-19	EF		Remember selected advertisements.
/// 2009-03-30	DSF		Fix BUG: ArmarStringSeleccionados() did not work properly when selected items count was 1.
/// 2009-03-30	DSF		Fix BUG: ArmarStringSeleccionadosPrint() did not work properly when selected items count was 1.
/// </changes>

// JScript File
  
function IniciarBusqueda()
{
    if(validateFormFields())
    {
		
        var valores = getFormValues();
       
       if (valores.textoBusqueda != null && valores.textoBusqueda.length > 0)
       {
			 sTextoBusqueda = valores.textoBusqueda;
       }
       
        
        //2008-07-16 IC Changed valores[0] for textoBusqueda
       
//        var sBusqueda = /*valores[0].Valor +*/ sSss + escapeSearchString(valores.textoBusqueda) + sSss +  valores[1].Valor + sSss + valores[2].Valor + sSss + valores[3].Valor + sSss + valores[4].Valor + sSss + valores[5].Valor;
        var sBusqueda = /*valores[0].Valor +*/ sSss + escapeSearchString(valores.textoBusqueda) + sSss +  valores[1].Valor + sSss + valores[2].Valor + sSss + valores[3].Valor + sSss + valores[4].Valor + sSss + valores[5].Valor + sSss + valores[6].Valor;
         // 2008-10-06   SS      Increment index of search string added area geof
//        for(var i = 6; i < valores.length; i++)
        for(var i = 7; i < valores.length; i++)
        {
            if(valores[i].Valor!=null)
            {
                if(typeof(valores[i].Valor)!='string')
                    for(var j = 0; j < valores[i].Valor.length; j++)
                        sBusqueda += sSss + valores[i].idCampo + sSss + valores[i].Operacion + sSss + valores[i].Valor[j];
                else if(valores[i].Valor!='')
                    sBusqueda += sSss + valores[i].idCampo + sSss + valores[i].Operacion + sSss + valores[i].Valor;
            }
        }
        c_IdCategoriaAvisoEnc = valores.IdCategoriaAvisoEnc;
        c_sBusqueda = sBusqueda;
       
//        if (sBusqueda == sSss)
//            alert ('Debe completar algunos de los datos para realizar la búsqueda.');
//        else
        {
            document.getElementById(divResultados).innerHTML = "<img src=\"" + c_ApplicationPath + "App_Images/Generic/loading_wheel.gif\" />";
//            AjaxPro.timeoutPeriod = 120000;
            nInicioActual = 0;
            nInicioActualPrint = 0;
            
			//2008-12-05	SS		To keep filter options when use lateral search
			CambiarPagina(nInicioActual, parseInt(GetStepPaginado()));    
        }

		
    }
}


function CambiarCategoria(IdCategoriaAvisoEnc)
{
    AjaxPro.timeoutPeriod = 120000;
//    Busqueda.CambiarCategoria(IdCategoriaAvisoEnc, c_sBusqueda, c_sBusquedaTextValues,  CambiarCategoria_callback);
    Busqueda.CambiarCategoria(IdCategoriaAvisoEnc, c_sBusqueda, CambiarCategoria_callback);
}

function CambiarCategoria_callback(res)
{
    if (res.error != null)
//        a=1;//alert(res.error.Message);;
        ProcessError(res);
    else
        document.location.href = res.value;   
}

function Buscar_callback(res)
{

    if(res.error!=null)
    {
        
        ProcessError(res);
    }
    else
    {
        dt = res.value.Avisos;
        
        ProcesarResultadoBusqueda(res.value.SelectedAdvertisements, res.value.CryptedQueryParameter,
            res.value.sCategoriaNombre, res.value.sCategoriasHijas, res.value.BreadCrumb, 
            res.value.AdvertisementsHtmlTable, res.value.nCantAvisosImpresos);

//        ProcesarCambioDePagina(res.value.SelectedAdvertisements,, res.value.BreadCrumb, res.value.CryptedQueryParameter, 
//            res.value.sCategoriaNombre, );
    }
}

function ProcesarResultadoBusqueda(selectedAdvertisements, cryptedQueryParameter, sCategoriaNombre, sCategoriasHijas, breadCrumb, 
    advertisementsHtmlTable, cantAvisosImpresos)
//function ProcesarCambioDePagina(selectedAdvertisements, breadCrumb, cryptedQueryParameter, sCategoriaNombre, advertisementsHtmlTable, cantAvisosImpresos)
{

    ArmarBreadCrumb(breadCrumb);
    
    //  Used to save current query
    c_sCryptedQueryParameter = cryptedQueryParameter;
    
    if(sCategoriaNombre != null && sCategoriaNombre.length > 0)
    {
//			document.getElementById('hidCatName').value = res.value.sCategoriaNombre;		
		sTextoBusqueda = sCategoriaNombre;
			
    }

    //  Selected advertisements string (saved in session variable)
    c_SearchSelectedAdvertisements = selectedAdvertisements;

    SetearSeleccionados(c_SearchSelectedAdvertisements);
            
    var nInicio;
    var nStep;
    if (nStepActual == 0)
    {
        nInicio = nInicioActual;
        nStep = GetStepPaginado();
//			ArmarTabla(nInicioActual, parseInt(GetStepPaginado()));
	}
	else if (nStepActual == parseInt(GetStepPaginado()))
	{
        nInicio = nInicioActual;
        nStep = nStepActual;
//			ArmarTabla(nInicioActual, nStepActual);
	}
	else
	{
        nInicio = nInicioActual;
        nStep = nStepActual;       
//			ArmarTabla(nInicioActual, nStepActual);

		SetStepPaginado(String(nStepActual));
	}
	
	if (GetLateSearchResultsLoad() == "")
	{
	    ArmarTablaNuevo(nInicio, nStep, advertisementsHtmlTable);
	}
	else
	{
        ArmarTabla(nInicio, nStep);
	}
	
    document.getElementById('orden').value = selectedOption;

    if(!bAdsCargados)
    {
        AjaxPro.timeoutPeriod = 120000;
        Busqueda.CargarAds(c_IdCategoriaAvisoEnc, CargarAds_callback);
    }
    
    document.getElementById('BtnImpresoSel').innerHTML = cantAvisosImpresos != -1 ? "(" + cantAvisosImpresos + ")" : "&nbsp;";
    //2008-10-28    DSF: Add functionality to return divCategoriasHijas data when the user search data using the right panel
    if(sCategoriasHijas != null && sCategoriasHijas != "" )
    {
        document.getElementById(divCategoriasHijas).innerHTML = sCategoriasHijas;
    }
  
    
}


function CambiarPagina(nInicio, nStep)
{
	
    document.getElementById(divResultados).innerHTML = "<img src=\"" + c_ApplicationPath + "App_Images/Generic/loading_wheel.gif\" />";
    nInicioActual = nInicio;
    nStepActual = nStep;  
   
    AjaxPro.timeoutPeriod = 120000;

    RemoveIFrame("ifrmBusqueda");
    AddIFrame("ifrmBusqueda",
        c_ApplicationPath + "CertificaTagPage.aspx?cryptedCategoryId=" + c_IdCategoriaAvisoEnc + 
        "&pageNumber=" + ((nInicio / 10) + 1) + "&originalUrl=" + c_SeoOriginalUrl);
    //  TODO: Use constant or global JS variable instead of the "10"
    //2009-01-29		SS	Added logic to execute the specific search given the selected tab	

    var selectedAndUnselectedItems = CargarSeleccionadosYDeseleccionados(idsAvisos, nStep);

    if (bIsWebTab)
    {
		Busqueda.BuscarSep(sSessionID, c_IdCategoriaAvisoEnc, c_sBusqueda +  GetOrdenCampos(), nInicio, nStep, 
            selectedAndUnselectedItems[0],  // Selected items
            selectedAndUnselectedItems[1],  // Unselected items
            false,                          // Do not clear selection
		    Buscar_callback);	
	}
	else
	{
		Busqueda.BuscarSepPrint(sSessionID, c_IdCategoriaAvisoEnc, c_sBusqueda +  GetOrdenCampos(), nInicio, nStep,
            selectedAndUnselectedItems[0],  // Selected items
            selectedAndUnselectedItems[1],  // Unselected items
            false,                          // Do not clear selection
		    CambiarPaginaPrint_callback);
	}

}

function ArmarStringSeleccionados()
{
    if(seleccionados.length > 0)
    {
        var sTemp = seleccionados[0];
        for(var i=1; i<seleccionados.length; i++)
            sTemp += "," + seleccionados[i];
        return sTemp;
    }
    else
    {
        return "";
    }
}

function ArmarStringSeleccionadosPrint()
{
    if(seleccionadosPrint.length > 0)
    {
        var sTemp = seleccionadosPrint[0];
        for(var i=1; i<seleccionadosPrint.length; i++)
            sTemp += "," + seleccionadosPrint[i];
        return sTemp;
    }
    else
    {
        return "";
    }
}

function usarAgregado(sAgregados, idAgregado)
{
    return sAgregados.indexOf(idAgregado) != -1 && (sAgregados == idAgregado || (sAgregados.indexOf(sSss + idAgregado + sSss) > -1) || (sAgregados.indexOf(idAgregado + sSss) == 0) || (sAgregados.indexOf(sSss + idAgregado) == sAgregados.length - idAgregado.length));
}
function getOpcionAgregado(sAgregados, idAgregado)
{
    var nIndex = -1;
    if(sAgregados.indexOf(idAgregado + '|') == 0)
        nIndex = idAgregado.length + 1;
    else if(sAgregados.indexOf(sSss + idAgregado + '|') > -1)
        nIndex = sAgregados.indexOf(sSss + idAgregado + '|') + idAgregado.length + 3;
    if(nIndex != -1)
    {
        var sTemp = sAgregados.substr(nIndex, sAgregados.length - nIndex);
        return sTemp.indexOf(sSss) != -1 ? sTemp.substr(0, sTemp.indexOf(sSss)) : sTemp;
    }
    else
        return "";
}

//function ChequearCantidadAnuncios (checkAnuncio, idAviso)
//{
//	
//    if(checkAnuncio.checked) 
//    {
////        if (seleccionados.length == 5)
////        {
////            alert ('No puede seleccionar más de cinco anuncios para comparar.');
////            checkAnuncio.checked = false;
////        }
////        else
//            seleccionados[seleccionados.length] = idAviso;
//    }
//    else
//    {
//		
//        seleccionados.splice(seleccionados.indexOf(idAviso), 1);
//    }
//     
//}

//function ChequearCantidadAnunciosPrint (checkAnuncio, idAviso)
//{
//    if(checkAnuncio.checked) 
//    {
//        if (seleccionadosPrint.length == 5)
//        {
//            alert ('No puede seleccionar más de cinco anuncios para comparar.');
//            checkAnuncio.checked = false;
//        }
//        else
//            seleccionadosPrint[seleccionadosPrint.length] = idAviso;
//    }
//    else
//        seleccionadosPrint.splice(seleccionadosPrint.indexOf(idAviso), 1);
//     
//}

//function CargarAds_callback(res)
//{
//    if(res.error!=null)
//        //a=1;//alert(res.error.Message);
//        ProcessError(res);
//    else
//        ArmarAds(res.value);
//}


