/*
 * BeanJQuery.js (JQuery)
 * This is almost a copy of the original Component.js by sh and bm.
 *
 * Including: i42Component, AjaxLoadedComponent
 * author: sl
 * @todo: rewrite using JQuery Notation
 * @todo: clean up AjaxLoadedBean::update
 * @todo: insert TabComponent 
 */
document.Beans = new Object(); // Container for Bean Objects
Bean = new Object(); // Container for Bean classes 

Bean.addCreateFunction = function(f)
{
    var oldonload = window.onload;
    if(typeof window.onload != 'function') 
    {
        window.onload = f;
    } 
    else 
    {
        window.onload = function() 
        {
            if (oldonload) 
            {
                oldonload();
            }
            try {
                f();
            } catch(e) {}
        }
    }
}

Bean.Bean = function(id)
{
    this.domElement = document.getElementById(id);
    this.id = id;
    
    var deactivated = false;
    
    this.hide = function(){jQuery("#" + this.id).hide();};
    this.show = function(){jQuery("#" + this.id).show();};
    this.flap = function(){jQuery("#" + this.id).toggle();};
    
    this.activate = function()
    {
        var element = this.getDeactivationDiv();
        element.style.display = 'none';
        this.domElement.deactivated = false;
    };
    
    this.deactivate = function()
    {
        var element = this.getDeactivationDiv();
        var style = window.getComputedStyle ? document.defaultView.getComputedStyle(this.domElement, null).getPropertyValue("position") :
                    this.domElement.currentStyle.position;
        
        if ((style != 'relative') && (style != 'absolute'))
        {
            this.domElement.style.position = 'relative';
        }

        element.style.display = 'block';
        element.style.position = 'absolute';
        element.style.top = '0px';
        element.style.left = '0px';

        element.style.height = this.domElement.clientHeight + 'px';
        element.style.width  = this.domElement.clientWidth + 'px';

        this.domElement.deactivated = true;
    };
    
    this.getDeactivationDiv = function()
    {
        var id = this.id + 'Deactivation';
        var result = document.getElementById(id);
        if (!result)
        {
            result = document.createElement('div');
            result.id = id;
            result.className = 'deactivation';

            this.domElement.appendChild(result);
        }
        return result;   
    };
    
    this.toggleActivation = function()
    {
        if (this.domElement.deactivated)
        {
            this.activate();
        }
        else
        {
            this.deactivate();
        }
    };
};

