$(document).ready(function(){

    //Desplegamos todos los menus (01-09-2009)
    $("#ctl00_PHBody_Menu1_divMenu dl dt").each(function(){        
        expandirMenu($(this).attr("id"));
    });
    //
    
    ShowTooltip = function(e)
        {
	        var text = $(this).next('.show-tooltip-text');
	        if (text.attr('class') != 'show-tooltip-text')
		        return false;

	        text.fadeIn()
		        .css('top', e.pageY)
		        .css('left', e.pageX+10);

	        return false;
        }
        HideTooltip = function(e)
        {
	        var text = $(this).next('.show-tooltip-text');
	        if (text.attr('class') != 'show-tooltip-text')
		        return false;

	        text.fadeOut();
        }

        SetupTooltips = function()
        {
	        $('.show-tooltip')
		        .each(function(){
			        $(this)
				        .after($('<span/>')
					        .attr('class', 'show-tooltip-text')
					        .html($(this).attr('title')))
				        .attr('title', '');
		        })
		        .hover(ShowTooltip, HideTooltip);
        }
        
    var error = ""; //Validaciones de formulario
    $(".submit").bind("click", function(e){
        var div = $(this).parents(".validable");        
		if (typeof filters == 'undefined') return;
	    $(div).find(":input, :radio, :checkbox").each(function(x,el){	        
	        if ($(el).attr("className") != 'undefined') {
	            $(el).siblings().removeClass("errorForm1");
		        $(el).removeClass("error");
	            $.each(new String($(el).attr("className")).split(" "), function(x, klass){
	                if ($.isFunction(filters[klass]))
	                    //Un campo no pasa el filtro, le añadimos clase="error" al elemento
	                    if (!filters[klass](el)){
	                        $(el).addClass("error");
	                        $(el).siblings().addClass("errorForm1");
	                    } 
	                });
	            }
	        });	        
		    if ($(this).parent().find(".error").size() > 0) {		        
		        //El formulario contiene errores
		        if($(div).attr('id') == "accesoPymes")
		        {		      
		            //El formulario de login contiene errores      
		            validarUsuario();
		        }
		        if($(div).attr('id') == "datosEmpresa")
		        {				            
		            //_AltaEmpresas.aspx
		            crearEmpresa1();
		        }
		        else if($(div).attr('id') == 'datosAdministrador')
		        {
		            //_AltaEmpresas.aspx
		            crearEmpresa2(); 
		        }
			    $.stop(e || window.event);			    
			    return false;
		    }else{
		        //El formulario no contiene errores
		        if($(div).attr('id') == "datosEmpresa")
		        {				            
		            //_AltaEmpresas.aspx
		            crearEmpresa1();
		        }
		        else if($(div).attr('id') == "accesoPymes")
		        {
		            //_PreHomePymes.aspx
                    $("#contenido").before(error);
		            validarUsuario();
		        }
		        else if($(div).attr('id') == "olvidoMail")
		        {
		            //_OlvidoClave.ascx
		            enviarMail();
		        }
		        else if($(div).attr('id') == "cambioMail")
		        {
		            //_CambioClave.ascx
		            cambiarClave();
		        }
		        else if($(div).attr('id') == 'datosAdministrador')
		        {
		            //_AltaEmpresas.aspx
		            //crearEmpresa2(); 
		        }
	        return false;
	    }
	});	
				
});
   
$.extend({
	stop: function(e){
        if (e.preventDefault) e.preventDefault();
        if (e.stopPropagation) e.stopPropagation();
    }
});

var filters = {
    requerido: function(el) { return ($(el).val() != '' && $(el).val() != -1); },
    email: function(el) { return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(el).val()); },                                 
    checkRequired: function(el) { return ($(el).attr("checked")); },
    nifcifnie: function(el){ return validar_nif_cif_nie($(el).val(), $('.validaTipoDocu').children().siblings().val()); },
    telefono: function(el){ return /^[0-9]*$/.test($(el).val()); }
};

function olvidoClave(){	    
    $("#contenido").slideUp("slow", function(){ $("#contenido").load("http://www.spanair.com/web/es-es/Empresas/Alta-Empresas/").slideDown("slow"); });
}

function cambioClave(){
    $("#contenido").slideUp("slow", function(){ $("#contenido").load("http://www.spanair.com/web/es-es/Empresas/Alta-Empresas/").slideDown("slow"); });
}
    
