/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function wxLogin(ajax, div, dir){

    var REDIRECT    = -1;
    var UPDATE_BOX  = -2;
    var EXECUTE     = -3;

    var obj = this; // Objet    

	this.ajax   = ajax;
	this.div    = div;
    this.dir    = dir;

    this.extra = {};

    this.busy = true;

    this.action = UPDATE_BOX;

    // ====================================================
    // INICIALIZA
    // ====================================================
    this.init = function(){

        var html = '<div class="jqmWindow" id="loginBox"><img src="http://www.victoriacwb.com.br/2009/images/ajax-loader.gif"><br>Carregando...</div>';
        html += '<div id="box">Carregando...</div>';

        $('#' + obj.div).html(html);

        // Configura jqmodal        
        $('#' + obj.div + ' #loginBox').jqm({modal:true});

        // Obtem Tela inicial
		$.ajaxSetup({async: true, cache: false});
		var arg = this.extra;
		arg.action = 'init';
		$.post(this.ajax, arg, obj.init2);

        
    }

    this.init2 = function(xml){

        $('#' + obj.div + ' #box').html(xml);
        obj.startEvents();
    }

    // ====================================================
    // CARREGA JANELA DE LOGIN
    // ====================================================
    this.openLoginBox = function(){
        $('#' + obj.div + ' #loginBox').html('<div align="center"><img src="http://www.victoriacwb.com.br/2009/images/ajax-loader.gif"><br>Carregando...</div>');
        $('#' + obj.div + ' #loginBox').jqmShow();

        // Obtem Tela inicial
		$.ajaxSetup({async: true, cache: false});
		var arg = this.extra;
		arg.action = 'getLogin';
		$.post(this.ajax, arg, obj.openLoginBox2);
        
    }
    
    this.openLoginBox2 = function(xml){

        $('#' + obj.div + ' #loginBox').html(xml);

        $('#' + obj.div + ' #loginBox').jqmHide();
        $('#' + obj.div + ' #loginBox').jqmShow();

        // Inicia Eventos
        obj.startEvents();
        
    }

    // ====================================================
    // ENVIA OS DADOS DE LOGIN PELO FORMULARIO
    // ====================================================
    this.sendLogin = function(login, password){

        // Envia formulario
		$.ajaxSetup({async: true, cache: false});
		var arg = this.extra;
		arg.action = 'sendLogin';
        arg.login = $("#" + obj.div + " #field-login").attr('value');
        arg.password = $("#" + obj.div + " #field-password").attr('value');

        $('#' + obj.div + ' #msg-box').html('<div>Enviando dados...  <img src="http://www.victoriacwb.com.br/2009/images/ajax-loader2.gif"></div>');
		$.post(this.ajax, arg, obj.sendLogin2);

    }

    this.sendLogin2 = function(xml){

        //------------- VERIFICAÇÃO DE ERRO ----------------------
        if ($(xml).find("erro").text()){
            alert($(xml).find("erro_desc").text());
            return false;
        }
        // ---------------------------------------------------------

        var msg = $(xml).find("msg").text();
        var login = $(xml).find("login").text();
        

        if (login){
            $('#' + obj.div + ' #loginBox').jqmHide();


             switch (obj.action) {
                case UPDATE_BOX:                   

                    // Obtem Tela inicial
                    $.ajaxSetup({async: true, cache: false});
                    var arg = obj.extra;
                    arg.action = 'init';
                    $.post(obj.ajax, arg, obj.init2);

                    break;

                case REDIRECT:

                    if (obj.new_window) {
                        obj.startEvents();
                        window.open(obj.url);
                    }
                    else {
                        window.location = obj.url;
                    }

                    break;

                case EXECUTE:

                    // Obtem Tela inicial
                    $.ajaxSetup({async: true, cache: false});
                    var arg = obj.extra;
                    arg.action = 'init';
                    $.post(obj.ajax, arg, obj.init2);

                    obj.execute_function();                    

                    break;
                    
                default:
                    break;
            }

        }else{

            $('#' + obj.div + ' #msg-box').html(msg);
            obj.startEvents();
            
        }
        
        
    }

    // ====================================================
    // LOGOUT
    // ====================================================
    this.logout = function(){

            // Obtem Tela inicial
            $.ajaxSetup({async: true, cache: false});
            var arg = this.extra;
            arg.action = 'logout';
            $.post(this.ajax, arg, obj.logout2);
        
    }

    this.logout2 = function(xml){

        //------------- VERIFICAÇÃO DE ERRO ----------------------
        if ($(xml).find("erro").text()){
            alert($(xml).find("erro_desc").text());
            return false;
        }
        // ---------------------------------------------------------

        // Obtem Tela inicial
        $.ajaxSetup({async: true, cache: false});
        var arg = obj.extra;
        arg.action = 'init';
        $.post(obj.ajax, arg, obj.init2);
        
    }
    // ====================================================
    // LINK PARA ALGUMA PÁGINA
    // ====================================================
    this.link = function(url, new_window){  // TODO: testar.

        if (!this.busy){
            
            obj.new_window = (!new_window) ? false : new_window;
            obj.action = REDIRECT;
            obj.url = url;

            obj.stopEvents();

            // Obtem Tela inicial
            $.ajaxSetup({async: true, cache: false});
            var arg = this.extra;
            arg.action = 'verifyLogin';
            $.post(this.ajax, arg, obj.link2);
            
        }
        
    }
    this.link2 = function(xml){

        //------------- VERIFICAÇÃO DE ERRO ----------------------
        if ($(xml).find("erro").text()){
            alert($(xml).find("erro_desc").text());
            return false;
        }
        // ---------------------------------------------------------
        
        var login = $(xml).find("login").text();        

        if (login){
            if (obj.new_window) {

                obj.startEvents();
                window.open(obj.url);

            } else {

                window.location = obj.url;

            }

        }else{

            obj.openLoginBox();

        }
    
    }
    // ====================================================
    // Executa alguma função se estiver logado
    // ====================================================
    this.execute = function(execute_function){
            
        if (!this.busy){
            $('#' + obj.div + ' #loginBox').html('<div align="center"><img src="http://www.victoriacwb.com.br/2009/images/ajax-loader.gif"><br>Carregando...</div>');
            $('#' + obj.div + ' #loginBox').jqmShow();

            obj.action = EXECUTE;
            obj.execute_function = execute_function;

            obj.stopEvents();

            // Obtem Tela inicial
            $.ajaxSetup({async: true, cache: false});
            var arg = this.extra;
            arg.action = 'verifyLogin';
            $.post(this.ajax, arg, obj.execute2);

        }
        
    }

    this.execute2 = function(xml){
        
        $('#' + obj.div + ' #loginBox').jqmHide();

        //------------- VERIFICAÇÃO DE ERRO ----------------------
        if ($(xml).find("erro").text()){
            alert($(xml).find("erro_desc").text());
            return false;
        }
        // ---------------------------------------------------------

        var login = $(xml).find("login").text();

        if (login){
            
            obj.execute_function();            
            obj.startEvents();

        }else{

            obj.openLoginBox();

        }


    }
    // ====================================================
    // EVENTOS
    // ====================================================

    this.startEvents = function(){
        this.busy = false;
		// -------------------------------------------------------------
		// ----------- LOGIN -----------------------
		// -------------------------------------------------------------
		$("#" + this.div + " #btn-login").bind('click', function(){
            obj.stopEvents();

            obj.openLoginBox();
            

		});

		// -------------------------------------------------------------
		// ----------- SEND DATA -----------------------
		// -------------------------------------------------------------

        $("#" + this.div + " #field-password").keypress(function (e){

            if (e.which == 13){
                obj.stopEvents();
                obj.sendLogin();
            }            
        });

        $("#" + this.div + " #field-login").keypress(function (e){

            if (e.which == 13){
                obj.stopEvents();
                obj.sendLogin();
            }
        });
        

         $("#" + this.div + " #btn-send").bind('click', function(){
            obj.stopEvents();
            obj.sendLogin();
             
         });
		// -------------------------------------------------------------
		// ----------- LOGOUT -----------------------
		// -------------------------------------------------------------
         $("#" + this.div + " #btn-logout").bind('click', function(){
            obj.stopEvents();
            obj.logout();

         });

		

    }

    this.stopEvents = function(){
        this.busy = true;

        //alert('parando');
        $("#" + this.div + " #btn-login").unbind();
        $("#" + this.div + " #btn-send").unbind();
        $("#" + this.div + " #field-password").unbind();

    }
}
