$(function () {
    /*desabilitamos el boton derecho (menu contextual)*/
    $(document).bind("contextmenu", function (e) {
        return false;
    });
    setInterval('cambiarFoto();', 10000);

    $('input.text-input').css({ backgroundColor: "#FFFFFF" });
    $('input.text-input').focus(function () {
        $(this).css({ backgroundColor: "#a1dcf2" });
    });


    $('input.text-input').blur(function () {
        $(this).css({ backgroundColor: "#FFFFFF" });
    });

    /* Red de Emergencia - Dialog			
    /*
	$('#REDEmergencia').html("<H3>Informacion Importante</H3><p>Notificamos a todos nuestros clientes del servicio TealcaBox que actualmente hay fuertes retrasos en las aerol&iacute;neas que transportan nuestra carga al pa&iacute;s y en las aduanas de Maiquet&iacute;a por el alto volumen de mercanc&iacute;a entrante. Esto ha demorado el ingreso de los paquetes de nuestros usuarios y estamos agotando todos los recursos para entregar sus paquetes a la brevedad posible . Adicionalmente informamos que el sitio web de Tealcabox ha cambiado su direcci&oacute;n a <a href='http://www.tealcabox.com.ve'>www.tealcabox.com.ve</a>. Pedimos disculpas por las molestias causadas y agradecemos su comprensi&oacute;n .</p><h4>TEALCA, el Aguila azul de tus encomiendas</h4>");
    $('#REDEmergencia').dialog({
        autoOpen: true,
        closeOnEscape: true, 
        position: 'top', 
        width: 510,
        bgiframe: true,
        modal: true,
        buttons: {
            "Aceptar": function () {
                $(this).dialog("close");
            } 				//fin del OK button
        } 				//fin del Dialog definition
    });
	*/
    // FIN DEL DIALOGO - REDEmergencia */

    /* Tracking Dialog			*/ 
    $('#trackingDialog').dialog({
        autoOpen: false,
        width: 650,
        bgiframe: true,
        modal: true,
        position: 'top', 
        buttons: {
            "Aceptar": function () {
                $(this).dialog("close");
            } 				/*fin del OK button*/
        } 				/*fin del Dialog definition*/
    });


    /* Dialog Link */
    $('#rastrear').click(function () {
		/*alert('entrando a rastrear....');*/
        /*aqui se debe hacer validacion del numero de guia*/
        var guia = $('#guia').val();
        var tipo = $("#tipoGuia").attr("checked")?"Guia":"NotaRecoleccion";
        /*Aqui se hace el llamado a la pag que busca la data*/
        var dataString = $("form").serialize();
		/*alert(dataString);*/
        $('#trackingDialog').html('<h3>Status ' + tipo + ': ' + guia + ' </h3>')
		.append("<div id='trackingDialog_result' style='z-index:9999;'><img id='checkmark' src='img/procesando.gif' /><br/></div>");
        $.ajax({
            dataType: "json",
            async: true,
            data: dataString,
            type: "POST",
            url: "wstealca.php",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('Se ha presentado un error (' + textStatus + '). Por favor intente de nuevo.');
                $('#trackingDialog').dialog("close");
            }, /* esta cierra la funcion de error --->  04123766472 Tte. Suarez Bomberos*/
            success: function (xml, textStatus) {
                var cantidad = 0;
				if (!(xml.length==null)){cantidad = xml.length;}
				if ((xml.length==null)&&(xml.GUIA!="")){cantidad = 1;}
                var subtitulo = "";
                var contenido = "";
                if (cantidad == 0) {/*este es el codigo que se ejecuta cuando no consiga guia*/
                    subtitulo = "<p><b>Informacion No Encontrada!</b></p>";
                    contenido = "<p><img id='checkmark' src='img/cancel.png' />Por favor verifique que esta utilizando el numero de guia correcto y no el numero de control de la factura y que ha seleccionado la opcion correcta (Guia o Nota de Recoleccion), o bien haga <a href='contacto.html'>click aqui para contactarnos</a> en referencia a su envio. Tambien puede comunicarse  con nuestro call center al 0-501-ENVIOS-1 (0-501-368467-1).</p>";
                } /*fin de cantidad 0*/
				else if (cantidad==1) {
					subtitulo = "<p>Informacion de Rastreo disponible para la guia " + xml.ORIGEN.trim() + "-" + xml.GUIA.trim() + " del servicio " + xml.SERVICIO.trim() + ":</p>" ;
                    contenido = "<table width='100%' border='0' id='trackingList'>";
                    contenido += "<tr class='ui-widget-header'><th>LUGAR</th><th>FECHA</th><th>STATUS</th></tr>";
					contenido += "<tr bgcolor='white'><td>" + xml.DESTINONOMBRE.trim() + "</td><td>";
					contenido += xml.FECHA.trim();
					contenido += "</td><td>"; 
					contenido += xml.STATUS.trim() + "</td></tr>";
				}  else {/*este es el codigo que se ejecuta cuando consiga MULTIPLES guias (si origen es true) hay q hacer una tabla con el detalle... si no con link a seleccionar cada una*/
					var origen = comprobarOrigen(xml);
                    subtitulo = (origen) ? "<p>Informacion de Rastreo disponible para la guia " + xml[0].GUIA.trim() + " del servicio " + xml[0].SERVICIO.trim() + ":</p>" : "<p>Se han conseguido varias guias que cumplen con este criterio. <b>Por favor <u>seleccione</u> la que corresponda y presione el boton de Rastrear:</b></p>";
                    /*if (tipo=="NotaRecoleccion") {contenido += '<p>El numero de Nota de Recoleccion suministrado corresponde al Numero de Guia Asignada:<strong> ' +  $('GUIA', obj).eq(0).text() + '</strong> originada en: <strong>' + $('ORIGEN', obj).eq(0).text() + '</strong> del Servicio: <strong>' + $('SERVICIO', obj).eq(0).text() + '</strong></p>';}*/
                    contenido = "<table width='100%' border='0' id='trackingList'>";
                    contenido += (origen) ? "<tr class='ui-widget-header'><th>LUGAR</th><th>FECHA</th><th>STATUS</th></tr>" : "<tr class='ui-widget-header'><th>Guia</th><th>Origen</th><th>Servicio</th></tr>";
                    for (i = 0; i < xml.length-1; i++) {
						var bgbolor = '';
						bgcolor =(i%2==0)?'white':'#F2F2F2'; 
                        if (origen) {
                            /*Primero validamos si la consulta es por NR y es la primera linea, entonces se crea una linea informativa del numero de guia*/
                            if (tipo=="NotaRecoleccion" && i==0) 
								{contenido += '<tr><td colspan=3 align=center bgcolor=#a1dcf2>Origen del Envio: <strong>' 
									+ xml[i].ORIGEN.trim() + '</strong><BR/>Numero de Guia Asignada:<strong> ' 
									+ xml[i].GUIA.trim() + '</strong><BR/>Servicio: <strong>' 
									+ xml[i].SERVICIO.trim() + '</strong></td></tr>';}
                            /*Detalle del Tracking*/
                            contenido += "<tr bgcolor='" + bgcolor + "'><td>" + xml[i].DESTINONOMBRE.trim() + "</td><td>";
							contenido += xml[i].FECHA.trim();
							contenido += "</td><td>"; 
							contenido += xml[i].STATUS.trim() + "</td></tr>";
                        } else {
                            if ((xml[i].ORIGEN.trim() == xml[i+1].ORIGEN.trim() && xml[i].GUIA.trim() == xml[i].GUIA.trim()) == false) {
                                contenido += "<tr><td  class='ui-state-hover'><code style='cursor:pointer;'>" + xml[i].ORIGEN.trim() + "-" + xml[i].GUIA.trim()
									+ "</code></td><td>" + (xml[i].ORIGENNOMBRE==null?'':xml[i].ORIGENNOMBRE.trim()) + "</td><td>" + xml[i].SERVICIO.trim() + "</td></tr>";
                            }
                        }
                    } /*fin del for i*/
                    contenido += "</table>";
                } /*fin de cantidad multi*/
                $('#trackingDialog_result').html(subtitulo).hide().fadeIn(1000, function () {
				    $('#trackingDialog_result').append(contenido);
				    $('#trackingDialog_result').animate({ height: 'show', opacity: 'show' }, 'slow');
				}); /* esta cierra el llamado a la funcion de fadeIn */
            }  /* esta cierra la funcion de success */
        });  /* esta cierra el llamado a .ajax */


        $('#trackingList').addClass("subtitulosfaq");
        $('#trackingDialog').dialog('open');
        return false;
    });


    /*hover states on the static widgets*/
	
    $('#dialog_link, ul#icons li').hover(

		function () { $(this).addClass('ui-state-hover'); },
		function () { $(this).removeClass('ui-state-hover'); }
	);


    /* Click en los numeros de guias*/
	
    $('code').live("click", function () { $('#guia').attr("value", $(this).html()); $('#trackingDialog').dialog("close"); $('#rastrear').click(); });

    /*Funcion para comprobar si todos los origenes son los mismos
    //Se usa para chequear si los distintos elementos recibidos son del mismo origen o no
    //Retorna true si todos los origenes son iguales */
    function comprobarOrigen(xmlO) {
        var origen = "";
		var chequear = "";
        if (!(xmlO.length==null)) {
			origen = xmlO[0].ORIGEN.trim();
			var chequear = xmlO[xmlO.length-1].ORIGEN.trim(); 
			}
        if (origen != chequear) { return false; } else { return true; }
    }


});
