// frame.js


// <![CDATA[

// General Purpose class level functions

// CLASS: Control
// A control can be added to panels
var Control = Class.extend({
	
	// C-tor
	// _class: HTML/CSS class of the control
	// The panel that contains this control
	construct: function(panel, props){
		this.panel = panel;
		
		// Setup properties
		// Override any default values with props passed in
		var defaults = {
			    
		};
		this.props = mergeWithDefaults(props,defaults);
	}
});

// CLASS: Panel - light-  Panels can be contained within panels
var Panel = Class.extend({

	// C-tor 
	// id - ID of the panel div
	// props - An object of properties
	construct: function(id, props) {
		this.id = id;
		this.jq = $('#'+id);  // JQuery of this Panel
		this.children = [];   // Child panels
		this.controls = [];   // Controls 
		
		// Setup properties
		// Override any default values with props passed in
		var defaults = {
		};
		this.props = mergeWithDefaults(props,defaults);	
		
		var thisPanel = this;
		
		// Find any child panels and add as panel objects
		this.jq.find('.panel').each(
    		function() { 
        		var id = $(this).attr('id');
        		var _props = $(this).attr("hsatts");
				var props = [];
				if (_props) 
	    			props = toProps(_props.split(';'));
        		thisPanel.addPanel(new Panel(id,props));
    	});
		
		// Find any controls and add as objects
		
	},
	
	// Add a child panel - the child can be accessed by
	// its id - the id of the child panel as set in its HTML tag
	addPanel: function(panel){
		this.children[panel.id] = panel;
	}
	
	/*
	// Add a control to this panel
	// id - of the object of class Control
	// div - div where control is to be placed, optional and can be undefined
	addControl: function(id, div) {
		if (!div)
			div = 'view';
	
	}
	*/
	
});

