﻿    var update_counter_timer;
    var carregar_perfil = false;
    //var update_posts_timer;
    //var update_sms24h_timer;


    function UpdateCounterSmsRetorno(data) {
        if (data.Valid) {
            if ($("#estatistica span").text() != data.TotalSms) {
                //TODO: Gerar animação do antigo para o atual;
                $("#estatistica span").text(data.TotalSms);
                
                UpdatePosts();
                UpdateSms24h();
            }
            
            if (!$("#estatistica").is(':visible')) {
                //$("#estatistica").fadeIn('slow');
                $("#estatistica").slideDown('slow');
            }
        }
    }

    function UpdateCounterSms() {
    
        jQuery.ajax({
            type: "GET",
            cache: false,
            url: "/v3/json/counter_sms.aspx",
            data: null,
            dataType: "json",
            beforeSend: function(){ clearTimeout(update_counter_timer); },
            success: function(data){ UpdateCounterSmsRetorno(data) },
            complete: function(){ update_counter_timer = setTimeout(UpdateCounterSms, 5000); },
            error: function(xhr, ajaxOptions, thrownError){  }
        });
    }
    


    function UpdateSms24hRetorno(data) {
        if (data.Valid) {
            $('#sparkline').sparkline(data.TotalSms, { type: 'bar', barColor: '#086DFF', height: 20, barWidth: 2, barSpacing: 1  });
        }
    }
    
    function UpdateSms24h() {
        
        jQuery.ajax({
            type: "GET",
            cache: false,
            url: "/v3/json/sms24h.aspx",
            data: null,
            dataType: "json",
            beforeSend: function(){ /* clearTimeout(update_sms24h_timer); */ },
            success: function(data){ UpdateSms24hRetorno(data) },
            complete: function(){ /* update_sms24h_timer = setTimeout(UpdateSms24h, 10000); */ },
            error: function(xhr, ajaxOptions, thrownError){  }
        });
    }


    
    function UpdatePostsRetorno(data) {
    
    }
    
    
    function UpdatePosts() {
        jQuery.ajax({
            type: "GET",
            cache: false,
            url: "/v3/json/posts.aspx",
            data: null,
            dataType: "json",
            beforeSend: function(){ /* clearTimeout(update_posts_timer); */ },
            success: function(data){ UpdatePostsRetorno(data) },
            complete: function(){ /* update_posts_timer = setTimeout(UpdatePosts, 15000); */ },
            error: function(xhr, ajaxOptions, thrownError){  }
        });
    
    }
    
    
    
    function GetProfile() {
    
        AtivaMobileAdd(true);
        ReativaMobileDel();

        jQuery.ajax({
            type: "GET",
            cache: false,
            url: "/v3/json/profile.aspx",
            data: null,
            dataType: "json",
            beforeSend: function(){ /* clearTimeout(update_posts_timer); */ },
            success: function(data){ GetProfileRetorno(data) },
            complete: function(){ /* update_posts_timer = setTimeout(UpdatePosts, 15000); */ },
            error: function(xhr, ajaxOptions, thrownError){  }
        });

        //TODO: Carregar ddl_operadora
        //TODO: Carregar Avatar e dados do Usuário
        //TODO: Carregar lista de celulares
    
    }
    
    
    function GetProfileRetorno(data) {
        if (data.Valid) {

            $("#celulares").text("");
        
            $("#profile #avatar").attr({src: data.ProfileImageUrl});
            $("#profile #avatar").attr({alt: data.ScreenName});
            $("#profile #screen_name").text(data.ScreenName);
            if (data.Protected) { $("#profile #protected").show(); } else { $("#profile #protected").hide(); }

            if (!$("#profile").is(':visible')) {
                $("#profile").fadeIn('slow');
                $("#frm_mobile").fadeIn('slow');
            }

            for (var i = 0; i < data.Mobiles.length; i++) {
                AdicionaCelularLista(data.Mobiles[i].Codigo, data.Mobiles[i].Numero, data.Mobiles[i].Operadora, data.Mobiles[i].Status);
            }
            
            
        } else {
        
            if ($("#profile").is(':visible')) {
                $("#profile").fadeOut('slow');
                $("#frm_mobile").fadeOut('slow');
            }            
        
            alert(data.Mensagem);
            
        }
    }
    
    
    
    
    
    function AtivaMobileAdd(ativa) {
        if (ativa) {
            //$("#frm_mobile a").fadeIn();
            $("#frm_mobile a").attr({'class': ""});
        } else {
            //$("#frm_mobile a").hide();
            $("#frm_mobile a").attr({'class': "loading"});
            //$("#frm_mobile a").click(function(e) { });//
        }
    }
    
    
    function MobileAdd() {
    
        if ($("#frm_mobile a").attr("class") != "") {
            return;
        }
        
        //Validar Formulario
        var sCelular = $("#txt_celular").val();
        var sOperadora = $("#ddl_operadora").val();
        
        sCelular = sCelular.replace(" ", "").replace("(", "").replace(")", "").replace("-", "");
        
        if (!isValidNumber(sCelular) || sCelular.length != 10) {
            //Aviso Celular
            alert("Celular deve ser informado com DDD (dois dígitos) e NÚMERO (oito dígitos)!");
            return;
        }
        if (!isValidNumber(sOperadora)) {
            //Aviso Operadora
            alert("Operadora deve ser selecionada!");
            return;
        }
        
        jQuery.ajax({
            type: "GET",
            cache: false,
            url: "/v3/json/mobile_add.aspx",
            data: $('#frm_mobile').serialize(),
            dataType: "json",
            beforeSend: function(){ AtivaMobileAdd(false); },
            success: function(data){ MobileAddRetorno(data) },
            complete: function(){ AtivaMobileAdd(true); },
            error: function(xhr, ajaxOptions, thrownError){  }
        });
        
        
    }
    
    
    
    function MobileAddRetorno(data) {
        if (data.Valid) {
            if (data.Novo) {
                AdicionaCelularLista(data.Codigo, data.Numero, data.Operadora, data.Status);
            } else {
            
            }
            //alert(data.Mensagem);

        } else {
            alert(data.Mensagem);
        }
    }
    
    
    
    
    function MobileDel(id) {
        if (!isValidNumber(id)) {
            alert("O Código do celular não foi informado!");
            return;
        }

        var btn_exclui = $("#celulares #celular_" + id + " .btn_exclui");

        if (btn_exclui.attr("class") != "btn_exclui") {
            return;
        }
        
        btn_exclui.attr({'class': "btn_exclui loading"});
        
        
        jQuery.ajax({
            type: "GET",
            cache: false,
            url: "/v3/json/mobile_del.aspx",
            data: {codigo: id},
            dataType: "json",
            beforeSend: function(){  },
            success: function(data){ MobileDelRetorno(data, id) },
            complete: function(){ 

                var btn_exclui = $("#celulares #celular_" + id + " .btn_exclui");
                btn_exclui.attr({'class': "btn_exclui"});
            
            },
            error: function(xhr, ajaxOptions, thrownError){  }
        });    
        
    }
    
    
    
    function MobileDelRetorno(data, id) {
        if (data.Valid) {
        
            $("#celulares #celular_" + id).fadeOut('slow');
            
        } else {
        
            alert(data.Mensagem);
            
        }
    }




    function ErroAjax(xhr, ajaxOptions, thrownError) {

    }



    
	$(document).ready(function(){

        UpdateCounterSms();


        $("#menu li a").click(function(event) {
            var selecao = $(this).attr("href");
            var selecao_r = selecao.replace("/v3/", "");
            
            if (!isBlank(selecao_r) && $(selecao_r) && $(selecao_r).attr("id") != $(".conteudo:visible").first().attr("id")) {
                if($(".conteudo:visible").size() == 0) {
                    $(selecao_r).fadeIn('slow');
                } else {
                    $(".conteudo:visible").fadeOut('slow', function() { $(selecao_r).fadeIn('slow'); });
                }
                event.preventDefault();
            }
            
        });
        

        $("#btn_cadastro").click(function(event) {
            var selecao = $(this).attr("href");
            var selecao_r = selecao.replace("/v3/", "");
            
            //alert(selecao + " " +  selecao_r);
            if (!isBlank(selecao_r) && $(selecao_r) && $(selecao_r).attr("id") != $(".conteudo:visible").first().attr("id")) {
                if($(".conteudo:visible").size() == 0) {
                    $(selecao_r).fadeIn('slow');
                } else {
                    $(".conteudo:visible").fadeOut('slow', function() { $(selecao_r).fadeIn('slow'); });
                }
                event.preventDefault();
            }
            
        });

        
        //$("#btnCanalSms").click(function(event) {
        //    $(".conteudo:visible").fadeOut('slow', function() { $("#canalsms").fadeIn('slow'); });
        //});

        
        if (carregar_perfil) {
		    //TODO: Carregar perfil com lista celulares
		    //TODO: Liberar cadastro de novo celular
		    
            GetProfile();
            
        }


	    $("#frm_mobile a").click(function(event) { 
            event.preventDefault();
            MobileAdd(); 
        });
        
        $("#txt_celular").keypress(PermiteApenasNumeros);
		
        	
		/*		   
		if(exibe_panel) {
		    $("#travatela_overlay").show();
		    $(".formulario").fadeIn('slow', function(){
		        if ($(".txtLogin")) $(".txtLogin").focus(); 
		    });
		} else {
		    //$(".formulario").hide();
		}
		*/
		
		
		if (!exibe_painel) {
		    $("#btn_cadastro").hide();
		}
		
		
		$("#btn_cadastro").click(function(){
		    $("#travatela_overlay").show();
		    $(".formulario").fadeIn('slow', function(){
		        $(".txtLogin").focus(); 
		    });
        });
        
        
        
        
		$("#btn_fechar").click(function(){
		    $(".formulario").fadeOut('slow', function(){
		        $("#travatela_overlay").hide();
		    });
		    
        });
        
        
        window.scrollTo(0, 1);
	});
	
	

    function AdicionaCelularLista(Codigo, Numero, Operadora, Status) {

        var item = '<li id="celular_'+Codigo+'" style="display: none;">' +
            '   <span class="numero">'+Numero+'</span>' +
            '   <span class="operadora">'+Operadora+'</span>' +
            '   <span class="status">'+Status+'</span>' +
            '   <a href="#" class="btn_exclui">Excluir</a>' +
            '</li>';

        var espaco = $("#celulares li:last");
        if (!espaco) {
            $("#celulares li:last").after(item);
        } else {
            $("#celulares").append(item);
        }


        $("#celulares li:last").fadeIn('slow');
        ReativaMobileDel();
    }

    function ReativaMobileDel() {
        $("#celulares .btn_exclui").click(function(event) {
            event.preventDefault();
            if (confirm("Deseja realmente excluir o celular " + $(this).parent('li').children('.numero').text() + "?")) {
                MobileDel($(this).parent().attr("id").replace("celular_", ""));
            }
        });
    }    
    
    	
	
	
	
	
	
	
    
    

    function isBlank(A){return A.replace(/\s+/g,"").length==0}
    
    
    function isValidEmailAddress(emailAddress) {
	    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	    return pattern.test(emailAddress);
    }
    
    
    function isValidLogin(login) {
        var pattern = new RegExp(/^([\w_]+[\w])(?!.)$/);
        return pattern.test(login);
    }
    
    
    function isValidDate(data) {
        var pattern = new RegExp(/^(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)\d\d$/);
        return pattern.test(data);
    }
    

    function isValidNumber(number) {
        var pattern = new RegExp(/^([\d]+)$/);
        return pattern.test(number);
    }
    
    
    
	function PermiteApenasNumeros(e) {
        var key = window.event ? e.keyCode : e.which;
        var keychar = String.fromCharCode(key);
        
        switch(key) {
            case 8:
            case 13:
            case 0:
                return true; break;
            default: return /[0-9]/.test(keychar); break;
        }
	}
	
	function PermiteApenasLogin(e) {
        var key = window.event ? e.keyCode : e.which;
        var keychar = String.fromCharCode(key);
        
        switch(key) {
            case 8:
            case 13:
            case 0:
                return true; break;
            default: return /[a-zA-Z0-9_]/.test(keychar); break;
        }
	}