// Namespace function
function namespace(ns) {
    ns = ns.split('.');
    var cur = window, i;
    while ( i = ns.shift() ) {
        if ( !cur[i] ) cur[i] = {};
        cur = cur[i];
    }
}

namespace("website");
namespace("booking");

$(document).ready(function(){
	// Hacks for IE, mostly for fake hover classes
	if ($.browser.msie) website.iehacks();

	// Setup the flash banners
	//website.banners.setup();

	// Form builder functions, comment out if your site doesn't need them
	// if ($("#survey_form fieldset.tabbed").length > 0) $("form#survey_form").tabbed_form({continue_buttons: true});  
	
	// Hide Labels from particular fieldsets
	$("form.hide_labels").each(website.hide_labels);	  

	// Attach lightbox to gallery links, comment out if your site doesn't need them
	// $('#photos a').lightBox();
	
	// Popup links
	$("#body a.popup, .submenu a.popup").each(website.popup);
	
	// Landing page tabs	
	website.landing_tabs.setup();
	
	// Document links
	website.document_links();
	
	// Print page
	if($("#print_page").length > 0) {
		$("#print_page").click(function(){window.print();});
	}
	
	// Embedded video links
	website.embed_videos();
	
	// Hosted video player
	if (($videos = $("#body a.flv, #body a.mp4, #body a.mov")) && $videos.length > 0) website.video($videos);
	
	// Gmaps embed code
	// website.google_maps();
	
	// Inline form validation
	if ($("form.inline_validation").length > 0) {
	  $("form.inline_validation").each( website.form_validation.setup($(this)) );
	}
	
	// Generic tabbed forms
	$tabbed_forms = $("form.tabbed_form");
	$tabbed_forms.each( function() {
		if ($("fieldset.tabbed", $tabbed_forms).length > 1) {
			$(this).tabbed_form();
		}		
	})
	
	if ($("#forgotten_password_form").length > 0) website.forgotten_password();
	
	// for the booking form
	$("label.remove").hide();
	if ($("a.remove").length > 1) $("a.remove").show();
	
	// Noticeboard functions
	$("ul.noticeboard > li").not(":first").find("div.toggleable").hide();
	$("ul.noticeboard > li").each( function(idx) {
		var $this = $(this);
		var href = "#" + $this.attr("id") + "_replies";
		$this.append($("<a>Close</a>").attr({href: href, rel: href}).addClass("icon delete").hide().css({float: "right"}));
		var $close = $("a.icon.delete", $this);
		(idx == 0) ? $close.show() : $close.hide();
		$close.click( function() {
			$("div.toggleable", $this).hide("fast");
			$(this).hide();
			$("a.icon.add", $this).show();
		});
		$this.append($("<a>Read Notice</a>").attr({href: href, rel: href}).addClass("icon add").css({float: "right"}));
		var $open = $("a.icon.add", $this);
		(idx == 0) ? $open.hide() : $open.show();
		$open.click( function() {
			$("div.toggleable", $this).show("fast");
			$(this).hide();
			$("a.icon.delete", $this).show();
		});
	});
	
	// Switch out the login link in the header to gcvs connect if were logged in
	if ($.cookie('logged_in')) {
		$("#login_link a").text("GVCS Connect").attr({"href": "/connect"})
	}
	
	// hide gcvs connect events after the first one
	$("#bookings ul.items.events li:not(:first) .hideable").hide();
	
	$("#bookings ul.items.events li form.optional").hide();
	// $("#bookings ul.items.events li .icon_link a").click( function() {
	// 	var $this = $(this);		
	// 	$($this.attr("rel")).show("fast");
	// 	return false;
	// });
	
	var $post_comment = $("#connect #post_comment");
	$("fieldset.buttons input", $post_comment).before($("<a>Close</a>").attr({href: "#post_comment", rel: "#post_comment"}).addClass("icon delete").css({float: "right"}));
	$post_comment.hide()
	$("a.icon.delete", $post_comment).click( function() {
		$($this.attr("rel")).toggle("fast");
		return false;
	});
	$("#connect a.icon.page").click( function() {
		var $this = $(this)
		$($this.attr("rel")).toggle("fast");
		return false;
	});
	
	var $news_prefs = $("#news_prefs");
	$("fieldset.buttons input", $news_prefs).before($("<a>Close</a>").attr({href: "#news_prefs", rel: "#news_prefs"}).addClass("icon delete").css({float: "right"}));
	$news_prefs.hide()
	$("a.icon.delete", $news_prefs).click( function() {
		var $this = $(this)
		$($this.attr("rel")).toggle("fast");
		return false;
	});
	$("#connect a.icon.add").click( function() {
		var $this = $(this)
		$($this.attr("rel")).toggle("fast");
		return false;
	});
	
	// Disable links for preview window
	website.disable_preview();
	
});

