/**
 * $Workfile: jquery.core.js $
 * $Revision: 11 $
 * $Modtime: 21/06/10 14:36 $
 * $Author: Aamir.afridi $
 *
 * Astun jQuery Core Function 
 * Copyright (c) 2010 Astun Technology
 */

//jQuery core function
jQuery.noConflict();
jqueryFunctions = function($,$eventElement,panelsToShow,options)
{
	function loadPanelWrapper()
	{
		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});
		var timer = 0;
		timer = setInterval(function(){
			if(astun.isReasterLayerLoaded && astun.isSourceLoad)
			{
				astun.isReasterLayerLoaded = false;
				astun.isSourceLoad = false;
				clearTimeout(timer);
				setTimeout(loadPanels,100);
			}
		},100);
	}
	//Function which will create the panels
	function loadPanels()
	{
		//Check if panels object(main object) is available
		if(typeof panelsToShow=='undefined') return;
		//Create panels
		$.each(panelsToShow,function(i,panelObj){
			//Append empty div for panel
				$('<div/>')
					.addClass(panelObj.cssClass)
					.attr('title',panelObj.title)
					.appendTo('#panels')
					.panel({
						hidePanelInstart	: options.hidePanelsInstart,
						closable			: options.closablePanel || false,
						collapseInStart		: panelObj.pluginOpts.collapseInStart || false,
						pluginName			: panelObj.pluginName || '',
						pluginData			: panelObj.pluginData,
						pluginOptions		: panelObj.pluginOpts || {},
						visibilityBindEvent	: panelObj.visibilityBindEvent || '',
						visibilityTriggerEvent : panelObj.visibilityTriggerEvent || ''
					});
		});
		//Remove the loader
		$('#atPanelWrapperLoader').remove();
		//Make the panels sortable and remove the panel loader
		$('#panels').sortable({ 
				items: '.ui-dialog',
				grid: [5000,1],
				handle: '.ui-sort-icon'
		})
		//This will stop the map to move around when user use arrow keys while input is focused
		.find('input,select').keydown(function(e){  Astun.JS.Common.stopEventProp(e);  });
		//Load infoBox if it is intranet application
		if(typeof astun.intranetApp!='undefined')
		{
			jQuery.fn.infobox();
		}
		//debug('Time took to load the application = '+((new Date()-intTime)/1000));		
	}//End of loadPanels

	//If we need jRibbon (only for intranet) than load it and load panels as callback function, otherwise just load panels (ishare)
	if(typeof options.showJribbon=='undefined') options.showJribbon=false;
	(options.showJribbon) ? $eventElement.jribbon({callBackFunction: loadPanelWrapper}) : loadPanelWrapper();
	//setTimeout(function(){(options.showJribbon) ? $eventElement.jribbon({callBackFunction: loadPanels}) : loadPanels();},3000);

	//Remove the search result panel if global setting is false;
	if(typeof atGlobalSettings!='undefined')
	{
		if(typeof atGlobalSettings.showSearchResultsUnderMap != 'undefined')
		{
			if(!atGlobalSettings.showSearchResultsUnderMap)
			{
				$('#atPanelResults').remove();
			}
		}
	}
	
	//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 && location.href.indexOf('intranet')>1)
	{
		$([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');
		});
		
		
		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 is empty
			if(typeof msg == 'string')
			{
				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/>').append(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() {
					$(this).dialog('destroy').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'));

		}
	}
	
	
	//Only for intranet
	if(location.href.indexOf('intranet')>1)
	{
		//On scroll page, don't move the page
		jQuery(window).scroll(function() { return false;});
	}
	
	
	//Theme switcher just for the demo on Ctrl+S
	//Check the key word in demo to see if the app is running on demo
	if((location.href.indexOf('demo.astun')>-1 || location.href.indexOf('87.75.6')>-1) && location.href.indexOf('intranet')>1)
	{
		var isCtrl=false;
		jQuery(document)
			.keyup(function (e) { if(e.which == 17) isCtrl=false; })
			.keydown(function (e) { 
				if(e.which == 17) isCtrl=true;
				if(e.which == 83 && isCtrl == true)
				{
					//run code for CTRL+S -- ie, save!
					if(jQuery('#switcher').length>0)
					{
						jQuery('#switcher').remove();
					}
					else
					{
						jQuery('<div id="switcher" />').css({'position':'absolute','top':5,'right':5,'z-index':10000000}).appendTo('body');
						jQuery('#switcher').themeswitcher();
					}
					return false; 
				}
			});
	}
	
}
