var context = "/fp";
//var context ="/opobusca";
var context = "";
function listarPaises() {
    $('#comboProvinciasAjax').html('<select class="campo_fijo_cupon_2"><option value="-1"> Cargando ...</option></select>');
    $.ajax({
        url: context+"/paises-ajax.action",
        cache: true,
        success: function(html){
            $('#comboPaisesAjax').html(html);
        }
    });
}

function listarProvincias() {
    $('#comboZonasAjax').html('<select class="campo_fijo_cupon_2"><option value="-1"> Cargando ...</option></select>');
        $.ajax({
        url: context+"/zonas-ajax.action",
        cache: true,
        success: function(html){
            $('#comboZonasAjax').html(html);
        }
    });    
}

function listarEstudios() {
    $('#comboEstudiosAjax').html('<select class="campo_fijo_cupon_2"><option value="-1"> Cargando ...</option></select>');
    $.ajax({
        url: context+"/cargarEstudios.action",
        cache: true,
        success: function(html){
            $('#comboEstudiosAjax').html(html);
        }
    });
}

function listarEdades() {
    $('#comboEdadAjax').html('<select class="campo_fijo_cupon_2"><option value="-1"> Cargando ...</option></select>');
    $.ajax({
        url: context+"/cargarEdades.action",
        cache: true,
        success: function(html){
            $('#comboEdadAjax').html(html);
        }
    });
}

/*Carga automática de combos de la página de cupón*/
if(document.getElementById('comboProvinciasAjax') != null) {
    listarProvincias();
}

if(document.getElementById('comboPaisesAjax') != null) {
    listarPaises();
}

if(document.getElementById('comboEstudiosAjax') != null) {
    listarEstudios();
}

if(document.getElementById('comboEdadAjax') != null) {
    listarEdades();
}
/* Fin de carga automática de combos de la página de cupón*/
/** Listar poblaciones */
function listarPoblaciones(provinciaId) {
    $('#comboPoblacionesDiv').html('<select class="campo_fijo_cupon_2"><option value="-1"> Cargando ...</option></select>');
    $("#cajaPoblaciones").slideDown("slow");  
    $.ajax({
        url: context+"/poblaciones-ajax.action?id="+ provinciaId,
        cache: true,
        success: function(html){
            $('#comboPoblacionesDiv').html(html);
        }
    });
    listarCP(-1);
}
/** Listar códigos postales */
function listarCP(poblacionId) {
    $('#comboCPDiv').html('<select class="campo_fijo_cupon_2"><option value="-1"> Cargando ...</option></select>');
    $("#cajaCP").slideDown("slow");
    $.ajax({
        url: context+"/cp-ajax.action?id="+ poblacionId,
        cache: true,
        success: function(html){
            $('#comboCPDiv').html(html);
        }
    });
}

/** Buscar en el buscador de noticias */
function buscar(formularioId) {
    formulario = document.getElementById(formularioId);
    if (formulario.q.value == '') {
        alert("Debes introducir algún criterio de búsqueda");
        return false;
    }
    else {
        formulario.submit();
        return true;
    }
}

/** Enviar formulario */
function enviarForm(id) {
    var form = document.getElementById(id);
    form.submit();
}

/** Cargar el resultado de una llamada en un div*/
function loadAjax(funcion, divId) {
//    divHeight = $('#'+divId).height();
//    $('#'+divId).attr("style", "height: "+divHeight+"px; background-color: #EDEDED");
//    $('#'+divId).html("");
    $.ajax({
        url: funcion,
        cache: true,
        success: function(html){
            $('#'+divId).html(html);
            //$('#'+divId).attr("style", "");
        }
    });
    
}

/** Cargar el resultado de una llamada en un div*/
function submitAjax(formId, divId) {
    var action = $('#'+formId).attr('action');
    var data = $('#'+formId).serialize();
    alert(action + '?' + data);
    $.ajax({
        url: action + '?' + data,
        cache: true,
        success: function(html){
            $('#'+divId).html(html);
        }
    });
}

