var mypets = null;
var mypets1 = null;
var botonActual=null;
var animatedcollapse={
    divholders: {}, //structure: {div.id, div.attrs, div.$divref}
    divgroups: {}, //structure: {groupname.count, groupname.lastactivedivid}
    statusholders: {}, //structure: {[statuselement.id, stype, [opensrc, closedsrc]], $target}
    lastactiveingroup: {}, //structure: {lastactivediv.id}

    show:function(divids){ //public method
        if (typeof divids=="object"){
            for (var i=0; i<divids.length; i++)
                this.showhide(divids[i], "show")
        }
        else
            this.showhide(divids, "show")
    },

    hide:function(divids){ //public method
        if (typeof divids=="object"){
            for (var i=0; i<divids.length; i++)
                this.showhide(divids[i], "hide")
        }
        else
            this.showhide(divids, "hide")
    },

    toggle:function(divid,boton){
        boton.className="current";
        var li="li"+boton.getAttribute("id").substring(5, boton.getAttribute("id").length);
        document.getElementById(li).className="current";
        if(botonActual!=null){
            if(botonActual.getAttribute("id")!=boton.getAttribute("id")){
                botonActual.className="green";
                document.getElementById("li"+botonActual.getAttribute("id").substring(5, botonActual.getAttribute("id").length)).className="green";
            }
        }
        if (typeof divid=="object"){
            divid=divid[0];
        }
        if(botonActual.getAttribute("id")!=boton.getAttribute("id") && (botonActual!=null)){
            this.showhide(divid, "toggle")
        }
        botonActual=boton;
    },

    addDiv:function(divid, attrstring){ //public function
        this.divholders[divid]=({
            id: divid,
            $divref: null,
            attrs: attrstring
        })
        this.divholders[divid].getAttr=function(name){ //assign getAttr() function to each divholder object
            var attr=new RegExp(name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
            return (attr.test(this.attrs) && parseInt(RegExp.$1)!=0)? RegExp.$1 : null //return value portion (string), or 0 (false) if none found
        }
        this.currentid=divid //keep track of current div object being manipulated (in the event of chaining)
        return this
    },

    showhide:function(divid, action){
        var $divref=this.divholders[divid].$divref //reference collapsible DIV
        if (this.divholders[divid] && $divref.length==1){ //if DIV exists
            var targetgroup=this.divgroups[$divref.attr('groupname')] //find out which group DIV belongs to (if any)
            if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group
                if (targetgroup.lastactivedivid && targetgroup.lastactivedivid!=divid){ //if last active DIV is set
                    this.slideengine(targetgroup.lastactivedivid, 'hide') //hide last active DIV within group first
                }
                this.slideengine(divid, 'show');

                targetgroup.lastactivedivid=divid //remember last active DIV
            }
            else{
                this.slideengine(divid, action)
            }
        }
    },

    slideengine:function(divid, action){
        var velocidad=300;
        if(action=="hide"){
            velocidad=1;
        }
        var $divref=this.divholders[divid].$divref
        if (this.divholders[divid] && $divref.length==1){ //if this DIV exists
            var animateSetting={
                height: action
            }
            if ($divref.attr('fade')){
                animateSetting.opacity=30
            }
            $divref.animate(animateSetting, $divref.attr('speed')? velocidad : 500, function(){
                if (animatedcollapse.ontoggle){
                    try{
                        animatedcollapse.ontoggle(jQuery, $divref.get(0), $divref.css('display'))
                    }
                    catch(e){
                        alert("An error exists inside your \"ontoggle\" function:\n\n"+e+"\n\nAborting execution of function.")
                    }
                }
            })
            return false
        }
    },

    generatemap:function(){
        var map={}
        for (var i=0; i<arguments.length; i++){
            if (arguments[i][1]!=null){ //do not generate name/value pair if value is null
                map[arguments[i][0]]=arguments[i][1]
            }
        }
        return map
    },

    init:function(botoninicial,divmenudesplegable){
        botonActual=document.getElementById(botoninicial);
        var el = document.getElementById(divmenudesplegable);
        var as = el.getElementsByTagName("div");
        for (var i=0; i<as.length; i++) {
            animatedcollapse.addDiv(as[i].id, 'fade=0,speed=400,group=pets')
        }

        var ac=this
        jQuery(document).ready(function($){
            animatedcollapse.ontoggle=animatedcollapse.ontoggle || null
            var urlparamopenids=animatedcollapse.urlparamselect() //Get div ids that should be expanded based on the url (['div1','div2',etc])
            var persistopenids=null;
            var groupswithpersist=null;
            if (persistopenids!=null) //if cookie isn't null (is null if first time page loads, and cookie hasnt been set yet)
                persistopenids=(persistopenids=='nada')? [] : persistopenids.split(',') //if no divs are persisted, set to empty array, else, array of div ids
            groupswithpersist=(groupswithpersist==null || groupswithpersist=='nada')? [] : groupswithpersist.split(',') //Get list of groups with divs that are persisted
            jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object
                this.$divref=$('#'+this.id)
                if ((this.getAttr('persist') || jQuery.inArray(this.getAttr('group'), groupswithpersist)!=-1) && persistopenids!=null){ //if this div carries a user "persist" setting, or belong to a group with at least one div that does
                    var cssdisplay=(jQuery.inArray(this.id, persistopenids)!=-1)? 'block' : 'none'
                }
                else{
                    var cssdisplay=this.getAttr('show')? 'none' : null
                }
                if (urlparamopenids[0]=="all" || jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains the single array element "all", or this div's ID
                    cssdisplay='block' //set div to "block", overriding any other setting
                }
                else if (urlparamopenids[0]=="none"){
                    cssdisplay='none' //set div to "none", overriding any other setting
                }
                this.$divref.css(ac.generatemap(['height', this.getAttr('height')], ['display', cssdisplay]))
                this.$divref.attr(ac.generatemap(['groupname', this.getAttr('group')], ['fade', this.getAttr('fade')], ['speed', this.getAttr('speed')]))
                if (this.getAttr('group')){ //if this DIV has the "group" attr defined
                    var targetgroup=ac.divgroups[this.getAttr('group')] || (ac.divgroups[this.getAttr('group')]={}) //Get settings for this group, or if it no settings exist yet, create blank object to store them in
                    targetgroup.count=(targetgroup.count||0)+1 //count # of DIVs within this group
                    if (jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains this div's ID
                        targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded). Overrides other settings
                        targetgroup.overridepersist=1 //Indicate to override persisted div that would have been expanded
                    }
                    if (!targetgroup.lastactivedivid && this.$divref.css('display')!='none' || cssdisplay=="block" && typeof targetgroup.overridepersist=="undefined") //if this DIV was open by default or should be open due to persistence
                        targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded)
                    this.$divref.css({
                        display:'none'
                    }) //hide any DIV that's part of said group for now
                }
            })
            jQuery.each(ac.divgroups, function(){ //loop through each group
                if (this.lastactivedivid && urlparamopenids[0]!="none") //show last "active" DIV within each group (one that should be expanded), unless url param="none"
                    ac.divholders[this.lastactivedivid].$divref.show()
            })
            if (animatedcollapse.ontoggle){
                jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object and fire ontoggle event
                    animatedcollapse.ontoggle(jQuery, this.$divref.get(0), this.$divref.css('display'))
                })
            }
            $(window).bind('unload', function(){
                ac.uninit()
            })
        })
    },

    uninit:function(){
        var opendivids='', groupswithpersist=''
        jQuery.each(this.divholders, function(){
            if (this.$divref.css('display')!='none'){
                opendivids+=this.id+',' //store ids of DIVs that are expanded when page unloads: 'div1,div2,etc'
            }
            if (this.getAttr('group') && this.getAttr('persist'))
                groupswithpersist+=this.getAttr('group')+',' //store groups with which at least one DIV has persistance enabled: 'group1,group2,etc'
        })
        opendivids=(opendivids=='')? 'nada' : opendivids.replace(/,$/, '')
        groupswithpersist=(groupswithpersist=='')? 'nada' : groupswithpersist.replace(/,$/, '')
    },
    urlparamselect:function(){
        window.location.search.match(/expanddiv=([\w\-_,]+)/i) //search for expanddiv=divid or divid1,divid2,etc
        return (RegExp.$1!="")? RegExp.$1.split(",") : []
    }

}
function showMenu(divid,boton,urlContenido){
    if (mypets == null & mypets1 == null )
    {

        if(urlContenido == null){
            //var botonPrincipal=document.getElementById("boton32");
            //if(boton==botonPrincipal) CargarContenidoPortal();
            animatedcollapse.toggle(divid,boton);
        }else{
            new Ajax.Request(urlContenido,{
                method: "get",
                onSuccess: function(t){
                    var div=document.getElementById(divid);
                    div.innerHTML=t.responseText;
                    animatedcollapse.toggle(divid,boton);
                    CargarContenidoPortal();

                }
            });
        }
    }else{
        mypets.cancelautorun();
        mypets1.cancelautorun();
 if(urlContenido == null){
            //var botonPrincipal=document.getElementById("boton32");
            //if(boton==botonPrincipal) CargarContenidoPortal();
            animatedcollapse.toggle(divid,boton);
        }else{
            new Ajax.Request(urlContenido,{
                method: "get",
                onSuccess: function(t){
                    var div=document.getElementById(divid);
                    div.innerHTML=t.responseText;
                    animatedcollapse.toggle(divid,boton);
                    CargarContenidoPortal();

                }
            });
        }
    }
}
function showMenu2(divid,boton,urlContenido){
    if (mypets == null & mypets1 == null )
    {
        animatedcollapse.toggle(divid,boton);
        CargarContenidoPortal();
    }else{
        mypets.cancelautorun();
        mypets1.cancelautorun();
        animatedcollapse.toggle(divid,boton);
        CargarContenidoPortal();
    }
}
