﻿// Archivo JScript

/*********************************************
    Main Menu
*********************************************/

function MainMenuOver(id)
{    
    // hide previous menu
    if (currentSubMenu != null)
    {
        currentSubMenu.style.display = 'none';
    }    
    // reassign current menu
    currentSubMenu = $(id);  
    // show submenu
    if (currentSubMenu != null)
    {
        currentSubMenu.style.display = '';
    }
}

/*********************************************
    Login
*********************************************/

function RemoveOtherLogin(id)
{
    var ctrls = document.getElementsByTagName('input');
    
    // find all controls that have names like "UserName, Password" and that
    // are not from the same control and remove them
    for (var i=0; i<ctrls.length; i++)
    {
        if ((ctrls[i].id.indexOf('Password') >= 0 || ctrls[i].id.indexOf('UserName') >= 0) &&
             ctrls[i].id.indexOf(id) == -1)
        {
            //ctrls[i].disabled = true;
            ctrls[i].parentNode.removeChild(ctrls[i--]);            
        }                       
    }
}

// Keeps text value of the control

function DCH(ctrl, id)
{
    $(id).value = ctrl.options[ctrl.selectedIndex].text;
}

/*******************************
    CATALOG
*******************************/
function LoadCatalogView()
{
    var type = Get_Cookie('catalogCSS');
    
    if (type != null && type != '')
    {
        ChangeView(type);
    }
    else
    {
        ChangeView('detail');
    }
}

function ChangeView(type)
{
    // Set Cookie
    Set_Cookie('catalogCSS', type, '', '/', '', '');

    var time=new Date();
    var src;    
    switch (type)
    {
        case 'list':
            type = 'catalog-list.css?date=' + time.getDate();            
            break;
        case 'icons':
            type = 'catalog-icons.css';
            ChangeCatalogImages('TN_Small', 'TN_Medium');
            break;
        default:
            type = 'catalog-detail.css';
            ChangeCatalogImages('TN_Medium', 'TN_Small');
            break;
    }        
    
    // Load CSS
    LoadCSS(type);        
}

function LoadCSS(name)
{
    var cssHolder = $('cssHolder');
    cssHolder.href = 'App_Themes/' + name;
}

function ChangeCatalogImages(from, to)
{
    var imgs = document.getElementsByTagName("img");
    
    for (var i=0; i<imgs.length; i++)
    {
        if (imgs[i].src.indexOf(from) > 0)
        {
            imgs[i].src = imgs[i].src.replace(from, to);
        }
    }
}

/*******************************
    end CATALOG
*******************************/

/*********************************************
AJAX Report to Administrator
*********************************************/

function SendTruoble(iuid,id)
{
    var message =$('problemaMessage').value;
    
    if (message && message != '\u00a0')
    {        
        document.body.style.cursor = 'wait';
        var panel = $('Problema_EmailMessagePanel');
        panel.style.display = '';    
        panel.innerHTML = 'Enviando...';
        var res = Controls_AJAXEmailControl.SendMail(null, '', '', 'ReportarProblema.xsl', '', '', '"info@guiacoches.com"', '', message);          
    }
    else
    {
        alert('Debe introducir todos los datos');
        return;
    }
    FinishEmail(res, panel);
    if (panel.className == 'okPanel')
    {
        ResetValues('textarea', $('problemaTable'));
        panel.style.display = 'none';
        tb_remove();
        jQuery.fancybox.close();
    }
    
    
}

/*********************************************
AJAX EMail
*********************************************/

function SendMail(iuid, categoria, id, viewName, transformation)
{
    var fromName =$('tuNombre').value;
    var toName =  $('suNombre').value;
    var fromEmail = $('tuEmail').value;   
    var toEmail = $('suEmail').value;
    var message =  $('mensajeAmigo').value;
    
    if (fromName && toName && fromEmail && toEmail && message)
    { 
        if(isValidEmail(fromEmail,true) && isValidEmail(toEmail,true))
        {
            document.body.style.cursor = 'wait';
            var panel = $('Amigo_EmailMessagePanel');
            panel.style.display = '';    
            panel.innerHTML = 'Enviando...';
            var res = Controls_AJAXEmailControl.SendMail(categoria, id, viewName, transformation, fromEmail, fromName, toEmail, toName, message);   
        }
        else
        {
            alert('Las direcciones de correo deben ser correctas');
            return;
        }
    }
    else
    {
        alert('Debe introducir todos los datos');
        return;
    }
    FinishEmail(res, panel);
    if (panel.className == 'okPanel')
    {
        ResetValues('input,textarea', $('amigoTable'));
        panel.style.display = 'none';
        tb_remove();
        jQuery.fancybox.close();
    }
}

function ContactVendor(cid, id, viewName, viewType)
{
    var fromName = $('NombreContacto').value;
    var fromEmail = $('EmailContacto').value;
    var telefono = $('TelefonoContacto').value;
    var contraoferta = $('ContraofertaContacto').value;
    var message = $('ComentariosContacto').value;
    
    if (fromName && fromEmail)
    { 
        if(isValidEmail(fromEmail,true))
        {
            document.body.style.cursor = 'wait';
            var panel = $('VendorMessagePanel');
            panel.style.display = '';
            panel.innerHTML = 'Enviando...';
            var res = Controls_ContactVendedorControl.SendMail(id, viewType, viewName, fromEmail, fromName, message, telefono, contraoferta);
        }   
        else
        {
            alert('La dirección de correo no es correcta');
            return;
        }
    
    }
    else
    {
        alert('Debe introducir su Nombre y E-mail válido');
        return;
    }

    FinishEmail(res, panel);
    if (panel.className == 'okPanel')
    {
        ResetValues('input,textarea', $('vendorTable'));
        panel.style.display = 'none';
        tb_remove();
        jQuery.fancybox.close();
    }
}


