/**
* Plataforma Linker
* ---
* Funciones para UI
* @uses Libreria jQuery 
* ---
*/

/**
* Mascara de entrada para los textbox
*/
function setMaskInputs(){    
    $("input[mask]").each(function(){
        if($(this).data("masked")==true)
            return;
        if($(this).attr("mask")!=undefined && $(this).attr("mask")!=""){
            $(this).data("mask",true);
            $(this).keypress(function(event){
                if(event.charCode==0)
                    return true;
                if(this.selectionStart!=this.selectionEnd)
                    $(this).val("");
                var value=$(this).val()+String.fromCharCode(event.charCode);
                if(event.charCode==0)
                    return true;
                var sel=selText();

                if(sel.length>0){
                    $(this).val("");
                }
                var regex=eval("/^"+$(this).attr("mask")+"$/g");
                if(!regex.test(value))
                    return false; 
            })
        }
    });
}

/**
* Habilita el alt del textbox
*/
function enableAlt(){
    $("input[alt!='']").each(function(){
        var caption=$(this).attr('alt');
        if(caption!='' && caption!=null){
            if($(this).attr('value')=='' || $(this).attr('value')==null){
                $(this).attr('value',caption);
                $(this).css('color','#cccccc');
            }
            $(this).focus(function(){
                if($(this).attr('value')==caption){
                    $(this).attr('value','');
                    $(this).css('color','black');
                }
            });
            $(this).blur(function(){
                if($(this).attr('value')==''){
                    $(this).css('color','#cccccc');
                    $(this).attr('value',caption);
                }    
            });
        }
    });
}

/**
* Esta funcion se ejecutara cada ves que el campo
* de tipo input tenga una regla de validacion y la regla
* no se haya cumplido
* - Esta funcion puede personalizarse para desplegar otro tipo de error -
*/
function displayError($msg){
    alert($msg);
    return true;
}

function toCheckbox(){
    $("input[check]").toCheckbox();
}
/**
* Tooltip
*/
function toolTip(obj,tip){
    opener=obj.id;
    tt=document.getElementById("tooltip");
    $("#tooltip").toggle("fast");
    if(tip!=''){
        tt.style.left=(getElementLeft(opener)+getElementWidth(opener)+10)+'px';
        tt.style.top=(getElementTop(opener)+5)+'px';
        tt.innerHTML=tip;
        $("#tooltip").animate({opacity: "show", top: "+=10"},"fast");
    }else{
        $("#tooltip").animate({opacity: "hide", top: "-=10"},"fast");
    }
}
/**
* Abre mensaje jgrowl
*/
function popMsg(msg,header){
    if(header==undefined)
        header="Error";
    $.jGrowl(msg,{
        header:header,
        life: 5000
    });
}

/**
* Agrega icono dependiendo la extension
*/
function fileIcon(){
    $("div.icon, span.icon, td.icon, a.icon").fileIcon();
}


function ajaxLinks(){
    $("a[rel]").ajaxLink();
}
function ajaxLinkClick(obj){
    var target=$(obj).attr("tar");
    if(target=="" || target==undefined || target==null){
        target="#tab_cont_ajax";
    }
    if(target=="#tab_cont_ajax"){
        $("#tab_main_cont").hide(); // Ocultamos tabs normales
    }
    showLoader();
    if($(target).length>0){
        var self=obj;
        $(target).load($(obj).attr("href"),function(){
            if($(self).attr("callback")!="" && $(self).attr("callback")!=undefined){
                eval($(self).attr("callback"));
            }
            hideLoader();
            if(target=="#tab_cont_ajax"){   
                $("#tab_cont_ajax").css("display","block");
            }
            docReady();
        });
    }
    return false;
}
function richEdit(){
    $("textarea.full-edit").each(function(){
        if($(this).data("richText")==true)
            return;
        $(this).wysiwyg({
            controls: {
              strikeThrough : { visible : true },
              underline     : { visible : true },
              separator00 : { visible : true },
              justifyLeft   : { visible : true },
              justifyCenter : { visible : true },
              justifyRight  : { visible : true },
              justifyFull   : { visible : true },
              separator01 : { visible : true },
              indent  : { visible : true },
              outdent : { visible : true },
              separator02 : { visible : true },
              subscript   : { visible : true },
              superscript : { visible : true },
              separator03 : { visible : true },
              undo : { visible : true },
              redo : { visible : true },
              separator04 : { visible : true },
              insertOrderedList    : { visible : true },
              insertUnorderedList  : { visible : true },
              insertHorizontalRule : { visible : true },
              h4mozilla : { visible : true && $.browser.mozilla, className : 'h4', command : 'heading', arguments : ['h4'], tags : ['h4'], tooltip : "Header 4" },
              h5mozilla : { visible : true && $.browser.mozilla, className : 'h5', command : 'heading', arguments : ['h5'], tags : ['h5'], tooltip : "Header 5" },
              h6mozilla : { visible : true && $.browser.mozilla, className : 'h6', command : 'heading', arguments : ['h6'], tags : ['h6'], tooltip : "Header 6" },
              h4 : { visible : true && !( $.browser.mozilla ), className : 'h4', command : 'formatBlock', arguments : ['<H4>'], tags : ['h4'], tooltip : "Header 4" },
              h5 : { visible : true && !( $.browser.mozilla ), className : 'h5', command : 'formatBlock', arguments : ['<H5>'], tags : ['h5'], tooltip : "Header 5" },
              h6 : { visible : true && !( $.browser.mozilla ), className : 'h6', command : 'formatBlock', arguments : ['<H6>'], tags : ['h6'], tooltip : "Header 6" },
              separator07 : { visible : true },
              cut   : { visible : true },
              copy  : { visible : true },
              paste : { visible : true }
            }
        });
        $(this).data("richText",true);
    })
    
    $("textarea.edit").each(function(){
        if($(this).data("richText")==true)
            return;
        $(this).wysiwyg();
        $(this).data("richText",true);
    })
}
function submitFormHandle(){
    $("form").richForms();
}
function ajaxFormSuccess(){
    popMsg("Registro guardado","Información");
}
function selectCurrent(){
    $("select[current]").each(function(obj){
        var value=$(this).attr("current");
        $(this).children().each(function(child){
            if($(this).is("optgroup")){
                $(this).children().each(function(){
                    if($(this).attr("value")==value){
                        $(this).attr("selected","selected");
                    }   
                })
            }
            if($(this).attr("value")==value){
                $(this).attr("selected","selected");
            }
        });
    });
}
function toolTips(){
    $(function(){
        $("input[tooltip],label[tooltip],span[tooltip],textarea[tooltip],a[tooltip],img[tooltip]").each(function(){
             var v_gravity=($(this).attr("gravity")=="" || $(this).attr("gravity")==undefined) ? "sw" : $(this).attr("gravity");
             if(v_gravity=="auto")
                v_gravity=$.fn.tipsy.autoNS;
             var v_trigger=($(this).attr("trigger")=="" || $(this).attr("trigger")==undefined) ? "hover" : $(this).attr("trigger");    
             $(this).tipsy({
                    title:'tooltip',
                    gravity:v_gravity,
                    trigger: v_trigger,
                    fade: false,
                    delayIn: 250,
                    html:true
             });  
        });  
    });
}

