﻿/*	Worthing Borough Council On-line, v3.1.

	wbc.sidebar.js - Sidebar and Gagdets Platform 0.6.1

	0.1b - Original Version
	0.2b - Supports show/hide of sidebar
	0.3 - Construct Icon Menu (Help, Config and Download)
	0.3.1 - Better Empty Sidebar handling
	0.4.0 - Handles Gadget Flipping and Downloading
	0.4.1 - Forced gadget support
	0.4.2 - Handles deleted gadgets or gadgets it could not load and removes them from sidebar order
	0.4.3 - Accessibility tweaks
	0.5.0 - New functions to create gadget components by function rather than cobbling together CSS strings on an ad-hoc basic per gadget
	0.6.0 - Revised to use #sidebar-marker as its containing element (to allow for siteManager configured gadgets to be 'pre-programmed'
			onto the side bar, this is notably for contact information although on v0.6 this functionality is not being used.
	0.6.1 - Gadgets can now omit a close button (close="<true|false>" support in gadget enumeration file)
	0.6.2 - Gadget flipping temporarily disabled

	Copyright (C)2008-9 Worthing Borough Council
	<webmaster@worthing.gov.uk>
*/
	var gadgetContainerBuffer=new Object; // Store buffer for gadgets

	var getDefaultGadgets=function(xmlData,getWhat){
		var gadget;
		var loadString='';
		$(xmlData).find('gadget').each(function(){
			gadget=$(this);
			if(($(gadget).attr('where')==getWhat || $(gadget).attr('where')=='all') && $(gadget).attr('default')=='true'){
				loadString=loadString+$(gadget).find('path').text()+','+$(gadget).find('name').text()+'|';
			}	
		});
		return loadString;
	};

	var attachGadgetDefaults=function(defaultsFile,toWhere,sortableClass,getWhat,sidebarType){
		$.ajax({
			url:	defaultsFile,
			cache:	false,
			async:	false, /* Do not get file asynchronously or the page will have no gadgets */
			success: function(xmlData){	
					var i=0;
					var response=getDefaultGadgets(xmlData,getWhat);
					response=response.split('|');

					for(i=0;i<response.length-1;i++){
						
						$(toWhere).append('<div id="'+response[i].split(',')[1]+'" class="'+sortableClass+'"><hr/></div>');
						getSideBarCode(response[i].split(',')[0],'#'+response[i].split(',')[1],sidebarType);
					}
				},
			error: function(){
					//alert('Sorry your gadgets could not be loaded. Please contact the webmaster at webmaster@worthing.gov.uk');
			}
		});
	};

	var getGadgetPath=function(defaultsFile,getWhat){

		var gadgetPath='';
		$.ajax({
			url:	defaultsFile,
			cache:	true,
			async:	false, /* don't do this asynchronously or the path will not be returned to the function that needs it in time */
			success: function(xmlData){
					$(xmlData).find('gadget').each(function(){
						gadget=$(this);
						
						if($(gadget).find('name').text()==getWhat){
							gadgetPath = $(gadget).find('path').text();
						}
					});
				},
			error: function(){
					//alert('Sorry your gadgets could not be loaded. Please contact the webmaster at webmaster@worthing.gov.uk');
			}
		});
		return gadgetPath;
	};

	var addGadgets=function(sidebarType){

		$('#sidebar-Marker').sortable(
			{
				containment:	'document',
				scroll:		'document',
				axis:		'y',
				helper:		'.sortableactive',
				items:		'.sortableitem',
				handle:		'.gadgetDragBar',
				placeholder:	'sorthelper',
				cursor:		'move',
				opacity:	0.5,
				change: function()
				{
					serial = $('#sidebar-Marker').sortable('serialize',{
											expression: '(.+)'
											});

					$.cookie(sidebarType, serial, { expires: 365 });
				}
			}
		);
	};

	var getSideBarCode=function(get_url,gadget,sidebarType){

		var sidebarType_Extended;
		if(sidebarType=='worthingGovUkSBar'){
			sidebarType_Extended='Homepage';
		}else{
			sidebarType_Extended='Content';
		}
		
		var type=get_url.split(".")[1];
		if(type=='html' || type=='htm' || type=='php' || type=='asp' || type=='aspx'){
			type='html';
		}
		else{
			if(type=='js'){
				type='script';
			}
		}

		$.ajax({
			url: get_url,
			cache: false, // as these are gadgets they need to be the most recent info e.g. weather, events...
			datatype: type,
			async: true,
			success: function(html){
						
						if(type=='script'){
							eval(html);
						}
						else{
	   						$(gadget).append(html);
						}
						var gadgetHeadId=gadget+'-Head';
						$(gadgetHeadId).prepend('<button title="Hide this gadget" class="gadgetClose" onclick="$(\''+gadget+'\').remove(); serial = $(\'#sidebar-Marker\').sortable(\'serialize\',{expression: \'(.+)\'}); $.cookie(\''+sidebarType+'\', serial, { expires: 365 }); if(serial==\'\'){insertEmptySidebar(\'#sidebar-Marker\',\'prepend\',\''+sidebarType_Extended+'\');}"><img src="/sidebar/gadgets/cross.png" alt="Hide"/></button>');
						},
			error: function(){
					//alert('Gadget not found '+gadget);
				}
		});
	};

	var enlargeContent=function(){
		$('#site-Content').animate({marginRight: '10px'},500);
	}

	var revealSidebar=function(){
		$('#sidebar-Marker').fadeIn(500);
	}

	var hideSidebar=function(){
		var sidebarStateMsg='<img src="/sidebar/gadgets/arrow_left.png" alt=""/>&nbsp;Show';
		$('#sidebar-state-msg').empty();
		$('#sidebar-state-msg').append(sidebarStateMsg);
		$('#showHideSidebar').attr('title','Show the sidebar (The page\'s right column)');

		$('#sidebar-Marker').fadeOut(500);
		setTimeout('enlargeContent()',500);
	};

	var showSidebar=function(){
		var sidebarStateMsg='<img src="/sidebar/gadgets/arrow_right.png" alt=""/>&nbsp;Hide';
		$('#sidebar-state-msg').empty();
		$('#sidebar-state-msg').append(sidebarStateMsg);
		$('#showHideSidebar').attr('title','Hide the sidebar (The page\'s right column)');

		$('#site-Content').animate({marginRight: '280px'},500);
		setTimeout('revealSidebar()',500);		
	};

	var initHideShowSidebar=function(typeDescription){
		// Purpose of this function is to add the hide/show button
		var curState;

		// check whether it is current hidden or shown

		var sidebarState,sidebarStateMsg; // can be either 'show' or 'hide'
		sidebarState=$.cookie('worthingSBarState');
		
		if(sidebarState==null || sidebarState=='show'){
			sidebarStateMsg='<img src="/sidebar/gadgets/arrow_right.png" alt=""/>&nbsp;Hide';
			curState='Hide';
		}else{
			sidebarStateMsg='<img src="/sidebar/gadgets/arrow_left.png" alt=""/>&nbsp;Show';
			curState='Show';
		}

		$('#side-bar-loading').append('<div class="button-Row" id="sidebar-state-button"><a title="Configure your ' + typeDescription + ' gadgets" class="positive-Button" href="/lib/wbc/sidebaradd.asp?type='+typeDescription+'&returnTo='+document.location.href+'"><img src="/sidebar/gadgets/cog.gif" alt=""/>&nbsp;Gadgets</a>&nbsp;<a title="'+curState+' the sidebar (The page\'s right columnn)" id="showHideSidebar" href="#" class="positive-Button"><span id="sidebar-state-msg">'+sidebarStateMsg+'</span></a></div>');

		$('#showHideSidebar').bind('click',function(){
			sidebarState=$.cookie('worthingSBarState');

			if(sidebarState==null || sidebarState=='show'){
				// hide it
				$.cookie('worthingSBarState','hide',{expires: 365});
				hideSidebar();
			}else{
				$.cookie('worthingSBarState','show',{expires: 365});
				showSidebar();
			}

		});
	};

	var getForcedGadgets=function(defaultsFile,currentOrder,sidebarType,typeDescription){
		$.ajax({
			url:	defaultsFile,
			cache:	true,
			async:	false,
			success: function(xmlData){	
					var forcedOrder='';
					$(xmlData).find('gadget').each(function(){
						gadget=$(this);
						
						if($(gadget).attr('force')=='true' && $(gadget).attr('where')==typeDescription){
							if(forcedOrder==''){
								forcedOrder=forcedOrder+$(gadget).find('name').text()+'[]=undefined';
							}else{
								forcedOrder=forcedOrder+'&'+$(gadget).find('name').text()+'[]=undefined';
							}
						}
					});

					var forcedOrderArray=forcedOrder.split('&');
					var i=0;
					var gadgetId='';
					var gadgetSrc='';

					for(i=0;i<forcedOrderArray.length;i++)
					{
						var forcedElementInternalName=forcedOrderArray[i].split("=")[0]
						forcedElementInternalName=forcedElementInternalName.split('[]')[0];
						if(forcedElementInternalName!=null)
						{
							if(currentOrder.indexOf(forcedElementInternalName)==-1){

								$('#sidebar-Marker').append('<div id="'+forcedElementInternalName+'" class="sortableitem"><hr/></div>');				
								getSideBarCode(getGadgetPath(defaultsFile,forcedElementInternalName),'#'+forcedElementInternalName,sidebarType);
							}
						}
					}					
				},
			error: function(){
					//forced gadgets could not be found
			}
		});
	};

	var initSidebar=function(defaultsFile,typeDescription,sidebarType){
		var typeDescription_Extended, sidebarState, attributionNote;

		attributionNote='';

		if(typeDescription=='content'){
			typeDescription_Extended='Content Page';
		}else{
			typeDescription_Extended=typeDescription;
		}
		
		//$('#sidebar-Marker').append('<div id="side-bar"></div>');
		var sidebarOrder=$.cookie(sidebarType);

		if(sidebarOrder!='NONE' || sidebarOrder.length!=null){
			$('#side-bar-loading').append('<img alt="Loading" src="http://www.worthing.gov.uk/sidebar/gadgets/spinner.gif"/>&nbsp;Loading');
			//$('#side-bar').prepend('<h2 class="screenReader">Your Worthing</h2>');
		
			sidebarState=$.cookie('worthingSBarState');

			if(sidebarState=='hide')
			{
				// the user wants the sidebar to be hidden
				$('#sidebar-Marker').hide();
				$('#site-Content').css('marginRight','10px');
			}

			if(sidebarOrder==null || sidebarOrder=='')
			{	
				if(sidebarOrder==null){
					// add default gadgets to side-bar as this is a new user or a user who has cleared cookies

					attachGadgetDefaults(defaultsFile,'#sidebar-Marker','sortableitem',typeDescription,sidebarType); // get the defaults for the homepage
		
					// add sidebar/gadgets
					addGadgets(sidebarType);

					// Write defaults to cookie
					serial = $('#sidebar-Marker').sortable('serialize',{expression: '(.+)'});
					$.cookie(sidebarType, serial, { expires: 365 });
				}else{
					
					insertEmptySidebar('#sidebar-Marker','append',typeDescription_Extended);	

					$('#side-bar-loading').empty();
					initHideShowSidebar(typeDescription);
				}
			}
			else
		    	{
				// first get forced gadgets

				getForcedGadgets(defaultsFile,sidebarOrder,sidebarType,typeDescription);

				var sidebarOrderArray=sidebarOrder.split('&');
				var i=0;
				var gadgetId='';
				var gadgetSrc='';
				var newOrder=''; // Joy Division were better, RIP Ian Curtis...
	
				for(i=0;i<sidebarOrderArray.length;i++)
				{
					var sidebarElementInternalName=sidebarOrderArray[i].split("=")[0]
					sidebarElementInternalName=sidebarElementInternalName.split('[]')[0];
					if(sidebarElementInternalName!=null)
					{
						if(getGadgetPath(defaultsFile,sidebarElementInternalName)!=''){
							$('#sidebar-Marker').append('<div id="'+sidebarElementInternalName+'" class="sortableitem"><hr/></div>');				

							getSideBarCode(getGadgetPath(defaultsFile,sidebarElementInternalName),'#'+sidebarElementInternalName,sidebarType);

							// remove gadget from sidebarOrder if it no longer exists
							newOrder=newOrder+sidebarOrderArray[i]+'&';
						}
					}
				}
				// get the new sidebar order into shape so any deleted gadgets still in the sidebar order are removed and not called again
				newOrder=newOrder.substr(0,newOrder.length-1); // remove trailing ampersand from end of string
				// save the new order
				$.cookie(sidebarType, newOrder,{ expires: 365 });
				
				addGadgets(sidebarType);
			}
		
			$('#side-bar-loading').ajaxStop(function(){
			  	$(this).empty();
				initHideShowSidebar(typeDescription);
				});
			
		}else{
			// narrow the sidebar down -- this is early functionality so this will be improved
	
			attributionNote='<p class="attributionText" style="clear:right;"><br/>Some icons used under the <a title="Visit External Site - Creative Commons" href="http://creativecommons.org/licenses/by-nc/3.0/">Creative Commons Non-commercial Attribution License</a>. Icons by <a title="Visit External Site - IconTexto" href="http://www.icontexto.com">Bruno Maia, IconTexto</a></p>';

			initHideShowSidebar(typeDescription);
			insertEmptySidebar('#sidebar-Marker','append',typeDescription_Extended);

			// $('#site-Content').css({marginRight: '140px'});
		}

		$('#sidebar-Marker').append('<hr/><h2 class="screenReader">Configure Sidebar Gadgets</h2><div class="button-Row" id="sidebar-add-button"><a class="positive-Button" href="/lib/wbc/sidebaradd.asp?type='+typeDescription+'&returnTo='+document.location.href+'"><img src="/sidebar/gadgets/cog.gif" alt=""/>&nbsp;Change My '+typeDescription_Extended+' Gadgets</a></div>'+attributionNote+'<hr/>');
		
	};

	/* Empty Sidebar Code */

	var insertEmptySidebar=function(toWhere,method,typeDescription_Extended){
		var emptySidebar='<div id="side-bar-notice"><h3><img src="http://www.worthing.gov.uk/styles/alilyforthespectre/web20icons/config.png" alt="Notice:" class="messageIcon"/>Empty Sidebar</h3><p><strong>Your sidebar is empty and has no gadgets.</strong></p><ul><li>To add gadgets click on the Change My <span class="capitalise">'+typeDescription_Extended+'</span> Gadgets button</li><li>To find out more about the sidebar and gadgets <a href="http://www.worthing.gov.uk/help-and-faqs/customiseyourpages/" title="Read the sidebar and gadgets user guide">read our user\'s guide</a>. It\'s very simple!</li></ul></div>';
		
		if(method=='append'){
			$(toWhere).append(emptySidebar);
		}else{
			$(toWhere).prepend(emptySidebar);
		}
	}

	/* Icon Menus */

	var constructIconMenu=function(gadgetHandle,ajaxSpinnerID,ajaxSpinnerDefault,e,defaultsFile){
			
		var gadgetContainerHandle, gadgetConfigureHandle, flipGadgetCode;

		gadgetContainerHandle='#'+gadgetHandle+'-container';
		gadgetConfigureHandle='#'+gadgetHandle+'-configure';

		if($(gadgetConfigureHandle).css('display')=='block'){

			$('#'+gadgetHandle+'-winVDownload').unbind('click');
			$('#'+gadgetHandle+'-macXDownload').unbind('click');

			$(gadgetConfigureHandle).remove();
			$(gadgetContainerHandle).show();
		}else{
			// Now fetch configuration information for this gadget from gadgetenum.xml
			$(ajaxSpinnerID).attr('src','/sidebar/gadgets/spinner_gadget.gif');
			$.ajax({
				url:	defaultsFile,
				success: function(xmlData){
					var gadgetEnumeration;
					$(xmlData).find('gadget').each(function(){
						gadgetEnumeration=this;
						if($(gadgetEnumeration).find('name').text()==gadgetHandle){
							// bingo found the gagdet in the enumeration file

							$(gadgetContainerHandle).hide();

							flipGadgetCode='<p class="noBorder rightAlign boldText gimmeLtGrey"><a id="'+gadgetHandle+'-flipGadget" href=#" title="Flip gadget over to its normal state">Flip Gadget Back to Normal</a>&nbsp;<img class="messageIcon" alt="Flip Arrow" src="/sidebar/gadgets/flipGadget.png"/></p>';
							$('#'+gadgetHandle).append('<div id="'+gadgetConfigureHandle.split('#')[1]+'" class="gadgetConfigure gadget-container"></div>');

							$(gadgetConfigureHandle).append('<h4><img src="/styles/alilyforthespectre/web20icons/infosm.gif" class="messageIcon">Help and Download</h4>'+$(gadgetEnumeration).find('help').text()+flipGadgetCode);


							$('#'+gadgetHandle+'-winVDownload').bind('click',function(){
								alert('Sorry this function is not yet on-line. Please check back soon though.');
								return false;
					        	});

							$('#'+gadgetHandle+'-macXDownload').bind('click',function(){
								alert('Sorry this function is not yet on-line. Please check back soon though.');
								return false;
					        	});

							$('#'+gadgetHandle+'-flipGadget').bind('click',function(){
								constructIconMenu(gadgetHandle,0,'/sidebar/gadgetsenum.xml');
								return false;
							});
						}
					});
					$(ajaxSpinnerID).attr('src',ajaxSpinnerDefault);
				},
				error: function(){
					// attach error to gadget
					$(ajaxSpinnerID).attr('src',ajaxSpinnerDefault);
				}
			});
		}
	};
	
	/* Gadget Building Kit - 0.5.0 */
	
	var constructGadget = function(gadget_id,drag_id,title,icon,menu_id,ajaxSpinner_ID,container_id){
		//$('#'+gadget_id).append('<h3 class="gadgetDragBar" id="' + drag_id + '"><button title="Click for help and to download this gadget to your desktop" class="gadgetIconMenu" id="' + menu_id + '"><img id="' + ajaxSpinner_ID + '" src="' + icon + '" alt="Weather Icon"/></button>&nbsp;' + title + '</h3>');
		$('#'+gadget_id).append('<h3 class="gadgetDragBar" id="' + drag_id + '"><img id="' + ajaxSpinner_ID + '" src="' + icon + '" alt="Weather Icon"/>&nbsp;' + title + '</h3>');
		 
		$('#'+gadget_id).append('<div id="' + container_id + '" class="gadget-container"></div>');
	};
	
	var attachToGadget = function(container_id,html){
		$('#'+container_id).append(html);
	};
	
	var emptyGadget = function(container_id){
		$('#'+container_id).empty();
	}
	
	var showGadgetAJAXActivity = function(ajaxIndicator_id){
		$('#'+ajaxIndicator_id).attr('src','/sidebar/gadgets/spinner_gadget.gif');
	};

	var hideGadgetAJAXActivity = function(ajaxIndicator_id,revertImg){
		$('#'+ajaxIndicator_id).attr('src',revertImg);
	};