function Contact()
{
    var tipoConsulta = $('TipoConsulta').value;
    var fromName = $('ContactName').value;
    var fromEmail = $('ContactEmail').value;
    var telefono = $('ContactPhone').value;
    var message = $('ContactMessage').value;
    
    if (tipoConsulta && fromName && fromEmail && message)
    {   
        if(isValidEmail(fromEmail,true))
        {
            document.body.style.cursor = 'wait';
            var panel = $('UserMessagePanel');
            panel.style.display = '';    
            panel.innerHTML = 'Enviando...';
            var res = Controls_ContactControl.SendMail(tipoConsulta, fromName, fromEmail, telefono, message);
        }
        else
        {
            alert('La dirección de correo no es correcta');
            return;
        }  
    }    
    else
    {
        alert('Debe introducir todos los datos a excepción del teléfono');
        return;
    }
    
    FinishEmail(res, panel);
    if (panel.className == 'okPanel')
    {
        ResetValues('input,textarea,select', $('contactTable'));
        panel.style.display = 'none';
        tb_remove();
        jQuery.fancybox.close();
    }
}

function ResetValues(types, container)
{
    var resets = types.split(',');
    
    for (var i=0; i<resets.length; i++)
    {
        var ctrls = container.getElementsByTagName(resets[i]);
    
        for (var j=0; j<ctrls.length; j++)
        {
            if (resets[i] == 'select')
            {
                ctrls[j].value = 0;
            }
            else
            {
                ctrls[j].value = '';
            }
        }
    }
}

function CrearAlerta(idAnuncio, tipoAnuncio, marcaID, modeloID, versionID, tipoID)
{        
    var alertaNombre = $('alertaNombre').value;
    var alertaEmail = $('alertaEmail').value;
    
    if (alertaNombre && alertaEmail)
    {
        if(isValidEmail(alertaEmail,true))
        {
            var panel = $('AlertaMessagePanel');
            panel.style.display = '';
        
            document.body.style.cursor = 'wait';
    
            panel.innerHTML = 'Enviando...';      
            
            var res = Controls_AJAXEmailControl.EnviarAlerta(alertaNombre, alertaEmail, idAnuncio, tipoAnuncio, marcaID, modeloID, versionID, tipoID);
        }
        else
        {
          alert('La dirección de correo no es correcta');
          return;
        }
    }
    else
    {
        alert('Introduzca todos los datos');
        return;
    }
    
    FinishEmail(res, panel);
    if (panel.className == 'okPanel')
    {
        ResetValues('input', $('alertaTable'));
        panel.style.display = 'none';
        tb_remove();
        jQuery.fancybox.close();
    }                  
}

function ExportarStock(id, viewName, viewType)
{
    var panel = $('VendorMessagePanel');
    panel.style.display = '';
        
    panel = $('VendorMessage');
    document.body.style.cursor = 'Por favor,espere...';
    
    panel.innerHTML = 'Enviando...';
    
    var fromCoches = $('CheckCoches').value;
    var fromMotos = $('CheckMotos').value;
    var fromQuads = $('CheckQuads').value;
    var fromRecambios = $('CheckRecambio').value;
    var fromCamion = $('CheckCamion').value;
    
    var res = Controls_UserExportControl.Exportar(id, viewType, viewName, fromCoches, fromMotos, fromQuads, fromRecambios, fromCamion);

    FinishEmail(res, panel);
}



function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}



function RecordarPassword(id,loginfield,reloginfield)
{            
    var fromEmail = GetControlValue(id,loginfield,'');
    var fromReEmail =GetControlValue(id,reloginfield,'');
    if(fromEmail.toString() == fromReEmail.toString()){
        if(isValidEmail(fromEmail,true)){   
                var res = CommonAJAX.ComprobarPassword(fromEmail);
                if (res.value != null)
                    {
                        alert('Se le ha enviado correctamente a su dirección de correo. Cierre esta ventana y verifique su correo.');
                      SetControlValue(id,'EmailBasic','','');
                      SetControlValue(id,'EmailRe','','');
                       tb_remove();
                       jQuery.fancybox.close();
                    }
                    else{
                      SetControlValue(id,'EmailBasic','','');
                      SetControlValue(id,'EmailRe','','');
                       tb_remove();
                       jQuery.fancybox.close();
                        alert('Esta dirección de correo no está asociada a ningún usuario del sistema.');
                    }
                  }
              else{
               alert('Las direcciones de correo no son correctas.');
               SetControlValue(id,'EmailBasic','','');
               SetControlValue(id,'EmailRe','','');
                tb_remove();
                jQuery.fancybox.close();
               }
       }
       else{
        SetControlValue(id,'EmailBasic','','');
        SetControlValue(id,'EmailRe','','');
        tb_remove();
        jQuery.fancybox.close();
        alert('Las direcciones de correo no coinciden.'); 
        }

}