Bean.AjaxLoadedBean = function(id, updateUrl, parameterList)
{
    var domElement = document.getElementById(id);
    var id = id;
    var containerId = id;
    var contentId = id + "Content";
    var contentDomElement = document.getElementById(containerId);
    var url = updateUrl;
    var showIndicator = true;
    var loadingContent = "Loading ...";
    var completeContent = "Complete!";

      
    this.setOnComplete = function(f)
    {
        onCompleteCallback = f;
    };

    this.setShowIndicator = function(value)
    {
        showIndicator = value;
    };

    this.setLoadingContent = function(content)
    {
        loadingContent = content;
    };

    this.setCompleteContent = function(content)
    {
        completeContent = content;
    };

    this.buildParameterSet = function(parameterList)
    {
        var result = {};
        
        // Input: parameter=value&parameter2=value2
        // oder: parameter/value/parameter2/value2
        if(parameterList)
        {
            if ((parameterList.substr(0,1) == '?') || (parameterList.substr(0,1) == '/'))
            {
                parameterList = parameterList.substr(1);
            }

            var parameterSet = parameterList.split('&');
            for (var i = 0; i < parameterSet.length; i++)
            {
                if (parameterSet[i].indexOf('=') != -1)
                {
                    var parameterSet2 = parameterSet[i].split('=');
                    // empty bracket check ... should be reconsidered
                    parameterSet2[0] = parameterSet2[0].replace(/\[\]$/, '[' + String(i) + ']'); 
                    result[parameterSet2[0]] = parameterSet2[1];
                }
                else
                {
                    var parameterSet2 = parameterSet[i].split('/');
                    var isKey = true;
                    var key = "";
                    for (var j = 0; j < parameterSet2.length; j++)
                    {
                        if (isKey)
                        {
                            key = parameterSet2[j];
                        }
                        else
                        {
                            result[key] = parameterSet2[j];
                        }
                        isKey = !isKey;
                    }
                }
            }
        }
        
        return result;
    };

    this.savedParameterSet = this.buildParameterSet(parameterList);

    // flatten an array or object in the super routing style a/b/x/y/
    // in: Array or Object
    // out: string /.../.../.../...
    this.buildParameterList = function(parameterSet)
    {
        result = "";
        for (key in parameterSet)
        {
            if (parameterSet[key] != '')
            {
                result += key + '/' + parameterSet[key] + '/';
            }
        }
        
        return result;
    };
 
    this.update = function(parameter, mergeParameter, post, smartRouting)
    {
        var currentParameterSet = (typeof parameter == 'object') ? parameter : this.buildParameterSet(parameter);

        if(mergeParameter)
        {
            var mergedParameterSet = this.savedParameterSet;
            for(key in currentParameterSet)
            {
                mergedParameterSet[key] = currentParameterSet[key];
            }
            currentParameterSet = mergedParameterSet;
        }

        this.savedParameterSet = currentParameterSet;

        post = post ? true : false;
        if (typeof(smartRouting=="undefined"))      
           smartRouting  = true;              
        else      
           smartRouting  = smartRouting ? true : false;

        if (showIndicator)
        {
            jQuery("#" + containerId + "Indicator").html(loadingContent);
            //new Effect.Appear(this.containerId+'Indicator', {duration:0.4, from:0, to:1.0});
        }

        if(smartRouting)         
        {        
           parameter = this.buildParameterList(currentParameterSet);        
           var completeUrl = url + '/parentId/'+ containerId + '/isAjaxLoaded/true/' + (parameter && !post ? parameter : '');           
        }        
        else         
        {        
           var completeUrl = url + '/parentId/'+ containerId + '/isAjaxLoaded/true?' + parameter;           
        } 
        if (completeUrl.indexOf('MediaFileWizard') > -1)
            completeUrl = completeUrl.replace(/\"/g,"___");
        jQuery.ajax({
            async: true,
            url: completeUrl,
            data: (post ? currentParameterSet : ''),
            success: function(data, textStatus){
                        jQuery("#" + containerId).html(data);
                     },
            complete:   onComplete,
            type: (post ? 'POST' : 'GET')
        });
    };

    
    function onComplete(request, json)
    {
        if(showIndicator)
        {
            jQuery("#" + containerId + "Indicator").html(completeContent);
        }
       
        onCompleteCallback(request, json);
        if (showIndicator)
        {
            //new Effect.SwitchOff(this.containerId+'Indicator');
        }
    };

    function onCompleteCallback(request, json)
    {

    };
    
    this.clear = function()
    {
        contentDomElement.innerHTML = '';
    };
};

Bean.AjaxLoadedBean.prototype = new Bean.Bean();

/*********************
//* jQuery Multi Level CSS Menu (horizontal)- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//* Menu instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//* Last modified: Sept 6th, 08'. Usage Terms: http://www.dynamicdrive.com/style/csslibrary/tos/
*********************/

//Specify full URL to down and right arrow images (25 is padding-right to add to top level LIs with drop downs):
var arrowimages={down:['downarrowclass', '/images/project/pixel.gif', 25], right:['rightarrowclass', '/images/project/pixel.gif']}


var jquerycssmenu={

fadesettings: {overduration: 350, outduration: 100}, //duration of fade in/ out animation, in milliseconds

buildmenu:function(menuid, arrowsvar){
	jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
			$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
				'<img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
				+'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
				+ '" style="border:0;" />'
			)
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					this._offsets={left:$(this).offset().left, top:$(this).offset().top}
					var menuleft=this.istopheader? 0 : this._dimensions.w
					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
					$targetul.css({left:menuleft+"px"}).fadeIn(jquerycssmenu.fadesettings.overduration)
				},
				function(e){
					$(this).children("ul:eq(0)").fadeOut(jquerycssmenu.fadesettings.outduration)
				}
				
			) //end hover
			
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
	}) //end document.ready
}
}

//build menu with ID="myjquerymenu" on page:
jquerycssmenu.buildmenu("myjquerymenu", arrowimages);

