// Namespace object for current site
cTHEFOOT = function(){
	
	// Constants
	this.SITE_ROOT = TFO_SITE_ROOT;
	this.SITE_NAME = TFO_SITE_NAME;
	this.DOMAIN_NAME = TFO_DOMAIN_NAME;
	this.PATH_IMAGES = 'assets/images/';
	this.DEFAULT_COOKIE_TIMEOUT = 86400; // 86400 Seconds = 24 hours
	this.COOKIE_NAME = 'tfo_ce_appdata';
	
	// Component constants
	this.GALLERY_PLAYMODE_NONE = 0;
	this.GALLERY_PLAYMODE_SEQUENTIAL = 1;
	this.GALLERY_PLAYMODE_RANDOM = 2;
	this.GALLERY_SCROLL_DIR_NONE = 0;
	this.GALLERY_SCROLL_DIR_VERTICAL = 1;
	this.GALLERY_SCROLL_DIR_HORIZONTAL = 2;
	
	// Preset component config objects
	this.optionsets = {
		qtipstyle	: { 
			padding		: 5,
			background	: '#69727E',
			color		: '#fff',
			textAlign	: 'center',
			fontSize	: '0.9em',
			border		: {
				width	: 3,
				radius	: 3,
				color	: '#363B41'
			},
			tip			: { 
				corner: 'topLeft', 
				color: '#363B41',
				size: {
					x: 8, y: 8
				}
			},
			name		: 'dark' // Inherit the rest of the attributes from the preset dark style
		},
		qtipposition : {
			corner: {
				target: 'bottomRight',
				tooltip: 'topLeft'
			},
			adjust: { 
				screen: true
			}
		}
	}
	
	// Properties
	this.o_current_menulink = null;
	this.o_cache_images = null;
	this.a_menulinks = [];
	this.v_rollover_image_id = '';
	this.server_error = '';
	this.galleries = new Array();
	this.slideshows = new Array();
	this.contentLoaders = new Array();
	this.gdataService = null;
	
	/*
		Initialise utility objects (preserve order)
	*/
	this.init = function(){
		this.cookie = new tfoCookie(this.COOKIE_NAME);
		this.sysinfo = new tfoSysInfo();
		//this.pageoverlay = new tfoPageOverlay();
	} // this.init()
	
	/*
		Handle an app error
	*/
	this.showError = function(v_error_msg){
		alert(v_error_msg);
	} // this.showError()

	// Update the current URL path in the main menu
	this.highlightCurrentMenuItem = function(v_menu_id){		
		$('#' + v_menu_id + ' li a').each(function(){
			$(this).removeClass('current');
			$(this).children().removeClass('current');
			if ($(this).attr('href') == $thisroot.active_url.replace('../', '')){
				$(this).addClass('current').parent().addClass('current');
				$(this).closest('li[rel="root"]').addClass('current').children('a').eq(0).addClass('current');

			}
		});
	}
	
	/*
		Get the current page name
	*/
	this.getCurrentPage = function(){
		var v_path = window.location.pathname;
		return (this.getPageFromURL(v_path) || 'index.php');
	} // this.getCurrentPage()
	
	/*
		Get the current page name
	*/
	this.getPageFromURL = function(v_url){
		if (!v_url || (v_url.length == 0)){return '';}
		return (v_url.substring(v_url.lastIndexOf('/') + 1).replace(document.location.hash, ''));
	} // this.getPageFromURL()

	/*
		Cache/Preload images
		Images cache object is created by the server
	*/
	this.cacheImages = function(){
		if(this.o_cache_images){
			var a_images = this.o_cache_images.images;
			for (var i = 0; i < a_images.length; i++){
				var o_image = new Image();
				o_image.src = a_images[i];
			}
		}
	} // this.cacheImages()
	
	/*
		Create a new image gallery and add it to the galleries collection
	*/
	this.createImageGallery = function(v_container_id, a_images, v_display_count, v_gallery_name){

		// Create new gallery
		var o_gallery = {
			container:	$('#' + v_container_id),
			images:		a_images,
			thumbs:		new Array()
		}
		this.galleries.push(o_gallery);
		if (!o_gallery.container){this.showError('Invalid DOM container element');return false;}
		if (!o_gallery.images){this.showError('Invalid images array');return false;}

		// Create thumb containers
		for (var i = 1; i <= v_display_count; i++){
			o_gallery.container.append($('<div/>').addClass('thumb'));
		}
		
		// Grab and format thumb elements
		o_gallery.container.children().each(function(v_index){		
		
			var o_thumb = $(this);
			
			// Create loading spinner
			var o_img_loading = $('<img/>').attr({
				'src'	: 'assets/images/spinner.gif', 
				'alt'	: 'Loading image...',
				'title'	: 'Loading image...',
				'id'	: 'thumb-img-' + v_index
			});
			
			// Create wrapper window
			var o_wrapper = $('<div/>')
				.addClass('wrapperwin')
				.append(o_img_loading)
				.attr('id', 'thumb-win-' + v_index);
				
			// Insert DOM element into UI and center
			o_thumb.attr('id', 'thumb-container-' + v_index);
			var o_thumbobj = {
				"container"		: o_thumb.get(0),
				"window"		: o_wrapper.get(0),
				"image"			: o_wrapper.children()[0]
			}
			o_thumb.append(o_thumbobj.window);
			
			// Center thumb
			/*o_thumbobj.window.setStyle({
				'marginLeft': (o_thumbobj.window.getWidth() - o_thumbobj.image.getWidth()) / 2,
			});*/

			// Add thumb to gallery thumbs array
			o_gallery.thumbs.push(o_thumbobj);			
			
		});		
	
		// Cache and display each thumbnail image
		$.each(o_gallery.images, function(v_index){
	
			var v_url = this;
		
			// Build dynamic thumb url
			var v_thumburl = THEFOOT.SITE_ROOT + 'assets/media/galleries/thumbnail.php?' +
				'max_h=140&max_w=140&galleryname=' + v_gallery_name +
				'&filename=' + THEFOOT.getPageFromURL(v_url);		
			// Cache the image
			var o_image = new Image();
			o_image.src = (v_thumburl || '');
	
			// Update the gallery with the cached image
			//var v_offset = ($j.browser.msie) ? 30 : (o_img_dom.width - 136) / 2;	
			var o_img_dom = $(o_gallery.thumbs[v_index].image);
			o_img_dom.attr({
				"src"		: o_image.src,
				"title"		: "",
				"alt"		: " "
			}).css({
				//'marginLeft': '-' + v_offset + 'px',
				'height': '140px',
				'width': 'auto'
			});
		
			// Add lightbox
			var v_lburl = THEFOOT.SITE_ROOT + 'assets/media/galleries/thumbnail.php?' +
				'max_h=500&max_w=800&galleryname=' + v_gallery_name +
				'&filename=' + THEFOOT.getPageFromURL(v_url);	
			o_img_dom.wrap($('<a/>').attr({
				'href': v_lburl,
				'id': 'thumb-link-' + v_index,
				'rel': 'lightbox'
			}));
					
		});
		
		// Create the lightbox
		$('#' + v_container_id + ' a[rel*=lightbox]').lightBox();
		
	} // this.createImageGallery()
	
	/*
		Convert a div containing linked thumbnail images into a lightbox-display photo gallery
	*/
	this.convertPhotoGallery = function(o_gallery){

		if (o_gallery){
		
			var $this = $(o_gallery);
		
			// Convert each image link into a lightbox link
			$this.find('a>img').each(function(v_idx){
				$(this).parent().colorbox({
					transition		: "elastic",
					slideshow		: true,
					slideshowSpeed	: 3500
				});
			});

		}
		
		return this;
	
	} // this.convertPhotoGallery()
	
	/*
		Create a new image slideshow and add it to the slideshows collection
	*/
	this.createSlideshow = function(
		v_container_id, 
		a_images, 
		v_sw_id, 
		v_sl_id,
		v_ss_fadein_duration
	){

		var v_cache_count = 0;
		var v_imageindex = 0;
		
		// Start the timer for the first image
		var v_starttime = new Date().getTime();
		
		if ($('#' + v_container_id).length == 0){this.showError('Invalid DOM container element');return false;}
		if ($('#' + v_sw_id).length == 0){this.showError('Invalid slideshow window element');return false;}
		if ($('#' + v_sl_id).length == 0){this.showError('Invalid slideshow loader element');return false;}
		
		// Create new slideshow object
		var o_ss = {
			container:	$('#' + v_container_id),
			images:		a_images,
			window:		$('#' + v_sw_id),
			loader:		$('#' + v_sl_id),
			duration:	v_ss_fadein_duration
		}
		this.slideshows.push(o_ss);
		if (!o_ss.images){this.showError('Invalid images array');return false;}

		// Private function to increment image counter
		var incrementImageCounter = function(){
			v_imageindex += 1;
			if (v_imageindex >= o_ss.images.length){v_imageindex = 0;}
		} // incrementImageCounter()
		
		// Private function to start the slideshow transition
		var kickOff = function(){
			o_ss.loader.fadeOut(500, function(){
				o_ss.window.css({
					"backgroundImage": "url(" + o_ss.images[v_imageindex] + ")"
				});
				o_ss.window.fadeIn(2000);
				incrementImageCounter();
			});
			
			// Start the timer for the rest of the images
			window.setInterval(function(){
				o_ss.window.fadeOut(500, function(){
					o_ss.window.css({
						"backgroundImage": "url(" + o_ss.images[v_imageindex] + ")"
					});
					o_ss.window.fadeIn(2000);
					incrementImageCounter();
				});
			}, (o_ss.duration * 1000));
		} // kickOff()
		
		// Cache each image, once all images are cached, then start slideshow
		$.each(o_ss.images, function(v_index){
			var o_image = new Image();
			$(o_image).load(function(e){

				v_cache_count += 1;				
				if (v_cache_count == o_ss.images.length){
				
					// Fade out loading image and fade in 1st image,
					// if we have reached or passed the slideshow interval period
					incrementImageCounter(); // Static image is first in slides array
					var v_now_time = new Date().getTime();
					if ((v_now_time - v_starttime) >= (o_ss.duration * 1000)){
						kickOff();
					} else {
						setTimeout(kickOff, ((o_ss.duration * 1000) - (v_now_time - v_starttime)));
					}					
							
				}
			});
			o_image.src = (this || '');
		});
		
	} // this.createSlideshow()
	
	/*
		Create iframe DOM element that holds a google calendar
	*/
	this.createGoogleCalendarElement = function(v_width, v_height, a_calendars, v_mode)	{
		
		// Build the calendar URL
		var v_url = "http://www.google.com/calendar/hosted/" + THEFOOT.DOMAIN_NAME + 
			"/embed?showTitle=0&height=" + v_height + "&" + 
			"bgcolor=%23cccccc&" + 
			((v_mode.length > 0) ? "mode=" + v_mode : "") + "&";
		for (var i = 0; i < a_calendars.length; i++){
			v_url += "src=" + a_calendars[i].id + "&" + 
				"color=%20" + a_calendars[i].color + "&";
		}
		v_url += "ctz=Europe%2FLondon";
		
		// Create the iframe
		var o_cal = $('<iframe/>').attr({
			"width"			: v_width + 'px',
			"height"		: v_height + 'px',
			"frameborder"	: 0,
			"scrolling"		: 'no',
			"src"			: v_url
		}).css({'borderWidth': '0'});
		
		return o_cal;
	} // this.createGoogleCalendarElement()
	
	/*
		Convert (ajaxify) a given contact form
	*/
	this.convertContactForm = function(o_form){
		if (o_form){
		
			var $this = $(o_form);
		
			// Set active field css
			$this.find('div.input input').each(function(){
				$(this).parent().css('opacity', 0.6);
				$(this).focus(function(e){
					$(this).parent().addClass('active-input')
						.removeClass('input').css('opacity', 1);
				});
				$(this).blur(function(e){
					$(this).parent().removeClass('active-input')
						.addClass('input').css('opacity', 0.6);
				});					
			});
			$this.find('div.message textarea').each(function(){
				$(this).parent().css('opacity', 0.6);
				$(this).focus(function(e){
					$(this).parent().addClass('active-message')
						.removeClass('message').css('opacity', 1);
				});
				$(this).blur(function(e){
					$(this).parent().removeClass('active-message')
						.addClass('message').css('opacity', 0.6);
				});			
			});
		
			// Capture the form submit event
			$this.submit(function(e){
				e.preventDefault();
			
				// Update UI
				var o_loading = $('<div/>').addClass('loading').attr('id', 'loading-notice').append(
						$('<div/>').addClass('image')
					).append(
						$('<div/>').addClass('message ').html('Sending your message..')
					);
				$(this).hide().after(o_loading.show());
			
				// Post form to server
				$.ajax({
					type		: "POST",
					url			: $(this).attr('action'),
					cache		: false,
					data		: $.param($(this).find(':input')) + '&responseformat=json&co=1',
					dataType	: "json",
					success		: function(o_data){
						// Check for errors and alert user if failed
						if (o_data.last_error.length == 0){

							var v_markup = '<h3>Thank you</h3>' +
								'<p>Your message has been sent and we will be in contact shortly.<hr />' +
								'Go to the <a href="/index.php" title="Go to our home page">' +
								'Home Page</a></p>';
							/*if (THEFOOT.contentLoaders['mainmenu']){
								THEFOOT.contentLoaders['mainmenu'].content
									.find('div.loading').width(490).html(v_markup);
								THEFOOT.contentLoaders['mainmenu'].updateLinks();
							} else {*/
							
								var o = $('#loading-notice');
								o.width(490).html(v_markup);
								THEFOOT.convertAllTooltips(o);
								//THEFOOT.convertLinksToPageLoaderLinks(o);
								
							//}
							
						} else {
					
							// Update UI to show errors						
							if (!$.isEmptyObject(o_data.failedfields)){
						
								// Remove previous validation errors and add new ones
								$this.find(':input').each(function(v_index){
									
									// Remove previous validation
									$(this).removeClass('failed');
									
									// Does this field have an error message?
									var v_fieldname = $(this).attr('id');
									for (var i in o_data.failedfields){
					
										if (i == v_fieldname){
										
											// Highlight the failed field
											var o_fld = $this.find('#' + v_fieldname);
											o_fld.addClass('failed').attr('title', o_data.failedfields[i]);
											THEFOOT.makeTooltipFromTitle(o_fld.get(0));
											
											// Show general error
											$('#' + $this.attr('id') + '-error').html('Please complete the form accurately.<br />' +
												'Mistakes are highlighted.').show();
												
											// Show form and focus first failed field
											$this.show(); 
											if (THEFOOT.contentLoaders['mainmenu']){
												THEFOOT.contentLoaders['mainmenu'].content
													.find('div.loading').hide();												
											} else {
												$('#lc-loading-notice').remove();
											}
											if ($this.find('input.failed').length > 0){
												$this.find('input.failed').get(0).focus();
											}
												
										}
									}
									
								});

							} else {
							
								// General failure
				
								$('#' + $this.attr('id') + '-error').html(o_data.last_error).show();
								$this.show(); 									
								$('#loading-notice').remove();
							
							}
						
						}
					},
					error		: function(o_ajax, v_status, o_error){
						THEFOOT.showError("An error occurred sending your request (" + 
							o_ajax.statusText + ").  Please refresh the page and try again.");
					}
				});
			
				return false;
			});
		
		}	
	} // this.convertContactForm()
	
	/*
		Convert an accordion class element into an interactive accordian
	*/
	this.convertAccordion = function(o_accordion, v_collapse){
		if (o_accordion){
		
			var $this = $(o_accordion);
			
			// Add the click handler to the header
			$this.find('div.header').toggle(
				function(){
					$(this).addClass('collapsed').next('div.content').slideUp(500, "easeOutExpo");
				},
				function(){
					$(this).removeClass('collapsed').next('div.content').slideDown(500, "easeInExpo");
				}		
			);
			
			// Add textual helper
			$this.before($('<div/>').addClass('accordion-helper').html('Click category header to expand/collapse section'));
			
			// Collapse all sections if required
			if (v_collapse){$this.find('div.header').click();}
			
		}
	} // this.convertAccordion()
	
	/*
	
	*/
	this.initCalendarFeed = function(){
	
		var feedUrl = "http://www.google.com/calendar/feeds/liz@gmail.com/public/full";
		this.gdataService = new google.gdata.calendar.CalendarService('exampleCo-exampleApp-1');
		this.gdataService.getEventsFeed(feedUrl, handleMyFeed, handleError);

	
	} // this.initCalendarFeed()
	
	/*
		Position under construction banner
		(Align top of viewport and make right width)
	*/
	this.positionUCBanner = function(){
		$('#uc-banner').width((THEFOOT.sysinfo.viewport.width  - 6) + 'px')
			.css({'top': $(window).scrollTop() + 'px'});
	} // this.positionUCBanner()
	
	/*
		Show a news flash banner
	*/
	this.showNewsFlash = function(v_title, a_messages){
		if (!this.cookie.get('news-flash') || (this.cookie.get('news-flash') != v_title)){
			var o_newsflash = $('<div/>').addClass('newsflash')
				.append($('<h1/>').html('News Flash!'))
				.append($('<h2/>').html(v_title));
			for (var i = 0; i < a_messages.length; i++){
				o_newsflash.append($('<p/>').html(a_messages[i]));
			}
			o_newsflash.append($('<button/>').attr({"type": 'button'}).html('Dismiss Message').val('Dismiss Message'));
			$(document.body).append($('<div/>').attr({'id': 'uc-banner'}).append(o_newsflash).hide());
			o_newsflash.find('button').click(function(){
				$('#uc-banner').slideUp();
				this.cookie.set('news-flash', v_title, (24 * 60));
			}.bind(this));
			THEFOOT.positionUCBanner();
			$('#uc-banner').slideDown().fadeIn();			
			$(window).resize(THEFOOT.positionUCBanner);
			$(window).scroll(THEFOOT.positionUCBanner);
		}
		return this;
	} // this.showNewsFlash()
	
	/*
		For a given list id, scan all links in listitems and add a class of "current" to the listitem
		where the link href matches the current URL
	*/
	this.highlightCurrentURL = function(v_menu_class){
		var v_current_url = this.getCurrentPage();
		$('ul.' + v_menu_class + ' li a').each(function(){
			if (THEFOOT.getPageFromURL($(this).attr('href')) == v_current_url){
				$(this).parent().addClass('current');
			}
		});
	} // this.highlightCurrentURL()

	/*
		Create a DHTML tooltip from [title] attribute
	*/
	this.makeTooltipFromTitle = function(o_node, v_delay){
		if ($(o_node)){
			$(o_node).qtip({
				"delay": ((v_delay) ? v_delay : 1000), 
				solo: true, 
				hide: { 
					delay: 0, when: {event: 'mouseleave'} 
				},
				position: this.optionsets.qtipposition, 
				style: this.optionsets.qtipstyle				   
			});
		}
	} // this.makeTooltipFromTitle()

	/*
		Make all links with rel*="popup" popup links
	*/
	this.activateExternalLinks = function(){
		
		// Convert all links to use link text as title if none specified
		$('a[rel*="popup"]').each(function(){
			$(this).attr('target', '_blank');					   
		});
		
		return this;
	} // this.activateExternalLinks()
	
	/*
		Fix any layout quirks
	*/
	this.fixLayout = function(){
	
		// Make the middle sections the same height
		return this;
			// Get max height
			var v_height = null;
			$('div#middle').children('div').each(function(){
				if ($(this).outerHeight(true) > v_height){v_height = $(this).outerHeight(true);}
			});
		
			// Make all the max height
			$('div#middle').children('div:not(div.clearfloat)').each(function(){
				var $this = $(this);
				$this.height(v_height - ($this.outerHeight(true) - $this.height()));
			});
	
		return this;
	} // this.fixLayout()
	
	/*
		Convert all relevant elements' title attributes to DHTML tooltips
	*/
	this.convertAllTooltips = function(o_parent){
	
		// Get parent
		if (!o_parent){o_parent = $(document)} else {o_parent = $(o_parent);}
			
		// Convert all links to use link text as title if none specified
		/*$('a[title=""]').each(function(){
			$this = $(this);
			$this.attr("title", $this.text());					   
		});*/
		
		// Store the title attr as data for links
		$('a[title!=""]').each(function(){
			$(this).data('title', $(this).attr('title'));
		});
		
		// If an element has a rel="notooltip" attribute specified,
		// then we remove the title attr
		// We remove the title attribute so that the native tooltip doesnt interfere with ours
		o_parent.find('*[title!=""][rel*="notooltip"]').each(function(){
			$(this).removeAttr("title");
		});
		
		// Convert each googlemap link as popups
		/*o_parent.find('.googlemap[href!=""]').each(function(){
			$(this).attr('title', '').qtip({
				solo: true, 
				delay: 1000, 
				content: {
					url: $(this).attr('href')
				},
				hide: { 
					fixed: true, delay: 0, when: {event: 'mouseleave'} 
				},
				position: THEFOOT.optionsets.qtipposition, 
				style: THEFOOT.optionsets.qtipstyle
			});
		});*/
		
		// Convert all elements with title attributes set, to DHTML tooltips
		o_parent.find('*[title!=""]').qtip({
			solo: true, 
			content: {
				prerender: true
			},
			delay: 1000, 
			hide: { 
				delay: 0, when: {event: 'mouseleave'} 
			},
			position: this.optionsets.qtipposition, 
			style: this.optionsets.qtipstyle					   
		});

		return this;
		
	} // this.convertAllTooltips()
	
	/*
		Convert all flash divs to flash players
	*/
	this.convertAllFlash = function(){
		
		$('div.flashembed').each(function(){
			THEFOOT.convertFlash(this);
		});

		return this;
		
	} // convertAllFlash()
	
	/*
		Convert given flash divs to flash player
	*/
	this.convertFlash = function(o_obj){
		var $this = $(o_obj);
		$this.append($('<a/>', {'href': $this.attr('src')}).addClass('target'));
		$this.find('a.target').eq(0).media({
		    'autoplay'	: false,
		    'width'		: 500,
		    'height'	: 395,
		    'bgColor'	: 'transparent'
		});
	
		return this;
		
	} // convertFlash()
	
	/*
		Page initialisation code
	*/
	this.initPage = function(){		
		
		// Preload images
		this.cacheImages();
		
		// Fix layout
		this.fixLayout();
		
		// Convert all tooltips
		this.convertAllTooltips();
		
		// Convert external links
		this.activateExternalLinks();
		
		// Load any flash
		this.convertAllFlash();
		
		// Process any server errors
		if (this.server_error.length > 0){
			alert(this.server_error);
		}

	} // this.initPage()

		
} // thefoot app namespace

// Scope bind function - allows binding of objects as "this" in functions
if (!Function.prototype.bind){
	Function.prototype.bind = function(obj) {
		var method = this,
		temp = function() {
			return method.apply(obj, arguments);
		};
		return temp;
	}
}

// String trim() function
if (!String.prototype.trim){
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
}

