// JavaScript Document - 9XB 2010 P. Smith

// EDIT THESE VALUES IF REQUIRED
var alertText = 'Are you sure you wish to perform this action' + "\n"; //DEFAULT TEXT DISPLAYED ON CONFIRM BUTTONS/LINKS WHEN NO ALT/TITLE
var newWindowLink = false; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?


var woms = new Array(); //CREATE ARRAY OF FUNCTIONS TO LAUNCH ONLOAD

//ONLOAD MANAGER
function womOn(){
  window.onload = womGo;
}

function womGo(){
  for(var i = 0;i < woms.length;i++)
    eval(woms[i]);
}

function womAdd(func){
  woms[woms.length] = func;
}

function CreateBookmarkLink() {

	title = document.title;
	url = window.location.href;
	
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,"");
	} else if(window.external) {
		window.external.AddFavorite( url, title); 
	} else if(window.opera && window.print) {
		return true;
	}
	
}

function objToggle(obj) { 

	var obj = document.getElementById(obj);

	if(obj.style.display == "block") { 
		obj.style.display = "none";
	} else { 
		obj.style.display = "block";
	}

}

// jquery ready to go
$(document).ready(function() {
	// initiate showcase scroller
	showcase.init();

	
	// initiate Google Maps api if in the locator page
	if ($("#map_canvas").length > 0) {
		maps.init();
	}
	
	// load any videos awaiting swfobjects
	videos.create();
	
	// add click event/blur to header search box
	if ($("#search_txt").length > 0) {
		$("#search_txt").click(function () { 
		  if ($("#search_txt").attr('value')=='Search Site') {
			  $("#search_txt").attr('value', '');
		  }
		});
		$("#search_txt").blur(function () { 
		  if ($("#search_txt").attr('value')=='') {
			  $("#search_txt").attr('value', 'Search Site');
		  }
		});		
	}
	
	// add target blank to new window links
	
	$("a.targetblank").attr('target', '_blank');
	$("a[href^=http]").each(
		function(){
			nonwww = location.hostname.replace("www.", "");
			if(this.href.indexOf('http://'+location.hostname) == -1 && this.href.indexOf('http://'+nonwww) == -1) {
				$(this).attr('target', '_blank');
			}
		}
	)	
	
	// correctly space out header tabs
	var num_tabs = $("#header_menu li").length+1;
	var total_width = 0;
	$("#header_menu li").each(function(){
		total_width+=$(this).width();
		
	});

	var spare_room = $("#header_menu").width() - total_width-0;
	if (spare_room>0) { $("#header_menu li").css('paddingRight', spare_room/num_tabs); }
	$("#header_menu li:last").css('paddingRight', '0');
	
	// init calendar on news page
	if ($("#cal_ajax_holder.news").length>0) { cal.init('news'); }
	
	// init calendar on events page
	if ($("#cal_ajax_holder.events").length>0) { cal.init('events'); }	
	
	trackAds.init();
	
});

function add_bookmark(url, title) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; }
}

var trackAds = {
	init:function() {
		
		$('div.banner').each(function() {
							id = $(this).attr('id');
							id = id.replace(/banner/, '');
							$(this).find('a').click(function() {
														href = $(this).attr('href');
														url = "ajax/adTracker/"+id+"/?uri="+encodeURIComponent(href);
														window.location = url;
														return false;
													});

						  });
	}
}

var videos = {
	items:Array(),

	create: function() {
		// create videos waiting in Items array
		for (i=0; i<videos.items.length; i++) {
			video = videos.items[i];
			swfobject.embedSWF(video['swf'], video['holder'], video['width'], video['height'], "9.0.0","expressInstall.swf", video['flashvars']);
		}
	}
}

var send_to_friend = {
	validate: function() {
		name1 = $('#sendfriend_name').attr('value');
		email1 = $('#sendfriend_email').attr('value');
		name2 = $('#sendfriend_name2').attr('value');
		email2 = $('#sendfriend_email2').attr('value');
		comments = $('#sendfriend_message').attr('value');
		
		msg = '';
		
		if (name1=='') { msg+='<li>Please enter your name</li>'; }
		if (email1=='') { msg+='<li>Please enter your email address</li>'; }
		if (name2=='') { msg+='<li>Please enter your friend\'s name</li>'; }
		if (email2=='') { msg+='<li>Please enter your friend\'s email address</li>'; }
		
		if (msg!='') {
			$('#sendfriend_errors').html(msg);
			$('#sendfriend_errors').css('display', 'block');
			return false;
		};
		
		return true;
	}
}