function BorrarAviso(id)
{   
    var res = CommonAJAX.BorrarAviso(id);
    window.location.reload();
}

function RecordarPasswordHead(id,loginfield,reloginfield)
{        
    var fromEmail = GetControlValue(id,loginfield,'');
    var fromReEmail =GetControlValue(id,reloginfield,'');
    if(fromEmail.toString() == fromReEmail.toString()){
            if(isValidEmail(fromEmail,true)){   
                var res = CommonAJAX.ComprobarPassword(fromEmail);
                if (res.value != null)
                    {
                        alert('Se le ha enviado correctamente a su dirección de correo. Cierre esta ventana y verifique su correo.');
                      SetControlValue(id,'EmailBasic_Head','','');
                      SetControlValue(id,'EmailRe_Head','','');
                       tb_remove();
                       jQuery.fancybox.close();
                    }
                    else{
                      SetControlValue(id,'EmailBasic_Head','','');
                      SetControlValue(id,'EmailRe_Head','','');
                        alert('Esta dirección de correo no está asociada a ningún usuario del sistema.');
                    tb_remove();
                    jQuery.fancybox.close();
                    }
              }
              else{
                tb_remove();
                jQuery.fancybox.close();
                SetControlValue(id,'EmailBasic_Head','','');
                SetControlValue(id,'EmailRe_Head','','');
               alert('Las direcciones de correo no son correctas.');
               }
       }
       else{
        tb_remove();
        jQuery.fancybox.close();
        SetControlValue(id,'EmailBasic_Head','','');
        SetControlValue(id,'EmailRe_Head','','');
        alert('Las direcciones de correo no coinciden.');
        }

}



function FinishEmail(res, panel)
{
    document.body.style.cursor = 'auto';
    
    if (FinishAJAXMethod(res))
    {
        var resparse = res.value.split('|');
        panel.innerHTML = resparse[1];
        
        if (resparse[0] == 'OK')
        {
            panel.className = 'okPanel';        
        }
        else
        {
            panel.className = 'errorPanel';        
        }
     }
     else 
     {
            panel.className = 'errorPanel';
            panel.innerHTML = res.error;
     }
}

/*********************************************
    end AJAX EMail
*********************************************/

/********************************************
  Anuncios Coches                          
********************************************/
function RefreshCarDetails(ctrl)
{
    versionE = ctrl.value;
    versionS = ctrl.value;
    
    $('Serie').style.display = 'none';
    $('Extras').style.display = 'none';
}

function AppendCB(panel, row, prefix, showCheckBoxes, prechecked)
{
    var line = panel.appendChild(document.createElement('div'));
    //line.setAttribute('class','col3Layout');    
    //line.setAttribute('class','col3LayoutDani');    
    
    var subLine;
    
    if (showCheckBoxes)
    {
        subLine = document.createElement("INPUT");
        subLine.type = "checkbox";
        subLine.name = prefix + row["Id"];
        subLine.value = row["Nombre"];
        subLine.className = "line3input";
                
        line.appendChild(subLine);
        subLine.checked = prechecked;    
    }
    
    subLine = line.appendChild(document.createElement('label'));
    //subLine.setAttribute('class','inputLabelWideL');
    subLine.setAttribute('for', prefix + row["Id"]);
    //dani
    //subLine.className = "line3cblabel";
    subLine.innerHTML = row["Nombre"]; 
}

function ValidatePanel(panelID, version)
{
    // Validate actions
    if (version == null)
    {
        return null;
    }
        
    var panel = $(panelID); 
    
    // panel must be visible and versionmust be selected
    if (panel.style.display == '')
    {
        return null
    }
       
    // clear all child controls
    for (var i=panel.childNodes.length - 1; i>=0; i--)
    {
        panel.removeChild(panel.childNodes[i]);
    }    
    return panel;
}

function ViewDimensions()
{   
    var panel = ValidatePanel('Dimensions', versionD);
    ShowHide('Dimensions','Extras,SerieInterior,SerieExterior,SerieSeguridad');    
    
    if (panel != null)
    {
        // call AJAX to get the new list of child nodes
        var fill = new FillDimensions();
        fill.panel = panel;       
        fill.version = versionD;
        fill.loader = 'DimensionsLoader';        
        
        fill.go();        
        
        versionD = null;    
    }
}

function ViewCarExtras(hidePanels, arguments, checkBoxes, versionID)
{       
    // Hide Brothers     
    var panel = ValidatePanel('Extras', versionE);
    
    if (hidePanels != 'Extras')
    {
        ShowHide('Extras', hidePanels);    
    }
    
    if (panel != null)
    {
        // call AJAX to get the new list of child nodes
        var fill = new FillDetail();
        fill.panel = panel;
        fill.prefix = 'DE.';
        fill.checkBoxes = checkBoxes;
        fill.checkBoxValue = false;
        fill.version = versionE;
        fill.loader = 'ExtrasLoader';
        fill.arguments = arguments;
        
        if (arguments == null || (versionID != null && versionID != versionE))
        {
            fill.goExtra();
        }
        else if (arguments != null)
        {                        
            if (checkBoxes == null)
            {
                fill.goExtraFiltered();
            }
            else
            {                                     
                fill.goExtraAnuncio();   
            }
        }
        
        versionE = null;    
    }
}

