/**
 *
 *
 *
 *  @revision
 *      v1.002
 *  @modified
 *      July 7, 2008 - dranzd
 *          - added feature to drag dialog box
 *          - added gray background - disabled
 *      April 9, 2008
 *  @created
 *      January 1, 2008
 		July 11, 2008 - cs
 			- added function to show only one button i.e Close or Cancel button
 */

/*********** STATIC DIALOG OBJECT ***********/
var DIALOG = {
    instance: [],

    generateID: function(){
        var id = Math.floor( (10000-4999) * Math.random() ) + 5000;
        for( var k in DIALOG.instance ){
            if( k == id ){
                return Dialog.generateID()
            }
        }
        return id
    },

    addInstance: function(instance,id){
        if( ! id )
            var id = DIALOG.generateID()
        DIALOG.instance.push( { 'id':id, 'instance':instance } )
        return id
    },

    delInstance: function(id,instance){
        var new_instances = []
        var keys_to_delete = []
        for( var x=0; x < DIALOG.instance.length; ++x ){
            if( DIALOG.instance[x]['id'] == id ){
                delete DIALOG.instance[x];
            } else {
                new_instances.push(DIALOG.instance[x])
            }
        }
        DIALOG.instance = new_instances
    },

    getInstance: function(code){
        var instance = '';
        for( var x=0; x < DIALOG.instance.length; ++x ){
            if( DIALOG.instance[x]['id'] == code ){
                instance = DIALOG.instance[x]['instance'];
                break
            }
        }
        return typeof instance == 'object' ? instance : false
    }
}

