
var intervalo;
function cargarDialogo(enlace) {
    $('#dialogo_titulo').html('<h1>'+enlace.innerHTML+'</h1>');
    $('#dialogo_cont').addClass('secc').html('').load(enlace.href, function() {
        //$('#dialogo').fadeIn();
        $('.scrollbar').jScrollPane();
        if($('.slideshow').length) {
            intervalo = setInterval( "slideSwitch()", 3000);
        }
        $(this).removeClass('cargando');
        //$(this).dialog({height: 300, width: 800, position: [0, 90]});
    }).addClass('cargando');
    $('#dialogo').fadeIn();
    return false;
}
var enlaceItemActivo;
var seccion;
function cargarDialogoItem(enlace) {
    enlaceItemActivo = enlace;
    $('#dialogo_cont').html('').load(enlace.href, function() {
        $('.scrollbar').jScrollPane();
        $(this).removeClass('cargando');
        //$('#dialogo').fadeIn();
        //$(this).dialog({height: 300, width: 800, position: [0, 90]});
    }).addClass('cargando');
    if(!iniciado) {
        if(seccion == 14 ) {
            $('#dialogo').prepend($('<div id="anteriorsiguiente"><a onclick="cambiarItem(-1)" class="anterior"><span>Anterior</span></a> <a onclick="cambiarItem(1)" class="siguiente"><span>Siguiente</span></a></div>'));
        }
        iniciado = true;
    }
    $('#dialogo').fadeIn();
    return false;
}
function cambiarItem(direccion) {
    var enlace;
    if(direccion == 1) {
        enlace = enlaceItemActivo.parentNode.nextSibling ? enlaceItemActivo.parentNode.nextSibling : enlaceItemActivo.parentNode.parentNode.firstChild;
    }
    else {
        enlace = enlaceItemActivo.parentNode.previousSibling ? enlaceItemActivo.parentNode.previousSibling : enlaceItemActivo.parentNode.parentNode.lastChild;
    }
    cargarDialogoItem(enlace.firstChild);
}
function cerrarDialogo(dialogo) {
    if(intervalo) {
        clearInterval(intervalo);
    }
    $('#'+dialogo).fadeOut(500, function() {
        $('#dialogo_titulo').html('');
    });
}

var iniciado = false;
function cargarMapas(mapas) {
    if(!iniciado) {
        iniciado = true;
        var latLng;
        var zoom;
        for(var i = 0; i < mapas.length; i++) {
            latLng = mapas[i][0];
            zoom = mapas[i][1];

            var z = zoom || 16;
            var myLatlng = new google.maps.LatLng(latLng[0],latLng[1]);
            var myOptions = {
                zoom: z,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.HYBRID,// ROADMAP SATELLITE,
                mapTypeControl: false
            }
            var map = new google.maps.Map(document.getElementById("mapa"+i), myOptions);
            var marcador = new google.maps.Marker({
                position: myLatlng,
                map: map
            });
        }
    }
    $('#contenedor_mapa').fadeIn();
    return false;
}


function mostrarForm() {
    $('#contenedor_agendarVisita').fadeIn();
}