function checkAll(){
    $("input[type=checkbox].checkall").click(function(){
        $(this).parents('form').find(':checkbox').attr('checked', this.checked);
    });
}

/**
* LLama a todas las funciones necesarias para emular el document load
* cuando se carga una pagina via ajax
*/
function docReady(){
    datepickers();
    richEdit();
    enableAlt();
    fileIcon();
    submitFormHandle();
    selectCurrent();
    toolTips();
    setMaskInputs();
    ajaxLinks();
    toCheckbox();
    $("a.fancybox").fancybox();
}

var loading_timer;
var loading_counter;
function showLoader(modal){
    if($("#loading_box").is("not(:hidden)"))
        return;
    if($("#loading_box").length==0){
        $("body").append($("<div></div>").attr("id","loading_box").show());
        $("#loading_box").css("top",($(window).height()/2)-($("#loading_box").height()/2));
        $("#loading_box").css("left",($(window).width()/2)-($("#loading_box").width()/2));
    }else{
        $("#loading_box").show();    
    }
    if(modal==true)
        $("#modal").show();
    loading_counter=1;
    loading_timer=setInterval("loaderTimer()",100);
}
function loaderTimer(){
    if(loading_counter>=12)
        loading_counter=1;
   
    $("#loading_box").css("background-position","0 "+((loading_counter*40)*-1)+"px");
    loading_counter++;
}
function hideLoader(){
    clearInterval(loading_timer);
    loading_counter=1;
    $("#loading_box").css("background-position","0 0");
    $("#loading_box").hide();
    //$("#loading_box").remove();
    $("#modal").hide();
    $("#loading_box").remove();
}

function getVars(){
    var get={};
    var url=document.location.href;
    if(url==undefined || url=="")
        url=window.location.href;
    if(url.indexOf('?')>=0){
        url=url.split("?");
        url=url[1];
        url=url.replace('#','');
        url=url.split("&");
        window.get={};
        for(var i in url){
            var kp=url[i].split("=");
            if(kp.length==1){
                window.get.tab=kp[0];
            }else{
                eval("window.get."+kp[0]+"='"+kp[1]+"';");
            }
        }
    }
    return window.get;
}

function datepickers(){
    $("input[type=text].date").each(function(i){
        $(this).datepicker();
        format=$(this).attr('format');
        if(format=='')
            format='yy-mm-dd';
        $(this).datepicker('option', {dateFormat: format});
    });
}

function toggleAdvanced(obj){
    //$('#advanced').css("top",obj.offsetTop-1).css("left",obj.offsetLeft-75).show();
    $('#advanced').animate({
        height:"113px"
    });
    $("#advanced_form").show();
}

function closeAdvanced(obj){
    $("#advanced_form").hide();
    $('#advanced').animate({
        height:"1px"
    },function(){
        $("#advanced").hide();
    });    
}
                                                                                                        
// --------------------------------
// Document LOAD
// --------------------------------
$(document).ready(function(){
    // Links tipo ajax
    ajaxLinks();
    
    getVars();
      
    setMaskInputs();

    $.datepicker.setDefaults({dateFormat: 'yy-mm-dd'});
    datepickers();
    
    // Auto select para combo box
    // el select debe tener el atributo current con el valor
    // del campo
    selectCurrent();
    

    $("ul[list='multiselect'] li").click(function(){
        if($(this).attr("class") == "select_item"){
            $(this).attr("class","");
            $(this).find("input").attr("checked","");
        }else{
            $(this).attr("class","select_item");
            $(this).find("input").attr("checked","checked");
        }
    });

    
    // Transformamos el select
    $("select[transform]").each(function(){
        var valor=$(this).find('option:selected').text();
        var parent=$(this).parent();
        $(this).remove();
        $(parent).append(valor);
    })
    
    // Tooltips
    toolTips();
    
    // Rich edit
    richEdit();

    // Mensajes de error
    if($('.sys-msg').length!=0){
        $(this).oneTime(8000,function(){
            $('.sys-msg').fadeOut('slow');
        })
    }

    // Checkall
    checkAll();
    
    // Rich forms
     submitFormHandle();
    
    // Alt
    enableAlt();
    
    // Iconos
    fileIcon();
    
    docReady();
    
});