// CLASS: Frame - heavy - don't put frames within frames 
// extends Panel
var Frame = Panel.extend({

	// C-tor 
	// id - ID of the panel div
	// props - An object of properties
	construct: function(id, props) {
		// Call super method
		arguments.callee.$.construct.call(this,id, props);
		
		// Setup properties
		// Override any default values with props passed in
		var defaults = {
			resize:"window",  // window - Auto resize when browser window is resized, none - no auto	
			width:400, // Default width - must be a number - unit is px
			wrap:0     
		};
		this.props = mergeWithDefaults(props,defaults);
		this.isMin = false;  // Initially maximised
		
		// Wrap then resize
		if (this.props.wrap)
			this.wrap();
		this.resize();
		
		// Bind to window resize event if resize==window
		var panel = this;
		if (this.props.resize == "window")
			$(window).bind("resize", function() {panel.resize();});
		
	},
	
	// Wrap a plain HTML div with Panel divs
	wrap: function() {
		var myStyle = this.jq.attr("style");
		this.jq.replaceWith('\
				<div id=' + this.jq.attr("id") + ' class="view" style="' + myStyle + '" >\
					<div class="top"  style="width:100%;height:18px">\
						<div class="hleft"></div>\
						<div class="hcenter"></div>\
						<div class="hbuttons"></div>\
					</div>\
					<div class="content">\
						<div class="left">&nbsp;</div>\
						<div class="middle">' + this.jq.html() + '</div>\
						<div class="right">&nbsp;</div>\
					</div>\
					<div class="bottom">\
						<div class="c_left">&nbsp;</div>\
						<div class="c_middle">&nbsp;</div>\
						<div id="drag" class="c_right">&nbsp;</div>\
					</div>\
				</div>');
		// Reset this.jq
		this.jq = $('#'+this.id);  // JQuery of this Panel
		return this;
	},
		
	
    // Options
    
    // Resizable ( note this is not automatic resize when browser window resizes)
    // Draggable corner to resize. When this panel is 
    // made resizable, the browser resizing, see note,
    // below will no longer take effect after user first
    // drags corner to resize.
    //
    // Note: To make panel resize when browser is resized
    // ensure central parts of panel are set to % and 
    // perform the following event binding
    // $(window).bind("resize", function() {panel.resize();});
    resizable: function() {
    	var id = this.id;
    	var p = this; // this panel
		var jq = this.jq;
    	$("#drag").bind("mousedown", function(e){
		    var x = e.pageX;
		    var y = e.pageY;
            var w = jq.width();
            var h = jq.height();
            //$("#qb").css("position",'absolute');
		    var str = "( " + e.pageX + ", " + e.pageY + " )";  
   
$('#'+id+" p").html("Mouse Down! " + str);
//console.log(str);	    
var m = 0;

			// Bind to mouse move
		    $("body").bind("mousemove", function(e) {
m+=1;
	            jq.css("width",w+(e.pageX-x)+'px');
	            jq.css("height",h+(e.pageY-y)+'px');
$('#'+id+" p").html("Mouse moving! " + m);
			    // Resize relative
			    p.resize();
		    });
		    $("body").bind("mouseup", function(e) {
$('#'+id+" p").html("Mouse up! " + str);
		      $(this).unbind("mousemove mouseup");
		    });
		});
		return this;
    },
    
    // Returns this instance
	moveable: function() {
//console.log("Make moveable called");	
		var id = this.id;
		var jq = this.jq;				
		// Move window events
		$('#'+id+" #bar").bind("mousedown", function(e){
		      var x = e.pageX;
		      var y = e.pageY;
              var offset = jq.offset();
              jq.css("position",'absolute');
		      var str = "( " + e.pageX + ", " + e.pageY + " )";  
		      $('#'+id+" p").html("Mouse Down! " + str);
//console.log(str);
		      // Bind to mouse move
		      var m = 0;
		      $("body").bind("mousemove", function(e) {
		      		m+=1;
                	jq.css("left",offset.left+(e.pageX-x)+'px');
                	jq.css("top",offset.top+(e.pageY-y)+'px');
		        	$('#'+id+" p"+id).html("Mouse moving! " + m);
		      });
		      $("body").bind("mouseup", function(e) {
		        	$('#'+id+" p").html("Mouse up! " + str);
		        	$(this).unbind("mousemove mouseup");
		      });
		});
		
		return this;
	},
	
	// Resize - Recalculates its size based on browser window
	// size - i.e. should be called when first loaded or when
	// browser window resizes
	resize: function() {
//console.log("I am resizing");
		var os = 1; // offset
		var h =  $('#'+this.id).height(); // My height
		var bh = $('#'+this.id+" .top").height(); // Bar (Header) height
		
		
	    //var bw = $('#'+this.id+" #bar").width();
		var bw = (this.props.resize=="window")?$(window).width()-40:this.props.width;
	    var hlw = $('#'+this.id+" .hleft").width();
	    var hrw = $('#'+this.id+" .hbuttons").width();
        var hcw = bw-(hlw+hrw+os);
        
        var lw = $('#'+this.id+" .left").width();
        var rw = $('#'+this.id+" .right").width();
        var cw = bw-(lw+rw+os);
        
        var c_lw = $('#'+this.id+" .c_left").width();
        var c_rw = $('#'+this.id+" .c_right").width();
        var c_cw = bw-(c_lw+c_rw+os);	          
        
//console.log("bw="+bw+",hlw="+hlw+",hrw="+hrw+",hcw="+hcw);
	    $('#'+this.id+" .hcenter").css("width",hcw+'px');      
	    $('#'+this.id+" .middle").css("width",cw+'px');     
	    $('#'+this.id+" .c_middle").css("width",c_cw+'px');
	    
	    // Added 27/09/2009
	    $('#'+this.id).css("width",(bw-os)+'px');
	    // Assume bar height is same as footer (bottom) height
	    $('#'+this.id+" .content").css("height",(h-2*bh)+'px');
	},
	
	// Add a button - Button requires hover image
	// Automatically changes to previous image
	// id - Button ID
	addButton: function(id, hImage) {
	    var btn = $('#'+this.id+' #'+id);
	    var btnParent =btn.parent().eq(0);
		var baseImage = btnParent.css("background-image");
console.log(btnParent.css("background"));
		
		btn.hover(function() {
    		btnParent.css({background:hImage});
console.log("hovering");
		}, function() { 
console.log("unhovering :"+baseImage);
    		btnParent.css({background:baseImage});
		});
	},
	
	/* Minimize panel - remove content 
	 * size: size whole panel shrinked to
	 */
	min: function(size) {
		if (!this.isMin) {
			var id = '#'+this.id;
			this.height = this.jq.css('height');
//console.log('height is '+this.height);
/*
			$(id+' .left').hide();
			$(id+' .middle').hide();
			$(id+' .right').hide();
*/
			$(id+' .content').hide();
			this.jq.css('height',size);
			this.isMin = true;
		}
	},
	/* Maximise panel - show content */
	max: function() {
		if (this.isMin) {
			var id = '#'+this.id;
			/*
			$(id+' .left').show();
			$(id+' .middle').show();
			$(id+' .right').show();
			*/
			$(id+' .content').show();
			this.jq.css('height',this.height);
			this.isMin=false;
		}
	}

});	
    	