ValidacionCampo = {
	CAMPO_ERR_REQUERIDO: 1,
	CAMPO_ERR_TIPO_DATO: 2,
	CAMPO_ERR_VALOR_INCORRECTO: 3,
	CAMPO_ERR_LARGO_MINIMO: 4,
	CAMPO_ERR_LARGO_MAXIMO: 5,
	esEmail: function(str) {
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
};


function mostrarContactoForm(dir) {
    $('div.panel').hide();
    if(dir == -1) {

        $('#cv h2').show().addClass('disponible');
        $('#consultas h2').hide();

//        $('#cv .descripcion').hide();
//        $('#cv .formulario').hide();
//        $('#consultas .descripcion').hide();
//        $('#consultas .formulario').hide();
        $('#consultas').animate({width: 532, opacity: 0.8}, 1000, function() {
            $('#consultas div.panel').fadeIn();
            $(this).addClass('expand');
        });
        $('#cv').removeClass('expand').animate({width: 222, opacity: 1}, 1000);
    }
    else if(dir == 1) {
        $('#consultas h2').show().addClass('disponible');
        $('#cv h2').hide();
//        $('#consultas .descripcion').hide();
//        $('#consultas .formulario').hide();
//        $('#cv .descripcion').hide();
//        $('#cv .formulario').hide();
//        $('#consultas .descripcion').fadeOut();
        $('#cv').animate({width: 532, opacity: 0.8}, 1000, function() {
            $('#cv div.panel').fadeIn();
            $(this).addClass('expand');
        });
        $('#consultas').removeClass('expand').animate({width: 222, opacity: 1}, 1000);
    }
}
function mostrarContactoFormB(k,value) {
    k++
    /**/
	$('div.panel.activo').hide().removeClass('activo');
    $('div.panel:nth-child('+k+')').fadeIn().addClass('activo');
	/**/
    $('#lateral h2.activo').removeClass('activo');
    $('#lateral h2:nth-child('+k+')').addClass('activo');
	
	//$('#form_cto').get(0).asunto.value = value;
    return false;
}

function campoLabel(event, target) {
    var evt = window.event || event;
    //var campo = $(this);
    var campo = $(target);
    var req_str = campo.hasClass('req') ? ' *' : '';
    var valor = $.trim(campo.val());
    if(evt.type == 'focus' && valor == campo.attr('title')+req_str) {
        campo.val('');
        campo.removeClass('label');
    }
    else if(evt.type == 'blur' && valor == '') {
        campo.addClass('label');
        campo.val(campo.attr('title')+req_str);
    }
}
function actualizarValorSelect(selector) {
    //console.log(selector.options[selector.selectedIndex].text);
    selector.previousSibling.innerHTML = selector.options[selector.selectedIndex].text;  
}
function actualizarValorSelectCto(selector) {
    //console.log(selector.options[selector.selectedIndex].text);
	
	switch(selector.selectedIndex){
		case 2:
			window.document.location = '/es/visitenos';
		break;
		case 3:
			window.document.location = '/es/legado_de_familia#nuestro_equipo';
		break;
		default:
			$('#form_contacto').get(0).asunto.value = selector.options[selector.selectedIndex].text;
			selector.previousSibling.innerHTML = selector.options[selector.selectedIndex].text; 
		break;
	}
}

function mostrarCategorias(enlace) {
    var item = enlace.parentNode;
    //$('#subcat'+cat_superior).addClass('visible');
    $(item.parentNode).find('.activo').removeClass('activo');
    $(item).addClass('activo');
    var items = $('#items');
    items.html('').hide();
    var alto;
    if($(item).has('ul').length) {
        alto = 312;
        items.removeClass('borde')
    }
    else {
        alto = 274;
        cargarItems(enlace)
        items.addClass('borde')
    }
    $('#categorias').css('height', alto+'px');
    return false;
}

function cargarItems(enlace,llamado_desde) {
    $('#items').html('<img src="/img/load_ch.gif" alt="" />').load(enlace.href, function() {
		if ( llamado_desde != 'trade' ){
			$(this).find('a').click(function(event) {
				event.preventDefault();
				cargarDialogoItem(this);
			});
		}
        //$(this).dialog({height: 300, width: 800, position: [0, 90]});
    }).show();
    return false;
}

function cargarInternas(enlace) {
    //console.log(enlace);
    $('#internas_cont').load(enlace.href, function() {
        
    });
    return false;
}


var precargaImgs = new Array();
function precargaimgs() {
    var img;
    for(i = 0; i < precargaimgs.arguments.length; i++) {
        img = new Image();
        img.src = precargaimgs.arguments[i];
        precargaImgs.push(img);
    }
}


$(window).load(function () {
    precargaimgs('/img/load_ch.gif', '/img/load_gr.gif');//'/img/load_gr.gif');
});

/* Share */
function ventanaPop(enlace, w, h) {
    var ancho = w || 550;
    var alto = h || 450;
    var left = Math.round((screen.width/2) - (ancho/2)), top = Math.round((screen.height / 2) - (alto/2))
    window.open(enlace.href, 'share', 'left='+left+',top='+top+',width='+ancho+',height='+alto+'toolbar=no, personalbar=0, scrollbars=1');
    return false;
}

function compartir(event, enlace, w, h) {
    evento = event || window.event;
    evento.stopPropagation();
    return ventanaPop(enlace, w, h);
}

function agregarEvento(elemento, evento, funcion) {
	if(typeof elemento == "string")
		elemento = document.getElementById(elemento);
	if(elemento == null)
		return false;
	if(elemento.addEventListener)
		elemento.addEventListener(evento, funcion, true);
	else
		elemento["on" + evento] = funcion;
	return true;
}

/* Blog comentarios */
function recargarCaptcha(rand) {
    var img = document.getElementById('captcha');
    var time = new Date();
    img.src = '/captcha.php?ref='+rand+'&timestamp='+time.getTime();
}

function responder(id, el) {
    var elSup = el.parentNode;//.parentNode;
    var formulario = document.getElementById('formedicion');
    formulario.elements[0].value = id;
    formulario.style.display = 'none';
    var clon = formulario.cloneNode(true);
    if(formulario.parentNode.id == 'ag_comentario') {
        formulario.parentNode.className = '';
        formulario.parentNode.removeChild(formulario);
    }
    else
        formulario.parentNode.parentNode.removeChild(formulario.parentNode);
    var nAgComCont = document.createElement('div');
    //nAgComCont.className = 'ag_comentario';
    $(elSup).addClass('ag_comentario');
//    if(elSup.nextSibling != null)
//        elSup.parentNode.insertBefore(nAgComCont, elSup.nextSibling);
//    else
//        elSup.parentNode.appendChild(nAgComCont);
    elSup.appendChild(nAgComCont);

    nAgComCont.appendChild(clon);
    clon.elements[2].focus();
    el.href = '#respuesta_'+id;
    $(clon).effect("highlight", {color: 'grey'}, 2000);
    return false;
}

function cancelarResp(boton) {
    //var formulario = boton.form;
    var formulario = document.forms[1];
    formulario.reset();
    formulario.elements[0].value = '';
    if(formulario.parentNode.id != 'ag_comentario') {
        var div_ag_comentario = document.getElementById('ag_comentario');
        var clon = formulario.cloneNode(true);
        $(formulario.parentNode.parentNode).removeClass('ag_comentario');
        formulario.parentNode.parentNode.removeChild(formulario.parentNode);
        div_ag_comentario.className = 'ag_comentario';
        div_ag_comentario.appendChild(clon);
        $(div_ag_comentario).effect("highlight", {color: 'grey'}, 2000);
    }
    return false;
}

function enviarComentario(formulario) {
    document.getElementById('enviar').disabled = true;
    $('#respuesta').html('').hide().removeClass('error');
    var envioObj = {};
    for(var i = 0; i < formulario.elements.length; i++) {
        envioObj[formulario.elements[i].name] = formulario.elements[i].value;
    }

    $.post(formulario.action, envioObj,
        function(data) {
            var respuesta = $('#respuesta');
            var respuestaStr = '';
            if(data.exito) {
                document.forms[1].reset();
                respuestaStr = '<p>Su comentario ha sido enviado, una vez revisado será dado de alta.</p>';
                //cancelarResp();
            }
            else {
                respuesta.addClass('error');
                var bind = {verif: 'verif', 60: 'nombre', 61: 'email', 62: 'mensaje', 63: 'enrespuestaa'};
                for(var k in data.errores) {
                    $('#'+bind[k]).addClass('error').one('keyup', function( event ) {
                        $(this).removeClass('error');
                    });
                }
                respuestaStr += '<ul>';
                for(var i = 0; i < data.mensajes.length; i++) {
                    respuestaStr += '<li>'+data.mensajes[i].descripcion+'</li>';
                }
                respuestaStr += '<ul>';
            }

            respuesta.html('<div>'+respuestaStr+'</div>').show('blind', 500);
            document.getElementById('enviar').disabled = false;
            //console.log(data);
        },
        "json");
    return false;
}



/********************************************************/



var LOGIN_TEXTOS = {
    0: "Enviando solicitud...",
    1: "Su navegador debe aceptar cookies para este dominio.",
    2: "La respuesta del servidor no pudo ser interpretada correctamente.",
    202: "Accediendo.",
    400: "Existen errores en los campos.",
    401: "Los datos proporcionados no son correctos.",
    500: "Error interno del servidor",
    mensajes: {
        7: "Debe completar ambos campos para ingresar.",
        8: "Existen campos con formato incorrecto."
    },
    errores: {
        1: "Campo requerido",
        3: "No existe el usuario indicado.",
        4: "El campo debe contener al menos 4 caracteres.",
        5: "El campo excede la cantidad de caracteres permitida."
    },
    9: "El usuario no se encuentra habilitado."
};

function loginAcceso(formulario) {
	
    var loginaviso = $('#aviso');
    loginaviso.html('');
    formulario.elements[4].disabled = true;
    var usuario = $.trim(formulario.elements[1].value);
    var clave = $.trim(formulario.elements[2].value);
    if(usuario == '' || clave == '') {
        loginaviso.text(LOGIN_TEXTOS['mensajes'][7]);
        formulario.elements[4].disabled = false;
        if(usuario == '') {
            $(formulario.elements[1]).addClass('error').one('keyup', function() {
                $(this).removeClass('error');
            });
        }
        if(clave == '') {
            $(formulario.elements[2]).addClass('error').one('keyup', function() {
                $(this).removeClass('error');
            });
        }
        return false;
    }

    //var params = {};
    var datos = {};
    datos.usuario = usuario;
    datos.clave = clave;
    if(formulario.elements[3].type == 'checkbox' && formulario.elements[3].checked == true)
        datos.recordarme = 1;

    loginaviso.className = 'cargando';
    loginaviso.text(LOGIN_TEXTOS[0]);
    //enviarXHR('/api/login', loginRespuesta, datos, false, params);

    $.ajax({
        url: formulario.action,
        type: 'POST',
        data: datos,
        success: function(data, textStatus, jqXHR) {
            //console.groupCollapsed('success');
            //console.log(data, textStatus, jqXHR);
            //console.groupEnd();
			$('#dialogo_cont').load('/plantillas/trade_tools.php');
			//$('#dialogo_cont').load('trade_tools');
			//document.location = 'trade_tools';
        },
        complete: loginRespuesta
//        error: function(jqXHR, textStatus, errorThrown) {
//            //console.groupCollapsed('error');
//            //console.log(jqXHR, textStatus, errorThrown);
//            //console.groupEnd();
//        }
    });
//    var envio = new XMLHttpRequest();
//    envio.onreadystatechange = function() { // hand();
//        if(envio.readyState == 4)
//            loginRespuesta(envio);//, params eval(hand+"(pet, elAviso)");
//    };
//    envio.open("POST", formulario.action, true);
//    envio.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//    envio.setRequestHeader('Accept', 'application/json, application/*; q=0.1');
//    envio.send(datos.join("&"));
    return false;
}

function loginRespuesta(request) {
	/**/
	var loginaviso = document.getElementById('aviso');
    while(loginaviso.firstChild)
        loginaviso.removeChild(loginaviso.firstChild);
    if(LOGIN_TEXTOS[request.status] != null)
        loginaviso.appendChild(document.createTextNode(LOGIN_TEXTOS[request.status]));
    if(request.status == 202) {
        if(document.cookie == '') {
            loginaviso.firstChild.data = LOGIN_TEXTOS[1];
            deshabilitarFormLogin(false);
        }
        else {
            //alert('OK');
            //document.location.href = '/login?ref='+document.forms[0].elements[1].value;//encodeURIComponent()
        }
        return;
    }
    $('#envio input').attr('disabled', false);
    var respuesta;
    try {
        respuesta = eval('('+request.responseText+')');
    }
    catch(e) {
        loginaviso.firstChild.data = LOGIN_TEXTOS[2];
        return;
    }

    if(respuesta['errores']) {
        var i = 0;
        for(var campo_k in respuesta['errores']) {
            //console.log(campo_k, respuesta.errores[campo_k].cod);
            //agregarErrorCampo(campo_k, respuesta.errores[campo_k].cod);
            if(i == 0)
                document.forms[0][campo_k].focus();
            i++
        }
    }
	/**/
}

/********/
function setHashAction(pagina,hash){
	switch(hash){
		case '#nuestro_equipo':
			$('#dialogo_cont').html('').load('/es/equipo', function() {
				$('.scrollbar').jScrollPane();
				$(this).removeClass('cargando');
			}).addClass('cargando');
			$('#dialogo').fadeIn();
		break;
		default:
		break;
	}
}

/********************************************************/


function respuestaFormulario(jqXHR, textStatus) {
    //console.log(jqXHR, textStatus);
}

var global = {};
function enviarFormulario(formulario, handler) {


//    document.getElementById('enviar').disabled = true;
    var mensaje = $('#respuesta_'+formulario.id);
    mensaje.html('').removeClass('error');

    var envioObj = {};
    var valor;
    var campo;
    var validacionErrores = [];
    var error;
    for(var i = 0; i < formulario.elements.length; i++) {
        campo = $(formulario.elements[i]);
//        var campos = [
//            {nombre: 'FDname', tipo: 'string'},
//            {nombre: 'FDsurname', tipo: 'string'},
//            {nombre: 'FDemail', tipo: 'email'},
//            {nombre: 'FDphone', tipo: 'string'},
//            {nombre: 'FScomment', tipo: 'string'},
//            {nombre: 'aceptotyc', tipo: 'check'}
//        ];


        error = false;
        valor = $.trim(campo.val());
        envioObj[formulario.elements[i].name] = valor;
        if(formulario.elements[i].type == 'submit') {
            //formulario.elements[i].disabled = true;
            global.botonEnviar = formulario.elements[i];
        }
        else {
            if(campo.hasClass('req')) {
                if(valor ==  '' || valor == campo.attr('title')) {
                    //alert('Por favor, complete todos los campos.');
                    validacionErrores.push("· Debe completar el campo '"+campo.attr('title')+"'");
                    error = true;
                }
            }
            if(campo.hasClass('email')) {
                if(!validarEmail(valor)) {
                    validacionErrores.push("· Ingrese una casilla de e-mail válida en '"+campo.attr('title')+"'");
                    error = true;
                }
            }
        }
//        else if(campos[i].tipo == 'check') {
//            if(!campo.is(':checked')) {
//                validacionErrores.push("· Debe aceptar los Términos y Condiciones");
//                error = true;
//            }
//        }

        if(error) {
            campo.addClass('error').one('keyup', function( event ) {
                    $(this).removeClass('error');
                });
        }
    }
    if(validacionErrores.length > 0) {
        mensaje.html('<ul><li>'+validacionErrores.join('</li><li>')+'</li></ul>').addClass('error');
        return false;
    }
    mensaje.html('');
    //$.post(formulario.action, envioObj, handler, "json");




    $.ajax({
        url: formulario.action,
        type: 'POST',
        data: envioObj,
        success: function(data, textStatus, jqXHR) {
            //console.groupCollapsed('success');
            //console.log(data, textStatus, jqXHR);
            //console.groupEnd();
			actForm(data);
        },
        complete: function(jqXHR, textStatus) {
            //respuestaFormulario(jqXHR, textStatus);
           // botonEnviar.disabled = false;
            //console.groupCollapsed('complete');
            //console.log(jqXHR, textStatus);
            //console.groupEnd();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            //console.groupCollapsed('error');
            //console.log(jqXHR, textStatus, errorThrown);
            //console.groupEnd();
        }
    });
    return false;
}
function actForm(data){
	if (data.exito == false){
		$('.errores_info').html(data.mensajes[0].descripcion);
	}
	else{
		$('.errores_info').html('Gracias por contactarte con nosotros!');
	}
}


function validarEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return email.match(re)
}

/* Newsletter */
function altaNewsletter(formulario) {
    var email = $.trim(formulario.elements[0].value);
    if(email == '') {
        alert('vacio')
        return false;
    }
    else if(validarEmail(email) == null) {
        alert('inválido')
        return false;
    }
//console.log('post '+formulario.action)
    formulario.elements[1].disabled = true;
    $.post(formulario.action, {casilla: email},
        function(data) {
            document.forms[0].elements[1].disabled = false;
            document.forms[0].reset();   
        },
        "json");
    return false;
}

/***
    Simple jQuery Slideshow Script
    Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc.  Please link out to me if you like it :)
***/

function slideSwitch() {
    var active = $('.slideshow IMG.active');

    if (active.length == 0 )
		active = $('.slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var next =  active.next().length ? active.next() : $('.slideshow IMG:first');

    // uncomment the 3 lines below to pull the images in random order

    // var \$sibs  = \$active.siblings();
    // var rndNum = Math.floor(Math.random() * \$sibs.length );
    // var \$next  = $( \$sibs[ rndNum ] );

    active.addClass('last-active');

    next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            active.removeClass('active last-active');
        });
}


var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-10463328-1']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();
/******************'******/

