/**
 * $Workfile: jquery.core.js $
 * $Revision: 27 $
 * $Modtime: 3/11/09 15:25 $
 * $Author: Aamir.afridi $
 *
 * Astun jQuery Core Function 
 *
 * Copyright (c) 2009 Astun Technology
 * Revision: 1.0
 */

//No conflict with prototype and other libraries
jQuery.noConflict();

//jQuery core function
jqueryFunctions = function($,$eventElement,panelsToShow,options)
{	
	//Function which will create the panels
	function loadPanels()
	{
		attachPanelWrapperElement = (typeof options.attachPanelWrapperTo!='undefined') ? options.attachPanelWrapperTo : '';
		//Create panel wrapper
		$eventElement.panelswrapper({id:"panels", floatOn:options.panelWrapperFloatOn,top:options.panelWrapperTopPosition, invisibleInStart:options.panelWrapperInvisibleInStart, attachToElement:attachPanelWrapperElement}).html('');	//Clear it (the loading msg)
		//Check if panels object is not available
		if(!panelsToShow) return;
		//Create panels
		$.each(panelsToShow,function(i,panelObj){
			if(!panelObj) return;
			if(!panelObj.title) panelObj.title = '';
			if(!panelObj.cssClass) panelObj.cssClass = '';
			if(!panelObj.visibilityBindEvent) panelObj.visibilityBindEvent = '';
			if(!panelObj.visibilityTriggerEvent) panelObj.visibilityTriggerEvent = '';
			//Append empty div for panel
				$('<div/>')
					.addClass(panelObj.cssClass)
					.attr('title',panelObj.title)
					.appendTo('#panels')
					.panel({
						hidePanelInstart	: options.hidePanelsInstart,
						closable			: options.closablePanel,
						pluginName			: panelObj.pluginName,
						pluginData			: panelObj.pluginData,
						pluginOptions		: panelObj.pluginOpts,
						visibilityBindEvent		: panelObj.visibilityBindEvent,
						visibilityTriggerEvent	: panelObj.visibilityTriggerEvent
					});
		});
		//Make the panels sortable
		$('#panels').sortable(
			{ 
				items: '.ui-dialog',
				grid: [5000,1],
				handle: '.ui-sort-icon'
			}
		)
		.find('input,select').keydown(function(e){  Astun.JS.Common.stopEventProp(e);  });
	}
	
	//Now create jRibbon
		(options.showJribbon) ? $eventElement.jribbon({callBackFunction: loadPanels}) : loadPanels();
	
	
	//Stop scrolling the page - Need a proper solution
	//window.onscroll=function() { window.scrollTo(0,0) }  //This one is not a good solution
	if($.browser.mozilla)
	{
		$([window, document.body]).keydown(function(e){ Astun.JS.Common.stopArrowKeys(e); });
	}
	
	//Popups
		//Converting Openlayers popUp into jQuery style
		$('.olFramedMarkerPopupContent').live('mouseover', function(){});

		//Creating jQuery popups
		$('.olFramedMarkerPopupContent').live('mouseover', function(){
			$(this).attr('rel',$(this).attr('id'));
			//Save the original zindex
			var $parent = $(this).parents('.olPopup');
			//Save the z-index in rel attribute
			if(typeof $parent.attr('rel')=='undefined') $parent.attr('rel',$parent.css('z-index'));
			//Increase the z-index
			$parent.css('z-index',10000);
			$(this).simpletooltip({fadeSpeed:'fast',width:180, html:$(this).find('.atPopupFeatureInfo p:first').html()}).trigger('mouseover');
		})
		.live('mouseout', function(){
			var $parent = $(this).parents('.olPopup');
			$parent.css('z-index',$parent.attr('rel'));
		})
		.live('popUpClicked', function(){
			$this = $(this);
			$this.find('h1:first').css('color','#666');
			//Remove other popups
			$('.atJQPopUp').remove();
			//Call the plugin again but this time the whole content will go in
			$this.simpletooltip({fadeSpeed:'fast',width:320, html:$this.find('.atPopupFeatureInfo').html()}).trigger('mouseover');

			//Remove the simpleToolTip class so that on mouse out it should not disapear - add another class for the refrence
			$('.simpleToolTip:last')
				.appendTo($('#atMap_OpenLayers_Container'))
				.fadeIn('fast')
				.attr('rel',$this.attr('id'))
				.css({'overflow-y':'auto', 'overflow':'hidden', 'max-height' : 400})
				.addClass('atJQPopUp')
				.removeClass('simpleToolTip')
				//Add info and close icons
				.find('.infoResult')
					.css('position','relative')
					.append(
						$('<a></a>')
							.attr({'title':'close', 'href':'#'})
							.addClass('olPopupCloseBox')
							.css({
								'position'	: 'absolute',
								'top'		: -2,
								'right'		: -2,
								'width'		: 17,
								'height'	: 17
							})
							.simpletooltip({fadeSpeed:1,width:30})
							.click(function(){ $(this).parents('.atJQPopUp').remove(); return false; })
					)
			
			//Setting the position of the popup
				//Take the css class of the popup and get the left and top position of the pop accordingly
			$eventElement.bind('adjustPopUp',function(){
					//$(window).trigger('mousemove');
				var position,
					$popUp = $('.atJQPopUp'),
					$smlPopUp = $eventElement.find("div[rel='"+$popUp.attr('rel')+"']"),
					$parent = $smlPopUp.parents('.olPopup');
					if(typeof $parent.position()=='undefined') return;
				var
					top  = $parent.position().top || 0,
					left = $parent.position().left || 0,
					w = parseInt($popUp.outerWidth(true),10),
					h = parseInt($popUp.outerHeight(true),10);
					sw = parseInt($smlPopUp.outerWidth(true),10),
					sh = parseInt($smlPopUp.outerHeight(true),10);
				if($parent.find('.olQuadrant-tl').length) position='tl';
				else if($parent.find('.olQuadrant-tr').length) position='tr';
				else if($parent.find('.olQuadrant-bl').length) position='bl';
				else if($parent.find('.olQuadrant-br').length) position='br';
				else position='br';

				switch(position)
				{
					case 'tl':
						left = left-w;
						top = top-h;
						break;
					case 'tr':
						top = top-h;
						left = left+sw;
						break;
					case 'bl':
						left = left-w;
						top = top+sh
						break;
					case 'br':
						left = left+sw;
						top = top+sh
						break;
				}
				
				//Set the position
					if(!$popUp.hasClass('adjusted')) $popUp.css({'top':top,'left':left}).addClass('adjusted');
					else $popUp.animate({top:top,left:left});
			});
			
			//Trigger the event to set the position, we can trigger the same event when map is moved
				$eventElement.trigger('adjustPopUp');
		});
		
		/*//Popups
		$('.olFramedMarkerPopupContent').live('mouseover', function(){
			//Save the original zindex
			var $parent = $(this).parents('.olPopup');
			//Save the z-index in rel attribute
			if(typeof $parent.attr('rel')=='undefined') $parent.attr('rel',$parent.css('z-index'));
			//Increase the z-index
			$parent.css('z-index',10000);
			//Increase the fontsize
			$(this).find('h1:first').animate({fontSize:'18px', color: '#000'}, 'fast');
			$(this).simpletooltip({fadeSpeed:'slow',width:320, html:$(this).find('.atPopupFeatureInfo').html()}).trigger('mouseover');
		}).live('mouseout', function(){
			var $parent = $(this).parents('.olPopup');
			$parent.css('z-index',$parent.attr('rel'));
			$(this).find('h1:first').animate({fontSize:'16px', color: '#666'}, 100);
		});*/
		
		
		if($eventElement.length!=0) $('#atButtonBar_btnOtherThings').live('click', function(){ $eventElement.trigger('togglePanelWrapper'); return false; });
		
	
	//Overwritting window's own alert with jQuery dialog
	if($.fn.dialog)
	{
		window.alert = function(msg) {
			//Hide all select dropdowns for ie6 only
			if($.browser.msie && $.browser.version=="6.0") $('select').css('visibility','hidden');
			//Check if msg
			if(!msg || $.trim(msg)=='') return;
			//rand num for id to make each dialog unique
			var dialogId = 'dialog'+Math.floor(Math.random()*10000);
			//Append new div to the body
			$('body').append($('<div/>').html(msg).attr({'title':'Alert', 'id':dialogId}));
			//Convert it into a dialog
			$('#'+dialogId).dialog({
				//bgiframe: true,
				modal: true,
				zIndex: 100000000,
				resizable: false,
				buttons: {
					OK: function() {
						$(this).dialog('close');
					}
				},
				close: function() {
					$('#'+dialogId).remove();
					//Show the drop downs
					$('select').css('visibility','visible');
				}
			})
			.closest('.ui-dialog').css('font-size',12);
			//Put the small icon with alert msg
			$('#'+dialogId)
				.css('padding-left',4)
				.before($('<span/>').css({'float':'left', 'margin-left':6, 'margin-top':6}).addClass('ui-icon ui-icon-alert'));

		}
	}
	
}