/*********** DIALOG BOX ***********/
var Dialog = function(){ this.initialize.apply(this,arguments) }
Dialog.prototype = {
    _id: 0,
    _type: 1,
    _div_box: '',
    _div_title: '',
    _div_pointer: '',
    _div_dragger: '',
    _div_close: '',
    _div_content: '',
    _div_buttons: '',
    _button_extra: '',
    _button_okay: '',
    _button_cancel: '',
    _context_set: false,
    _content_set: false,
    _old_content: null,
    _button_observer: [],
    _options: {},
    _dragger: '',
   
    _div_forcefield: '',
    
    DIALOG_POP:1,
    DIALOG_CONTEXTUAL:2,
    DIALOG_FREESTYLE:3,

    initialize: function(){
        /*arguments: dialog type, prefered id, options in hash{}*/

        if(arguments[1]){
            var _instance = DIALOG.getInstance(arguments[1]);
            if(_instance){
                Object.extend(this,_instance);
                //console.log('popup exists!');
                return this;
            }
            var id = this._id = DIALOG.addInstance(this,arguments[1]);
        } else {
            var id = this._id = DIALOG.addInstance(this);
        }
       
        Object.extend(this._options, arguments[2] || {});

        var container = this._createContainer(id);
        this._div_box       = container;
        this._div_pointer   = container.down('div.dialog_pointer',0);
        this._div_close     = container.down('div.dialog_container span.dialog_close',0);
        this._div_title     = container.down('div.dialog_container h2.dialog_title span',0);
        this._div_content   = container.down('div.dialog_container div.dialog_content div.dialog_user_content',0);
        this._div_buttons   = container.down('div.dialog_container div.dialog_content div.dialog_buttons',0);
        this._button_extra   = container.down('div.dialog_container div.dialog_content div.dialog_buttons input[value="Extra"]',0);
        this._button_okay   = container.down('div.dialog_container div.dialog_content div.dialog_buttons input[value="Okay"]',0);
        this._button_cancel = container.down('div.dialog_container div.dialog_content div.dialog_buttons input[value="Cancel"]',0);
        document.body.appendChild(container);
        
        this._div_pointer.hide();
        if(typeof arguments[0] == 'number'){
            switch(arguments[0]){
                case this.DIALOG_POP:
                    this._type = this.DIALOG_POP;
                    this._moveDefault();
                    break;
                case this.DIALOG_CONTEXTUAL:
                    this._type = this.DIALOG_CONTEXTUAL;
                    this._div_pointer.show();
                    break;
                default: this._type = 1; break;
            }
        }

        this._div_box.setStyle({'zIndex':1001});
        this._div_close.observe('click',this._onClose.bindAsEventListener(this));
        
        if (this._options.isDraggable) {this.initDragger();}
        
        // to have a gray background
        //this.initForceField();

        return this;
    },
    
    initDragger: function(){
        if (this._dragger == '' || this._dragger == null) {
            return;
        }
        this._div_dragger = new Element('div').addClassName('dialog_dragger');
        this._div_box.insert({'top':this._div_dragger});
        this._dragger = new Dragger(this._div_dragger,{'toAnimate':this._div_box});
        this._dragger.start();
    },
    
    initForceField: function(){
        this._div_forcefield = new Element('div')
            .addClassName('dialog_forcefield')
            .hide()
            .setStyle({'width':'100%','height':'100%','position':'fixed','left':0,'top':0,'zIndex':1000,'backgroundColor':'gray'});
        this._div_forcefield.style.opacity = .5;
        this._div_box.insert({'before':this._div_forcefield});
    },

    showMessage: function(){
        var title = typeof arguments[0] == 'string' && arguments[0] != '' ? arguments[0] : 'Dialog Title';
        var content = typeof arguments[1] == 'string' && arguments[1] != '' ? arguments[1] : 'Dialog Content';
        var button_confirm = typeof arguments[2] == 'string' && arguments[2] != '' ? arguments[2] : 'Okay';

        if(arguments[0] != null)
            this._div_title.update(title)
        if(arguments[1] != null)
            this._div_content.update(content);

        this._button_extra.hide();
        this._button_cancel.hide();
        this._button_okay.value = button_confirm;

        if(! this._button_observer['okay'+this._id]){
            // :TODO: add checkpoint if button has not been observe by a handler.  prevent memory leak.
            var binderOkay = this._onConfirm.bindAsEventListener(this);
            this._button_okay.observe('click',binderOkay);
            this._button_observer['okay'+this._id] = true;
        }

        this._moveDefault();
        this.show();
        return this;
    },
    
    showMessage1: function(){
        var title = typeof arguments[0] == 'string' && arguments[0] != '' ? arguments[0] : 'Dialog Title';
        var content = typeof arguments[1] == 'string' && arguments[1] != '' ? arguments[1] : 'Dialog Content';
        var button_cancel = typeof arguments[3] == 'string' && arguments[3] != '' ? arguments[3] : 'Cancel';

        if(arguments[0] != null)
            this._div_title.update(title)
        if(arguments[1] != null)
            this._div_content.update(content);

        this._button_extra.hide();
        this._button_okay.hide();
        this._button_cancel.value = button_cancel;

                
        //if(this._button_observer['cancel'] != true){
            // :TODO: add checkpoint if button has not been observe by a handler.  prevent memory leak.
            var binderCancel = this._onCancel.bindAsEventListener(this);
            this._button_cancel.observe('click',binderCancel);
            this._button_observer['cancel'] = true;
        //}
        this._button_cancel.show();
        
        this._moveDefault();
        this.show();
        return this;
    },

    showChoice: function(){
    	
        var title = typeof arguments[0] == 'string' && arguments[0] != '' ? arguments[0] : 'Dialog Title';
        //var content = typeof arguments[1] == 'string' && arguments[1] != '' ? arguments[1] : 'Dialog Content';
        var content = arguments[1];
        var button_confirm = typeof arguments[2] == 'string' && arguments[2] != '' ? arguments[2] : 'Okay';
        var button_cancel = typeof arguments[3] == 'string' && arguments[3] != '' ? arguments[3] : 'Cancel';

        if(arguments[0] != null)
            this._div_title.update(title);
        if(arguments[1] != null)
            this.setContent(content);
        if(arguments[2] != null)
            this._button_okay.value = button_confirm
        if(arguments[3] != null)
            this._button_cancel.value = button_cancel
		this._button_extra.hide();
            
        if(this._button_observer['okay'+this._id] != true){
            var binderOkay = this._onConfirm.bindAsEventListener(this);
            this._button_okay.observe('click',binderOkay);
            this._button_observer['okay'+this._id] = true;
        }
        this._button_okay.show();
        if(this._button_observer['cancel'+this._id] != true){
            // :TODO: add checkpoint if button has not been observe by a handler.  prevent memory leak.
            var binderCancel = this._onCancel.bindAsEventListener(this);
            this._button_cancel.observe('click',binderCancel);
            this._button_observer['cancel'+this._id] = true;
        }
        this._button_cancel.show();

        this.show();
        return this;
    },

    showChoices: function(){
        var title = typeof arguments[0] == 'string' && arguments[0] != '' ? arguments[0] : 'Dialog Title';
        //var content = typeof arguments[1] == 'string' && arguments[1] != '' ? arguments[1] : 'Dialog Content';
        var content = arguments[1];
        var button_extra = typeof arguments[2] == 'string' && arguments[2] != '' ? arguments[2] : 'Extra';
        var button_confirm = typeof arguments[3] == 'string' && arguments[3] != '' ? arguments[3] : 'Okay';
        var button_cancel = typeof arguments[4] == 'string' && arguments[4] != '' ? arguments[4] : 'Cancel';

        if(arguments[0] != null)
            this._div_title.update(title);
        if(arguments[1] != null)
            this.setContent(content);
        if(arguments[2] != null)
            this._button_extra.value = button_extra
        if(arguments[3] != null)
            this._button_okay.value = button_confirm
        if(arguments[4] != null)
            this._button_cancel.value = button_cancel

        //if(this._button_observer['extra'+this._id] != true){
            var binderExtra = this._onExtra.bindAsEventListener(this);
            this._button_extra.observe('click',binderExtra);
            this._button_observer['extra'] = true;
        //}
        this._button_extra.show();    
        if(this._button_observer['okay'+this._id] != true){
            var binderOkay = this._onConfirm.bindAsEventListener(this);
            this._button_okay.observe('click',binderOkay);
            this._button_observer['okay'+this._id] = true;
        }
        this._button_okay.show();
        //if(this._button_observer['cancel'] != true){
            // :TODO: add checkpoint if button has not been observe by a handler.  prevent memory leak.
            var binderCancel = this._onCancel.bindAsEventListener(this);
            this._button_cancel.observe('click',binderCancel);
            this._button_observer['cancel'] = true;
        //}
        this._button_cancel.show();

        this.show();
        return this;
    },

    onextra: null,
    
    onconfirm: null,

    oncancel: null,

    onclose: null,

    setContext: function(element){
        if(this._type != this.DIALOG_CONTEXTUAL) return this;
        if(this._context_set == false){
            this._context_set = true;
            if(element)
                this._div_box.clonePosition($(arguments[0]),{'setWidth':false,'setHeight':false,'offsetTop':element.getHeight(),'offsetLeft':element.getWidth()/2});
            else
                this._moveDefault();
        }
        return this;
    },

    setContent: function(html){
        //if(this._type != this.DIALOG_FREESTYLE) return this;
        this._content_set = true;
        this._div_content.update(html);
        return this;
    },

    setExtraButtonLabel: function(label){
        this._button_extra_previous = this._button_extra.value;
        this._button_extra.value = label;
    },
    
    setOkayButtonLabel: function(label){
        this._button_okay_previous = this._button_okay.value;
        this._button_okay.value = label;
    },

    setCancelButtonLabel: function(label){
        this._button_cancel_previous = this._button_cancel.value;
        this._button_cancel.value = label;
    },

    setPreviousExtraButtonLabel: function(){
        if( this._button_extra_previous ){
            var label = this._button_extra.value;
            this._button_extra.value = this._button_extra_previous;
            this._button_extra_previous = label;
        }
    },
    
    setPreviousOkayButtonLabel: function(){
        if( this._button_okay_previous ){
            var label = this._button_okay.value;
            this._button_okay.value = this._button_okay_previous;
            this._button_okay_previous = label;
        }
    },

    setPreviousCancelButtonLabel: function(){
        if( this._button_cancel_previous ){
            var label = this._button_cancel.value;
            this._button_cancel.value = this._button_cancel_previous;
            this._button_cancel_previous = label;
        }
    },

    setStyle: function() {
    	var property, value;
    	
    	if(arguments.length == 2 ){ // single property set
    		property = arguments[0];
    		value = arguments[1];
    		
			if(typeof property == 'string' && typeof value == 'string'){
				//console.log('property set accepted');
        		this._div_box.setStyle(property, value);
    		}else{
//    			console.log('property set denied');	
    		}
    	}else if(arguments.length == 1){ // multiple property set
    		if(typeof arguments[0] == 'object'){
//    			console.log('property set accepted');
    			properties = arguments[0];

				for (var i in properties){
 					property = i;
 					value = properties[i];
 					
 					this._div_box.setStyle(property, value);	
				}
    		}else{
//    			console.log('property set denied');
    		}
    	}else{
//    		console.log('invalid property set encountered');
    	}
    	
    	return this;
  	},
  		
    remove: function(){
        this._destruct();
    },

    show: function(){
        if (this._div_forcefield != '') this._div_forcefield.show();
        this._div_box.show();
    },

    hide: function(){
        if (this._div_forcefield != '') this._div_forcefield.hide();
        this._div_box.hide();
    },

    destroy: function(){
        if (this._div_forcefield != '') this._div_forcefield.hide();
        this._destruct();
    },
    
    enableDragging: function(){
        if (typeof this._dragger == 'object') return;
        this.initDragger();
    },

    _onExtra: function(){
        if(this.onextra && typeof this.onextra == 'function'){
            freturn = this.onextra();
            if( freturn == true ) this.hide();
            return;
        }
        this.hide();
    },
    
    _onConfirm: function(){
        if(this.onconfirm && typeof this.onconfirm == 'function'){
            freturn = this.onconfirm();
            if( freturn == true ) this.hide();
            return;
        }
        this.hide();
    },

    _onCancel: function(){
        if(this.oncancel && typeof this.oncancel == 'function'){
            this.oncancel();
            return;
        }
        this.hide();
        this._destruct();
    },

    _onClose: function(){
        if(this.onclose && typeof this.onclose == 'function'){
            this.onclose();
        }
        this.destroy();
    },

    _destruct: function(){
        this._button_observer['okay'+this._id] = false;
        this._button_observer['cancel'+this._id] = false;
        DIALOG.delInstance(this._id,this);
        this._div_box.remove();
        //TODO::add stopObserving
    },

    _moveDefault: function(){
    	
    	var scrollXY=this._getScrollXY();//added on 7-11-08
    	      
		
		//=========Added by Ashok===============================//
		
		var screenHW=this._getAvilableSreenSize();
		var theTop=this._div_box.getHeight()<screenHW[0]?(((screenHW[0]-this._div_box.getHeight()))/3)+scrollXY[1]:(screenHW[0])/3+scrollXY[1];
		var theLeft=this._div_box.getWidth()<screenHW[1]?(((screenHW[1]-this._div_box.getWidth()))/2)+scrollXY[0]:(screenHW[1])/2+scrollXY[0];
		
		//========================================//
        theTop -= 120;
        if(theTop < 0) theTop = 1;
        //BY LG on 20-11-2008
        //=======ADDITIONAL CODE FOR BOTH IE6,IE7,Mozila=========//
        this._div_box.setStyle({'position':'absolute','top':theTop+'px','left':theLeft+'px'});/*fixed is changed to absolute [4-11-08]*/
    	//=======END ADDITIONAL CODE FOR BOTH IE6,IE7,Mozila=========//
    },
    
    //Added by aShok
    //
    //use to move the dialog box to desired position
    //
    moveTo: function(theTop,theLeft){    	    
       
        //=======ADDITIONAL CODE FOR BOTH IE6,IE7,Mozila=========//
        this._div_box.setStyle({'position':'absolute','top':theTop+'px','left':theLeft+'px'});/*fixed is changed to absolute [4-11-08]*/
    	//=======END ADDITIONAL CODE FOR BOTH IE6,IE7,Mozila=========//
    },

    _createContainer: function(){
        var id = arguments[0];
        var dialog_container = "";
        dialog_container += "    <div class='dialog_forcefield'><span/></div>";
        dialog_container += "    <div class='dialog_pointer'><span/></div>";
        dialog_container += "    <table style='border-collapse:collapse' cellspacing='0' cellpadding='0'><tr><td class='trans_border_top_left'></td><td class='trans_border'></td><td class='trans_border_top_right'></td></tr>";
        dialog_container += "    <tr><td class='trans_border'></td><td class='trans_border'>";
        dialog_container += "    <div class='dialog_container'>";
        dialog_container += "        <span class='dialog_close'><a>x</a></span>";
        dialog_container += "        <h2 class='dialog_title'><span>Generic Dialog Title</span></h2>";
        dialog_container += "        <div class='dialog_content' id='dialog_content' style='background:white'>";
        dialog_container += "            <div id='dialog_user_content' class='dialog_user_content' style='background:white'></div>";
        dialog_container += "            <div class='dialog_buttons' id='dialog_buttons'>";
        /*dialog_container += "                <input type='button' class='inputsubmit' value='Okay' />";
        dialog_container += "                <input type='button' class='inputsubmit' value='Cancel' />";*/
        dialog_container += "                <input type='button' style='font-size:11px;' value='Extra' class=\"c_mid\" />";
        dialog_container += "                <input type='button' style='font-size:11px;' value='Okay' class=\"default\"/>";
        dialog_container += "                <input type='button' style='font-size:11px;' value='Cancel' class=\"c_mid\" />";
        dialog_container += "            </div>";
        dialog_container += "        </div>";
        dialog_container += "    </div>";
        dialog_container += "    </td><td class='trans_border'></td></tr>";
        dialog_container += "    <tr><td class='trans_border_bottom_left'></td><td class='trans_border'></td><td class='trans_border_bottom_right'></td></tr></table>";
        
        return new Element('div',{'id':'generic_dialog_'+id,'class':'generic_dialog','style':'display:none;'}).update(dialog_container);
    },
    //added by Ashok on 7-11-08
     _getScrollXY:function() {
		
		  var scrOfX = 0, scrOfY = 0;
		 // alert("X="+window.pageXOffset );
		  	  if( typeof( window.pageYOffset ) == 'number' ) {
			    //Netscape compliant
			    scrOfY = window.pageYOffset;
			    scrOfX = window.pageXOffset;
			  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			    //DOM compliant
			    scrOfY = document.body.scrollTop;
			    scrOfX = document.body.scrollLeft;
			  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			    //IE6 standards compliant mode
			    scrOfY = document.documentElement.scrollTop;
			    scrOfX = document.documentElement.scrollLeft;
			  }
			
			 var scrOfXY=new Array();
			  scrOfXY[0]=scrOfX;
			  scrOfXY[1]=scrOfY;
			
			  return scrOfXY;
	},
	 //added by Ashok on 20-11-08
	_getAvilableSreenSize:function(){
		<!--

		 var viewportwidth;
		 var viewportheight;
		 
		 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		 
		 if (typeof window.innerWidth != 'undefined')
		 {
		      viewportwidth = window.innerWidth,
		      viewportheight = window.innerHeight
		 }
		 
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		
		 else if (typeof document.documentElement != 'undefined'
		     && typeof document.documentElement.clientWidth !=
		     'undefined' && document.documentElement.clientWidth != 0)
		 {
		       viewportwidth = document.documentElement.clientWidth,
		       viewportheight = document.documentElement.clientHeight
		 }
		 
		 // older versions of IE
		 
		 else
		 {
		       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		       viewportheight = document.getElementsByTagName('body')[0].clientHeight
		 }
		
		
		 var scrOfHW=new Array();
			  scrOfHW[0]=viewportheight-50;
			  scrOfHW[1]=viewportwidth;
		return(scrOfHW);	  
		//-->
	}
}