var cal = {
	loading:false,
	mode:'',
	event_type:'',
	
	// initialize
	init:function(mode) {
		cal.mode = mode;
		if ($('.event_type_feature').length>0) { cal.event_type = 'feature'; }	
		if ($('.event_type_club').length>0) { cal.event_type = 'club'; }	
	},
	
	// jump calendar to previous month
	prev:function(month, year){
		if (cal.loading) { return; }
		month--;
		if (month==0) {
			month=12; 
			year--;
		}
		cal.reload(month, year);
	},
	
	// jump calendar to next month
	next:function(month, year){
		if (cal.loading) { return; }
		month++;
		if (month==13) {
			month=1; 
			year++;
		}
		cal.reload(month, year);
	},
	
	// jump calendar to today
	today:function(){
		if (cal.loading) { return; }
		cal.reload('today', 'today');
	},	
	
	reload: function(month, year) {
		cal.loading=true;
		setTimeout(function() {
			if (cal.loading) { $('#loading_msg').css('display', 'block'); }
		}, 200);
		base = document.getElementsByTagName("base");
		base = base[0].href;
		$.ajax({
			type: "POST",
			url: base+"ajax/calendar-"+cal.mode+"/",
			data: "cal_month="+month+"&cal_year="+year+"&event_type="+cal.event_type,
			success: function(msg){
				$('#cal_ajax_holder').html(msg);
				cal.loading=false;
				$('#loading_msg').css('display', 'none');
			}
		});
		
	},

	select_event: function(str, cell_id){
		html='';
		items = str.split('__');
		
		// remove any previous 'selected_day' classes from td cells
		$('#calendar td').removeClass('selected_day');
		// add 'selected_day' class to this td cell
		$('#'+cell_id).addClass('selected_day');
		
		j=0;
		for (var i in items) {
			components = items[i].split('||');
			j++;
			if (components.length==4 && items.length==2) {
				html += '<a href="'+components[3]+'"><img src="'+components[0]+'" alt="'+components[2]+'" /></a>';
				html += '<p class="event_date">'+components[1]+'</p>';	
				html += '<a class="single_event_link" href="'+components[3]+'">'+components[2]+'</a>';	
			}
			else if (components.length==4) {
				components[2] = shorten_string(components[2], 33);
				if (j==1) { html += '<a href="'+components[3]+'"><img src="'+components[0]+'" alt="'+components[2]+'" /></a>'; }
				html += '<a class="single_event_link" href="'+components[3]+'">'+components[2]+'</a><br/><br/>';	
			};		
		}
		
		$('#calendar_single').fadeOut('fast', function() {
			$('#calendar_single').html(html);
			$('#calendar_single').fadeIn('fast');
		});
	},
	
	select_news: function(str, cell_id){
		html='';
		items = str.split('__');
		
		// remove any previous 'selected_day' classes from td cells
		$('#calendar td').removeClass('selected_day');
		// add 'selected_day' class to this td cell
		$('#'+cell_id).addClass('selected_day');
		
		j=0;
		for (var i in items) {
			components = items[i].split('||');
			j++;
			if (components.length==3 && items.length==2) {
				html += '<img src="'+components[0]+'" alt="'+components[1]+'" />';
				html += '<a class="single_event_link" href="'+components[2]+'">'+components[1]+'</a>';	
			}
			else if (components.length==3) {
				if (j==1) { html += '<img src="'+components[0]+'" alt="'+components[1]+'" />'; }
				html += '<a class="single_event_link" href="'+components[2]+'">'+components[1]+'</a><br/><br/>';	
			};		
		}
		$('#calendar_single').fadeOut('fast', function() {
			$('#calendar_single').html(html);
			$('#calendar_single').fadeIn('fast');
		});
	}	
}

var showcase = {
	fade_time:0.3,
	view_time:7,
	t:-1,
	selected:1,
	num_items:0,
	init: function() {		
		// if showcase ul doesn't exist, don't bother doing anything else
		if ( $("#showcase_items").length == 0 ) { return; }
		showcase.t = setInterval("showcase.next()", showcase.view_time*1000);
		
		// define number of lis in showcase ul
		showcase.num_items = $("#showcase_items li").length;
		
		// correctly space out showcase tabs
		var num_tabs = $("#showcase_nav li").length;
		var total_width = $("#showcase_nav").width() - num_tabs;
		
		var num_tabs = $("#showcase_nav li").length;
		var total_width = 0;
		$("#showcase_nav li").each(function(){
			total_width+=$(this).width();
		});
		var spare_room = $("#showcase_nav").width() - total_width-10;
		$("#showcase_nav li").css('paddingRight', spare_room/num_tabs/2);
		$("#showcase_nav li").css('paddingLeft', spare_room/num_tabs/2);
		$("#showcase_nav li:last").css('paddingRight', '0');
		
		// init calendar on news page
		if ($("#cal_ajax_holder.news").length>0) { cal.init('news'); }
		
		// init calendar on events page
		if ($("#cal_ajax_holder.events").length>0) { cal.init('events'); }			
	},
	
	jump_to: function(n) {
		$("#showcase_items li:nth-child("+showcase.selected+")").fadeOut(showcase.fade_time*1000, 
			function() {
				showcase.selected = n;						
				$("#showcase_items li:nth-child("+n+")").fadeIn(showcase.fade_time*1000);
			}
		);
	},
	
	// jumps to the next element in the list, or the 1st when it reaches the end
	next: function() {
		n = showcase.selected+1;
		if (n>showcase.num_items) { n=1; }
		showcase.jump_to(n);
	}
};

