/*
    Document   : main
    Created on : 20/10/2010, 09:31:00
    Author     : CarlosGarcia
    Description: New features added, no DB Manager access
    Purpose of the javascript follows.
*/
var textura_botao;
var cor_botao;
var cor_titulo;
var cor_subtitulo;
var icon_titulo;
var icon_topic;
var last_input_focused;

$(document).ready(function(){
    initButtonsListeners(); 
});//Close Document Ready


function updateIntro(result){

    $('body').css("background-image", 'url(/media/images/textures/intro/' + result["textura_intro"] + ')');
    //$('.overlay').css("background-image", 'url(/media/images/textures/' + result["textura_overlay"] + ')');
    //$('.shadow').css("background-image", 'url(/media/images/textures/' + result["textura_sombras"] + ')');
    $('body').css("background-repeat", result["tipo_textura_intro"]);
    $('body').css("background-color", result["cor_textura_intro"]);
    
    $('.container_pan_status').css("background-image", 'url(/media/images/textures/mensagem/' + result["textura_mensagem"] + ')');
    //getStageSize();
}

 /*
  * Método responsável por setar o tamanho do rodape e o menu componente
  * quando esse é adicionado em topos e rodapes
  * 
  * @param number
  * @param number
  * 
  */
 function setContainerHTMLProperties(rodape_id, height){ 
     $('.footermainPan').css("height", height + "px");                 
 }

/*
 * Sets the banner's height.
 * Just Height, nothing more, if needed a width different
 * use the 7 differents banner's size, like: Min, Block, Spark,
 * Corona, Banner
 *
 */
function setSizeHeader(alt, larg, id){
    $(".canvas_stage" + id).css("height", alt + "px");
    $(".headermainPan").css("height", alt + "px");
}

 /*
  * Método responsável por carregar os modulos.
  * Esse modulos são features pre-prontas que podem ser 
  * utilizadas no meio de textos com tags como <galeria></galeria> e etc
  * 
  * @loader - id da div que ira carregar o moduloe
  * @modulo - nome do modulo como tipo galeria
  * @layout - laoyt que o modulo terá, pode ser por diferença de tamanho, features etc.
  * @id - id da galeria, produto, serviço, banner ou outra coisa que será carregada.
  * @animation - boolean se tera'ou não animação.
  * @action
  * @qtd - numero de blocks, 1,2 3, 4 full é 1
  * 
  * 
  */
 function loadModule(loader, modulo, layout, id, divider, animation, action, qtd){ 
     //if(modulo == "images"){alert(layout + " loader: " + loader + " " + id);}
     $("#" + loader).hide();
     $.post("/site/modulos/",{                
        id_general: id,
        modulo: modulo,
        layout: layout,
        divider: divider,
        action: action,
        begin: "0",
        qtd: qtd
     },function(data){              
        $("#" + loader).append(data);
        if(animation){ $("#" + loader).fadeIn("fast");}else{$("#" + loader).css('display', 'block');};                  
     });         
 }

 /*
  * Método responsável por recarregar os modulos.
  * Esse modulos são features pre-prontas que podem ser 
  * utilizadas no meio de textos com tags como <galeria></galeria> e etc
  * 
  * @loader - id da div que ira carregar o moduloe
  * @modulo - nome do modulo como tipo galeria
  * @layout - laoyt que o modulo terá, pode ser por diferença de tamanho, features etc.
  * @id - id da galeria, produto, serviço, banner ou outra coisa que será carregada.
  * @animation - boolean se tera'ou não animação.
  * @action - if it's loads or reloads
  * @begin  - inicio da nova pesquisa, LIMIT 0, 10
  * @qtd - numero de blocks, 1,2 3, 4 full é 1
  * 
  */
 function reloadModule(loader, modulo, layout, id, divider, animation, action, begin, qtd){ 

    if(animation)$("#" + loader).hide();

     $.post("/site/modulos/",{                 
            id_general: id,
            modulo: modulo,
            layout: layout,
            divider: divider,
            action: action,
            begin: begin,
            qtd: qtd
        },function(data){
            $("#" + loader).append(data);
            if(animation)$("#" + loader).fadeIn("fast");  
        });

 }

function initButtonsListeners(){

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

     $('.flash_notice_button_close').click(function(){
         $('.flash_notice').fadeOut("slow");
     }); 
     
     $(".container_inputs_middle").click(function(){          
        handleInputFocus(this.id);
     });
     
     $(".container_inputs_middle").blur(function(){          
        handleInputLostFocus(this.id);
     });
     
 }
 
 /*
  * Adds a listners for the banners clickeds
  * Its works together extremos site
  * 
  * PS: All links must use this statement
  * 
  */
