/**********************
**
**		JukeBox.Dialog 1.0
**		Copyright by Thomas Foelker
**	
***********************/
(function($) {
	
	$.jbdialog = function (data, options) {
		return $.jbdialog.impl._init(data, options);
	};
	
	$.jbdialog.close = function () {
		$.jbdialog.impl._close(true);
	};
	
	$.fn.jbdialog = function (options) {
		return $.jbdialog.impl._init(this, options);
	};
	
	
	$.jbdialog.impl = {
		
			_options:{
				startDrag: false
			}, 
			
			_defaults : {
					overlay: 50,
					overlayCss: {},
					buttons: [],
					ids: '',
					names: '',
					title: 'Dialog',
					label: '',
					containerId: 'jb_container',
					containerCss: {},
					headerId: 'jb_header',		
					close: true,
					closeTitle: 'Close',
					closeClass: 'jb_close',
					titleClass: 'jb_title',
					closeIconWidth: 24,
					persist: false,
					onOpen: null,
					onShow: null,
					onClose: null,
					art: 'OK',
					icon: '',
					icon_width: 50,
					height: 55,
					width: 350,
					btnbarheight: 75,
					url: '',
					imgpath: 'images/'
				},
				
			opts: null,
			
			dialog: {},
			
			_init: function (data, options) {
				// merge defaults and user options
				this.opts = $.extend({}, this._defaults, options);
				
				// determine how to handle the data based on its type
				if (typeof data == 'object') {
					// convert DOM object to a jQuery object
					data = data instanceof jQuery ? data : $(data);

					// if the object came from the DOM, keep track of its parent
					if (data.parent().parent().size() > 0) {
						this.dialog.parentNode = data.parent();

						// persist changes? if not, make a clone of the element
						if (!this.opts.persist) {
							this.dialog.original = data.clone(true);
						}
					}
				}
				else if (typeof data == 'string' || typeof data == 'number') {
					// just insert the data as innerHTML
					data = $('<div>').html(data);
				}
				else {
					// unsupported data type!
						return false;
				}
					
				this.dialog.data = data.addClass('modalData');
				data = null;
				
				// create the modal overlay, container and, if necessary, iframe
				this._create();
				
				// display the modal dialog
				this._open();				
				
			},

			/*
			 * Create and add the modal overlay and container to the page
			 */
			_create: function () {
				
				var self = this;
				var _div_dialog_width = 0;
				var _div_dialog_height = 0;
				var _div_icon_width = 0;				
				var _div_content_width = 0;
				var _div_icon_height = 0;
				var _div_content_height = 0;
				
				/*
				 * Standard Aufbau
				 */
	
				$.jukebox.createOverlay(this.dialog, this.opts.overlay);
				//this.createDiv(this, 'overlay');
				var jbContainer = this.createDiv(this, 'container');
							
				jbContainer.append('<div class="jb_titlebar" name="jb_titlebar"></div>');
				var jbTitlebar = $('.jb_titlebar', jbContainer);	
					
				jbTitlebar.append('<div class="jb_title" name="jb_title"></div>');
				var jbTitle = $('.jb_title', jbTitlebar);
				
				jbTitlebar.append('<div class="jb_titlebar_icon"></div>');
				var jbTitlebarIcon = $('.jb_titlebar_icon', jbTitlebar)

				jbContainer.append('<div class="jb_content" id="jb_content"></div>');
				var jbContent = $('.jb_content', jbContainer);
				
				jbContent.append('<div class="jb_content_icon"></div>');
				var jbContentIcon = $('.jb_content_icon', jbContent);
				
				jbContent.append('<div class="jb_content_text" id="jb_content_text"></div>');
				var jbContentText = $('.jb_content_text', jbContent);
								
				jbContainer.append('<div class="jb_buttonpane"></div>');
				var jbButtonpane = $('.jb_buttonpane', jbContainer);
				
				
				
				
				/*
				 * Titel des Dialogs
				 */
				jbTitle.append(this.opts.title);
				
				
			
				/*
				 * Schliessen-Icon in der Titeleiste
				 */
				
				this.setStyles("titleicon", jbTitlebarIcon);				
				//jbTitlebar.append('<a href="#" class="jb_titlebar_close"><span>X</span></a>');
				jbTitlebarIcon.append('<img src="'+this.opts.imgpath+'close.png" border="0">');
				
				
				
				jbTitlebarIcon.mousedown(function(ev) {
					ev.stopPropagation();
				})
			
				.click(function() {
					self._close();
					return false;
				})
				.keydown(function(ev) {
					var ESC = 27;
					ev.keyCode && ev.keyCode == ESC && self._close(); 
				});
		
				
				
				// fix issues with IE and create an iframe
				if ($.browser.msie && ($.browser.version <= 7)) {
					this.fixIE();
				}
				
				
				this.drawIcon(jbContentIcon);
				
					
				
				var _btnwidth = 20;
				var _btnpane_cssname = 'right';
				var _btnpane_cssval = 'right';
				var jb_element = null;
				var jb_element_name = "";
				
				
				switch(this.opts.art)
				{
				case 'OK':
					
					_btnpane_cssname = "text-align";
					_btnpane_cssval = "center";	
					
				break;
				
				case 'IFRAME':
					
					_btnpane_cssname = "text-align";
					_btnpane_cssval = "center";
					jb_element = $(document.createElement('iframe'))
					.attr('id', 'jb_iframe')
					.attr('name', 'jb_iframe')
					.attr('width', this.opts.width - 10)
					.attr('height', this.opts.height -10)				
					.attr('src', this.opts.url)
					.addClass('jb_iframe');
									
				break;			
				
				case 'INPUT':
					_btnpane_cssname = "right";
					_btnpane_cssval = "12px";	
					jb_element = $(document.createElement('input'))
					.attr('id', 'jb_input')
					.attr('name', 'jb_input')
					.attr('size', '60')
					.attr('type', 'text')
					.addClass('jb_input');
								
					_btnwidth = 55;
					
					if(this.opts.label.length > 0)
	          			_btnwidth += this.opts.label.length + (this.opts.label.length * 5);
					
				break;
				
				case 'TEXTAREA':
					_btnpane_cssname = "right";
					_btnpane_cssval = "12px";
					jb_element = $(document.createElement('textarea'))
					.attr('id', 'jb_textarea')
					.attr('cols', '30')
					.attr('rows', '4')
					.attr('name', 'jb_textarea')
					.addClass('jb_textarea');

				break;

				
				case 'SELECT':
					_btnpane_cssname = "right";
					_btnpane_cssval = "12px";				
					
					jb_element = $(document.createElement('select'))
					.attr('id', 'jb_selectbox')
					.attr('name', 'jb_selectbox')
					.attr('size', '1')
					.addClass('jb_selectbox');
					        		
	          		var values = this.opts.ids.split("~");
	          		var names = this.opts.names.split("~");
	          		
	          		for( var i=0; i<values.length; i++)
					{
						if(_btnwidth < names[i].length)
						 	_btnwidth = names[i].length + 30;
						 	
	          			$('<option value="'+ values[i]+'">'+ names[i]+'</option>').appendTo(jb_element)
	   				}
	          		
	          		
	          		if(this.opts.label.length > 0)
	          			_btnwidth += this.opts.label.length + (this.opts.label.length * 5);
	          		
	
				break;
				
				case 'LISTBOX':
					_btnpane_cssname = "right";
					_btnpane_cssval = "12px";				
					
					jb_element = $(document.createElement('select'))
					.attr('id', 'jb_listbox')
					.attr('name', 'jb_listbox')
					.attr('size', '5')
					.attr('style', 'width:100%')
					.addClass('jb_listbox');

					
	          		var values = this.opts.ids.split("~");
	          		var names = this.opts.names.split("~");
	          		
	          		for( var i=0; i<values.length; i++)
					{
						if(_btnwidth < names[i].length)
						 	_btnwidth = names[i].length + 30;
						 	
	          			$('<option value="'+ values[i]+'">'+ names[i]+'</option>').appendTo(jb_element)
	   				}
	          		
	          		
	          		
	
				break;				
				
				default:
					_btnpane_cssname = "right";
					_btnpane_cssval = "12px";
				
				break;		
				}

								
				_div_dialog_width = this.opts.width;
				
				if(_btnwidth > 22)
					_div_dialog_width += _btnwidth;
				
				this.opts.width = _div_dialog_width;
				
				_div_dialog_height = this.opts.height + this.opts.btnbarheight;
				_div_content_height= this.opts.height;
				_div_icon_width = this.opts.icon_width;
				
				if(_div_icon_width > 0)
					_div_content_width = _div_dialog_width - _div_icon_width;
				else
					_div_content_width = _div_dialog_width;
				
			/*	
				// fix issues with IE and create an iframe
				if ($.browser.msie && ($.browser.version <= 7)) {
					$('.jb_container').css.width = 300;
					_div_dialog_width = $('.jb_container').css.width;
					this.opts.width = _div_dialog_width;
				}else{
					_div_dialog_width = $('.jb_container').outerWidth();
					this.opts.width = _div_dialog_width;
				}	
				*/
				
		//		if(_btnwidth > 22)
			//		_width += _btnwidth;
		
				
				
						
				jbContentText.css("left", _div_icon_width);			
				jbContentText.css("height", _div_content_height);			

				
				jbContentText.append(this.dialog.data);
	
				
				if(jb_element)
				{
					this.drawElement(jb_element, jbContentText)
				}
				
				var objCss ={
						'height'	: _div_dialog_height
				}
				
	
				jbContainer.css("width", _div_dialog_width);
				
				jbContainer.css(objCss);	
		
				/*
				jbContainer.css({width: _width});											
				jbContent.css({width: _width});									
				jbContent.css({width: _width});
				jbContentText.css({width: _width});
*/
				
			//	this.setStyles("title", jbTitle);

			/*
				
				jbContentText.append("_div_content_width: " +  _div_content_width);
				jbContentText.append("<br>jbContainer.width(): " +  jbContainer.css("width"));
				jbContentText.append("<br>jbTitlebar.width(): " + jbTitlebar.css("width"));
				jbContentText.append("<br>jbTitle.width(): " + jbTitle.css("width"));
				jbContentText.append("<br>jbTitlebarIcon.width(): " + jbTitlebarIcon.css("width"));
				jbContentText.append("<br>jbContent.width(): " +  jbContent.css("width"));
				jbContentText.append("<br>jbContentIcon.width(): " +  jbContentIcon.css("width"));
				jbContentText.append("<br>jbContentText.width(): " +  jbContentText.css("width"));
				jbContentText.append("<br>jbButtonpaneText.width(): " + jbButtonpane.css("width"));

			*/		
	
				
				this.drawButtons(jbButtonpane,_btnpane_cssname, _btnpane_cssval);
				
			},
			
			_open: function () {
				// display the iframe
				if (this.dialog.iframe) {
					this.dialog.iframe.show();
				}
				
				
				var wnd = $(window), doc = $(document), _top = 0, _left = 0;
				
				var yOffSet = wnd.scrollTop();
				var xOffSet = wnd.scrollLeft();
				
				_top += ((wnd.height() / 2) - (this.opts.height / 2) - 100) + yOffSet;
				_left += ((wnd.width() / 2) - (this.opts.width / 2)) + xOffSet;
				
				if(_top < 0)
					_top = 0;
				
				if(_left < 0)
					_left = 0;
												
				this.dialog.container.css({top: _top, left: _left});
				
				this.dialog.overlay.show();
				this.dialog.container.show();			
				
				this.bindEvents(this);
			},
			
			
			_close: function (external) {
				// prevent close when dialog does not exist
			
				if (!this.dialog.data) {
					return false;
				}
				
				// if the data came from the DOM, put it back
				if (this.dialog.parentNode) {
					// save changes to the data?
					if (this.opts.persist) {
						// insert the (possibly) modified data back into the DOM
						this.dialog.data.hide().appendTo(this.dialog.parentNode);
					}
					else {
						// remove the current and insert the original, 
						// unmodified data back into the DOM
						this.dialog.data.remove();
						this.dialog.original.appendTo(this.dialog.parentNode);
					}
				}
				else {
					// otherwise, remove it
					this.dialog.data.remove();
				}

				// remove the remaining elements
				this.dialog.container.remove();
				this.dialog.overlay.remove();
				if (this.dialog.iframe) {
					this.dialog.iframe.remove();
				}

				// reset the dialog object
				this.dialog = {};
				
				this.unbindEvents();
			},
			
			setStyles: function (_key, _object) {
				
				
				switch(_key)
				{
				
					case "title":						
						_object.css("width", this.opts.width - this.opts.closeIconWidth-10);						
					break;
					
					case "titleicon":
						_object.css("width", this.opts.closeIconWidth);
						
						
					break;	
					
					case "contenticon":						
						var objCss ={
								'width' : this.opts.icon_width
						}
						_object.css(objCss);
					
						if ($.browser.msie && ($.browser.version <= 7)) 
						{
							_object.css("padding-top", '1em');	
						}
						
					break;						
					
					
				}
				
			},
			
			drawElement: function (_element, _object) {
				
				switch(_element.attr('id'))
				{
					case 'jb_iframe':
						_element.appendTo(_object);
					break;
									
					case 'jb_input':
						_object.append('<br>');			          		
		          		_object.append(this.opts.label);				
						_element.appendTo(_object);
					break;
					
					case 'jb_textarea':
						_element.appendTo(_object);
					break;					
					
					case 'jb_login_name':
						_object.append('<br><table class="tt" border="2">');		
						_object.append('<tr><td>Name:</td><td><input  type="text" id="jb_login_name" class="jb_login_name" size="30" name="jb_login_name"/></td></tr>');
						_object.append('<tr><td>Passwort:</td><td><input type="password" id="jb_login_pass" class="jb_login_pass" size="30" name="jb_login_pass"/></td></tr>');
						_object.append('</table>');

					break;					

					case 'jb_selectbox':
						_object.append('<br>');			          		
		          		_object.append(this.opts.label);				
						_element.appendTo(_object);
					break;
					
					case 'jb_listbox':
						_object.append('<br>');			          		
		          		_object.append(this.opts.label);
		          		_object.append('<br>');
						_element.appendTo(_object);
					break;
		
				}
				
			},
			
			drawButtons: function (_object,_btnpane_cssname, _btnpane_cssval) {
			
				$.each(this.opts.buttons, function() { l = 1; return false; });	
				if (l == 1) {					
					_object.css(_btnpane_cssname, _btnpane_cssval);
					$.each(this.opts.buttons, function(name, value) {
						var btn = $(document.createElement('button')).text(name).click(value);
						if(name.length > 8)
							btn.css("width", name.length + 80);
						else
							btn.css("width", name.length + 60);
							
						btn.css("width", 75);
						_object.append(btn);
						
					});
									
				}				
				
			},
			
			drawIcon: function (_object) {
				
				switch(this.opts.icon)
				{
				case "info":
			
					this.setStyles("contenticon", _object);
					_object.append('<img src="'+this.opts.imgpath+'ic_info.png" border="0">');
					
				break;
			
				case "quest":
					this.setStyles("contenticon",_object);
					_object.append('<img src="'+this.opts.imgpath+'ic_help.png" border="0">');
					
				break;
			
				case "err":
					this.setStyles("contenticon",_object);
					_object.append('<img src="'+this.opts.imgpath+'ic_err.png" border="0">');
				break;		
			
				default:
					this.opts.icon = "";
					this.opts.icon_width = 0;
				break;
				}
			},
			
			bindEvents: function (self) {
				
				
				$('.' + self.opts.titleClass).mousedown(function (e) {
					var jb_container = document.getElementById("jb_container") //reference dhtml window div
					
					e.preventDefault();
					
					var pageX = e.pageX;
					var pageY = e.pageY; 
					
					//$('.' + self.opts.titleClass).append('<span style="color:#00F;">Mouse down.</span>');

					
					self.initmousex = pageX; //store x position of mouse onmousedown
					self.initmousey = pageY;
					
					self.initx=parseInt(jb_container.offsetLeft) //store offset x of window div onmousedown
					self.inity=parseInt(jb_container.offsetTop)
					self.width=parseInt(jb_container.offsetWidth) //store width of window div
					self.height=parseInt(jb_container.offsetHeight) //store height of window div's content div					
				
									
					self._options.startDrag = true;
					
				});
				
				$('.' + self.opts.titleClass).mousemove(function(e){
				
					if(self._options.startDrag == true)
					{
						var jb_container = document.getElementById("jb_container") //reference dhtml window div
						var pageX = e.pageX;
						var pageY = e.pageY; 
					
						self.distancex = pageX - self.initmousex;
						self.distancey = pageY - self.initmousey;
					
						jb_container.style.cursor = "pointer";
					
						// fix issues with IE and create an iframe
						if ($.browser.msie && ($.browser.version <= 7)) {
							jb_container.style.background = "#E0E0E0";
						}else{
							jb_container.style.backgroundColor = "#E0E0E0";
							jb_container.style.border = "1px dotted grey";	
						}	
																	
						jb_container.style.left = self.distancex + self.initx + 'px';
						jb_container.style.top = self.distancey + self.inity + 'px';
					
					//	$('.' + self.opts.titleClass).append('<span style="color:#00F;">'+self.initx+'</span>');
					
					}
					return false;
				});	
				
				$('.' + self.opts.titleClass).mouseup(function(e){
				//	$('.' + self.opts.titleClass).append('<span style="color:#00F;">Mouse up.</span>');
					
					
					var jb_container = document.getElementById("jb_container") //reference dhtml window div
				
					self._options.startDrag = false;
					jb_container.style.cursor = "default";
					//alert(self._options.startDrag);
					
					// fix issues with IE and create an iframe
					if ($.browser.msie && ($.browser.version <= 7)) {
						jb_container.style.background = "#D0D0D0";
					}else{
						
						jb_container.style.backgroundColor = "#D0D0D0";	
						jb_container.style.borderTop = "1px solid grey";
						jb_container.style.borderLeft = "1px solid grey";
						jb_container.style.borderRight = "1px solid black";				
						jb_container.style.borderBottom = "1px solid black";
						
					}
					return false;
				});	
				
				$('.' + self.opts.titleClass).mouseout(function(e){
					//	$('.' + self.opts.titleClass).append('<span style="color:#00F;">Mouse up.</span>');
						
						
						var jb_container = document.getElementById("jb_container") //reference dhtml window div
					
						self._options.startDrag = false;
						jb_container.style.cursor = "default";
						//alert(self._options.startDrag);
						
						// fix issues with IE and create an iframe
						if ($.browser.msie && ($.browser.version <= 7)) {
							jb_container.style.background = "#D0D0D0";
						}else{
							
							jb_container.style.backgroundColor = "#D0D0D0";	
							jb_container.style.borderTop = "1px solid grey";
							jb_container.style.borderLeft = "1px solid grey";
							jb_container.style.borderRight = "1px solid black";				
							jb_container.style.borderBottom = "1px solid black";
							
						}
						return false;
					});					
				
					
			},
			
			
			unbindEvents: function () {
				// remove the close event
				$('.' + this.opts.closeClass).unbind('click');
			},			
			
			dragDialog: function (event, _left, _top) {
			
				var self = this;
				
				var jb_container = document.getElementById("jb_container") //reference dhtml window div
				
				
			//	var e=window.event || event;
				
				self.initmousex = _left; //store x position of mouse onmousedown
				self.initmousey = _top;
				
				
				
				//alert(event.type);
				
			//	alert(event.pageX);
				self.initx=parseInt(jb_container.offsetLeft) //store offset x of window div onmousedown
				self.inity=parseInt(jb_container.offsetTop)
				self.width=parseInt(jb_container.offsetWidth) //store width of window div
				self.height=parseInt(jb_container.offsetHeight) //store height of window div's content div
				
				document.onmousemove = function(e, _left, _top){
				
					
				
				
					self.distancex = e.PageX - self.initmousex;
					
					alert(self.distancex);
					
					self.distancey = _top - self.initmousey;
					jb_container.style.backgroundColor = "#E0E0E0";
					jb_container.style.border = "1px dotted grey";
				
					
					jb_container.style.left = self.distancex + self.initx + "px";
					jb_container.style.top = self.distancey + self.inity;				
				};				
				
				document.onmouseup = function(){
					jb_container.style.backgroundColor = "#D0D0D0";	
					jb_container.style.borderTop = "1px solid grey";
					jb_container.style.borderLeft = "1px solid grey";
					jb_container.style.borderRight = "1px solid black";				
					jb_container.style.borderBottom = "1px solid black";
					document.onmousemove=null;
					document.onmouseup=null;
				};
				
			return false;
				
				
			},
			
			/*
			 * Fix issues in IE 6
			 */
			fixIE: function () {
				var wHeight = $(document).height() + 'px';
				var wWidth = $(document).width() + 'px';

				// position hacks
				this.dialog.overlay.css({position: 'absolute', height: wHeight, width: wWidth});
				this.dialog.container.css({position: 'absolute'});

				// add an iframe to prevent select options from bleeding through
				this.dialog.iframe = $('<iframe src="javascript:false;">')
					.css($.extend(this.opts.iframeCss, {
						opacity: 0, 
						position: 'absolute',
						height: wHeight,
						width: wWidth,
						zIndex: 1000,
						top: 0,
						left: 0
					}))
					.hide()
					.appendTo('body');
			},
			
			createDiv: function (_parent, _name) {
				
				
				if(_name == 'container')
				{
					_parent.dialog.container = $('<div>')
					.attr('id', _parent.opts.containerId)
					.addClass('jb_container')
					.css($.extend(_parent.opts.containerCss, {
						position: 'absolute', 
						overflow: 'hidden',					
						zIndex: 3100
					}))

					.hide()
					.appendTo('body');
										
					return _parent.dialog.container;
				}
			}
	};
	
})(jQuery);
