// JavaScript Document
var PopOverNamespaces = [];
var aHiddenSelects = [];
function PopOver(sGlobal){
    if (typeof(sGlobal) != 'string')
    {
        throw new exception('Namespace required');
    }


    this.namespace = sGlobal;
    PopOverNamespaces.push(sGlobal);
    this.data = {};
    this.inputs = {};
    this.paneurl = {};
    this.paneheight = null;
    this.panetitle = '';
    this.collapseToContents = false;
    this.onComplete = function() {};
    this.onHide = function() {};
    this.onShow = function() {};
    this.reloadOnShow = true;
    this.waitTag = '<img src="/im/_else/loading.gif" />';

    PopOver.prototype.$_namespace = function (oElement)
    {
        if (typeof(oElement) == 'string')
        {
            return $(oElement+this.namespace);
        }

        return $(oElement);
    }

    PopOver.prototype.hide = function()
    {
    	this._ieFix(false);
        this.onHide();
        new Effect.Fade(this.$_namespace('_popForm'),{duration:0.2});
    }

    PopOver.prototype.getContainer = function ()
    {
        return this.$_namespace('_popDetails');
    }

    PopOver.prototype.getForm = function ()
    {
        return this.$_namespace('_popDetailsForm');
    }



    PopOver.prototype.validOption = function(options,option,defaultOpt)
    {
        if (typeof(options[option]) != 'undefined')
        {
            return options[option];
        }
        return defaultOpt;
    }


    PopOver.prototype.showWait = function(bShow)
    {
        if (bShow)
        {
            this.$_namespace('_popWaitTag').innerHTML = this.waitTag;
            this.$_namespace('_popWaitTag').style.top = this.$_namespace('_popForm').getHeight()/1.2+'px';
            this.$_namespace('_popWaitTag').style.left = this.$_namespace('_popForm').getWidth()/2+'px';
            this.$_namespace('_popWaitTag').show();
        }
        else
        {
            this.$_namespace('_popWaitTag').hide();
        }
    }


    PopOver.prototype.setOptions = function(options)
    {
        this.data = this.validOption(options,'data',this.data);
        this.reloadOnShow = this.validOption(options,'reloadonshow',this.reloadOnShow);
        this.inputs = this.validOption(options,'inputs',this.inputs);
        this.paneurl = this.validOption(options,'paneurl',this.paneurl);
        this.onComplete = this.validOption(options,'onComplete',this.onComplete);
        this.onHide = this.validOption(options,'onHide',this.onHide);
        this.onShow = this.validOption(options,'onShow',this.onShow);
        this.panetitle = this.validOption(options,'panetitle',this.panetitle);
        this.paneheight = this.validOption(options,'paneheight',this.paneheight);
        this.waitTag = this.validOption(options,'waitTag',this.waitTag);

    }

    PopOver.prototype.clearForm = function ()
    {
        if (this.getForm() == null)
        {
            return;
        }
        this.getForm().getElements().each(
            function (node)
            {
                if ($(node).tagName.toLowerCase() == 'input' && ($(node).type == 'button' || $(node).type == 'radio'))
                {
                       return;
                }

                $(node).selectedIndex = 0;
                $(node).clear();


            }
        );
    }


    PopOver.prototype.populateFields = function(hFields) {
        hFields = $H(hFields);
//        console.log(hFields);
        oRadioButtons = this.$_namespace('_popForm').select('input').findAll(
                            function(oNode) {
                                return (oNode.type == 'radio' || oNode.type == 'checkbox');
                            });

        hFields.each(
            function (oField)
            {

                oInput = oRadioButtons.find(
                            function(oNode) {
                                return (oNode.id == oField.key+oField.value)
                            });

              //  console.log('selector:'+'#'+oField.key);
                sSelector = '#'+oField.key;
              //  console.log(this.$_namespace('_popDetailsForm').select(sSelector));
               $A( this.$_namespace('_popDetailsForm').getElements()).each(function(oNode){console.log(oNode.id)})

                oInput = (typeof(oInput) == 'undefined') ? this.$_namespace('_popDetailsForm').select(sSelector)[0] : oInput ;


                if (typeof(oInput) != 'undefined' && oInput != null)
                {
              //         console.log(oInput.id);
                    sTagName = oInput.tagName.toLowerCase();
                    sType = oInput.type;
                    sCombinedType = sTagName+'|'+sType;

                    switch(sCombinedType)
                    {
                        case 'select|select-one':
                            aOpts = this.$_namespace('_popDetailsForm').select('option[value='+oField.value+']');
                            if (aOpts.length > 0)
                            {
                                oInput.selectedIndex = aOpts[0].index;
                            }
                            break;

                        case 'input|text':
                        case 'input|hidden':
                        case 'textarea|textarea':
                            oInput.value = oField.value;
                            break;
                        case 'input|radio':
                        case 'input|checkbox':
                            oInput.checked = true;
                            break;
                    }
                }
            }
        );



    }
    
    
 
    
    PopOver.prototype._ieFix = function(bHide)
    {	
    
    	if (navigator.appName == 'Microsoft Internet Explorer' && /msie|MSIE 6/.test(navigator.userAgent)){
			if (bHide)
	    	{
				$A(document.getElementsByTagName('SELECT')).
				findAll(
					function (oNode) 
					{
						return ($(oNode).visible() &&             
				                !$(oNode).ancestors().findAll(
				                    function (oNode) 
				                    {
				                        return (!oNode.visible() || oNode.getStyle('visibility') == 'hidden')
				                    }
				                ).length > 0);
					}
			    ).each(
						function (oNode)
						{
							aHiddenSelects.push(oNode);
							$(oNode).hide();
						}
				);
	    	}
	    	else
	    	{
	    		$A(aHiddenSelects).invoke('show');
	    		aHiddenSelects = [];
	    	}
    	}
    }

    //setup function
    PopOver.prototype.show = function(elCaller,oOptions){
    	this._ieFix(true);
        if (typeof(oOptions) == 'object')
        {
            this.setOptions(oOptions);
        }


        needsUpdate = true;
        
        if (this.$_namespace('_popForm') != null){
            this.$_namespace('_popForm').show();
            needsUpdate = this.reloadOnShow;
        } else {
            elDiv = document.createElement('div');
            elDiv.id = '_popForm'+this.namespace;

            sInnerHTML = '<div id="_popWaitTag{namespace}" style="display:none; position:absolute; "></div><img src="/im/_else/taskform_arrow_left.gif" id="_popArrow{namespace}" />' +
                              '<div id="_popWrapper{namespace}"><div id="_popShadowLeft{namespace}"></div><div id="_popShadowRight{namespace}"></div>' +
                              '<div id="_popFormInner{namespace}"><h4 id="_popHeader{namespace}"><div style="float:right;margin-top:2px">' +
                              '<a href="javascript:void(0)" onclick="{namespace}.hide()"><img src="/im/buttons/cancel.gif" border="0" /></a></div><span>' +
                              '</span></h4><div id="_popDetails{namespace}"><div id="_popDetailsForm{namespace}"><p>Loading...</p></div></div></div><div id="_popShadowBottom{namespace}"></div></div>';

            elDiv.innerHTML = sInnerHTML.replace(/\{namespace\}/g,this.namespace);
            document.body.appendChild(elDiv);
        }
        vTop = 0;
        onRight = true;
        vLeft = 0;
        vOffset = 60;

        elCaller = $(elCaller);
        
        
        if ((elCaller.cumulativeOffset().top - 60) > 0){

            if (elCaller.cumulativeOffset().top > ($(document.body).getHeight() - 400)){
                //console.log('caller object top: ' + elCaller.cumulativeOffset().top + 'page height - 400:' + ($(document.body).getHeight() - 400));
                vTop = (elCaller.cumulativeOffset().top - vOffset);
            } else {

                vTop = (elCaller.cumulativeOffset().top - vOffset);
            }
        } else {
            vTop = (elCaller.cumulativeOffset().top);
            vOffset = 0;
        }

        if (($(document.body).getWidth()) < (elCaller.cumulativeOffset().left + elCaller.getWidth() + 520)){
            onRight = false;
            vLeft = elCaller.cumulativeOffset().left - 520;

        } else {
            //console.log('body: ' + $(document.body).getWidth() + ', elcaller + 500: ' + (elCaller.cumulativeOffset().left  + elCaller.getWidth()  + 520));
            vLeft = elCaller.cumulativeOffset().left + elCaller.getWidth() + 15;
        }

        $(elDiv).setStyle({display: 'none', position:'absolute', width:'500px',
                           left:vLeft + 'px', top: vTop + 'px'});
        this.$_namespace('_popDetails').setStyle({padding:'3px',overflow:'hidden'});
        this.$_namespace('_popHeader').setStyle({borderBottom:'1px solid #999999'});
        this.$_namespace('_popShadowLeft').setStyle({padding:'2px',backgroundColor:'#000000',opacity:'0.1',float:'left',height:'396px',
                                       marginTop:'4px'});
        this.$_namespace('_popShadowRight').setStyle({padding:'2px',backgroundColor:'#000000',opacity:'0.1',float:'right',height:'396px',
                                       marginTop:'4px'});
        this.$_namespace('_popShadowBottom').setStyle({padding:'4px',backgroundColor:'#000000',opacity:'0.1',clear:'both',lineHeight:'1px',height:'1px',overflow:'hidden'});
        this.$_namespace('_popFormInner').setStyle({border:'2px solid #666666',backgroundColor:'#FFFFE3',marginLeft:'4px',
                                      marginRight:'4px',height:'400px'});

        if (onRight){
            this.$_namespace('_popArrow').src = '/im/_else/taskform_arrow_left.gif';
            this.$_namespace('_popArrow').setStyle({position:'relative',top:vOffset + 'px',left:'-4px'});
        } else {
            this.$_namespace('_popArrow').src = '/im/_else/taskform_arrow_right.gif';
            this.$_namespace('_popArrow').setStyle({position:'relative',top:vOffset + 'px',left:'494px'});
        }

        $$('#_popHeader'+this.namespace+' > span')[0].innerHTML = this.panetitle;

        if (this.paneheight != null)
        {
            this.setHeight(this.paneheight);
        }

        fAfterFinish = function ()
            {



                if (this.collapseToContents)
                {
                    iHeight = this.$_namespace('_popDetailsForm').getHeight();
                    this.setHeight(iHeight);
                }
            }.bind(this);

        new Effect.Appear(elDiv,{duration:0.2,
            afterFinish: fAfterFinish
        });
        onShow = this.onShow.bind(this);
        if (needsUpdate){
            new Ajax.Updater(this.$_namespace('_popDetailsForm'),this.paneurl,{method:'post',parameters:this.data, evalScripts:true,
                onComplete:function () {
                     onShow();
                }
            });

        }
        else
        {

            this.onShow();
        }


    }

    PopOver.prototype.setHeight = function(iHeight)
    {
        if (iHeight != null)
        {
            iHeight = parseFloat(iHeight);
            iHeight = iHeight + 35;
            this.$_namespace('_popFormInner').style.height = iHeight+'px';
            this.$_namespace('_popShadowLeft').style.height = (iHeight - 4)+'px';
            this.$_namespace('_popShadowRight').style.height = (iHeight - 4)+'px';
            this.paneheight = iHeight;
        }



    }


    PopOver.prototype.validateTask = function(hForm,oOptions) {


        fOnComplete = oOptions.onComplete;


        new Ajax.Request('/ajaxtasks/validategenerictask',
            {method:'post',postBody:hForm.toQueryString(), evalScripts:true,
                onComplete: function (t) {
                    fOnComplete(t);
                }
             });

    }


    PopOver.prototype.sendTask = function(hForm,oOptions) {


        fOnComplete = oOptions.onComplete;


        new Ajax.Request('/ajaxtasks/generictask',
            {method:'post',postBody:hForm.toQueryString(), evalScripts:true,
                onComplete: function (t) {
                    fOnComplete(t);
                }
             });

    }




}