// Used by the multi-model form JS
replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}

website = {
	// Forgotten password link
	forgotten_password: function() {
		if ($("#forgotten_password_form fieldset div").length > 0) {
			$("#forgotten_password_form a").hide();
			if ($("#forgotten_password_form #notice").length > 0) {
				$("#forgotten_password_form label, #forgotten_password_form input").hide();
			}
		} else {
			$("#forgotten_password_form fieldset").hide();
			$("#forgotten_password_form a").click(function(){
				$("#forgotten_password_form fieldset").toggle();
				return false;
			});
		}
	},
	
	disable_preview: function() {
		if (location.href.match(/cms_preview/)) {
			$("a").click(function(){
				alert("Links are disabled as this is a preview window."); 
				return false; 
			});
		}
	}, 
    
	// Hide labels, set text to targets value
	hide_labels: function() {
		$(this).find("label").each(function() {
			$('#' + this.htmlFor).val(this.innerHTML);
			$(this).hide();
			$('#' + this.htmlFor).click(website.clearbox);
		})
	},

	// Clear default text in an input box
	clearbox: function() {
		if (!this.default_value) this.default_value = this.value;

		if (this.value == '') {
			this.value = this.default_value;
			this.select();
		} else if (this.value == this.default_value) {
			this.value = '';
		}
	},
  
	// Jump to URL
	jump_to_url: function(url) {
		if (url == "") return false;
		location.href = "/" + url;
	},

	// Popup link
	popup: function() {
		this.target = "_blank";
		this.title =  this.title ? this.title += ". " : "";
		this.title += "Link opens in a new window.";
	}, 
  
	document_links: function() {
		$("#body a[href$='.doc']").addClass("doc");
		$("#body a[href$='.xls']").addClass("xls");
		$("#body a[href$='.ppt']").addClass("ppt");

		$("#body a.pdf:has(img)").removeClass("pdf");
		$("#body a.doc:has(img)").removeClass("doc");
		$("#body a.xls:has(img)").removeClass("xls");
		$("#body a.ppt:has(img)").removeClass("ppt");
	}, 
  
	embed_videos: function() {
		$('#body a[href*="youtube.com"]').not($('#replies a')).flash(
			{ width: 425, height: 350, wmode: 'transparent' },
			{ version: 8 },
			function(htmlOptions) {
				htmlOptions.src = "http://www.youtube.com/v/" + this.href.match(/v=(.+)/)[1];
				$(this).before($.fn.flash.transform(htmlOptions));
				$(this).remove();
			}
		);

		$('#body a[href*="vimeo.com"]').not($('#replies a')).flash(
			{ width: 453, height: 340, quality:'best', allowfullscreen:'true', scale:'showAll' },
			{ version: 8 },
			function(htmlOptions) {
				htmlOptions.src = "http://vimeo.com/moogaloop.swf?clip_id=" + this.href.match(/(\d+)/)[1] + "&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=FFCF4C";
				$(this).before($.fn.flash.transform(htmlOptions));
				$(this).remove();
			}
		);
	}, 
  
	videos: function(target) {	
		
		var flashvars = {
			image: "/images/video_intro.png",// pass image URL if there is one

			autoplay: false,					// use to autoplay video
			//buffer: 3,						// set buffer length (default is 3)
			
			navAutoHideIdleTime: 2,				// set mouse idle time for navigation to hide
			navAutoHide: true,					// disable navigation auto hide
			//hideNav: true,					// turn off navigation

			//debug: true,						// debug mode
			//scaleMode: "crop",				// use "crop" to change, default mode is "fit"

			// THEMES //////////////////////////////////////////////////
			
			// theming is based on setting hue, saturation, brightness and constrast values
			// to 0xff0000 (red) colour
			
			customTheme: false			// enables custom colours
			
			// themeHue: 100,       // icons and GUI elements params
			// themeBrightness: 100,
			// themeConstrast: 25,
			// themeSaturation: -100,
			// 
			// handleHue: 0,        // handles (sliders) params
			// handleBrightness: 100,
			// handleConstrast: 100,
			// handleSaturation: 0,
			// 
			// preloaderHue: 100,     // preloader progress params
			// preloaderBrightness: -80,
			// preloaderConstrast: -50,
			// preloaderSaturation: 50,
			// 
			// backgroundFrom: 0xff9697A9,  // background colours (use rgb32, AARRGGBB)
			// backgroundTo: 0xff5C5E74
		};
		
    $(target).flash(
	    {
			src: '/flash/flvplayer.swf',
			width: 460,
			height: 368,
			allowFullScreen: true,
			flashvars: flashvars
	    },
	    { 
			update: false,
			expressInstall: false, 
			expressInstallSrc: "/flash/expressInstall.swf", 
			version: "9.0.115"
	    },
	    function(htmlOptions) {
			htmlOptions.flashvars.video = $(this).attr("href");
			$(this).empty().append($.fn.flash.transform(htmlOptions));
	    }
	);
    		
	}, 

	google_maps: function() {
		if (($google_map = $("#google_map")) && $google_map.length > 0) {
			$google_map.googleMap(
				map.lat, 
				map.lng, 
				map.zoom, 
				{ 
					controls: ["GSmallMapControl"], 
					markers: [{lat: map.lat, lng: map.lng, txt: map.txt}]
				}
			);
		}
	}, 
    
	iehacks: function() {
		if (parseInt($.browser.version) == 7) {
			// IE7 hacks
		} else if (parseInt($.browser.version) < 7) {
			// IE6 and below hacks

			// Menu popdown
			$("#menu li").hover(
				function(){ $(this).addClass("hover"); },
				function(){ $(this).removeClass("hover"); }
			);

		} else {
			// All IE versions
			// $("#search").hover(
			// 	function(){ $(this).addClass("hover"); },
			// 	function(){ $(this).removeClass("hover"); }
			// );
		}
	}
};