function ViewCarSerie(seriePanel, hidePanels, arguments, checkBoxes, versionID)
{
    if (seriePanel)
    {
        var panel = ValidatePanel('SerieExterior', versionS);        
        panel = ValidatePanel('SerieInterior', versionS);        
        panel = ValidatePanel('SerieSeguridad', versionS);        
        ShowHide('Serie' + seriePanel, hidePanels);
    }
    else
    {
        var panel = ValidatePanel('Serie', versionS);
        ShowHide('Serie', hidePanels);
    }
           
    if (panel != null)
    {
        // call AJAX to get the new list of child nodes
        var fill = new FillDetail();
        fill.panel = panel;
        fill.prefix = 'DS.';
        fill.groupBy = 'Seccion';
        fill.checkBoxes = checkBoxes;
        fill.checkBoxValue = true;
        fill.loader = seriePanel ? ('Serie' + seriePanel + 'Loader') : 'SerieLoader';
        fill.version = versionS;
        fill.arguments = arguments;
        fill.columns = seriePanel ? 1 : 3;
                         
        if (arguments == null || (versionID != null && versionID != versionS))
        {       
            fill.goSerie();
        }        
        else if (arguments != null)
        {
            if (checkBoxes == null)
            {
                fill.goSerieFiltered();
            }
            else
            {                                     
                fill.goSerieAnuncio(); 
            }
        }
        
        versionS = null;     
    }
}

function RefreshVersionData(versionCheck, id, anuncioID)
{
    var versionID = GetControl(id,'VersionID','');
    var versionText = GetControl(id,'Version','');
    versionID.value = '';
    versionID.disabled = versionCheck.checked;
    versionText.disabled =!versionCheck.checked;    
    RefreshCarDetails(versionID);
    MarkStandardEquipment(id, '', anuncioID);

    var removed = versionCheck.checked ? 'VersionID' : 'Version';
    var inserted = !versionCheck.checked ? 'VersionID' : 'Version';
    
    if (versionCheck.checked)
    {
        removed = 'VersionID';
        inserted = 'Version';
        $('liVersion').style.display = '';
    }
    else
    {
        removed = 'Version';
        inserted = 'VersionID';
        $('liVersion').style.display = 'none';
    }
   
    // Process validators    
    for (var i=1; i<validators_ctl00_MainPlaceHolder_ctl00_Anuncio.length; i++)
    {
        if (validators_ctl00_MainPlaceHolder_ctl00_Anuncio[i].indexOf(removed) != -1)        
        {
            validators_ctl00_MainPlaceHolder_ctl00_Anuncio.splice(i, 1);
            var ancla = $(id + '_' + removed + 'Validator_' + '');
            ancla.style.display = 'none';
            break;
        }        
    }
        
    validators_ctl00_MainPlaceHolder_ctl00_Anuncio.push("ValidateRequired(GetControl('ctl00_MainPlaceHolder_ctl00', '" + inserted + "', ''),'')");    
}

