/*
 * xWindows v2 - Windows Manager
 * by kieran boyle (semantic.value@gmail.com)
 *
 * original concept was Daniel Lin
 */

var z = 1000;
var ontop = "";
var oDimensions = new Array();
var oPosition = new Array();

var xWindows =
{
	blank					: '/moflick/style/1000/images/e.gif',
	windows				: [],
	minimizeorder	: 0,

	init : function( id ){

		var win = $('<div class="x-windows" id="'+id+'"></div>');

		win.append(
			'<table width="100%" cellpadding="0" cellspacing="0" border="0">'+
				'<tbody>'+
					'<tr>'+
						'<td class="tl"></td><td class="tc"><div class="'+ id + '"></div><div class="x-windows-title">Window</div></td><td class="tc x-windows-controls"><img class="x-windows-mini" src="'+this.blank+'" title="Minimize" /><img class="x-windows-max" src="'+this.blank+'" title="Maximize" /><img class="x-windows-restore" src="'+this.blank+'" title="Restore" /><img class="x-windows-close" src="'+this.blank+'" title="Close"/></td><td class="tr"></td>'+
					'</tr>'+
					'<tr>'+
						'<td class="lc"></td>'+
						'<td colspan="2" valign="top">'+
							'<div class="x-windows-content"></div>'+
						'</td>'+
						'<td class="rc"></td>'+
					'</tr>'+
					'<tr>'+
						'<td class="bl"></td><td colspan="2" class="bc"></td><td class="br"><div class="x-window-resize" title="Resize"><img src="'+this.blank+'" /></div></td>'+
					'</tr>'+
				'</tbody>'+
			'</table>'
		);

		$(document.body).append(win);

		win.css('zIndex', z + 1); // $('div.x-windows').length + 1010);

		win.handler  = win.find('td.tc, .x-windows-controls');
		win.title    = win.find('div.x-windows-title');
		win.controls = win.find('td.x-windows-controls');
		win.content  = win.find('div.x-windows-content');
		win.status   = win.find('td.bc');
		win.resize   = win.find('div.x-window-resize');

		win.handler._parent = win;
		win.controls._parent = win;
		win.content._parent = win;

		win.onclose = function(){ return true };

		/*
		win.title.dblclick(function(){
				xWindows.maximizeWindow(this);
		});
		*/

		win.isResizable = function(bol){
			xWindows.resizable(this, bol);
		};

		win.isScrolling = function(bol){
			xWindows.isScrolling(this, bol);
		};

		win.setSize = function(w, h){
			xWindows.setSize(this, w, h);
		};

		win.fullsize = function(bol){
			xWindows.isFullSize(this, bol);
		};

		win.moveTo = function(x, y){
			xWindows.moveTo(this, x, y);
		};

		win.show = function(){
			xWindows.show(this);
		};

		win.hide = function(){
			xWindows.close(this);
		};

		win.load = function(type, source, title, ajaxOpt){
			xWindows.load(this, type, source, title,ajaxOpt);
		};

		win.dispose = function(){
			xWindows.dispose(this);
		}

		win.attr('uid', this.windows.length);

		win.uid = this.windows.length;

		this.windows[this.windows.length] = win;

	  return win;

	},


	load : function(win, type, source, title, ajaxOpt)
	{

		var type = type.toLowerCase();

		if( typeof title != 'undefined' )

			win.title.get(0).firstChild.nodeValue = title;

			if ( type == "inline" ){
				win.content.html(source);
			}
			else if ( type == "div" ){
				win.content.html($('#'+source).html());
			}
			else if ( type == "iframe" ){
				win.content.css("overflow", "hidden");

				if( win.content.children().length < 1 || win.content.children().get(0).tagName != "IFRAME" )
					win.content.html('<iframe src="" style="margin: 0; padding: 0; width: 100%; height: 100%" name="_iframe-' + win.uid + '"></iframe>');

				window.frames["_iframe-" + win.uid].location.replace( source );
			}

			win.content.datatype = type;

			// check if plugin exists
			if( jQuery.fn.moTooltip ) {
				$(".x-windows-mini, .x-windows-max, .x-windows-restore, .x-windows-close").moTooltip({
						x: -15,
						y: -10
				});
			}

	},


	open : function(id, type, source, title, attr, ajaxOpt)
	{
		var win;

		function getAttribute(Name)
		{
			var config = new RegExp( Name + "=([^,]+)", "i");

			return ( config.test(attr) ) ? eval( '('+RegExp.$1+')' ) : 0;
		}

		if ( $('#'+id+'-win').length == 0 )
			win = this.init(id);
		else
			win = xWindows.windows[parseInt( $('#'+id+'-win').get(0).getAttribute('uid') ) ];

		try {
			win.setSize( getAttribute( ("width") ), ( getAttribute("height") ) );
		}
		catch( err ){
			alert( "line 158: windows.js open err: " + err.description + " height: " + getAttribute("height"));
		}

		finally {

		}

		var xpos = getAttribute("center") ? "middle" : getAttribute("left");

		var ypos = getAttribute("center") ? "middle" : getAttribute("top");

		win.css("visibility" ,"visible");

	  win.css("display" , "block");

	  win.content.css("display","block");

		win.isResizable( getAttribute("resize") );

		win.isScrolling( getAttribute("scroll") );

		win.isModel = getAttribute("model");

		win.minimizable = getAttribute("min");

		win.maximizable = getAttribute("max");

		win.closable = getAttribute("close");

		$('.x-windows-restore').hide();

		if(win.isModel) xWindows.showModel();

		if(win.resizeBool)
		{
			win.resize.mousedown(function(e){
				xWindows.etarget = this;
				xWindows.setupDrag(e);
			});
		}
		else{
			win.resize.remove();
		}

		if( !win.minimizable ){
			if( win.controls.find('img[title=Minimize]').length > 0 ) win.controls.find('img[title=Minimize]').hide();
		};

		if( !win.closable ){
			if( win.controls.find('img[title=Close]').length > 0 ) win.controls.find('img[title=Close]').hide();
		};

		if( !win.maximizable ){
			if( win.controls.find('img[title=Maximize]').length > 0 ) win.controls.find('img[title=Maximize]').hide();
			win.controls.find('img[title=Restore]').hide();
		};

		if( getAttribute("drag") )
		{
			win.handler.mousedown(function(e){
				xWindows.etarget = this;
				xWindows.setupDrag(e);
			});
		}

		if(getAttribute("scroll"))
		{
			win.resize.mousedown(function(e){
				xWindows.etarget = this;
				xWindows.setupDrag(e);
			});
		}

		win.click(function(e){ xWindows.setFocus(e); });

		win.controls.click(function(e){
			xWindows.setupControls(e);
		});

		win.moveTo(xpos, ypos);

		win.load(type, source, title, ajaxOpt);

		win.fullsize( getAttribute("fullsize") );

		return win;

	},

	showOnTop: function(win){

		var el = $("#"+win).attr("id");
		var original_id	= el.split("-win");

		$(".x-windows").each(function(){
			var temp = $(this).attr("id").split("-win");

			if( $(this).attr("id") != el ) {
				//if( !$.browser.msie ) $(this).fadeTo(500,0.8);
				$("#"+temp[0]+"-btn").find("table").removeClass("active-win");
			}
		});

		z = z + 1;

		$("#"+el).css({'z-index' : z});

		//if( !$.browser.msie ) $("#"+el).fadeTo(500,1);

		$("#" + original_id[0] + "-btn").find("table").addClass("active-win");

		ontop = el;

		return false;

	},

	setFocus : function(e){

		var w = xWindows;
		var $clicked = $(e.target);
		var win = w.getUID($clicked);
		var btn	= win.attr('id').split("-win");

		$(".x-windows").each(function(){
			var tmp	= $(this).attr("id").split("-win");

			if( $(this).attr("id") != win.attr('id') ) {
				$('#'+tmp[0]+'-btn').find("table").removeClass("active-win");

				//if( !$.browser.msie ) $('#'+tmp[0]+'-win').fadeTo(500,0.8);
			}
		});

		z = z + 1;

		win.css({'z-index': z});

		//if( !$.browser.msie ) win.fadeTo(500,1);

		$( !$("#"+btn[0]+"-win").is(":hidden") )
			$("#"+btn[0]+"-btn").find("table").addClass("active-win");

		ontop = btn[0]+"-win";
	},

	resizable : function(win, bol){
		win.resizeBool = (bol) ? 1 : 0;
	},

	isScrolling : function( win, bol ){
		win.content.css("overflow", (bol) ? "auto" : "hidden");
	},

	setSize : function( win, w, h ){
		win.css("width", Math.max(parseInt(w), 150) + 'px');
		win.content.css("height", Math.max(parseInt(h), 150) + 'px');
	},

	resizeWindow : function(win, e){
		win.css('width', Math.max(xWindows.width + xWindows.distancex, 150) + "px");
		win.content.css('height', Math.max(xWindows.contentheight + xWindows.distancey, 100) + "px");
	},

	moveTo : function( win, x, y ){
		this.getViewPoint();
		win.css("left",( x == "middle" ) ? this.scrollPos[0] + (this.docSize[0]-win.get(0).offsetWidth) / 2 + "px" : this.scrollPos[0] + parseInt(x) + "px");
		win.css("top",( y == "middle" ) ? this.scrollPos[1] + (this.docSize[1]-win.get(0).offsetHeight) / 2 + "px" : this.scrollPos[1] + parseInt(y) + "px");
	},

	// window taskbar button
	createTaskbarButton : function(id, title){

		// create new button through DOM
		var	btn = document.createElement('div');

		// check if it exists or not
		if( $("#"+id+'-btn').length == 0 ){

			$(".x-windows").each(function(){

				var tmp = $(this).attr("id").split("-win");

				$("#"+tmp[0]+"-btn").find("table").removeClass("active-win");

			});

			// truncate title if length is greater than 18 chars
			var btnTitle = xWindows.truncateTitle(title, 18);

			$(btn).attr('id', id+'-btn');

			$(btn).css({
				float: 'left',
				marginTop: '2px',
				marginLeft: '3px'
			});

			$(btn).html(

				'<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap">'+

					'<tbody><tr>'+

						'<td class="x-taskbutton-left"><i>&#160;</i></td>'+

						'<td class="x-taskbutton-icon"><img class="'+ id + '-btn" src="/moflick/style/1000/images/e.gif"></td>'+

						'<td class="x-taskbutton-center"><button class="x-btn-text" type="button">' + btnTitle + '</button></td>'+

						'<td class="x-taskbutton-right"><i>&#160;</i></td>'+

					'</tr></tbody>'+

				'</table>'

			);

			// set active button
			$(btn).find("table").addClass("active-win");


			$(btn).bind("click", function(){

				var current = $(this).attr("id").split("-btn");

				var active_window = $("#"+current[0]+"-win");

				var task_button = $(this).attr("id");


				if( active_window.is(":visible") ){

					var windows = $(document.body).find(".x-windows");

					if( windows.length > 1 ){

						$(".x-windows").each(function(){

							var tmp = $(this).attr("id").split("-win");

							$("#"+tmp[0]+"-btn").find("table").removeClass("active-win");

							if( $(this).attr("id") == $(active_window).attr("id") ){

								if( $(active_window).attr("id") == ontop ){

									xWindows.minimizeWindow( tmp[0] );

									return false;

								}
								else{

									if($("#"+id+"-btn").find("table tbody .x-taskbutton-icon img").hasClass("icon-chat-btn-pending") )
										$("#"+id+"-btn").find("table tbody .x-taskbutton-icon img").removeClass("icon-chat-btn-pending").addClass("icon-chat-btn");

									xWindows.showOnTop( id+"-win" );

									return false;

								}
							}
						});

						return false;

					}
					else{

						if ( $(active_window).attr("id") == ontop )
							xWindows.minimizeWindow( id );
						else
							xWindows.showOnTop( id+"-win" );

						if($("#"+id+"-btn").find("table tbody .x-taskbutton-icon img").hasClass("icon-chat-btn-pending") )
							$("#"+id+"-btn").find("table tbody .x-taskbutton-icon img").removeClass("icon-chat-btn-pending").addClass("icon-chat-btn");

						return false;

					}
				}
				else{

					$(".x-windows").each(function(){

						var tmp = $(this).attr("id").split("-win");

						$("#"+tmp[0]+"-btn").find("table").removeClass("active-win");

					});

					$("#"+id+"-win").show();

					xWindows.showOnTop( id+"-win" );

					if($("#"+id+"-btn").find("table tbody .x-taskbutton-icon img").hasClass("icon-chat-btn-pending") )
						$("#"+id+"-btn").find("table tbody .x-taskbutton-icon img").removeClass("icon-chat-btn-pending").addClass("icon-chat-btn");

				}

			});

			// append button to taskbar
			$(".taskbar-collection").append(btn);


			xWindows.checkScroll();

		}
		else{

			return false;
		}

	},

	checkScroll : function(){

			var buttons = $('.taskbar-collection').find(".x-btn-wrap").size();

			var total_size = buttons * parseInt($(".x-btn-wrap").css("width"));

			var maxSize = $.iUtil.getSize(document.body);

			var swidth = maxSize.w;

			//alert(swidth);

			if ( total_size > swidth ){
				//alert("total size: "+total_size+"   screen size: "+swidth);

    		$("#x-taskbar").find("a.next").show();
				$("#x-taskbar").find("a.prev").hide();
			}
			else{
    		$("#x-taskbar").find("a.next").hide();
				$("#x-taskbar").find("a.prev").hide();
			}
	},



	minimizeWindow : function( id ){

		var el = $("#"+id+"-win");
		var btn = $("#"+id+"-btn");

		if( btn.find("table").hasClass("active-win") ){
			btn.find("table").removeClass("active-win");
		}

		el.hide();

	},


	maximizeWindow : function( id, type ){

		var o = xWindows;
		var el = $('#'+id+'-win');

		var maxSize = $.iUtil.getSize(document.body);

		var h = maxSize.h-100+"px";
		var w = maxSize.w+"px";
		//alert(h);
		//alert(w);

		if( type == "max" ){
			el.find('.x-windows-max').hide();

			el.find('.x-windows-restore').show();

			el.css({left: '0px', top: "30px", width: w});

			el.find('.x-windows-content').css({"height": h});

		}
		else{

			var original = o.saveViewState( el );

			oDimensions = original.dimensions;

			oPosition = original.position;

			el.find('.x-windows-max').hide();

			el.find('.x-windows-restore').show();

			el.css({left: '0px', top: "30px", width: w});

			el.find('.x-windows-content').css({"height": h});
		}




		return false;

	},


	isFullSize : function( win, bol ){

		var tmp = win.attr("id").split("-win");

		if(bol){
			xWindows.maximizeWindow(tmp[0], "max");
		}
	},

	revertWindow: function(id){

		var o = xWindows;

		var el = $("#"+id+"-win");

		el.find('.x-windows-restore').hide();

		el.find('.x-windows-max').show();

		if( oDimensions == null || oDimensions == "" || oDimensions == "undefined" ){

			el.css("width", Math.max(parseInt(500), 150) + 'px');

			el.find('.x-windows-content').css("height", Math.max(parseInt(500), 150) + 'px');

		}
		else{

			el.css("width", oDimensions[0] +"px");

			el.find('.x-windows-content').css("height", oDimensions[1] + "px");

			el.css({left: oPosition[0]+"px", top:oPosition[1]+"px"});
		}

		return false;

	},



	truncateTitle : function( text, length, ellipsis )

	{

		if (typeof length == 'undefined')
			var length = 18;

		if (typeof ellipsis == 'undefined')
			var ellipsis = '...';

		if (text.length < length) return text;

		for (var i = length-1; text.charAt(i) != ' '; i--) {

			length--;

		}

		return text.substr(0, length) + ellipsis;

  },


	manageTaskbarButton : function( id ){

		if( $("#"+id).is(":hidden") ){

			$(".x-windows").each(function(){

				var tmp = $(this).attr("id").split("-win");

				$("#"+tmp[0]+"-btn").find("table").removeClass("active-win");

			});

		}

	},


	show : function( win )
	{

		var o = xWindows;

		win.css('display', 'block');

		win.state = 'restore';

		o.showOnTop(win.attr('id'));

		o.manageTaskbarButton(win.attr('id'));

		if(win.isModel) xWindows.showModel();

	},


	close : function( win )
	{

		try{

			var closewinbol = win.onclose();

		}
		catch(err){

			var closewinbol = true;

		}
		finally{

			if( typeof closewinbol == "undefined" )
			{

				var closewinbol = true

			}

		}

		if( closewinbol )
		{

			if(win.state != "minimized"){

				win.css('display', 'none');

				var tmp = win.attr('id').split("-win");

				var nid = tmp[0] + '-btn';

				$('#' + nid).remove();

				xWindows.dispose(win);

			}

			if(win.isModel)	xWindows.hideModel();

		}

		return closewinbol;

	},


	dispose : function( win )
	{

		if( win.isModel ) xWindows.hideModel();


		for (var i = 0; i< xWindows.windows.length; i++)
		{

			if(xWindows.windows[i] == win)
			{

				win.handler._parent = null;

				win.controls._parent = null;

				win.content._parent = null;

				xWindows.windows[i] = null;

				break;

			}

		}

		win.remove();

		xWindows.checkScroll();

	},


	setupControls : function(e)
	{

		var o = xWindows;

		var sourceobj = window.event ? window.event.srcElement : e.target;

		var win = o.getUID(sourceobj);

		var tmp = win.attr('id').split("-win");

		if (/Minimize/i.test(sourceobj.getAttribute("title"))) {
			o.minimizeWindow(tmp[0]);
		}
		else if(/Maximize/i.test(sourceobj.getAttribute("title"))) {
			o.maximizeWindow(tmp[0]);
		}
		else if (/Restore/i.test(sourceobj.getAttribute("title"))) {
			o.revertWindow(tmp[0]);
		}
		else if (/Close/i.test(sourceobj.getAttribute("title"))) {
			o.close(win);
		}


		return false;
	},


	showModel : function(){

		var model = $('#xWindows_hideIframe');

	  if ( model.length == 0 )
		{

			model = $('<iframe id="xWindows_hideIframe" scrolling="no" frameborder="0" style="position:absolute; top:0px; left:0px;-moz-opacity:0.7; opacity:0.7;filter:alpha(opacity=70);background:#fff;"></iframe>');

			model.appendTo( document.body );

			$(window).bind( 'resize', function(){xWindows.showModel();})

	  }

		xWindows.getViewPoint();

	  model.css('width' , xWindows.pageSize[0]+'px');

	  model.css('height', xWindows.pageSize[1]+'px');

	},


	hideModel : function(){

		$(window).unbind('resize')

		var model = $('#xWindows_hideIframe');

		if( model.length > 0 )	model.remove();

	},


	setupDrag : function(e){

		var o = xWindows;

		var target = o.etarget;

		var win = o.getUID(target);

		var e = window.event || e;

		o.initmousex = e.clientX;
		o.initmousey = e.clientY;

		o.initx = parseInt(win.get(0).offsetLeft);
		o.inity = parseInt(win.get(0).offsetTop);
		o.width = parseInt(win.get(0).offsetWidth);

		o.contentheight = parseInt( win.content.get(0).offsetHeight );

		if( win.content.datatype == "iframe" ){
			win.css('backgroundColor', '#f8f8f8');
			win.content.css('visibility', 'hidden');
		}

		document.onmousemove = o.getDistance;

		document.onmouseup = function(){
			if( win.content.datatype == "iframe" ){
				win.content.css('visibility','visible');
			}

			o.stopDrag();
		}

		return false;

	},


	getDistance : function(e)
	{

		var o = xWindows;
		var etarget = o.etarget;
		var e = window.event || e;

		o.distancex = e.clientX - o.initmousex;
		o.distancey = e.clientY - o.initmousey;

		var win = o.getUID(etarget);

		if( etarget.className == "tc"){
			win.css('left', o.distancex + o.initx + "px");
			win.css('top', o.distancey + o.inity + "px");
		}
		else if( etarget.className == "x-window-resize" ){
			o.resizeWindow(win, e);
		}

		return false;

	},


	stopDrag : function(){

		xWindows.etarget = null;
		document.onmousemove = null;
		document.onmouseup = null;

	},


	getViewPoint : function(){

		var ie = document.all && !window.opera

		var domclientWidth = document.documentElement && parseInt( document.documentElement.clientWidth ) || 100000;

		this.standardbody = ( document.compatMode == "CSS1Compat" )? document.documentElement : document.body;

		this.scrollPos = [ (ie) ? this.standardbody.scrollLeft : window.pageXOffset, (ie)? this.standardbody.scrollTop : window.pageYOffset];

		this.docSize = [(ie) ? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent)) ? window.innerWidth : Math.min(domclientWidth, window.innerWidth-16), (ie)? this.standardbody.clientHeight: window.innerHeight];

		if( ie ){
			this.scrollSize  = [(document.body.scrollWidth > document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth, (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight];
		}
		else{
			this.scrollSize = [document.body.scrollWidth,window.innerHeight + window.scrollMaxY];
		}

		this.pageSize = [(this.scrollSize[0] < this.docSize[0])?this.docSize[0]:this.scrollSize[0], (this.scrollSize[1]< this.docSize[1])?this.docSize[1]:this.scrollSize[1]];

	},


	saveViewState : function(win){

		this.getViewPoint();

		win.lastPos = [ parseInt((win.css('left')||win.get(0).offsetLeft))-xWindows.scrollPos[0], parseInt( (win.css('top')||win.get(0).offsetTop))-xWindows.scrollPos[1] ];
		win.lastSize = [parseInt (win.css('width')),parseInt( win.find(".x-windows-content").css('height'))];

		var viewstate = {
			dimensions: win.lastSize,
			position: win.lastPos
		};

		return viewstate;
	},


	getUID : function(dom){
		return xWindows.windows[ parseInt(  $(dom).parents('div.x-windows').get(0).getAttribute('uid') ) ];
	}
}