function initAdvertisingListeners(){
    
    $('.bt_link_banner_advertise').live('click', function(){
        var id = this.id;
        var link_advertise = this.name;
        var type_launch = "external_link";
         
        var link_type = link_advertise.charAt(0);
        
        switch(link_type){
            case "/":
                type_launch = "internal_link";
                launchLinkPurplePier(id, type_launch, link_advertise);
                break;
            case "!":
                type_launch = "popup_link";
                launchLinkPurplePier(id, type_launch, link_advertise);
                break;
                
            default:
                window.open(link_advertise, '_blank');
                break;
        }        
     }); 
 }
 
 /*
  * It works together the statement above;
  * They are brother and sister, the method above split the
  * link and this one makes the launch!
  * 
  */
function launchLinkPurplePier(id, type, link_advertise){
    
    $.post("/site/relatar/click",{            
            id: id
    },function(data){         
       switch(type){
           case "internal_link":
               window.open(link_advertise, '_self');
               break;

           case "popup_link":
               openPopUp(link_advertise);
               break;
        }        
    });
 }

/*
* Adds a fav link into favorites
* 
* 
*/
function addFavorite(){
   if(document.all){
      window.external.AddFavorite(location.href, document.title);
   }else if(window.sidebar){
       window.sidebar.addPanel(document.title, location.href, '');
   }
} 


//Produtos
//***********************************************************************************
//***********************************************************************************
//***********************************************************************************
//Produtos

/*
 * Put an item into shopping cart
 * Makes shopping cart part
 * 
 */
function buyItem(id_item, tipo, id_button){
    
    var qtd_item_pp = $("#item_pp_"+ id_button).val();
    var valor = $("#item_pp_"+ id_button).attr('alt');
    
    $.post("/loja/add_item",{                
        id_item: id_item,
        tipo: tipo, 
        qtd: qtd_item_pp,
        valor: valor
        
    },function(data){
        var jsonObject = eval('(' + data + ')');
        
        if(jsonObject['amount'][0]['SUM(amount)'] > 0){
            var items_sc = "";
            $("#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);
            }
        }
        $("#amount_shopping_cart").empty().text(jsonObject['amount'][0]['SUM(amount)']); 
    });   
}

/*
 * Put an item into shopping cart
 * Makes shopping cart part
 * 
 */
function buyCredits(id_item, tipo, valor){
    
    var qtd_item_pp = 1;
    
    $.post("/loja/add_item",{                
        id_item: id_item,
        tipo: tipo, 
        qtd: qtd_item_pp,
        valor: valor
        
    },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']);
        $("#helper_amount_total").val(jsonObject['amount']['valor']);        
    });   
}

/*
 * Uploads and apply Produto picture
 *
 * This method is called when the upload is completed
 * See the upLoadfy above.
 * 
 */
function applyPictureProduto(){
    var path_image_produto = "/media/user/images/thumbs_120/" + $("#file_helper").val();        
    //alert(path_image_produto);
    applyPictureSize(path_image_produto, nr_slot, '120');        
}

/**
 *
 * It firts calculates the images sizes before apply it.
 * 
 * There are severals methods that uses this system.
 * The most of them use a request updateSlotProdutoPicture(), bellow
 * It's just to follow a pattern.
 * 
 * path_cool_stuff = image path
 * id_slot = id recebido pela foto
 * sizeT = tamanho max que a imagem deve ter em px
 * container_loader = container da imagem no caso de slideshow etc
 * place = onde será exibida, main ou thumbs
 *
 * @param string
 * @param number
 * @param number
 * @param number
 * @param string
 * @param string
 *
 */
