/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var empty = "";
var fontSize = 12;
var isLoggedIn = false;
var profileLevel = 0;
var isCartItemsShowed = false;

$(document).ready(function(){
        //It's avoid some delay with aplly listeners
        setTimeout("initListenersComponent()", 1000);
        verifyIfIsLogged();
    }
);


function initListenersComponent(){       

    var urlShare = "";//Declarado abaixo
    var contentV = "";//Declarado abaixo
    var urlImg   = "";//Declarado abaixo
    var vlink = document.location.href;

    $('.share_facebook_icon, .share_facebook').click(function(){
        contentV = "Compartilhe com seus amigos";
        urlShare = "http://www.facebook.com/sharer.php?u=" + vlink + "&t=" + contentV;
        shareHeight = 340;
        shareWidth = 570;

        NewWindow(urlShare, "Sharing", shareWidth, shareHeight, 'no', "center");
    });

    $('.share_twitter_icon, .share_twitter').click(function(){
         contentV2 = $("#social_network_title").val();
         urlShare2 = "http://twitter.com/share?url=" + vlink + "&text=" + contentV2;
         shareHeight2 = 350;
         shareWidth2 = 550;

         NewWindow( urlShare2,  "Sharing Twitter", shareWidth2, shareHeight2, 'no', "center");
    });

    $('.share_orkut_icon, .share_orkut').click(function(){
         contentT3 = $("#social_network_title").val();
         contentV3 = $("#social_network_description").val();
         urlLink3 =  vlink;
         urlImg = $("#social_network_image").val();
         urlShare3 = "http://promote.orkut.com/preview?nt=orkut.com&tt=" + contentT3 + "&cn=" + contentV3 + "&du=" + urlLink3+ "&tn=" + urlImg;
         shareHeight3 = 400;
         shareWidth3 = 650;

         NewWindow( urlShare3,  "Sharing Orkut", shareWidth3, shareHeight3, 'no', "center");
    });

    $('.share_mail_icon, .share_mail').click(function() {
         showPopUp("modulo", "indique_amigo", "indique_amigo_common", 485, 300, false);
    });

    $('.share_error_icon, .share_error').click(function() {            
        showPopUp("modulo", "relatar_erro", "error_simple", 485, 260, false);
    });
    
    $('.post_status').click(function() {            
        showPopUp("modulo", "form", "inhamer_post", 485, 260, false);
    });

    $('.google_maps_icon').click(function(){
         urlMap = "site/app/googlemaps";
         mapHeight = 480;
         mapWidth = 640;
         NewWindow( urlMap,  "GoogleMaps", mapWidth, mapHeight, 'no', "center");
    });


    $('.icon_shortUrl_copy').click(function(){             
         showPopUp("message", "copy_done", "message_simple", 350, 20, false);
     });

    //General button for all kind of newsletter's submit
    $('.submit_newsletter').click(function() {            
        submitNewsletter();             
    });

    //General button for a special kind of searchbar
    $('.searchbar_button').click(function(){            
        submitSearch();             
    });  

    //
    //PS the parameters bellow: 
    //@tipo - componente, inscricao, modulo
    //@folder - categoria do objeto selecionado acima
    //@layout - qual layout do componente ou modulo será carregado
    //@width - largura do popUp
    //@height - altura do popUp
    //@action - se deve carregar ou redirecionar depois de logado por exemplo.
    //
    //

    //It's used for business submit
    $(".submit_user_business, .login_component_nao_cadastrado").click(function(){            
        showPopUp("componente", "form_submit", "cadastrar_business", 850, 360, false);
    });

    //It's used for signup business submit
    $(".submit_event_signup").click(function(){
        showPopUp("inscricao", "inscricao", "inscricao_senac", 850, 360, true);
    });

    //It's used for signup business submit
    $(".submit_associar").click(function(){
        showPopUp("modulo","form", "associate_half_popup", 500, 250, false);
    });

    //PS: Dentro do login area existe uma requisão deste método também
    $(".bt_home").click(function(){            
        window.location = "/home";
    });

    //PS: Dentro do login area existe uma requisão deste método também
    $(".bt_facebook_profile").click(function(){            
        window.open("http://www.facebook.com/ACICampinas", "_blank");
    });

    //PS: Dentro do login area existe uma requisão deste método também
    $(".bt_twitter_profile").click(function(){            
        window.open("http://twitter.com/#!/ACICampinas", "_blank");
    });

    //PS: Dentro do login area existe uma requisão deste método também
    $(".bt_linkedin_profile").click(function(){            
        window.open("http://www.linkedin.com/company/acic---associa-o-comercial-e-industrial-de-campinas", "_blank");
    });

    $('#font_increase').click(function() {
        fontSize++;
        $(".textMateria").css("font-size", fontSize + "pt");            
    });

    $('#font_decrease').click(function() {
        fontSize--;
        $(".textMateria").css("font-size", fontSize + "pt");            
    });

    $('#font_regular').click(function() {
        fontSize = 12;
        $(".textMateria").css("font-size", fontSize + "pt");            
    });
    
    //Carrinho de compras
    $('.cart_container_shopping').click(function(){
        if(!isCartItemsShowed){
            $(".item_sh_c").show();
            $(".container_items_shopping_cart").fadeIn("fast");
            //Verifica se tem itens no carrinho
            if($("#amount_shopping_cart").text() > 0){
                $("#bt_payment_shopping_cart").show();
                $(".bt_loja_limpar_lista").show();
            }
            isCartItemsShowed = true;
        }else{
            $(".item_sh_c").hide();
            $(".container_items_shopping_cart").fadeOut("fast");
            //Verifica se tem itens no carrinho
            if($("#amount_shopping_cart").text() > 0){
                $("#bt_payment_shopping_cart").hide();
                $(".bt_loja_limpar_lista").hide();
            }
            isCartItemsShowed = false;
        }
    });
    
    //Botão de pagamento do carrinho de compras
    $('#bt_payment_shopping_cart, .bt_payment_shopping_cart').click(function(){
        window.location = "/loja/pagamento";            
    });
    
    $('#bt_clear_cart, .bt_clear_cart').click(function(){
        $.post("/loja/limpar",{
            empty: empty
        },function(data){
            $("#items_shopping_cart").empty();       
            $("#amount_shopping_cart").empty().text(0);   
            $("#bt_payment_shopping_cart").hide();
            $(".bt_loja_limpar_lista").hide();
            $("#items_shopping_cart").append("<div class='item_sh_c_empty'>Nenhum item adicionado</div>");
        });          
    });
}

