/**
 * $Workfile: jquery.panelswrapper.js $
 * $Revision: 49 $
 * $Modtime: 4/08/10 17:08 $
 * $Author: Aamir.afridi $
 *
 * jQuery Panels Wrapper Plugin
 * Copyright (c) 2009 Astun Technology (http://www.isharemaps.com)
 * @name $.panelswrapper
 * @cat Plugins/Wrapper
 * @author Aamir Afridi / info@aamirafridi.com
 */


/**
 * Create a Wrapper over the Map where we can place panels or anything else.
 *
 * @example $('#element').panelswrapper();
 * @desc Create a wrapper on the top of #element
 * @options 
 *		background: '#fff', 			//Background color of the wrapper
 *		borderWidth:	5, 				//Border width
 *		callBackFunction: 'callback',	//Any callback function which will recive the object itseft i.e. $('#element')
 *		closeButtonClass: 'myCloseBtn',	//The css that will be added to the close button of wrapper
 *		closeButtonTopPush: 10,			//Top push of close button
 *		cssClass: '', 					//Any additional CSS class if you want to add
 *		fontColor: '#000',				//CSS color (text color)
 *		fontSize: '15px',				//Leave empty for the body default font size
 *		height: 'auto', 				//Height of the wrapper
 *		hideable: true, 				//We will have cross button where we can hide or show the wrapper and its content
 *		hideInStart: false,				//Depends of hideable=true
 *		html: 'Initial text.', 			//The html of the wrapper
 *		id: 'jqPanelWrapper', 			//Give it an id
 *		padding: '5px', 				//CSS padding
 *		position: 'absolute',			//CSS position absolute or relative etc
 *		roundCorner:	true,			//Radius depends on css Class which will come from jQuery CSS framework (.ui-corner-all) Works only in Mozilla and Webkit browsers like Safari, Camino etc
 *		saveStatus: true,				//Depends of hideable=true
 *		top:	5, 						//Distance from top (If position is absolute)
 *		width: '310px' 					//Width of the wrapper
 */