/** validador de la busqueda **/
function validarBusqueda(formulario) {
    if (formulario.tagsBuscador.value == '') {
        alert("Debes introducir algún criterio de búsqueda");
        return false;
    } else {
        return true;
    }
}
function busquedaAutomatica(){
    var formularioBuscador = document.getElementById('formularioBuscador');
    formularioBuscador.submit()
}
function nodoOrientador(nodoId){
    $('#organizador').html("<p>Cargando...</p><div style='margin-top: 20px; text-align: center'><img src='images/load-orientador.gif' align='middle'></div>");
    $.ajax({
        url: context+"/orientador-ajax.action?id=" + nodoId,
        cache: false,
        success: function(html){
            $('#organizador').html(html);
        }
    });
}
//-- newsletter deprecated
function validarEmail(valor) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
        return (true)
    } else {
        alert("Email no valido.\nPor favor, revisa este dato para poder recibir nuestro boletín de noticias.");
        return (false);
    }
}
function getNewsletter(email) {
    if (validarEmail(email) == true){
        $('#divNewsletter').html('<div class="newsletter">Enviando...<br/><br/></div>');
        $.ajax({
            url: context+"/getNewsletter.action?emailNewsletter=" + email,
            cache: false,
            success: function(html){
                $('#divNewsletter').html(html);
            }
        });
    }
}
function cambiaweb(){
    if (document.f.pais.value == "portugal") {
        window.open("http://www.masterd.pt");
    } else if (document.f.pais.value == "grecia") {
        window.open("http://www.masterd.gr");
    } else if (document.f.pais.value == "brasil") {
        window.open("http://www.masterd.com.br");
    } else if (document.f.pais.value == "china") {
        window.open("http://www.masterd.cn");
    } else{
        document.location.href="http://www.masterd.es";
    }
}

function selected(obj){
    if(document.getElementById('menu') != null) {
        var lilist = document.getElementById('menu');
        var alist = lilist.getElementsByTagName('a');
        for (i=0; i<alist.length; i++ )
        {
            alist[i].className="";
        }
    }
    obj.className="seleccionado";
}

function unselected(obj){
    if(document.getElementById('menu') != null) {
        var lilist = document.getElementById('menu');
        var alist = lilist.getElementsByTagName('a');
        for (i=0; i<alist.length; i++ ) {
            alist[i].className="";
        }
    }
    if(document.getElementById("default") != null ){
        document.getElementById("default").className = "seleccionado";
    }
}

function validarNacionalidad(){
    var nacionalidadId = document.getElementById("cupon_comboNacionalidadId").value;
    if(nacionalidadId != 90){
        $("#divDni").slideDown(500);
    }else{
        $("#divDni").slideUp(500);
    }
}

/*
 * Cupon fijo en pantalla, se desplaza según se va haciendo scroll
 */
var topCupon;
var leftCupon;
var heigthCupon;
var topFoot;
var alturaPie;
var anchoPantalla;
var altoPantalla;
var desplazamientoCuponActivo = false;
function scrollCupon(y){
    // SI la pantalla es muy pequeña, no hacemos el scroll
    if(anchoPantalla > 1000 && altoPantalla > 600){
        //alert('Scroll de cupon,  heigthCupon: ' + heigthCupon + ' topFoot: '  + topFoot + " top: " + top);
        if ( (y >= topCupon) && ( (y + heigthCupon) < topFoot ) ) {
            // Zona intermedia
            $('#cupon-right').addClass('fixed');
            $('#cupon-right').removeClass('fixed-bottom');
            $('#cupon-right').css("top", 0);
        } else if(y < topCupon){
            // Cabecera
            $('#cupon-right').css("top", '');
            $('#cupon-right').removeClass('fixed');
            $('#cupon-right').removeClass('fixed-bottom');
        }else{
            // Pie
            $('#cupon-right').removeClass('fixed');
            $('#cupon-right').addClass('fixed-bottom');
            $('#cupon-right').css("top", alturaPie);
        }
    }
}
function resizeWindow(y){
    //Si hace resize volvemos a calcular los valores de left
    $('#cupon-right').removeClass('fixed');
    $('#cupon-right').removeClass('fixed-bottom');
    leftCupon = $('#cupon-right').offset().left;
    $('#cupon-right').css("left", leftCupon);
    anchoPantalla = $(window).width();
    altoPantalla = $(window).height();
    scrollCupon(y);
}
$(function () {
    if(document.getElementById('cupon-right') != null && desplazamientoCuponActivo) {
        var msie6 = $.browser == 'msie' && $.browser.version < 7;
        if (!msie6) {
            // Inicializamos los valores fijos
            topCupon = $('#cupon-right').offset().top - parseFloat($('#cupon-right').css('margin-top').replace(/auto/, 0));
            heigthCupon = $('#cupon-right').height();
            topFoot = $('#ft').offset().top - parseFloat($('#ft').css('margin-top').replace(/auto/, 0));
            alturaPie = topFoot - heigthCupon;
            //Estos pueden cambiar por redimensionar la pantalla
            anchoPantalla = $(window).width();
            altoPantalla = $(window).height();
            leftCupon = $('#cupon-right').offset().left;
            $('#cupon-right').css("left", leftCupon);
            $(window).scroll(function (event) {
                $(this).stop();
                scrollCupon($(this).scrollTop());
            });
            $(window).resize(function(event) {
                resizeWindow($(this).scrollTop());
            });
        }
    }
});