/*
 * It calls the google maps from the falsh buttons
 * It's the same the method above;
 * 
 */
function callGoogleMapsFromFlash(){

    urlMap = "site/app/googlemaps";
    mapHeight = 480;
    mapWidth = 640;

    NewWindow( urlMap,  "GoogleMaps", mapWidth, mapHeight, 'no', "center");
}

/*
 * It submits the newsletter form.
 * Just a e-mail is needed. 
 * 
 */
function submitNewsletter(){

    var e_mail = $(".email_newsletter").val();

    $.post("/admin/newsletter/cadastrar",{
        email: e_mail
    },function(data){
        $(".email_newsletter").val("");
        $(".message_newsletter_input").empty().text(data);           
    });
}

/*
 * It submits a search into website
 * or Purplepier System 
 * 
 */
function submitSearch(){

    var search = $(".search_input").val();

    $.post("/site/buscar/",{
        search: search
    },function(data){ 
        $("#panMain").empty().append(data);            
    });
}

//Updates the main pan height
function updateSearchCanvas(){        
    var height_pan = ($(".container_pan_buscar").height() + 80) + "px";        
    $(".pan").css("height", height_pan);        
}

/*
 * This method verifies if the user is logged in.
 * It shows the correct animation.
 * 
 */
function verifyIfIsLogged(){   
    //Initate the loggin off;
    $(".login_container_login").css("display", "none");

    $.post("/admin/login/verificar",{
        empty: empty
    },function(data){           
        var jsonObject = eval('(' + data + ')');
  
        if(jsonObject['logado'] == '1'){
            $(".login_signed_name").empty().append(jsonObject['user']);
            $(".user_avatar_picture").attr("src", jsonObject['avatar']);
            $(".login_container_login").css("display", "none");//Bug fix Chrome
            $(".login_container_signed").fadeIn("fast");
            $(".bt_menu_conta_site").fadeIn("slow");
            setTimeout("initLoginListenersButtons()", 1000);
            isLoggedIn = true;
            profileLevel = jsonObject['profile_level'];

        }else if(jsonObject['logado'] == 2){                
            window.location = "/home";            
        }else{                
            $(".login_container_login").css("display", "block");
            //Its a rich HTML component
            //See the methods bellow
            //launchLoginArea();
        }
    });
}

/*
 * This method verifies if there are items
 * into shopping cart
 * 
 */