Dialog.button = function(){ this.initialize.apply(this,arguments); }
Dialog.button.prototype = {
    initialize: function(){
    
    },
    create: function(){
    }
   
}
/**
 * TODO: Move this to a different file
 */
var Dragger = Class.create();
Dragger.prototype = {
    _isDrag: false,
    _isStart: false,
    _listener: '',/*element to listen for drag events*/
    _toAnimate: '',/*element to animate when dragging starts*/
    _options: {},
    _posBeforeDrag: [0,0],
    _posOnDrag: [0,0],
    _posAfterDrag: [0,0],
    _cornerPtDiff: [0,0],
    initialize: function(){
        Object.extend(this._options,arguments[1] || {});
        this._listener = arguments[0];
        this._toAnimate = Object.isElement(this._options.toAnimate) ? this._options.toAnimate : this._listener;
        this._listener.observe('mousedown',this._onMouseDown.bindAsEventListener(this));
    },
    start: function(){
        this._isStart = true;
    },
    _onMouseDown: function(e){
        if (this._isStart != true) return;
        e.stop();
        this._posBeforeDrag = [e.pointerX(),e.pointerY()];
        var toAnimateVP = this._toAnimate.viewportOffset();
        this._cornerPtDiff = [this._posBeforeDrag[0] - toAnimateVP.left,this._posBeforeDrag[1] - toAnimateVP.top];
        this._isDrag = true;
        document.observe('mouseup',this._onMouseUp.bindAsEventListener(this))
        document.observe('mousemove',this._onDrag.bindAsEventListener(this))
    },
    _onMouseUp: function(e){
        e.stop();
        this._isDrag = false;
        document.stopObserving('mousemove',this._onDrag.bindAsEventListener(this));
        document.stopObserving('mouseup',this._onMouseUp.bindAsEventListener(this));
        this._posAfterDrag = [e.pointerX(),e.pointerY()];
        typeof this.ondragcomplete == 'function' ? this.ondragcomplete(this) : function(){};
    },
    _onDrag: function(e){
        if (this._isDrag != true) return;
        this._posOnDrag = [e.pointerX(),e.pointerY()];
        var vp = document.viewport.getDimensions();
        var ta = this._toAnimate.getDimensions();
        var nposx = this._posOnDrag[0] - this._cornerPtDiff[0];
        var nposy = this._posOnDrag[1] - this._cornerPtDiff[1];
        nposx = nposx > 0 ? nposx : 0;
        nposy = nposy > 0 ? nposy : 0;
        nposx = nposx + ta.width > vp.width ? vp.width - ta.width : nposx;
        nposy = nposy + ta.height > vp.height ? vp.height - ta.height : nposy;
        this._toAnimate.setStyle({'top':nposy+'px','left':nposx+'px'});
        typeof this.ondragafter == 'function' ? this.ondragafter(this) : function(){};
    }
}