//* FUNCTION
function FillDetail() {     
    this.panel = null;   
    this.prefix = '';
    this.groupBy = null;
    this.arguments = '';
    this.checkBoxes = ''
    this.checkBoxValue = '';  
    this.version = '';  
    this.loader = null;
    this.columns = 3;
    
    // Main callback function
    this.callback = function(res) {
        if (FinishAJAXMethod(res))
        {
            var linePanel;
            var groupByField = "";
            // now loop through collection and append all extras
            if (res != null && res.value != null && res.value.Rows.length > 0)
            {
                for (var i=0; i<res.value.Rows.length; i++)
                {            
                    // We add 3 by line
                    //if (i % 3 == 0 || (this.groupBy != null && res.value.Rows[i][this.groupBy] != groupByField))
                    //if ((this.groupBy != null && res.value.Rows[i][this.groupBy] != groupByField))
                    
                    if (i % 1 == 0 || (this.groupBy != null && res.value.Rows[i][this.groupBy] != groupByField))
                    {
                        // We add groupby header                                                
                        if (this.groupBy != null && res.value.Rows[i][this.groupBy] != groupByField)
                        {
                            // Titulo de los datos....
                            //linePanel = this.panel.appendChild(document.createElement('div'));
                            //linePanel.className = 'modLeftTitular3Col fdo5';
                            
                            groupByField = res.value.Rows[i][this.groupBy];
                            
                            if (this.columns == 1)
                            {
                                this.panel = $('Serie' + groupByField);
                                linePanel = this.panel.appendChild(document.createElement('div'));
                                linePanel.className = 'tituloEquipamiento';
                            
                                linePanel = linePanel.appendChild(document.createElement('h1'));                            
                                
                            }
                            else
                            {
                                linePanel = this.panel.appendChild(document.createElement('div'));
                                linePanel.className = 'modLeftTitular3Col fdo5';
                            }
                            
                            linePanel.innerHTML = res.value.Rows[i][this.groupBy];
                        }
                        
                        // Contenedor con los datos
                        linePanel = this.panel.appendChild(document.createElement('div'));
                        //linePanel.className = 'col3LayoutHolder';
                        //linePanel.className = this.columns == 1 ? 'col1LayoutHolder' : 'col3LayoutHolder';
                        linePanel.className = 'col1LayoutHolder';
                    }
                    
                    if (res.value.Rows[i]['Value'] == null)
                    {
                        AppendCB(linePanel, res.value.Rows[i], this.prefix + i + ".", this.checkBoxes, this.checkBoxValue);
                    }
                    else
                    {
                        AppendCB(linePanel, res.value.Rows[i], this.prefix + i + ".", this.checkBoxes, res.value.Rows[i]['Value']);
                    }
                }
            }
            else
            {
                if (this.columns == 3)
                {
                    linePanel = this.panel.appendChild(document.createElement('div'));
                    linePanel.innerHTML = '<div class="contentHolder">No hay datos</div>';
                }
                else
                {
                    linePanel = $('SerieExterior');
                    linePanel.innerHTML = '<div class="contentHolder">No hay datos</div>';
                    linePanel = $('SerieInterior');
                    linePanel.innerHTML = '<div class="contentHolder">No hay datos</div>';
                    linePanel = $('SerieSeguridad');
                    linePanel.innerHTML = '<div class="contentHolder">No hay datos</div>';
                }   
            }
            
            // hide loader
            ShowHide(this.loader + 'On');
            ShowHide(this.loader + 'Off');
        }    
    };
    this.goExtra = function() {    
        // Call callback function
        ShowHide('ExtrasLoaderOn');
        ShowHide('ExtrasLoaderOff');
        CommonAJAX.GetExtras(this.version, this.callback.bind(this));
    };
    this.goExtraAnuncio = function() {    
        // Call callback function
        ShowHide('ExtrasLoaderOn');
        ShowHide('ExtrasLoaderOff');
        var argumentSplit = this.arguments.split(',');          
        CommonAJAX.GetExtrasAnuncio(this.version, argumentSplit[0], argumentSplit[1], argumentSplit[2], argumentSplit[3], argumentSplit[4], argumentSplit[5], argumentSplit[6], this.callback.bind(this));
    };
    this.goSerie = function() {
        ShowHide('SerieLoaderOn');
        ShowHide('SerieLoaderOff');
        CommonAJAX.GetSerie(this.version, this.callback.bind(this));
    };
    this.goSerieAnuncio = function() {
        ShowHide('SerieLoaderOn');
        ShowHide('SerieLoaderOff');
        var argumentSplit = this.arguments.split(',');
        CommonAJAX.GetSerieAnuncio(this.version, argumentSplit[0], argumentSplit[1], argumentSplit[2], argumentSplit[3], argumentSplit[4], this.callback.bind(this));
    };
    this.goSerieFiltered = function() {
        ShowHide(this.loader + 'On');
        ShowHide(this.loader + 'Off');
        var argumentSplit = this.arguments.split(',');          
        CommonAJAX.GetSerieFiltered(this.version, argumentSplit[0], argumentSplit[1], argumentSplit[2], argumentSplit[3], argumentSplit[4], this.callback.bind(this));
    };
    this.goExtraFiltered = function() {
        ShowHide('ExtrasLoaderOn');
        ShowHide('ExtrasLoaderOff');
        var argumentSplit = this.arguments.split(',');          
        CommonAJAX.GetExtrasFiltered(this.version, argumentSplit[0], argumentSplit[1], argumentSplit[2], argumentSplit[3], argumentSplit[4], argumentSplit[5], argumentSplit[6], this.callback.bind(this));
    };
}

function FillDimensions() {     
    this.panel = null;      
    this.version = '';  
    this.loader = null; 
    
    // Main callback function
    this.callback = function(res) {
        if (FinishAJAXMethod(res))
        {            
            // now loop through collection and append all extras
            if (res.value != '')
            {
                this.panel.innerHTML = res.value;
            }
            else
            {
                this.panel.innerHTML = '<div class="contentHolder">No hay datos</div>';
            }
            
            // hide loader
            ShowHide(this.loader + 'On');
            ShowHide(this.loader + 'Off');
        }    
    };
    this.go = function() {                    
        // Call callback function
        ShowHide('DimensionsLoaderOn');
        ShowHide('DimensionsLoaderOff');
        Controls_CatalogControl.GetDimensiones(this.version, this.callback.bind(this));
    };
}

function MarkStandardEquipment(uid, id, anuncioID)
{
    if (anuncioID != null && anuncioID != '' && id == versionS)
    {
        var res = CommonAJAX.GetStandardEquipment('AnuncioCochesExtra', anuncioID);
    }
    else
    {        
        var res = CommonAJAX.GetStandardEquipment('EquipamientoPrincipalCoches', versionS);
    }
    
    if (FinishAJAXMethod(res))
    {
        for (var i=1; i<res.value.Columns.length; i++)
        {
            var checkBox = GetControl(uid, res.value.Columns[i].Name, '');
            checkBox.checked = false;
            
//            if (versionS != null && versionS != '')
//            {
                if (res.value.Rows[0] != null)
                {                
                    checkBox.checked = (res.value.Rows[0][res.value.Columns[i].Name] == '1');
                }
//            }
        }
    }
}

function ShowHide(ctrlId, hides)
{
    if ($(ctrlId) != null)
    {
        if ($(ctrlId).style.display == 'none')
        {
            $(ctrlId).style.display = '';        
        }
        else
        {
            $(ctrlId).style.display = 'none';
        }
    }
    
    if (hides != null)
    {
        var others = hides.split(',');
        for (var i=0; i<others.length; i++)
        {
            if ($(others[i]) != null)
            {
                $(others[i]).style.display = 'none';
            }
        }        
    }
}