function verifyShoppingCartItems(){
    
    $.post("/loja/verificar",{
        tipo: "produto"
    },function(data){

        var jsonObject = eval('(' + data + ')');
        
        if(jsonObject['amount'][0]['SUM(amount)'] > 0){
            var items_sc = "";            
            //Avoid some problems with blank
            $(".shopping_cart_compontent_html").hide();
            
            $("#items_shopping_cart").empty();
            for(i = 0; i < jsonObject['items'].length; i++){
                items_sc  = "<div class='item_sh_c'>";
                items_sc += "<div class='item_sh_c_qtd'>" + jsonObject['items'][i]['amount'] + "</div>";
                items_sc += "<div class='item_sh_c_name'>" + jsonObject['items'][i]['nome'] + "</div>";
                items_sc += "<div class='item_sh_c_value'>" + jsonObject['items'][i]['valor_format'] + "</div>";
                items_sc += "</div>";
                $("#items_shopping_cart").append(items_sc);
            }
            $(".bt_shopping_cart_pay_it").css("display", "block");
            $(".shopping_cart_compontent_html").fadeIn("fast");
            $("#amount_shopping_cart").empty().text(jsonObject['amount'][0]['SUM(amount)']);
        }       
    });
}

/*
 * This method verifies if there are credits
 * into shopping cart
 * 
 */
function verifyShoppingCartCredits(tipo){
    
    $.post("/loja/verificar",{
        tipo: tipo
    },function(data){

        var jsonObject = eval('(' + data + ')');
        
        if(jsonObject['amount'][0]['SUM(amount)'] > 0){
            var items_sc = "";
            $("#items_credits_container").empty();
            for(i = 0; i < jsonObject['items'].length; i++){
                items_sc  = "<div class='item_cred_c' id='obj_item_" + jsonObject['items'][i]['id'] + "'>";
                items_sc += "<div class='item_cred_c_name'>" + jsonObject['items'][i]['nome'] + "</div>";
                items_sc += "<div class='item_cred_c_value'>" + jsonObject['items'][i]['valor_format'] + "</div>";
                items_sc += "<input class='item_cred_c_bt_close' id='item_"+jsonObject['items'][i]['id']+"' type='button'/>";
                items_sc += "</div>";
                $("#items_credits_container").append(items_sc);
            }    
            
            $(".bt_line_transparent").show();  
            $("#amount_cart_credits").empty().text(jsonObject['amount']['valor_format']);            
            $(".amount_subtotal_credits").empty().text("Subtotal - " + jsonObject['amount']['valor_format']); 
        }
        $(".amount_user_credits").empty().text(jsonObject['user']['credit_User_format']); 
        $(".amount_value_credits, #amount_cart_credits").empty().text(jsonObject['amount']['valor_format']);             
        $("#helper_amount_total").val(jsonObject['total_no_prefix']);
    });
    
    
}


/*
 * This method log out the user
 * 
 */
function logOut(){

    var local_logout = $("#helper_local_logout").val();        
    $.post("/admin/logout", {
        action: local_logout
    },function(data){

        $(".login_container_signed").animate({width: "hide"},{duration: "500"});
        $(".login_container_login").animate({width: "show"},{duration: "1000"});
        $(".bt_menu_conta_site").fadeOut("slow");
        isLoggedIn = false;

        if(data == "Logout redirect"){
            window.location = "/home";
        }else{                
            //launchLoginArea();
        }            
    });
}

/*
 * Main listeners for login components
 * 
 */
function initLoginListenersButtons(){

    $('.login_sair_conta').click(function(){            
        logOut();
    }); 

    $('.login_minha_conta').click(function(){            
        window.location =  "/conta/home";
    });
}

/*
 * Triggers a click for the listeners listed above:
 * 
 * 
 * PS: It works together the method launchLinkPurplePier(); from 
 * the main.js 
 * 
 */
function openPopUp(link){
   
    switch(link){
    
        case "!popup_associese":  
            $(".submit_associar").trigger('click');
            break;        
        
        case "!popup_publicidade":
            showPopUp("modulo","form", "advertise_interest_half_popup", 500, 280, false);
            break;
            
        case "!popup_esqueci_senha":
            showPopUp("modulo","form", "esqueci_senha_popup", 480, 200, false);
            break;
            
        case "!popup_reputation":
            showPopUp("modulo","reputation", "reputation_user", 480, 160, false);           
            break;
    }
    
}

/*
 * Animation the preloader bar
 * Just moving
 *
 */
var countPreloader = 0;
function loadingPreloader(){
    if(countPreloader > 5) countPreloader = 0;
    $("#preloader_loaderbar").css("background-position", countPreloader + "px 0px");
    countPreloader++;    
}

function startPreloaderAnimation(){
    id_interval = setInterval("loadingPreloader()", 300);
}

function removePreloaderAnimation(){
    clearInterval(id_interval);
}

//New window
//It's a pop up window
var win=null;
function NewWindow(mypage,myname,w,h,scroll,pos){
if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=0,menubar=no,toolbar=no,resizable=no';
win=window.open(mypage,myname,settings);}
// -->