jQuery.fn.openxWindows = function(boxAttr, title){

	var $this = jQuery(this);

	$this.attr('uid', xWindows.open($this.attr('id')+'-win', 'div', $this.attr('id'), title, boxAttr).uid);
	xWindows.createTaskbarButton($this.attr('id'), title);
}

jQuery.fn.disposexWindows = function(boxAttr, title){

	var $this = jQuery(this);

	if ( $this.get(0).getAttribute( 'uid' ) != null ){
	   xWindows.windows[parseInt($this.get(0).getAttribute( 'uid' ))].dispose();
	   $this.removeAttr('uid' );
	}
	else{
		// alert("You must initialize the xWindows object first!");
		return false;
	}
}

jQuery.fn.showxWindows = function(boxAttr, title){

	var $this = jQuery(this);

	if (  $this.get(0).getAttribute( 'uid' ) != null  ){
	   xWindows.windows[parseInt($this.get(0).getAttribute( 'uid' ))].show();
	}
	else{
		// alert("You must initialize the xWindows object first!");
		return false;
	}
}

jQuery.fn.hidexWindows = function(boxAttr, title){

	var $this = jQuery(this);

	if ( $this.get(0).getAttribute( 'uid' ) != null  ){
	   xWindows.windows[parseInt($this.get(0).getAttribute( 'uid' ))].hide();
	}
	else{
		// alert("You must initialize the xWindows object first!");
		return false;
	}
}