(function($) {
	$.fn.panelswrapper = function(options) {
		// Extend the options if any provided
		var o = $.extend({}, $.fn.panelswrapper.defaults, options),
			$innerWrapper,
			resizeTimeout;
		
		// Iterate and reformat each matched element
		this.each(function() {

			//Save 'this' so can be used globally inside the plugin
				$this = $(this);
			
				//If there is no scroll, the positioning creates a problem on window.resize
				if(o.attachToElement!='') o.shadowCssClass = '';

			//If ID not provided than assign one itself
				if(!o.id || $.trim(o.id)=='') o.id='jqPanelWrapper';
			//Remove any previous panels wrapper
				$('#atPWparent, .atJQPanelContent').remove();
			//See if the border width is 0 than make it atleast 1
				o.borderWidth = (o.borderWidth<1) ? 1 : o.borderWidth;
				if(o.attachToElement!='')
				{
					o.borderWidth = 2;
				}
			//Create if not found, an empty div which wraps everything inside body
			//Add empty DIV at the end of body
				$('body').append(
					$('<div/>')
						.addClass('atMainJQWrapper')
						.hide()
						.css({
							'position'	: o.position,
							'font-size'	: o.fontSize,
							'color'		: o.fontColor,
							'top'		: o.top,
							'right'		: 0,
							'z-index'	: 99999,
							'font-weight': 'normal',
							'display'	: 'block'
						})
						.addClass(o.shadowCssClass+' ui-corner-bl')
						.append(
							$('<div/>')
								.css('position','relative')
								.addClass('ui-state-default ui-corner-bl')
								.append(
									//Open/Close button
									$('<a href="#"></a>')
										.addClass(o.shadowCssClass+' atJqOpenClose ui-icon ui-icon-carat-1-e ui-state-default ui-corner-bl ui-corner-tl')
										.width(18)
										.css({
											'border-width'	: o.borderWidth,
											'position'		: 'absolute',
											'border-right-width': 0,
											'left'			: -19,
											'top'			: -1,
											'outline'		: 'none'
										})
										.html('Hide/Show') //Will be shown if CSS is not available
									,
									$('<div/>')
										.addClass('ui-state-default ui-corner-bl '+ o.cssClass)
										.addClass((!o.hideable) ? 'ui-corner-tl' : '')
										.height('auto')
										.css({
											'border-width'	: 0,
											'background'	: o.background,
											'border-right-width' : 0
										})
										.append(
											$('<div/>')
												.addClass('atPanelInnerWrapper ui-corner-bl ')
												.width(o.width)
												.attr('id',o.id)
												.css({'padding':o.padding, 'max-height': $(o.attachToElement).height()-((o.attachToElement!='') ? 10 : 120)})
												.html(o.html)
										)
									)
					)
				);

			//Save the refrences
				var $mainWrapper = $('.atMainJQWrapper'),
					$hideShowBtn = $('.atJqOpenClose');
			//Update the refrence
				$innerWrapper = $('#'+o.id);
				//set its height
				if(o.attachToElement!='')
				{
					$innerWrapper.css('height',parseInt($innerWrapper.css('max-height'),10)-1);
					$innerWrapper.css('max-height','');
				}
				
				
			//Determine the position of the element and set the position of the panel wrapper accordingly
				if(o.attachToElement!='')
				{
					//Remove the top and bottom border of the panels div
						$mainWrapper.find('div').css({'border-top':'none','border-bottom':'none'})
					//Set the width of outer Div
					$mainWrapper
						.width($innerWrapper.outerWidth(true)+(o.padding))
						.css({'position':'relative', 'top':0, 'float': (o.floatOn=='right') ? 'right' : 'left'})
						.wrap('<div/>');
					$mainWrapper
						.parent()
						.addClass('atPanelWrapperParent')
						.attr('id','atPWparent')
						.css({'position':'absolute', 'overflow':'hidden'})
						.width(parseInt($mainWrapper.width(),10)+20)
						.height(parseInt($(o.attachToElement).height(),10))
					
					//If float on left than do some css tweeks
					if(o.floatOn=='left')
					{
						//styling other divs
						$mainWrapper.find('div:eq(0), div:eq(1), .atJqOpenClose').removeClass('ui-state-default').addClass('ui-state-hover');
						$mainWrapper.find('div:eq(0)').addClass('ui-corner-br');
						//also the close link
						$mainWrapper.find('.atJqOpenClose').removeClass('ui-corner-bl ui-corner-tl').addClass('ui-corner-br ui-corner-tr');
						
						//Styling wrapper
						$mainWrapper
							.removeClass('ui-corner-bl')
							.find('div:first')
								.removeClass('ui-corner-bl')
								.css({
									'border-left-width'	: 0,
									'border-right-width': o.borderWidth
								})
								.find('div:first')
									.removeClass('ui-corner-bl')
									.css({
										'border-left-width'	: 0
									});
						//Moving the hide and show button
						$mainWrapper
							.find('.atJqOpenClose')
								.css({
									'left'	: 'auto',
									'right'	: '-'+parseInt(18+o.borderWidth,10)+'px',
									'border-left': 'none',
									'border-right-width': o.borderWidth
								})
								.attr('title','Expand/Collapse')
								.addClass('ui-icon-carat-1-w')
								.removeClass('ui-icon-carat-1-e');
						//Move the map zoom bar
							$(o.attachToElement).bind('moveZoomBarWithPanelWrapper',function(){
								//If no jRibbon than move the zoombar a little bit away from panel wrapper
								$('.olControlPanZoomBar').css({'top':21, 'left':($.browser.msie && $.browser.version=="6.0") ? 14 : 4 });
							})
							
							setTimeout(function(){ $this.trigger('moveZoomBarWithPanelWrapper') } ,100 );
					}
					
					//Call the function to set the position
						setWrapperPosition($mainWrapper.parent());
				}
				else $mainWrapper.attr('id','atPWparent').show();
				
				function setWrapperPosition(element)
				{
					if(o.resizeMap && o.attachToElement!='')
					{
						var newWidth = '100%';
						//If jRibbon is opened than subtract the width of panel wrapper from the new width
						if(parseInt($mainWrapper.css('right'),10)==0) newWidth = parseInt($(o.attachToElement).parent().width(),10)-parseInt($mainWrapper.width(),10);
						$(o.attachToElement).trigger('resizeMapElement',[newWidth]);
						//debug: document.title = ""+ Date()+ " - panelswrapper 4";
						$(o.attachToElement).css('float', (o.floatOn=='left') ? 'right' : '');
					}
					
					if(o.attachToElement!='')
					{
						var e = $(o.attachToElement).parent();
						var additionalTop = 0;
						var offsetFix = parseInt(e.offset().left,10);
						//Changes for non-IE browsers
						if(!$.browser.msie) additionalTop = (document.doctype.publicId.indexOf("Transitional")>0) ? 1 : 0;
						//Get the offsets
							var newTop		= parseInt(e.offset().top,10)+parseInt(o.top,10),//+parseInt(additionalTop,10),
								newRight	= (parseInt(e.offset().left,10)+parseInt(e.outerWidth(true),10))-parseInt($mainWrapper.parent().width()),
								newLeft		= (offsetFix<0) ? 3 : offsetFix+3;
								
						
						element.css({
							'top'	: newTop,
							'left'	: (o.floatOn=='right') ? newRight : newLeft
						});
						$mainWrapper.show();
					}
				}
			
			
			
			//If the panel wrapper can be hideable
				if(!o.hideable) $hideShowBtn.remove(); //Hide the minimize button
			//Addjust the height of the inner wrapper on window.resize event
				//For details about the following two lines, open atolMapCreator.js file and search for the string 'Peter' ;)
				var winWidth = $(window).width(),
					winHeight = $(window).height();
				
				$(window).resize(function(e,fakeResize){
										  
					onResize = function() {
						if(o.attachToElement!='')
						{
							$innerWrapper.css('height', $(o.attachToElement).height()-((o.attachToElement!='') ? 10 : 120));
						}
						else
						{
							$innerWrapper.css('max-height', $(o.attachToElement).height()-((o.attachToElement!='') ? 10 : 120));
							if($.browser.msie && $.browser.version=="6.0") $innerWrapper.css('height', $(o.attachToElement).height()-((o.attachToElement!='') ? 10 : 120));
						}
						setWrapperPosition($mainWrapper.parent());
					}
					//onResize();
					
					var winNewWidth = $(window).width(),
						winNewHeight = $(window).height();
					if(winWidth!=winNewWidth || winHeight!=winNewHeight || typeof fakeResize!='undefined')
					{
						window.clearTimeout(resizeTimeout);
						resizeTimeout = window.setTimeout(onResize, 10);
					}
					//Update the width and height
					winWidth = winNewWidth;
					winHeight = winNewHeight;
				});
			
			$(o.attachToElement).unbind('togglePanelWrapper').bind('togglePanelWrapper',function(){ $hideShowBtn.trigger('click'); });
			
			//Do hide and show on click
			$hideShowBtn.click(function(e,speed){
				//If we need to hide the panel on page load than we should have speed
					o.animationSpeed = (speed!='') ? speed : o.animationSpeed;
				//vars
					var cookieValue  = false,
						wrapperWidth = parseInt($mainWrapper.width(),10);
				//If main wrapper is visible
				if(parseInt($mainWrapper.css('right'),10)==0)
				{
					var rightPos = (o.floatOn=='left') ? wrapperWidth : '-'+wrapperWidth;				
					//Animate the main wrapper
					$mainWrapper.animate( { right: rightPos }, o.animationSpeed,
						function(){
							//Change icon
								(o.floatOn=='left') ? $hideShowBtn.addClass('ui-icon-carat-1-e').removeClass('ui-icon-carat-1-w') : $hideShowBtn.addClass('ui-icon-carat-1-w').removeClass('ui-icon-carat-1-e');
							//resizeMap
								if(o.resizeMap && o.attachToElement!='')
								{
									$(o.attachToElement).trigger('resizeMapElement',['100%']);
									//debug: document.title = ""+ Date()+ " - panelswrapper 1";
									$(o.attachToElement).css('float', (o.floatOn=='left') ? '' : ''); //by default it is left/single quotes are just to overwrite if there is any other value i.e. left/right
								}
							//Reduce the main wrapper size - otherwise ie6 will overlap the zoombar
							$mainWrapper.parents('.atPanelWrapperParent').width(20);
							/*Cookie value is already false by default in above lines - else part will make it true (below)*/
							
							//Change the value of the 'other things that may interest you' button
							$('#atButtonBar_btnOtherThings').val('Show side panel');
						}
					);
				}
				else
				{
					//Restore the parent mainWrapper size - before animating the mainWrapper
					$mainWrapper.parents('.atPanelWrapperParent').width(parseInt($mainWrapper.width(),10)+20);
					//Animate the main wrapper
					$mainWrapper.animate( { right:0 }, o.animationSpeed,
						function(){
							//Change icon
								(o.floatOn=='left') ? $hideShowBtn.addClass('ui-icon-carat-1-w').removeClass('ui-icon-carat-1-e') : $hideShowBtn.addClass('ui-icon-carat-1-e').removeClass('ui-icon-carat-1-w');
							//resizeMap
								if(o.resizeMap && o.attachToElement!='')
								{
									 var newWidth = parseInt($(o.attachToElement).parent().innerWidth(),10)-wrapperWidth;
									 $(o.attachToElement).trigger('resizeMapElement',[newWidth]);
									 //debug: document.title = ""+ Date()+ " - panelswrapper 2";
									 $(o.attachToElement).css('float', (o.floatOn=='left') ? 'right' : '');
								}
							//Cookie value
								cookieValue = true;
							//Change the value of the 'other things that may interest you' button
							$('#atButtonBar_btnOtherThings').val('Hide side panel');
						}
					);
				}
				//Callback
					checkCallback(o.callBackFunction);
				//Set Cookie to save the status
					if(o.saveStatus) Astun.JS.Common.setCookie('showJQWrapper',cookieValue,o.savePanelPositionsForDays);
				
				return false;
			});
		
			//Check save status
			if(o.saveStatus)
			{
				//First make options.hideInStart = false
				o.hideInStart=false;

				var cookie = Astun.JS.Common.getCookie('showJQWrapper');//Get Cookie's value
				//If value is false, Hide the wrapper, otherwise leave it as 'show'
				if(cookie && cookie=='false'/*false is a string here*/) $hideShowBtn.trigger('click',[1]);
			}
			
			//If we want to hide the wrapper in start, just trigger 'click' event of Hide (minus signed) button
				if(o.hideInStart) $hideShowBtn.trigger('click',[1]);
				else
				{
					if(o.resizeMap && o.attachToElement!='')
					{
						var newWidth = parseInt($(o.attachToElement).parent().width(),10)-parseInt($mainWrapper.width(),10);
						$(o.attachToElement).trigger('resizeMapElement',[newWidth]);
						//debug: document.title = ""+ Date()+ " - panelswrapper 3";
						$(o.attachToElement).css('float', (o.floatOn=='left') ? 'right' : '');
					}
					$('#atButtonBar_btnOtherThings').val('Hide side panel');
				}
			
			//Bind hide and show events to the map
				$this.unbind('panelWrapperVisibility').bind('panelWrapperVisibility',function(evt,visible){
					var visiblePanels = $mainWrapper.find('.ui-dialog').length,
						hiddenPanels  = $mainWrapper.find('.atPanelHidden').length,
						$grabber      = $mainWrapper.find('.ui-dialog .ui-sort-icon');
					if(visible)
					{
						//Show the whole wrapper
							if($mainWrapper.css('visibility')=='hidden')
							{
								//We should make a slide in effect so first hide
									$mainWrapper.css('right','-'+parseInt($mainWrapper.width(),10)+'px');
								//Show it
									$mainWrapper.css('visibility','visible');
								//Slide in
									$hideShowBtn.trigger('click');
							}
							else
							{
								$mainWrapper.css('visibility','visible');
							}
						//If slided in, show it
							if(parseInt($mainWrapper.css('right'),10)!=0) $hideShowBtn.trigger('click');
					}
					else
					{
						//Hide the whole wrapper if there are no panels it
							if($mainWrapper.find('.ui-dialog').length == $mainWrapper.find('.atPanelHidden').length)
								$mainWrapper.css('visibility','hidden');
					}
					//Check if there is only one shown panel than remove the dotted icon as there is no need to sort a panel with itself :)
							if(visiblePanels-1 == hiddenPanels) //Means there is only one shown panel
								$grabber.css('visibility','hidden');
							else
								$grabber.css('visibility','visible');
								
				}) //End of .bind
				
				//Make it invisible in start
				if(o.invisibleInStart)
					$this.trigger('panelWrapperVisibility',false) //The last argument is hideOnLoad=true
			
			
		}); //End of .each
		
		//Return the main body of the wrapper not the parent itself ( this )
		return $innerWrapper;
		
	};

	//Private function: Check callback
	function checkCallback(cb)
	{
		if(cb || cb!='')
		{
			if(typeof window[cb] === 'undefined') alert('Callback function not found.');
			else window[cb].call(this,$innerWrapper);
		}
	}
	
	// Public: plugin defaults (for options details, read the comments on the top of the this file)
	$.fn.panelswrapper.defaults = {
		animationSpeed:800,
		attachToElement: 'body',
		background: '#fff',
		borderWidth: 0,
		callBackFunction: '',
		closeButtonClass: 'jqCloseBtn',
		closeButtonTopPush: 10,
		cssClass: '',
		fontColor: '#000',
		fontSize: '15px',
		hideable: true,
		hideInStart: false,//Depends of hideable=true //This will just slide in the panel wrapper, while the next option make it invisible completely
		invisibleInStart: false,
		html: '<div style="text-align:center;margin:25px 0;font-size:17px" id="atPanelWrapperLoader">Loading panels...</div>',
		id: 'jqPanelWrapper',
		left: '',
		right: '',
		padding: 5,
		position: 'absolute',
		floatOn: 'left', // right or left only
		roundCorner: true,
		resizeMap: true, //When closing and opening the panel wrapper, it will also resize the map div
		savePanelPositionsForDays : 7,
		saveStatus: false,
		shadowCssClass :'ui-shadow',
		top: 40,
		width: 330
	};	
	
})(jQuery);

