/**
 * @name Produtos Js
 * @author L.F.Martins
 * @since 10-11-2010
 * @version 2.0
 */

/* Variável que define o caminho da session - Ajax */
var SessionPath = "./library/produtos-js/session.php";
var ComparePath = "http://www.cceinfo.com.br/comparar_produtos";

/* JQuery - Carrega com a página. */
jQuery(function($){
    try{
        AutoStart();
        $(':checkbox').click(CheckboxClicked);
        $('#button_comparar').click(SendCompare);        
        $('.comparar_botao').click(SendCompare);
        $('.comparar_botao_alert').click(SendCompare);
        $('.fechar_botao_alert').click(HideAlert);        

        /**
         * @name HideAlertEsc
         * @param <Int> e - Tecla Apertada
         * @internal Quando aperta Esc fecha o alerta.
         */
        $("*").keydown(function (e) {
            e.stopPropagation();
            var o = $("#opacidade");
            if ( (e.keyCode == '27') && (o.is(':visible')) ) {
                HideAlert();
            } // if
        }); // function

    }catch(e){
        alert(e);
    }
})

/* Variável que recebe a quantidade de produtos selecionados */
var somador = 0;

/**
 * @name CheckboxClicked
 * @internal Quando um checkbox é clicado posta no session os parametros do
 * produto e exibe na tela a miniatura do produto.
 */
function CheckboxClicked() {
    /* Recebe valor do checkbox */
    var val = this.value;

    /* Verifica se foi checado ou deschecado para postar no session */
    if (this.checked){
        SetProduct(this.name, this.className, somador+1, val);
    } // if
    else {
        UnSetProduct(val);
    } // else

    /* Verifica a quantidade de produtos selecionados. */
    if (somador > 3) {
        ShowAlert('max3');
        UnSetProduct(val);
        this.checked = false;
    } // if
    else {
        if (this.checked) {
            AddField(this.name, this.className, somador, val);
        } // if
        else {
            RemoveField("div_"+this.name);
        } // else
    } // else
} // function

/**
 * @name MakeTagImg
 * @param <String> n - this.name
 * @param <String> c - this.className
 * @param <Int> s - Somador
 * @param <String> v - val
 * @return <String> Tag Img
 * @internal Cria a DIV com imagem e botão remover que será anexado na página.
 */
function MakeTagImg(n,c,s,v) {
    return "<div id='div_" + n + "' class='compara_prod_imagem'><img src='" + c + "' class='" + s + "' id='img_compara'/><input type='button' class='remove_compara' onclick=\"javascript:RemoveCompare('" + n + "','" + v + "')\" name='" + n + "'/></div>";
} // function

/**
 * @name RemoveCompare
 * @param <String> n - this.name
 * @param <String> v - val
 * @internal Remove o produto da caixa de produtos a comparar.
 */
function RemoveCompare(n,v) {
    $("#"+n).each(function() {
        this.checked = false;
    });
    UnSetProduct(v);
    RemoveField("div_"+n);
} // function

/**
 * @name SetProduct
 * @param <String> v
 * @internal Adiciona o produto do XML.
 */
function SetProduct(n,c,s,v){
    $.post(SessionPath, {
        val: v,
        image: MakeTagImg(n,c,s,v),
        checked: 1
    });
    somador++;
} // function

/**
 * @name UnSetProduct
 * @param <String> v
 * @internal Remove o produto do XML.
 */
function UnSetProduct(v) {
    $.post(SessionPath, {
        val: v,
        checked: 0
    });
    somador--;
} // function

/**
 * @name RemoveField
 * @param <String> n
 * @internal Remove o produto com o id passado... o id é o nome do produto.
 */
function RemoveField(n){
    var posicao = parseInt($("div#"+n+" > img").attr('class'));
    $("div#"+n).remove();
    var p = ((3-posicao) == 1) ? 1 : 0;
    for (var i=1;i<=(3-posicao);i++) {
        var campo = $("#campo"+(posicao+i)).html();
        if (campo != "") {
            var id_campo = $("#campo"+(posicao+i)+" > div").attr('id');
            $("div#"+id_campo).remove();
            $("#campo"+(i+p)).html(campo);
            $("#campo"+(i+p)+" > div >img").attr('class',i+p);
        } // if
    } // for
} // function

/**
 * @name AddField
 * @param <String> n - this.name
 * @param <String> c - this.className
 * @param <Int> s - Somador
 * @param <String> v - val
 * @internal Anexa Imagem produto a Página.
 */
function AddField(n,c,s,v,k,f) {
    k = k || false;
    var tag_imagem = f || null;
    if (!k) {
        tag_imagem = MakeTagImg(n, c, s, v);
    } // if
    $("#campo"+somador).html(tag_imagem);
} // function

/**
 * @name UncheckAllCheckboxes
 */
function UncheckAllCheckboxes(){
    $("input[type=checkbox]").each(function() {
        this.checked = false;
    });
} // function

/**
 * @name AutoStart
 * @internal Ao iniciar a página procura na session por produtos selecionados.
 */
function AutoStart() {
    /* Recebe via Ajax quais produtos estão setados no $_SESSION(PHP) */
    $.ajax({
        type: "GET",
        url: SessionPath,
        dataType: "xml",
        success: function(xml) {
            $("valor", xml).each(function(){
                var v = $(this).find("id").attr("id");
                var f = $(this).find("id").text();
                var p = false;                
                if (v != null) {
                    somador++;                    
                    $('#chk_comparar'+v).each(function() {                        
                        AddField(this.name,this.className,somador,this.value);
                        this.checked = true;
                        p = true;
                    }) // each
                    if (!p) {
                        AddField(null,null,null,null,true,f);
                    } // if
                } // if
                else {
                    UncheckAllCheckboxes();
                } // else
            }) // each
        } // success
    }) // ajax
} // function

/**
 * @name SendCompare
 * @internal Vai para página de comparação de produtos.
 */
function SendCompare() {
    if (somador <= 1){
        ShowAlert('min2');
    } // if
    else {
        window.location=ComparePath;
    } // else
} // function

/**
 * @name ShowAlert
 * @param <Bool/String> k - Chave que decide qual será a mensagem exibida.
 * @param <String> t - Texto que irá na mensagem.
 * @internal Ex.: ShowAlert(false,'mensagem alerta') ou ShowAlert(max3)
 */
function ShowAlert(k,t) {
    var o = $("#opacidade");
    var a = $("#alert_container");
    var c = $("div.comparar_corpo");
    c.css('z-index','1001');
    o.css('height', $(document).height()).hide();
    o.fadeTo("fast",0.65);
    o.fadeIn(500);    
    a.delay(400).fadeIn(500);
    if (k !== false) {
        $("div."+k).fadeIn(500);
    } // if
    else {
        $("div.generic").fadeIn(500).text(t);
    } // else
} // function

/**
 * @name HideAlert
 * @internal Esconte DIV de alerta.
 */
function HideAlert() {
    var o = $("#opacidade");
    var a = $("#alert_container");
    var d = $(".texto_botao_alert");
    var c = $("div.comparar_corpo");
    c.css('z-index','1');
    d.fadeOut(500);
    a.fadeOut(500);
    o.delay(400).fadeOut(500);
} // function

/**
 * @name GoTo
 * @internal Vai para URL do produto pesquisado.
 */
function GoTo(p) {
    if (p != '')
        window.location = p;
} // function
