$(function () {


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


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

    });


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

    // Dialog Link
    $('#rastrear').click(function () {

        //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 = $("#frmConsultarAprobacion").serialize();

        $('#ResultadoAprobaciones').html('<h3>Status Aprobacion</h3>')
		.append("<div id='aprobaciones_result' style='z-index:9999;'><img id='checkmark' src='http://www.angulo-lopez.com/img/procesando.gif' /><br/></div>");

        //alert('Iniciando llamada a Ajax');
        $.ajax({
            //dataType: "json",
            async: true,
            data: dataString,
            type: "POST",
            url: "/webservice2.php?t=a",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('Se ha presentado un error (' + textStatus + '). Por favor intente de nuevo.');
                $('#ResultadoAprobaciones').dialog("close");

            }, // esta cierra la funcion de error 

            success: function (xml, textStatus) {

                //var cantidad = $('GUIA', xml).length;
                //var origen = comprobarOrigen(xml);
                var subtitulo = "Se ha obtenido el siguiente resultado de la base de datos: "; 
                //alert(xml.length);
                var contenido = xml;
                //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 {//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
//                    subtitulo = (origen) ? "<p>Informacion de Rastreo disponible:</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>";
//                    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>";
//                    var obj = $('vwTRACK', xml);
//                    for (i = 0; i < obj.length; i++) {
//                        if (origen) {
//                            contenido += "<tr><td>" + $('DESTINONOMBRE', obj).eq(i).text() + "</td><td>" + $('FECHA', obj).eq(i).text() + "</td><td>"; 
//				if (tipo=="NotaRecoleccion" && i==0) {contenido += '<i>Guia Asignada: ' + $('ORIGEN', obj).eq(i).text() + "-" + $('GUIA', obj).eq(i).text() + '</i><BR/>';}
//				contenido += $('STATUS', obj).eq(i).text() + "</td></tr>";
//                        } else {
//                            if (($('ORIGEN', obj).eq(i).text() == $('ORIGEN', obj).eq(i + 1).text() && $('GUIA', obj).eq(i).text() == $('GUIA', obj).eq(i + 1).text()) == false) {
//                                contenido += "<tr><td  class='ui-state-hover'><code style='cursor:pointer;'>" + $('ORIGEN', obj).eq(i).text() + "-" + $('GUIA', obj).eq(i).text()
//									+ "</code></td><td>" + $('ORIGENNOMBRE', obj).eq(i).text() + "</td><td>" + $('SERVICIO', obj).eq(i).text() + "</td></tr>";
//                            }
//                        }
//
//
//                    } //fin del for i
//
//                    contenido += "</table>";
//                } // fin de cantidad multi
                $('#aprobaciones_result').html(subtitulo)
				.hide()
				.fadeIn(1000, function () {
				    $('#aprobaciones_result').append(contenido);
				    $('#aprobaciones_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");

        $('#ResultadoAprobaciones').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 = $('ORIGEN:first', xmlO).text();
        var chequear = $('ORIGEN:last', xmlO).text();
        if (origen != chequear) { return false; } else { return true; }
    }


});