function pasar() {
    obj=document.getElementById('ctl00_PHBody_usuariosEmpresa');
    if (obj.selectedIndex==-1) return;
    for (i=0; opt=obj.options[i]; i++) {     
        if (opt.selected) {
            valor=opt.value; // almacenar value
            txt=obj.options[i].text; // almacenar el texto    	
            obj2=document.getElementById('ctl00_PHBody_usuariosAutorizados');        
            if (obj2.options[0] == '-') // si solo está la opción inicial borrarla
                obj2.options[0]=null;
            opc = new Option(txt,valor); 
            eval(obj2.options[obj2.options.length]=opc);         
            obj.options[i]=null; // borrar el item si está seleccionado
        }	    
    }
}
function quitar() {
    obj=document.getElementById('ctl00_PHBody_usuariosAutorizados');
    if (obj.selectedIndex==-1) return;
    for (i=0; opt=obj.options[i]; i++){
        if (opt.selected) {
            valor=opt.value; // almacenar value
            txt=obj.options[i].text; // almacenar el texto    	        
            obj2=document.getElementById('ctl00_PHBody_usuariosEmpresa');        
            if (obj2.options[0] == '-') // si solo está la opción inicial borrarla          
                obj2.options[0]=null;
            opc = new Option(txt,valor);
            eval(obj2.options[obj2.options.length]=opc);      
            obj.options[i]=null; // borrar el item si está seleccionado
        }	              
    }
}

function validar_nif_cif_nie(documento) 
{            
    documento = documento.toUpperCase();
	var temp=documento.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
 
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			return -1;
		}
         
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			posicion = documento.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni)
			{			   	
//			   	if(tipoDocumento == 1) return 1;
//			   	return -1;
                return 1;
			}
			else
			{				
				return -1;
			}
		}        
		//comprobacion de codigos tipo CIF		
		suma = parseInt(documento.substring(2,3))+parseInt(documento.substring(4,5))+parseInt(documento.substring(6,7));
		//suma = parseInt(documento[2])+parseInt(documento[4])+parseInt(documento[6]);		
		for (i = 1; i < 8; i += 2)
		{
			//temp1 = 2 * parseInt(documento[i]);
			temp1 = 2 * parseInt(documento.substring(i,i+1));
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(documento.substring(i,i+1));
			temp2 += '';
			temp2 = temp2.substring(1,2);
			if (temp2 == '')
			{
				temp2 = '0';
			}
 
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
 
		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp))
		{
			if (documento.substring(8,9) == String.fromCharCode(64 + n))
			{				
//				if(tipoDocumento == 1) return 1;
//				else return -1;
                return 1;
			}
			else
			{				
				return -1;
			}
		}
 
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
		{
			temp = n + '';
			if (documento.substring(8.9) == String.fromCharCode(64 + n) || documento.substring(8,9) == parseInt(temp.substring(temp.length-1, temp.length)))
			{				
//				if(tipoDocumento == 2) return 2;
//				else return -2;	
                return 2;			
			}
			else
			{				
				return -2;
			}
		}
 
		//comprobacion de NIEs		
		if (/^[T]{1}/.test(temp))		
		{
			if (documento.substring(8,9) == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
			{				
//				if(tipoDocumento == 3) return 3;
//				else return -3;	
                return 3;			
			}
			else
			{				
				return -3;
			}
		}
 
		//XYZ
		if (/^[XYZ]{1}/.test(temp))
		{			
			pos = str_replace(['X', 'Y', 'Z'], 0, ['0','1','2'], temp).substring(0, 8) % 23;
		
			if (documento.charAt(8) == cadenadni.substring(pos, pos + 1))
			{				
//				if(tipoDocumento == 3) return 3;
//				else return -3;		
                return 3;		
			}
			else
			{
				return -3;
			}
		}
		//formato desconocido (devolvemos true por si acaso)
		return 0;
	}
	
	return 0;
}

function str_replace(search, position, replace, subject) {

    var f = search, r = replace, s = subject, p = position;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        if (s[i]) {
        while (s[p] = s[p].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };

    return sa ? s : s[0];
    
}

function deshabilitaPage()
{
    //Desabilita todos los imputs, checkbox, radio, buttons de la pagina
    //Pendiente de revision (Alberto)
    //$(document).find(":input, :radio, :checkbox").each(function(){
    //    $(this).attr('disabled', true);
    //}); 
}

function habilitaPage()
{
    //Desabilita todos los imputs, checkbox, radio, buttons de la pagina
    //Pendiente de revision (Alberto)
    //$(document).find(":input, :radio, :checkbox").each(function(){
    //    $(this).attr('disabled', false);
    //}); 
}

var busName; //Variable para CalendarCustumdatepicker

function validarEmail(valor) {    
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(valor));
}

function redirectPymes()
{
    window.location.href = "http://www.spanair.com/web/es-es/Empresas/";
}

// Efecto acordeon tabla formularios
//$('.tablaEstadoVuelo table tr img').click(function(){
//    $(this).parent().toggleClass('select');
//    if($(this).parent().hasClass('select')){
//        $(this).attr('src','/Web1024/img/less-icon.gif');
//    }else{
//        $(this).attr('src','/Web1024/img/more-icon.gif');
//    }
//    $(this).parent().nextAll().each(function(){if($(this).is('td')){$(this).slideToggle(200);}else{return false;}});
//    return false;
//});

//******** FUNCION TRIM ********//
    function ltrim(s) { return s.replace(/^\s+/, ""); }
    function rtrim(s) { return s.replace(/\s+$/, ""); }
    function trim(s) { return rtrim(ltrim(s)); }
//******************************//