/*	Worthing Borough Council On-line, v3.1.

	wbc.core.js - Core Progressive JavaScript initialisation and enhancements

	Copyright (C)2008-9 Worthing Borough Council
	<webmaster@worthing.gov.uk>

		Version 2.0 November 13th 2009
		
		Website Localisation functionality with centralised postcode lookup services available to all pages
*/

	var postcodeChanged = false;

	var initLilyForTheSpectreNoSidebar=function(){
		compactTables();
		enablePostcodeLookup();
		$('#sn').prepend('<a href="#" onclick="$(\'#qt\').focus()">Skip to search box</a>');
	};

	var initLilyForTheSpectre=function(defaultsFile,typeDescription,sidebarType){
		// Progressively Enhance and Setup Page
		
		compactTables();
		enablePostcodeLookup();
		$('#sn').prepend('<a href="#" onclick="$(\'#qt\').focus()">Skip to search box</a>');

		// Make sure this is Safari 3/Webkit r522+
		if($.browser.safari==true && $.browser.version<522){
			$('#sidebar-Marker').append('<h3>Sidebar Disabled</h3><p>Because Safari versions older than 3.0 have basic Javascript support that can crash the web browser, this website has disabled the sidebar. You can upgrade to Safari 3 for free at <a href="http://www.apple.com/safari/download/" title="Download Safari from Apple.com">Apple\'s Safari webpage</a>.</p>');
		}
		else{
			initSidebar(defaultsFile,typeDescription,sidebarType);
		}
	};
	
	var enablePostcodeLookupCB = function(){
		dlgPostcodeClose(null);
	};
	
	var enablePostcodeLookup = function(){
		
		$('#smlForm').bind('submit',function(){
			
			dlgPostcodeLookup('smlForm',enablePostcodeLookupCB,null);			
			return false;
		});	
	};
		
	var dlgPostcodeLookup = function(attachToID, c, b){
		
		/* First establish if the user has already stored their location
			If they have we do a reverse UPRN lookup to get their postcode and northings and eastings
			If they have not we present them the chance to enter their or a postcode
		*/
		
		if(b!=null){
			$('#'+b).attr('disabled',true);
		}
		
		var currentUPRN = $.cookie('worthingGovUkUPRN');
		var currentUSRN = $.cookie('worthingGovUkWstUSRN');
		var dlgBoxContent = '';
		var dlgSaveClose = '<div id="dlgPostcodeButtons" class="button-Row"><button title="Use the selected address for this facility" id="dlgPostcodeSave" class="positive-Button"><img alt="" src="/styles/alilyforthespectre/tick.png"/>&nbsp;Use this location</button>&nbsp;<button id="dlgPostcodeCancel" class="positive-Button"><img alt="" src="/styles/alilyforthespectre/cross.png"/>&nbsp;Cancel</button>&nbsp;<button class="positive-Button" id="dlgPostcodeDelete" title="Remove your saved location from your computer\'s browser cookies"><img src="/sidebar/gadgets/bin.png" alt=""/>&nbsp;Delete my location</button></div>';
		
		dlgBoxContent = '<h3><img id="dlgAjaxActivity" src="/sidebar/gadgets/world.png" alt=""/>&nbsp;Your Location</h3><p class="button-Row" id="dlgPostcodeRow"><input value="'+currentUSRN+'" id="dlgPostcodeUSRN" type="hidden"/><input value="'+currentUPRN+'" id="dlgPostcodeUPRN" type="hidden"/><label for="dlgPostcodeInput"><strong>Please enter a postcode to find an address</strong></label>&nbsp;&nbsp;<input id="dlgPostcodeInput" class="dlgInput" type="text" maxlength="8" value="';
		
		if(currentUPRN != null){
			
			// a UPRN is stored so we need to reverse this to a postcode
			
			$('#dlgAjaxActivity').attr('src','/styles/rsrc/dlgAjaxSpinner.gif');
			
			$.ajax({
				url: '/dev/postcode/postcodelu.asp?llpg=worthing&mode=reverseuprn&rv=true&fields=POSTCODE&pclu='+currentUPRN,
				cache: false,
				datatype: 'html',
				async: true,
				success: function(result){

					dlgBoxContent = dlgBoxContent + result + '"/><button id="dlgPostcodeFind" class="positive-Button" ><img alt="" src="/sidebar/gadgets/magnifier.png"/>&nbsp;Find</button></p><p id="dlgPostcodeRowChoices" class="button-Row">&nbsp;</p><p>You can optionally store this location for use on this computer only. This will allow this website\'s location \'aware\' tools to show you your bin collection days, nearest facilities and your councillor without having to enter it each time.</p><p><label title="No personal information is stored on the council\'s computer system. This location is saved to your computer\'s browser cookies only." for="dlgPostcodeStore" class="dlgLabelHighlight">Store this address as My Location?</label>&nbsp;<input type="checkbox" id="dlgPostcodeStore"/></p>' + dlgSaveClose;
					$('#'+attachToID).append('<div id="dlgModal">' +dlgBoxContent + '</div>');
					
					$.ajax({
						url: '/dev/postcode/postcodelu.asp?llpg=worthing&mode=list&rv=true&fields=USRN,UPRN&default=' + currentUPRN + '&matchon=UPRN&pclu='+result,
						cache: false,
						datatype: 'html',
						async: true,
						success: function(result){
							
							if(result!='False'){
								$('#dlgPostcodeRowChoices').empty().append('<label><strong>Current address</strong></label>&nbsp;&nbsp;<select id="dlgPostcodeProperty" class="dlgSelect">'+result+'</select>');
							}
							$('#dlgAjaxActivity').attr('src','/sidebar/gadgets/world.png');
							
							
						},
						error:	function(){
							$('#dlgAjaxActivity').attr('src','/sidebar/gadgets/world.png');
							alert('Error working with that postcode');
						}
					});
					
						
					
					$('#dlgModal').modal({onClose: function (dialog){
							dlgPostcodeClose(b);
						}
					});
					
					dlgPostcodeBindEvents(c);
									
				},
				error:	function(){
					alert('Error, could not reverse unique property reference number to a postcode!');
					}
			});
		}else{
			dlgBoxContent = dlgBoxContent + 'BN"/><button id="dlgPostcodeFind" class="positive-Button"> <img alt="" src="/sidebar/gadgets/magnifier.png"/>&nbsp;Find</button></p><p id="dlgPostcodeRowChoices" class="button-Row">&nbsp;</p><p>You can optionally store this location for use on this computer only. This will allow this websites location aware tools to show you your bin collection days, nearest facilties and your councillor without having to enter it each time.</p><p><label class="dlgLabelHighlight" for="dlgPostcodeStore" title="No personal information is stored on the council\'s computer system. This location is saved to your computer\'s browser cookies only.">Store this address as My Location?</label>&nbsp;<input type="checkbox" id="dlgPostcodeStore"/></p>' + dlgSaveClose;
			$('#'+attachToID).append('<div id="dlgModal">' +dlgBoxContent + '</div>');
			$('#dlgModal').modal({onClose: function (dialog){
					dlgPostcodeClose(b);
				}
			});
			
			dlgPostcodeBindEvents(c);			
		}
		
		
	};
	
	var dlgPostcodeClose = function(b){
		if(b!=null){
			$('#'+b).attr('disabled',false);
		}
		$.modal.close();
		$('#dlgModal').remove();
	};
	
	var dlgPostcodeBindEvents=function(c){
		$('#dlgPostcodeDelete').bind('click',function(){
			savePropertyDetails(null,null);
			dlgPostcodeClose();
		});
		
		$('#dlgPostcodeInput').bind('keypress',function(){
			if(postcodeChanged==false){
				$('#dlgPostcodeUSRN').val('null');
				$('#dlgPostcodeUPRN').val('null');
				$('#dlgPostcodeRowChoices').empty().append('&nbsp;');
				postcodeChanged=true;
			}
		});
	
		$('#dlgPostcodeFind').bind('click',function(){
			postcodeChanged=false;
			var searchString=$('#dlgPostcodeInput').val();

			// Send Street to Search

				if(searchString.length>=7){ // all Worthing postcodes are at least 7 chars e.g. bn111ha, unlike b'ton which has e.g. bn24gb
					
					$('#dlgAjaxActivity').attr('src','/styles/rsrc/dlgAjaxSpinner.gif');
					
					$.ajax({
						url: '/dev/postcode/postcodelu.asp?llpg=worthing&mode=list&rv=true&fields=USRN,UPRN&defVal=&matchOn=&pclu='+searchString,
						cache: false,
						datatype: 'html',
						async: true,
						success: function(result){
						
							if(result=='False'){
								alert('Sorry no postcode match found');
							}
							else{
								$('#dlgPostcodeRowChoices').empty().append('<label><strong>Pick the address</strong>&nbsp;&nbsp;<select id="dlgPostcodeProperty" class="dlgSelect">'+result+'</select>');
								
							}
							$('#dlgAjaxActivity').attr('src','/sidebar/gadgets/world.png');
						},
						error:	function(){
							$('#dlgAjaxActivity').attr('src','/sidebar/gadgets/world.png');
							alert('Error working with that postcode');
						}
					});
				}
				else{
					alert('Sorry, that postcode was too short');
				}			
		});
		
		$('#dlgPostcodeSave').bind('click',function(){
			var selectedProperty = $('#dlgPostcodeProperty').val();
			
			if($('#dlgPostcodeUPRN').val() != 'null' && $('#dlgPostcodeUSRN').val() != 'null'){
				extractPropertyDetails(selectedProperty);

				savePropertyDetails($('#dlgPostcodeUSRN').val(),$('#dlgPostcodeUPRN').val());				
				
				return c(true,$('#dlgPostcodeUSRN').val(),$('#dlgPostcodeUPRN').val(),$('#dlgPostcodeInput').val());
			}else{
				if(selectedProperty != null){
					extractPropertyDetails(selectedProperty);

					savePropertyDetails($('#dlgPostcodeUSRN').val(),$('#dlgPostcodeUPRN').val());	
					
					return c(true,$('#dlgPostcodeUSRN').val(),$('#dlgPostcodeUPRN').val(),$('#dlgPostcodeInput').val());
				}else{
					alert('Please enter a postcode to search for a property');
				}
			}
			
		});
		
		$('#dlgPostcodeCancel').bind('click',function(){			
			return c(false,false,false,false);
		});		
	};
	
	var savePropertyDetails=function(usrn,uprn){
		if(usrn == null && uprn == null){
			$.cookie('worthingGovUkWstUSRN',null);
			$.cookie('worthingGovUkUPRN',null);
		}else{
			if($('#dlgPostcodeStore').attr('checked')==true){
				$.cookie('worthingGovUkWstUSRN',usrn,{ expires: 1095 });
				$.cookie('worthingGovUkUPRN',uprn,{ expires: 1095 });						
			};	
		}
	};
	
	var extractPropertyDetails=function(selectedProperty){
		if(selectedProperty != null){
			selectedProperty = selectedProperty.split(',');
			
			if(selectedProperty[0] != $('#dlgPostcodeUSRN').val() || selectedProperty[1] != $('#dlgPostcodeUPRN').val()){
				$('#dlgPostcodeUSRN').val(selectedProperty[0]);
				$('#dlgPostcodeUPRN').val(selectedProperty[1]);
			}
		}		
	};
	
	var compactTables=function(){		
		$('table.worthingTable').each(function(){
			$(this).attr('cellspacing','0');
		});

		$('table.worthingTable-no-stripe').each(function(){
			$(this).attr('cellspacing','0');
		});
	};
	
	var initHomepageLinks=function(){
		$('#li1').addClass('wwwLBg');
		$('#links-image-byline').append('<strong>Worthing Leisure</strong><br/>Leisure Centres and Swimming facilities');
		$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/wlc.png) center center no-repeat #fff');
		$('#links-image-img').append('<a title="Visit External Site : Worthing Leisure" href="https://www.worthingleisure.co.uk" id="links-image-img-link"></a>');
		
		$('.wwwL').bind('mouseover',function(){
			
			//$('#links-image-img-link').remove();
			$('#links-list li a.wwwLBg').removeClass('wwwLBg');
			switch($(this).attr('id')){
				case 'li1':
					
					$('#links-image-byline').empty().append('<strong>Worthing Leisure</strong><br/>Leisure Centres and Swimming facilities');
					
					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/wlc.png) center center no-repeat #fff').append('<a title="Visit External Site : Worthing Leisure" href="https://www.worthingleisure.co.uk" id="links-image-img-link"></a>');								
					
					$('#li1').addClass('wwwLBg');
					break;
				case 'li2':
					
					$('#links-image-byline').empty().append('<strong>Worthing Theatres</strong><br/>Cinema and Theatres in Worthing');
					
					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/wt.png) center center no-repeat #fff').append('<a title="Visit External Site : Worthing Theatres" href="http://www.worthingtheatres.co.uk" id="links-image-img-link"></a>');								
					$('#li2').addClass('wwwLBg');
					break;
				case 'li3':
					
					$('#links-image-byline').empty().append('<strong>Visit Worthing</strong><br/>Your guide to visiting Worthing');

					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/vw.png) center center no-repeat #fff').append('<a title="Visit External Site : Visit Worthing" href="http://www.visitworthing.co.uk" id="links-image-img-link"></a>');																
					$('#li3').addClass('wwwLBg');
					break;								
				case 'li4':
					
					$('#links-image-byline').empty().append('<strong>Worthing Musuem and Art Gallery</strong><br/>Exhibitions, Workshops, Events');
					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/wma.png) center center no-repeat #fff').append('<a title="Visit Site : Worthing Museum and Art Gallery" href="http://www.worthingmuseum.co.uk" id="links-image-img-link"></a>');	
					$('#li4').addClass('wwwLBg');
					break;							
				case 'li5':
					
					$('#links-image-byline').empty().append('<strong>Highdown Gardens</strong><br/>Award winning gardens in Worthing');
					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/hg.png) center center no-repeat #fff').append('<a title="Visit External Site : Highdown Gardens" href="http://www.highdowngardens.co.uk" id="links-image-img-link"></a>');									
					$('#li5').addClass('wwwLBg');
					break;
				case 'li6':
					
					$('#links-image-byline').empty().append('<strong>Worthing Regeneration</strong><br/>All about Worthing\'s future development');
					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/wr.png) center center no-repeat #fff').append('<a title="Visit External Site : Worthing Regeneration" href="http://www.worthingregeneration.com" id="links-image-img-link"></a>');																	
					$('#li6').addClass('wwwLBg');
					break;
				case 'li7':
					
					$('#links-image-byline').empty().append('<strong>Worthing Together</strong><br/>Local Strategic Partnership');
					$('#links-image-img').css('background','url(/styles/rsrc/websitelogos/wto.png) center center no-repeat #fff').append('<a title="Visit Site : Worthing Together" href="http://www.worthingtogether.org" id="links-image-img-link"></a>');																	
					$('#li7').addClass('wwwLBg');
					break;	
			};
		});
	};