website.landing_tabs = {
  active: "#tab-0", 
  
  setup: function() {
    
    if (window.location.hash.indexOf("#tab-") == 0) {
      website.landing_tabs.active = window.location.hash;
    }
    
    var $links = $("<ul id=\"tablinks\" class=\"clearfix\"></ul>");
    var $first_tab = $("#tabs .tabbed:first");
    
    // Wrap all the tabs in a new div so we can set the height of the div to the content
    $("#tabs .tabbed").wrapAll("<div class=\"inner\"></div>");    
    
    // Hide all of the existing tabs that aren't active 
    $("#tabs .tabbed").hide();
    
    $("#tabs").css("height", $first_tab.height());

    $("#tabs .tabbed").each( function(idx) {
		var $this = $(this);
      $this.attr("id", "tab-"+idx);      
      $links.append("<li><a class=\"" + $("h3", $this).text().toLowerCase().replace(/ /g,"_") + "\" href=\"#" + $this.attr("id") + "\">" + $("h3", $this).text() + "</a></li>");
      $("h3", $this).remove();
    });    
    
    $("a", $links).click( function() {
      return website.landing_tabs.change_tab("#"+$(this).attr("href").split("#")[1]);
    });
    
    $("#tabs .inner").before($links);
    
    $("#tabs #tablinks li:last").addClass("last");
    
    website.landing_tabs.change_tab(website.landing_tabs.active);
  }, 
  
  change_tab: function(tab_id) {
    $(website.landing_tabs.active).hide();
    $("#tabs").css("height", $(tab_id).css("height"));
    $(tab_id).show();

    // Remove all of the active classes and set the new active one
    $("#tablinks li").removeClass("active");
    $("#tablinks a[href$=" + tab_id + "]").parent("li").addClass("active");

    website.landing_tabs.active = tab_id;
    return false;
  }
};

booking = {
	add: function(container, type) {
		var html = replace_ids(type);
		$(container).append(html);
		$(container + ">fieldset:last input[type=text]:first").focus();
		$("fieldset:first .first_show_only", container).show();
		$("a.remove").show();
		$("label.remove").hide();
		
        return false;
	},
	
	remove: function(_this) {
		var fs = $(_this).parents("fieldset")[0];
		$("input.delete_input", fs)[0].checked = true;
		$("ul, .remove", fs).hide();
		// if($("a.remove:visible").length < 1){
			$(_this).parents('form:first').submit();
		// }else{
			// $("p.undo", fs).show();
			// if ($("fieldset.application fieldset ul:visible").length < 2)  $("a.remove").hide();
			// return false;
		// }
	},
	
	undo: function(_this) {
		var fs = $(_this).parents("fieldset")[0];
		$("input.delete_input", fs)[0].checked = false;
		$(_this).parent().hide();
		$("ul, .remove", fs).show();
		$("a.remove").show();
		$("label.remove").hide();
		return false;
	}  
  
};