function FlipTab(ctrl)
{
    tabSelected.className = '';
    ctrl.className = 'selected';
    tabSelected = ctrl;
}

/*********** Busqueda horizontal *******/

function ChangeHBView(ctrl, id)
{
    if (ctrl.selectedIndex < 2)
    {
        SetControlValue(id, 'Buscar', 'Categoria', ctrl.selectedIndex);
        FillRelated(GetControlName(id, 'Buscar', 'Marca'));
    }
    
    // Chcnge link value
    $('AdvancedSearchLink').href = ctrl.value;
}

/******************* Login control ***/

var currentCount = 0;
function Check3(ctrl)
{   
    if (!ctrl.checked)
    {
        currentCount--;        
    }
    else if (ctrl.checked)
    {
        if (currentCount > 2)
        {
            alert('No se pueden comparar más de 3 vehículos');
            return false;
        }
        currentCount++;
    }
    
    return true;
}

/******************* Image upload control control ***/
function SetImageControlSize(count)
{
    var frame = $('ImageUploadFrame');
    
    if (count == 0)
    {
        frame.style.height = '100px';
    }
    else if (count < 5)
    {
        frame.style.height = '295px';
    }
    else
    {
        frame.style.height = '480px';
    } 
}

function AddImage(id, description)
{
    $('ImageUploadIDs').value += id + ';';
    $('ImageUploadDescriptions').value += description + ';';
    
    imageUploadDescriptions[id] = description;
}

function DeleteImage(id)
{    
    var ids = $('ImageUploadIDs');
    
    ids.value = ids.value.replace(id + ';', '');    
    imageUploadDescriptions[id] = null;
    
    var descs = $('ImageUploadDescriptions');
    var idsValues   = ids.value.split(';');
    
    descs.value = '';
    for (var i=0; i<idsValues.length; i++)
    {
        if (idsValues[i] != '')
        {
            descs.value += imageUploadDescriptions[idsValues[i]] + ';';
        }
    }
}

function SetImageSessionID(id)
{
    $('ImageSessionID').value = id;
}

/****** read EMAIL ****/

function ReadEmail(cell, id)
{
    var table = cell.parentNode.parentNode;
    var parentRow = cell.parentNode;
    
    // check if message has not been red
    var nextRow = table.rows[parentRow.rowIndex + 1];    
    if (nextRow != null && (nextRow.cells[0].attributes['colSpan'] != null && nextRow.cells[0].attributes['colSpan'].value != 1))
    {
        if (nextRow.style.display == '')
        {
            nextRow.style.display = 'none';
        }
        else
        {
            nextRow.style.display = '';
        }
        return;
    }
    
    // find image and show loading animation
    var firstCell = parentRow.cells[0].childNodes[0];    
    while (firstCell.tagName != 'IMG')
    {
        firstCell = firstCell.nextSibling;
    }         
    firstCell.style.display = '';
    
    // read data from DB
    var res = CommonAJAX.ReadEmail(id);
    
    if (FinishAJAXMethod(res))
    {
        // create new row
        var row = table.insertRow(parentRow.rowIndex + 1);
        
        // create window with message                
        var message = document.createElement('TD');                       
        message.setAttribute('colSpan', 6)
        
        message.className = 'messageWindow';    
        message.innerHTML = res.value;

        row.appendChild(message);
    }
    
    // hide loading animation
    firstCell.style.display = 'none';
}


/****** read Avisos ****/

function ReadAvisos(cell, id)
{
    var table = cell.parentNode.parentNode;
    var parentRow = cell.parentNode;
    
    // check if message has not been red
    var nextRow = table.rows[parentRow.rowIndex + 1];    
    if (nextRow != null && (nextRow.cells[0].attributes['colSpan'] != null && nextRow.cells[0].attributes['colSpan'].value != 1))
    {
        if (nextRow.style.display == '')
        {
            nextRow.style.display = 'none';
        }
        else
        {
            nextRow.style.display = '';
        }
        return;
    }
    
    // find image and show loading animation
    var firstCell = parentRow.cells[0].childNodes[0];    
    while (firstCell.tagName != 'IMG')
    {
        firstCell = firstCell.nextSibling;
    }         
    firstCell.style.display = '';
    
    // read data from DB
    var res = CommonAJAX.ReadAviso(id);
    
     if (FinishAJAXMethod(res))
    {
        // create new row
        var row = table.insertRow(parentRow.rowIndex + 1);
        
        // create window with message                
        var message = document.createElement('TD');                       
        message.setAttribute('colSpan', 6)
        
        message.className = 'messageWindow';    
        message.innerHTML =  res.value;

        row.appendChild(message);
    }
    
    // hide loading animation
    firstCell.style.display = 'none';
}