// Panel


// Class: Floating Frame
var FloatingFrame = Frame.extend({

	// C-tor 
	// id - ID of the popup window of CSS class box
	construct: function(id, props) {
		// Call super method
		arguments.callee.$.construct.call(this,id, props);
		
		// Make moveable and resizeable
		//this.moveable();
		//this.resizable();
	},
    	
    // Popup
    popup: function() {
		this.jq.css('visibility','visible');
    },
		
	// Popdown
    popdown: function() {
    	//TODO
		this.jq.css('visibility','hidden');
    } 
   
});	
// End FloatingPanel



// Class Notice Editor
var FP_NEdit = FloatingFrame.extend({ 
	// Create a Popup that turns the specified text area into a WYSIWYG editable object
	// id: ID of popup div
	// textarea: ID of area to turn into an editor
	construct: function(id, props, textarea) {
		// Call super method
		arguments.callee.$.construct.call(this,id, props);
		//alert(textarea);
		
		this.textarea = textarea; // Text area element ID
		
		tinyMCE.settings = {
			// General options 
			mode : "none", 
			theme : "advanced", 
			//plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager", 
			plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview",
			// Theme options 
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect", 
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", 
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", 
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage", 
			theme_advanced_toolbar_location : "top", 
			theme_advanced_toolbar_align : "left", 
			theme_advanced_statusbar_location : "bottom", 
			theme_advanced_resizing : false,
			setup : function(ed) { 
				ed.onInit.add(function(ed) {
					// Forces editor to render properly else editor is not editable until it is resized
					// To be resizable 'theme_advanced_resizing' needs to be true
					ed.show();
				});
			} 
			
		};
		

		tinyMCE.execCommand('mceAddControl', true, textarea);
		
		// NOTE we use the same tinyMCE instance as we use same popup for all queries
		// Content of each query is automatically loaded into the tinyMCE when it is 
		// popped up
		
		//tinyMCE.execInstanceCommand(textarea,'mceRepaint');
		// Hide the textarea until popup is called
	},
	
	// Override parents popup
	popup: function() {
		// unhide text area
		
		//alert("PopupEdit:popup called");
		
		// call super method
		arguments.callee.$.popup.call(this);
		
		//tinyMCE.execCommand('mceAddControl', true, this.textarea);
		//tinyMCE.execInstanceCommand(this.textarea,'mceRepaint');
		//tinyMCE.execInstanceCommand(this.textarea,'mceResize');
	},
	
	//Popup edit specific methods
	setQuery: function(query) {
    	this.query = query;
    	//tinyMCE.setContent(this.query.getNotice());
    	tinyMCE.get(this.textarea).setContent(this.query.getNotice());
    },
    
    getQuery: function() {
    	return this.query;
    },
    
    save: function() {
    	this.query.setNotice(tinyMCE.getContent());
    	this.popdown();
    }
	
});
// End FP_NEdit


// ]]>
	
	
	
/*
	var cc = "5";
	var bb = true;
	var props = [ "a:1", "b:2", "c:"+bb ]; // Array
	
	var _props = new Object();  // key value pairs - should use objects
	jQuery.map(props, function(n,i) {
	    var t = new Array();
	    t = n.split(':');
	    console.log("prop: "+t[0]+" value: "+t[1]);
	    _props[t[0]]=t[1];
	});
	
	console.log("prop b is "+_props["b"]);
*/