function location_popup() {
	window.open('locator/', 'location', 'width=800, height=600, menubar=0');
}

var maps = {
	map:null,
	marker_array:Array(),
	event_marker:Array(),
	init_location_lat:'',
	init_location_lon:'',
	zoom:11,
	selected:'',
	active_marker_type:'',
	location_find_error:false,
	t:-1,
	init: function() {

		// remove JS fallback
		$('.no_javascript').css('display', 'none');
		$('#map_options').css('display', 'block');
		
		if (GBrowserIsCompatible()) {
			maps.map = new GMap2(document.getElementById("map_canvas"));
			maps.map.addControl(new GLargeMapControl3D() );
			maps.map.enableScrollWheelZoom();

			// lat and lon not set, look for cookie
			if (maps.init_location_lat=='' && maps.init_location_lon=='') {
				maps.init_location_lat = getCookie('lat');
				maps.init_location_lon = getCookie('lon');
				if (maps.init_location_lat!='' && maps.init_location_lon!='') { maps.zoom = 9; }
			}
			
			// scroll to initial location, or attempt to geolocate
			if (maps.init_location_lat!='' && maps.init_location_lon!='' && maps.init_location_lat!='0' && maps.init_location_lon!='0') {
				lat = maps.init_location_lat;
				lon = maps.init_location_lon;
				var myGeographicCoordinates = new GLatLng(lat, lon);
				maps.map.setCenter(myGeographicCoordinates, maps.zoom);						
			}
			else {

				script = document.createElement('script')
				script.src = "http://api.ipinfodb.com/v3/ip-city/?format=json&callback=maps.geolocatecallback&key=60695ea1ee9b52e1a2a9f06428037a439cdc291f2dbc5b94bb9fbd8516d46988";
				document.body.appendChild(script)
				return;		
			};
			
			// add table icons to map
			maps.create_icons();
			
			// highlight correct map type tab
			maps.set_map_type_tab_style();
			
			// no location returned from search
			if (maps.location_find_error) { alert('Location could not be found. Please try aagain.'); }
		}
		
		// add unload event to destroy google api and avoid memory leaks
		window.onbeforeunload = function() { 
			GUnload();
		}

	},
	geolocatecallback:function(geoDict) {

		// geolocate success
		if (geoDict.Latitude && geoDict.Longitude) {
			setCookie('lat', geoDict.Latitude);
			setCookie('lon', geoDict.Longitude);
			lat = geoDict.Latitude;
			lon = geoDict.Longitude;	
			maps.zoom = 9;
		}
		
		// geolocate fail - use defaults
		else {
			lat = 53.800651;
			lon = -1.54911;	
			maps.zoom = 6;
		};
		
		var myGeographicCoordinates = new GLatLng(lat, lon);
		maps.map.setCenter(myGeographicCoordinates, maps.zoom);
		maps.create_icons();
		
	},
	
	change_location: function() {
		search_txt = $('#map_location_txt').attr('value');
		if (search_txt=='') { return; }
		var geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode('uk');
		geocoder.getLatLng(search_txt+',uk',
			function(point) {
				if (!point) {
					alert(search_txt + " not found");
				} else {
					 maps.zoom=11;
					$('#map_title_middle').html(search_txt);
					maps.map.setCenter(point, maps.zoom);
					var marker = new GMarker(point);
					maps.map.addOverlay(marker);
					marker.openInfoWindowHtml(search_txt);
				}
			}
		);
	},
		
	create_icons:function() {
		// Create our "tiny" marker icon
		var tinyIcon = new GIcon();
		tinyIcon.image = "images/maps/icon.png";
		tinyIcon.shadow = "images/maps/icon_shadow.png";
		tinyIcon.iconSize = new GSize(31, 50);
		tinyIcon.shadowSize = new GSize(56, 50);
		tinyIcon.iconAnchor = new GPoint(15, 50);
		tinyIcon.infoWindowAnchor = new GPoint(45,30);

		// Set up our GMarkerOptions object literal
		markerOptions = { icon:tinyIcon };
		
		// add marker for selected event
		if (maps.event_marker.length>0) {
			var point = new GLatLng(maps.event_marker[0], maps.event_marker[1]);				
		 	var marker = new GMarker(point, markerOptions);	
			var caption = '<b>'+maps.event_marker[2]+"</b><br/>" + maps.event_marker[3] + "<br/>" + maps.event_marker[4];
			maps.selected = this;
			maps.map.addOverlay(marker);
			marker.openExtInfoWindow(
				maps.map,
				"map_bubble",
				caption,
				{beakOffset: 1}
			); 
			GEvent.addListener(marker, 'click', function(){ 		
				var caption = '<b>'+maps.event_marker[2]+"</b><br/>" + maps.event_marker[3] + "<br/>" + maps.event_marker[4];
				maps.selected = this;
				this.openExtInfoWindow(
					maps.map,
					"map_bubble",
					caption,
					{beakOffset: 1}
				); 
			});				

			
		}

		// Add markers for each of marker_array (defined inline)
		for (i=0; i<maps.marker_array.length; i++) {
			var point = new GLatLng(maps.marker_array[i].lat, maps.marker_array[i].lon);				
		 	var marker = new GMarker(point, markerOptions);
			marker.i=i;
			maps.marker_array[i]['marker_ref'] = marker; 
			
			// big popup on click
			GEvent.addListener(marker, 'click', function(){ 							 
				var caption = '<b>'+maps.marker_array[this.i].name+' '+maps.marker_array[this.i].number+"</b><br/>" + maps.marker_array[this.i].meetingplace + "<br/>" + maps.marker_array[this.i].postcode;
				if (maps.marker_array[this.i].setup_complete==1) { caption += '<br/><a href="http://'+maps.marker_array[this.i].url+'" target="_blank">Visit Website</a>'; }
				caption += '<br/><a href="http://'+maps.marker_array[this.i].email_url+'" target="_blank">Email Us</a>';
				caption += '<br/><br/>Meet: '+maps.marker_array[this.i].meetingtime;
				maps.selected = this;
				maps.active_marker_type = 'big';
				this.openExtInfoWindow(
					maps.map,
					"map_bubble",
					caption,
					{beakOffset: 1}
				); 				
			});	
			
			// small popup on mouseover
			GEvent.addListener(marker, 'mouseover', function(){ 
				var caption = '<b>'+maps.marker_array[this.i].name + ' ' + maps.marker_array[this.i].number+"</b><br/>(Click for more info)";
				maps.selected = this;
				maps.active_marker_type = 'mini';
				this.openExtInfoWindow(
					maps.map,
					"map_bubble",
					caption,
					{beakOffset: 1}
				); 				
			});	
			
			// remove mini popup on mouseout
			GEvent.addListener(marker, 'mouseout', function(){
				if (maps.active_marker_type == 'big') { return; }
				this.closeExtInfoWindow(maps.map);
			});				

			maps.map.addOverlay(marker);
		}
	},
	
	// scroll map to marker position and open its popup
	jump_to_marker:function(id) {
		for (i=0; i<maps.marker_array.length; i++) {
			if (maps.marker_array[i].id==id) {
				// remove any prevoius popups
				if (maps.selected!='') {
					maps.selected.closeExtInfoWindow(maps.map);
					maps.selected='';
				}
				
				// open new popup
				GEvent.trigger(maps.marker_array[i]['marker_ref'], 'click');
				
				// center map on point
				var myGeographicCoordinates = new GLatLng(maps.marker_array[i].lat, maps.marker_array[i].lon);
				maps.map.panTo(myGeographicCoordinates);
			}
		}
	},
	
	changetype: function(type) {
		switch(type) {
			case 'sat':
			  maps.map.setMapType(G_SATELLITE_MAP );
			  break;
			case 'ter':
			  maps.map.setMapType(G_PHYSICAL_MAP);
			  break;
			default:
			  maps.map.setMapType(G_NORMAL_MAP );
		}
		maps.set_map_type_tab_style();
	},
	
	change_search_area: function() {
		$('#map_change_area_link').css('display','none');
		$('#map_location_txt').css('display','inline');
		$('#map_location_btn').css('display','inline');
		$('#map_location_txt').select();
	},
	
	set_map_type_tab_style:function() {
		var current_type = maps.map.getCurrentMapType();	
		if (current_type==G_NORMAL_MAP ) { $('#map_type_map').addClass("selected"); }
		else {$('#map_type_map').removeClass("selected"); };

		if (current_type==G_PHYSICAL_MAP) { $('#map_type_ter').addClass("selected"); }
		else {$('#map_type_ter').removeClass("selected"); };
		
		if (current_type==G_SATELLITE_MAP) { $('#map_type_sat').addClass("selected"); }
		else {$('#map_type_sat').removeClass("selected"); };	
	}
}

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
 
function setCookie(c_name,value){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+30);
	document.cookie=c_name+ "=" +escape(value)+";expires="+exdate.toGMTString();
}

function shorten_string(str, len) {
	if (str.length <=len ) { return str; }
	
	str = str.substr(0, len) + '...';
	return str;
}