/********************************************
  Reportajes
********************************************/
function ReportajeReader() {     
    this.position = 0;
    this.lastid = 0;
    this.canmove = true;
    
    // Main callback function
    this.callback = function(res) {
        if (FinishAJAXMethod(res))
        {
            // We check if we did hit the end of reports
            if (this.lastid == res.value.Rows[0]['Id'])
            {                
                this.position--;
                this.canmove = false;
                $('ReportajesLoader').style.display = 'none';
                return;
            }
            // Otherwise fill details;
            
            $('ReportajeTitulo').innerHTML = res.value.Rows[0]['Titulo'];
            $('ReportajeTexto').innerHTML = res.value.Rows[0]['DescripcionBreve'];
            $('ReportajeImagen').src = 'Data/Reportajes/TN_Big/' + res.value.Rows[0]['Imagen'];
            $('ReportajeEnlace').href = 'Reportajes/'+  res.value.Rows[0]['Titulo'] + '/' + res.value.Rows[0]['Id'];
            $('ReportajeEnlace2').href = 'Reportajes/'+  res.value.Rows[0]['Titulo'] + '/' + res.value.Rows[0]['Id'];

            
            this.lastid = res.value.Rows[0]['Id'];
            
            // Hide loader
            $('ReportajesLoader').style.display = 'none';            
        }    
    };
    this.Left = function() {    
        // Call callback function
        if (this.position > 0)
        {
            ShowReportajeLoader();
            Controls_NoticiasPreviewControl.GetReportaje(--this.position, this.callback.bind(this));
            this.canmove = true;
        }
    };
    this.Right = function() {   
        if (this.canmove)
        {   
            ShowReportajeLoader();
            Controls_NoticiasPreviewControl.GetReportaje(++this.position, this.callback.bind(this));
        }
    };    
}

function ShowReportajeLoader()
{
    var reportajeImagen = $('ReportajeImagen');
    var reportajeLoader = $('ReportajesLoader');
    reportajeLoader.style.height = reportajeImagen.height + 'px';
    
    // now find and loader image and set correct height
    for (var i=0; i<reportajeLoader.childNodes.length; i++)
    {
        if (reportajeLoader.childNodes[i].nodeName.toLowerCase() == 'img')
        {
            reportajeLoader.childNodes[i].style.marginTop = (Math.round(reportajeImagen.height / 2) - 25) + 'px';
            break;
        }
    }
    reportajeLoader.style.display = '';
}

/********************************************
  ENCUESTAS
********************************************/

function Vote(id, pollID, pollAnswerID, view, transform)
{
    var res = Controls_PollControl.Vote(pollID, pollAnswerID, view, transform)
    {
        if (FinishAJAXMethod(res))
        {
            $(id + '_Poll').innerHTML = res.value;
        }
    }
}

function ViewResults(id, pollID, view, transform)
{
    var res = Controls_PollControl.ViewResults(pollID, view, transform)
    {
        if (FinishAJAXMethod(res))
        {
            $(id + '_Poll').innerHTML = res.value;
        }
    }
}

/********************************************
  Image upload control control
********************************************/
function ChangeMainImage(id, category, fk)
{
    var res = Controls_ImageUploadControl.ChangeMainImage(id, category, fk);
}

/******************************
 COCHES NUEVOS
******************************/
function ParseNumber(number)
{
    // remove thousands separator
    var returnNumber = number.toString().replace('.','');
    
    // find grade
    var grade = returnNumber.length - returnNumber.indexOf(',') - 1;
    if (grade < returnNumber.length)
    {
        grade = Math.pow(10, grade); 
        returnNumber = returnNumber.replace(',','');
    }
    else grade = 1;
         
    // return results
    return parseFloat(returnNumber) / grade;
    
}

function Recalculate(ctrl)
{
    var control = $('PVP');
    var price = ParseNumber(ctrl.value);
    var precio = ParseNumber(control.innerHTML);
    var sum;
    
    if (ctrl.checked)
    {
        sum = precio + price;                
    }
    else
    {
        sum = precio - price;
    }
    
    
    control.innerHTML = FormatNumber(Math.round(sum * 100) / 100, 2, true);
}

/* statistics */
function ChangeStatisticsPanel(ctrl)
{
    ShowHide(null, 'results,coches,motos,recambios,camiones');
    ShowHide(ctrl.value);
}

/***************************************/
/* Comments */
/***************************************/
function ViewAllComments(id, categoria, idDetail)
{
    var comments = new ViewComments();
    comments.id = id;
    comments.categoria = categoria;
    comments.fk = idDetail;
    
    comments.go();
}

function ViewComments() {         
    this.categoria = '';      
    this.id = '';  
    this.fk = '';
    this.holder = null;
    
    // Main callback function
    this.callback = function(res) {
        if (FinishAJAXMethod(res))
        {            
            // now loop through collection and append all extras
            if (res.value != '')
            {
                var panel = $(this.id + 'Comentarios');
                var newDiv;
                var newSub;
                
                for (var i=2; i< res.value.Rows.length; i++)
                {
                    
                    newDiv = document.createElement('div');
                    newDiv.className = 'comentarioLine';
                    newSub = document.createElement('div');
                    newSub.className = 'comentarioTitle';
                    newSub.innerHTML = res.value.Rows[i]['Nombre'] + ' ' + res.value.Rows[i]['Fecha'];
                    newDiv.appendChild(newSub);
                    newSub = document.createElement('div');
                    newSub.innerHTML = res.value.Rows[i]['Comentario'];
                    newDiv.appendChild(newSub);                    
                    panel.appendChild(newDiv);
                }
            }                    
        }   
        // hide loader            
        ShowHide('ComentariosLoaderOff');
        ShowHide('ComentariosLoaderOn');     
    };
    this.go = function() {                    
        // Call callback function
        ShowHide('ComentariosLoaderOn');
        ShowHide('ComentariosLoaderOff');
        Controls_ComentarioControl.ShowAllComments(this.categoria, this.fk, this.callback.bind(this));
    };
}