function applyPictureSize(path_cool_stuff, id_slot, sizeHeight, sizeWidth, container_loader, place){

    var img = new Image();

    img.onload = function(){

        if(this.width > this.height) {
            percet = sizeWidth / this.width;
        } else {
            percet = sizeHeight / this.height;
        }

        $("#slot_picture" + id_slot).hide();

        if((sizeWidth > this.width) && (sizeHeight > this.height)){

            $("#" + container_loader).css("height",  sizeHeight+"px");

            $("#slot_picture" + id_slot).attr('width', this.width);
            
            if(place != "full"){
            $("#slot_picture" + id_slot).attr('height', this.height);
            }
            
            $("#slot_picture" + id_slot).css("margin-top", ((this.height / 2) * -1)+ "px");
            $("#slot_picture" + id_slot).css("top",  "50%");
            
            $("#slot_picture" + id_slot).attr("src",  path_cool_stuff);
            $("#slot_picture" + id_slot).css("position", "relative");          

            $("#slot_picture" + id_slot).css("margin-left", ((this.width / 2) * -1)+ "px");
            $("#slot_picture" + id_slot).css("left",  "50%");                

         }else{

            var result = new Array();
            result[0] = this.width * percet;
            result[1] = this.height * percet; 

            //Attributes
            $("#slot_picture" + id_slot).attr('width', result[0]);
            if(place != "full"){
            $("#slot_picture" + id_slot).attr('height', result[1]);
            }
            $("#slot_picture" + id_slot).attr("src",  path_cool_stuff);
            $("#slot_picture" + id_slot).css("position", "relative");            

            if(this.width <= this.height){                   
                //Height smaller
                if(place != "full"){
                $("#slot_picture" + id_slot).css("margin-top", ((result[1] / 2) * -1)+ "px");
                $("#slot_picture" + id_slot).css("top",  "50%");
                }

                if(result[0] <= (sizeWidth - 10) || place == "thumbs" ){
                    $("#slot_picture" + id_slot).css("left",  "50%");
                    $("#slot_picture" + id_slot).css("margin-left",  ((result[0] / 2) * -1)+ "px"); 
                }

            }else{                    
                //Width smaller
                $("#slot_picture" + id_slot).css("left",  "50%");
                $("#slot_picture" + id_slot).css("margin-left",  ((result[0] / 2) * -1)+ "px"); 

                if((result[1] <= (sizeHeight - 10) || place == "thumbs") && place != "full"){
                    $("#slot_picture" + id_slot).css("margin-top", ((result[1] / 2) * -1)+ "px");
                    $("#slot_picture" + id_slot).css("top",  "50%");
                }
            }             
        }
        
        //Avoid unecessary error
        if(place == "main"){
            $("#full_picture0").attr("href", path_cool_stuff);
            $("#full_picture0").attr("title", path_cool_stuff);
        }
        
        $("#formSlotPicture" + id_slot).val(path_cool_stuff);            
        $("#slot_picture" + id_slot).fadeIn("slow");            
        nr_slot++;

    }        
    img.src = path_cool_stuff;
}

/*
 * This method is called from a javascript request
 * in view produtos, slots pictures
 * 
 * PS: Pay attention into num variable, depends on the id its can be a problem, so sometimes it's
 * better using a letter as id the slot it's default, so try something like PP or anything else. 
 * 
 */
function updateSlotProdutoPicture(path_image, num, sizeH, sizeW, container_loader, place){
    applyPictureSize(path_image, num, sizeH, sizeW, container_loader, place);
}   

/*
 * Calculate if is needed put the menu fonts smaller
 * 
 */
function calculateMenuButtonsPosition(qtd){
    var qtdt = qtd * 1;
    var fontSizeMenu = "";
    var widthFontSizeMenu = "";
    var marg = "";

    switch(qtdt){
        case 7:
            fontSizeMenu =  "0.84em";
            widthFontSizeMenu = "140px";
            marg = (980 / ((qtd * 1) * 2))/5;
            break;
        case 8:
            fontSizeMenu =  "0.82em";
            widthFontSizeMenu = "89px";
            marg = (980 / ((qtd * 1) * 2))/6;
            break;
        case 9:
            fontSizeMenu =  "0.84em";
            widthFontSizeMenu = "90px";
            marg = (980 / ((qtd * 1) * 2))/5;
            break;
        case 10:
        case 11:
            fontSizeMenu =  "0.70em";
            widthFontSizeMenu = "70px";
            marg = (980 / ((qtd * 1) * 2))/7;
            break;
        case 12:
        case 13:
            fontSizeMenu =  "0.62em";
            widthFontSizeMenu = "70px";
            marg = (980 / ((qtd * 1) * 2))/7;
            break;
        case 14:
        case 15:
            fontSizeMenu =  "0.6em";
            widthFontSizeMenu = "60px";
            marg = (980 / ((qtd * 1) * 2))/8;
            break;
        case 16:
        case 17:
            fontSizeMenu =  "0.4em";
            widthFontSizeMenu = "70px";
            break;
        default:
            fontSizeMenu =  "0.9em";
            widthFontSizeMenu = "95px";
            marg = (980 / ((qtd * 1) *2))/4; 
                
            break;
    }

    $("#menu ul li a ").css("padding-left", marg + "px");
    $("#menu ul li a ").css("padding-right", marg +  "px");
    
    $("#menu ul li:last-child a ").css("padding-left", marg + "px");
    $("#menu ul li:last-child a ").css("padding-right", "0px");

    $("#menu ul li a").css("font-size", fontSizeMenu);
    $("#menu ul li a").css("min-width", widthFontSizeMenu);
}