//**** CALCULATOR **********//
function ClearCalculator()
{
	$('Precio').value = '';
	$('Plazo').value = '';
	$('CalculadoraResult').innerHTML = '0 €';
}

function CalculatorGetPrice()
{
    if ($('thePrice') && ($('thePrice').value != '0') )
    {
	    $('Precio').value = $('thePrice').value;
	    $('Plazo').value = '60';
	    CalculateCalculator();
	}
	else
	{
	    $('Calculadora').style.display = 'none';	    
	}
}

function CalculateCalculator()
{
    var precio = parseInt($('Precio').value);
    var plazo = parseInt($('Plazo').value);
    
    if (isNaN(precio) || isNaN(plazo))
    {
        $('CalculadoraResult').innerHTML = 'Error';
    }
    else
    {	    
        $('CalculadoraResult').innerHTML = Math.round(precio / plazo * 1.08) + ' €';
    }
}

  /**** CATALOG LIST RH ***/
  function showCatalogTip(elem, url, id)
  {      
	  var cssHolder = $('cssHolder');
	  if (cssHolder.href.indexOf('catalog-icons') == -1)
	    return;
	   
	  var el = elem; 
	  var tipElement = $('tipMsg');
		 
	  var iX, iY;
	  iX = 0;
	  iY = 0;

	  for(; el; el = el.offsetParent)
	  {
		iX += el.offsetLeft || 0;
	 	iY += el.offsetTop || 0;
	  }

	  tipElement.innerHTML = $('TipContent' + id).innerHTML;
	  tipElement.style.top = iY + 'px';
	  tipElement.style.left = iX + 'px';
	  tipElement.style.visibility = 'visible';
	  tipElement.onclick = function () {window.location = applicationRoot + url};	 	  
  }

  function hideTip(event)
  {
	  var tipElement = $('tipMsg');
	  var current, related;

      if (window.event) 
      {
        current = tipElement;
        related = window.event.toElement;        
      }
      else 
      {
        current = event.currentTarget;
        related = event.relatedTarget;
      }

      if (current != related && !contains(current, related))
	      tipElement.style.visibility = 'hidden';
  }
  
  function contains(a, b)
  {
     // Return true if node a contains node b.
     while (b.parentNode)
       if ((b = b.parentNode) == a)
          return true;
     return false;
  }
  
  
function showSellerPhone(id)
{
    $('hiddenPhone').style.display = 'none';
    $('showedPhone').style.display = 'block';    
    var res = CommonAJAX.UpdatePhone(id);
}

function RunFoo(object, embed)
{
//This player starts sounding
//    document.write('<object id="pruebaVideoFlan" width="287" height="270" align="middle" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">\n');
//    document.write('<param value="http://www.supermotortv.com/player400.swf" name="movie" />\n');
//    document.write('<param value="high" name="quality" />\n');
//    document.write('<param value="#ffffff" name="bgcolor" />\n');
//    document.write('<param value="peli=' + object + '" name="FlashVars" />\n');
//    document.write('<embed width="287" height="270" align="middle" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" name="pruebaVideoFlan" bgcolor="#DBE1E4" quality="high" flashvars="peli=' + embed + '" src="http://www.supermotortv.com/player200.swf" wmode="transparent" />');
//    document.write('</object>\n');
    //This player starts muted
    document.write('<object data="http://www.supermotortv.com/player200.swf" type="application/x-shockwave-flash" width="287" height="270" align="middle">\n');
    document.write('<param name="allowScriptAccess" value="sameDomain" />\n');
    document.write('<param value="http://www.supermotortv.com/player200.swf" name="movie" />\n');
    document.write('<param value="high" name="quality" />\n');
    document.write('<param value="#ffffff" name="bgcolor" />\n');
    document.write('<param value="opaque" name="wmode" />\n');  
    document.write('<param value="peli=' + object + '" name="FlashVars" />\n');
    document.write('</object>\n');
}


/**** Register user ****/
function ShowEmailCheck(ctrl)
{
    $('SelectorId').style.display = 'none';
    
    var val = ctrl.value.toLowerCase();    
    if (val == 'concesionario' || val == 'multimarca')
    {
        $('SelectorId').style.display = '';
    }
}

function SubmitForwarder(e, c, m)
{
    var kod;
    if (!e) var e = window.event;
    if (e.keyCode) kod = e.keyCode;
    if (kod == 13)
    {
        eval (m);
        var s = document.getElementById(c);
        if (s)
        {
            //setTimeout(m,1);            
            var f = document.forms[0];
            var h = document.createElement("INPUT");
            h.type = "hidden";
            h.name = s.name;
            h.value = s.value;            
            f.appendChild(h);
            f.submit();
            
        }
        else
        {
            alert("Submit element not found");
        }
        return false;
       
    }
    return true;
}


//function ShowTooltipsLife(id){
//$(id).style.display = 'inline';
//}

//function NoShowTooltipsLife(id){
//$(id).style.display = 'none';
//}

function printDetail(tipo, id, ficha)
{
    var res = Controls_PrintControl.Print(tipo, id, ficha);
}
