path = (top.location.host == "localhost" ? "/kellys/bin/" : "/");

var flashVars = { };
var flashParams = { menu: "false", wmode: "transparent"};
var flashID = { id : "flashMain" };
swfobject.embedSWF (path+"swf/main.swf", "flashMain", "960px", "325px", "9.0.0", "swf/expressInstall.swf", flashVars, flashParams, flashID);

$(document).ready (function () {
	replaceFonts ();
	initMenu ();
	initHeader ();
	initNews ();
	Shadowbox.init ({ overlayOpacity: 0.35 });
	//$.history.init (loadhash);
});

function resizeWindow () {
	$("#background").height($(document).height () - $("#menu").height());
}

function replaceFonts () {
	Cufon.replace ('#menu li', {fontFamily: 'kellys'});
	Cufon.replace ('#footer div', {fontFamily: 'kellys.body', hover: true});
}

// History
var Home = true;
var currentHash = "";

function loadhash (hash) {
	/*if (!Home && hash == ""){
		hash = "index.php";
	}
	
	if (hash) {
		Home = false;
		$.post (hash, {ajax: 1}, function (data) { $("#container").html (data); });
		if (hash == "index.php") $("#mainHeader .back").hide ();
		else if (hash != "")  $("#mainHeader .back").show ();
	}
	
	getIntroText (hash);
	if (hash != "") checkBackground (hash);*/
	
	if (hash) {
		Home = false;
		currentHash = hash;
		$.post (hash, {ajax: 1}, function (data) { $("#container").html (data); });
		if (hash == "index.php") $("#mainHeader .back").hide ();
		else if (hash != "")  $("#mainHeader .back").show ();
		$("#history").attr("src", path+"php/history.php?p="+hash);
	}
	getIntroText (hash);
	if (hash != "") checkBackground (hash);
}

function checkHash (hash) {
	if (hash != currentHash) loadhash (hash);
}

// Menu
var prodback = false;

function initMenu () {
	/*for (var i=0; i<$("#menu li").length; i++) {
		copy = "#"+$($('#menu li')[i]).attr("id");
		hash = path+$('#menu li a')[i].href.split("/").pop();
		$(copy).bind("click", {hash: hash}, loadPage);
	}
	$("#menu li a").removeAttr('href');*/
}

function loadPage (evnt) {
	checkBackground (evnt.data.hash);
	//$.history.load (evnt.data.hash);
	loadhash (evnt.data.hash);
}

function flashLink (hash) {
	checkBackground (path+hash);
	//$.history.load (path+hash);
	loadhash (path+hash);
}

function getIntroText (hash) {
	hash = hash.replace(".php", "");
	hash = hash.replace(path, "");
	hash = hash.replace("/", "");
	if (hash != "") {
		if(hash.indexOf("products")!=-1) hash = "products";
		
		switch(hash) {
			case "products":
				header	= "PRODUCTS";
				intro	= "You can enjoy Kelly's delicious<br/>creamy ice cream made with Cornish milk and<br />Cornish clotted cream either in the comfort of<br />your own home or in a cone when you're out<br/>and about over the summer months.";
				break;
			case "farm":
				header	= "VISIT THE FARM";
				intro	= "Here you can learn all about the diary<br/>farms that supply the creamy Cornish milk<br/>and cream that goes in to making Kelly's ice cream. Meet some of our farmers and enjoy watching our short film on a day in the life of a diary cow on Daisy's Day. You can vote for your favourite cow in our beauty pageant.";
				break;
			case "recipes":
				header	= "RECIPES";
				intro	= "Here is a selection of some delicious<br/>desert recipes using Kelly's ice cream<br />for you to try. We'd love to hear from<br />you if you have any recipe ideas to<br/>share with us too.";
				break;
			case "whatson":
				header	= "WHAT'S ON";
				intro	= "The team at Kelly's have found a whole heap of exciting events that are taking place over the UK this summer and we want to tell you all about them. So, to find out about these events, find your nearest region and click on the date that interests you. You'll find all the information you need for a great family day out.";
				break;
			case "win":
				header	= "WIN";
				intro	= "You can win great prizes here.<br/>For your chance to win a taste of<br/>life's simple pleasures check back<br/>every month for more<br/>competitions.";
				break;
			case "trade":
				header	= "TRADE";
				intro	= "This information is for our<br/>trade customers who would like to<br/>sell our delicious ice cream.";
				break;
			default:
				header	= "SIMPLE<br/>PLEASURES";
				intro	= "Take some time to play<br/>around and discover why the<br/>simple pleasures are the best.";
		}
		$("#mainHeader .header h1").html (header);
		$("#mainHeader .header p").html (intro);
		$(document).ready (function () {
			Cufon.replace ('#mainHeader .header p', {fontFamily: 'kellys.body', textShadow: '#61a7c5 1px 1px'});
			Cufon.replace ('#mainHeader .header h1', {fontFamily: 'kellys', textShadow: '#61a7c5 2px 2px'});
		});
	}
}


function checkBackground (hash) {
	hash = hash.replace(path, "");
	if (hash.substr(0, 8) == "products" && !prodback) {
		prodback = true;
		$("#background").css ("background-image", "url("+path+"img/background_products.jpg)");
	} else if (hash.substr(0, 7) == "aboutus") {
		prodback = false;
		$("#background").css ("background-image", "url("+path+"img/aboutus_bg.jpg)");
	} else {
		prodback = false;
		$("#background").css ("background-image", "url("+path+"img/background.jpg)");
	}
}

// Header 
function initHeader () {
	$("#mainHeader .news .scrollPane ul").jScrollPane ({scrollbarWidth: 4, scrollbarMargin: 12});
	Cufon.replace ('#mainHeader .news h4', {fontFamily: 'kellys.news'});
	Cufon.replace ('#mainHeader .news p', {fontFamily: 'kellys.body'});
	Cufon.replace ('#mainHeader .header p', {fontFamily: 'kellys.body', textShadow: '#61a7c5 1px 1px'});
	Cufon.replace ('#mainHeader .header h1', {fontFamily: 'kellys', textShadow: '#61a7c5 2px 2px'});
	
	/*$('#mainHeader .recipe a').bind ("click", {hash: path+"recipes/"}, loadPage);
	$("#mainHeader .recipe a").removeAttr ('href');
	
	$('#mainHeader .win a').bind ("click", {hash: path+"win/"}, loadPage);
	$("#mainHeader .win a").removeAttr ('href');*/
}

// News
function initNews () {
	$("#news .close").click (closeNews);
}

function toggleNews (id) {
	$("#news li.prev").fadeTo (0, 0);
	$("#news li.next").fadeTo (0, 0);
	$("#news li.prev").unbind ("click");
	$("#news li.next").unbind ("click");
	$.post (path+"php/newsentry.php", {id: id}, function (data) {
		var vars = data.split ("&var=");
		var date = vars[1];
		var headline = vars[2];
		var copy = vars[3];
		var filename = vars[4];
		var previd = vars[5];
		var nextid = vars[6];
		$("#news li.header .left").html (headline);
		$("#news li.header .right").html (date);
		Cufon.replace ('#news li.header', {fontFamily: 'kellys'});
		$("#news li.copy .scrollPane").html (copy).jScrollPane ({scrollbarWidth: 7, scrollbarMargin: 8});
		$("#news li.image").html ("<img src='"+path+"php/phpthumb.php?q=90&w=245&h=148&src="+path+"content/"+filename+"' alt='News' />");
		if (previd != 0) {
			$("#news li.prev").fadeTo (200, 1);
			$("#news li.prev").click (function () { toggleNews (previd); });
		}
		if (nextid != 0) {
			$("#news li.next").fadeTo (200, 1);
			$("#news li.next").click (function () { toggleNews (nextid); });
		}
	});
		
	if ($("#frame").css("marginTop") == "-227px") $("#frame").animate ({marginTop: '0px'}, 300, function() {});
}

function closeNews () {
	$("#frame").animate ({marginTop: '-227'}, 300, function() {});
}

// Home
function initHome () {
	var flashVars = { };
	var flashParams = { menu: "false", wmode: "transparent", allowscriptaccess: "always"};
	var flashID = { id: "home_daisy" };
	//swfobject.embedSWF (path+"swf/home_daisy.swf", "home_daisy", "303px", "307px", "9.0.0", "", flashVars, flashParams, flashID);
	
	/*$('#homepage .products a').bind ("click", {hash: path+"products/"}, loadPage);
	$("#homepage .products a").removeAttr ('href');
	
	$('#homepage .daisy a').bind ("click", {hash: path+"farm/daisysday/"}, loadPage);
	$("#homepage .daisy a").removeAttr ('href');*/
	
	$("#homepage li").mouseover (function(e) {
		var xx = $(this).position().left;
		var yy = $(this).position().top - 20;
		var display = true;
		switch ($(this).attr('class')) {
			case 'products': xx += 90;break;
			case 'cow': xx += 150; break;
			case 'daisy': display = false; break;
			case 'calendar': xx -= 10; break;
			case 'facebook': xx += 20; yy -= 20; break;
		}
		if (display) {
			$("#tooltip").css ("left", xx+"px");
			$("#tooltip").css ("top", yy+"px");
			$("#tooltip #label").html ($(this).find("img").attr ("alt"));
			Cufon.replace ('#tooltip #label', {fontFamily: 'kellys'});
			$("#tooltip").show()
			if (!$.browser.msie) $("#tooltip").stop().animate ({opacity: 1, top: yy-10}, 300);
		}
	}).mouseout (function() {
		if ($.browser.msie) { 
			$("#tooltip").hide();
		} else {
			$("#tooltip").stop().animate ({opacity: 0}, 300, function() { $("#tooltip").hide(); });
		}
	});
}

// Products
function initProductsFlash () {
	checkBackground ("products.php");
	var flashVars = { };
	var flashParams = { menu: "false", wmode: "transparent"};
	var flashID = { id : "flashProducts" };
	swfobject.embedSWF (path+"swf/products.swf", "flashProducts", "960px", "440px", "9.0.0", "swf/expressInstall.swf", flashVars, flashParams, flashID);
}

function initProductsLanding () {
	checkBackground ("products.php");
	Cufon.replace ('#content #container #productsLanding a', {fontFamily: 'kellys', hover: true});
	
	/*for (var i=0; i<$("#productsLanding li").length; i++) {
		var tmp = $('#productsLanding li a')[i].href;
		//hash = tmp.split("/").pop();
		hash = path+"products"+tmp.split("products").pop();
		$($('#productsLanding li a')[i]).bind("click", {hash: hash}, loadPage);
	}
	
	$("#productsLanding li a").removeAttr('href');*/
}

function initProducts () {
	replaceProductFonts ();
	checkBackground ("products.php");
	
	// TOOL TIPS	
	$("#content #container #thumbnails ul li").mouseover (function() {
		$("#tooltip").css ("left", $(this).position().left-14+"px");
		$("#tooltip #label").html ($(this).find("img").attr ("alt"));
		Cufon.replace ('#content #container #page #tooltip  #label', {fontFamily: 'kellys'});
		$("#tooltip").show();
		if (!$.browser.msie) $("#tooltip").stop().animate ({opacity: 1, top: '20'}, 300);
	}).mouseout (function() {
		if ($.browser.msie) { 
			$("#tooltip").hide();
		} else {
			$("#tooltip").stop().animate ({opacity: 0, top: '24'}, 300, function() { $("#tooltip").hide(); });
		}
	});
	
	$("#tooltip").mouseover (function() {
		if (!$.browser.msie)
			$("#tooltip").stop().animate ({opacity: 1, top: '20'}, 300);
		else $("#tooltip").show();
	}).mouseout (function() {
		if (!$.browser.msie)
			$("#tooltip").stop().animate ({opacity: 0, top: '24'}, 300, function() { $("#tooltip").hide(); });
		else $("#tooltip").hide();
	});
	
	// NUTRITION ETC
	$("#content #container #page h3").click (function () { $(this).next().slideToggle (300); });
	
	// THUMB LINKS
	/*for (var i=0; i<$("#thumbnails li").length; i++) {
		copy = "#"+$($('#thumbnails li')[i]).attr("id");
		var tmp = $('#thumbnails li a')[i].href;
		hash = path+"products"+tmp.split("products").pop();
		$(copy).bind("click", {hash: hash}, loadPage);
	}
	
	$("#thumbnails li a").removeAttr('href');*/
	
	// OUT AND ABOUT / AT HOME
	/*for (var i=0; i<$("#content #container #page h4 a").length; i++) {
		var tmp = $('#content #container #page h4 a')[i].href;
		hash = path+"products"+tmp.split("products").pop();
		$($('#content #container #page h4 a')[i]).bind("click", {hash: hash}, loadPage);
		$($('#content #container #page h4 a')[i]).css ("cursor", "pointer");
	}
	$("#content #container #page h4 a").removeAttr("href");*/
}

function replaceProductFonts () {
	Cufon.replace ('#content #container #page h4', {fontFamily: 'kellys', hover: true});
	Cufon.replace ('#content #container #page h3', {fontFamily: 'kellys'});
	Cufon.replace ('#content #container #page h2', {fontFamily: 'kellys'});
}

// Recipes
function sidePanelFunctions () {
	$(".sidepanel li").click (function() {
		var id = $(this).attr("id").replace ("recipe_", "");
		$.post(path+"php/recipe.php", {id: id}, function (data) {
			$("#recipes").html(data);
			replaceRecipeFonts ();
			initRecipes();
			//$("#content #container #recipes h4").click (function () { $(this).next().slideToggle (300); });
		});
	});
}

function initRecipes () {
	replaceRecipeFonts ();
	
	$("#content #container #recipes h4").click (function () { $(this).next().slideToggle (300); });
	
	$(document).ready(function () {
		$(".sidepanel ul").jScrollPane ({scrollbarWidth: 7, scrollbarMargin: 0});
	});
	
	sidePanelFunctions ();
	
	$("#search_submit").click (function () {
		$.post (path+"php/recipesearch.php", {string: $("#search_string").val()}, function (data) {
			$(".sidepanel .search_clear").show ();
			$(".sidepanel ul").html (data);
			sidePanelFunctions ();
			$(".sidepanel ul").jScrollPane ({scrollbarWidth: 7, scrollbarMargin: 0});
		});
	});
	
	$(".sidepanel .search_clear").click (function () {
		 $("#search_string").val("");
		$.post (path + "php/recipesearch.php", {string: ""}, function (data) {
			$(".sidepanel .search_clear").hide ();
			$(".sidepanel ul").html (data);
			sidePanelFunctions ();
			$(".sidepanel ul").jScrollPane ({scrollbarWidth: 7, scrollbarMargin: 0});
		});
	});
}

function replaceRecipeFonts () {
	Cufon.replace ('#content #container #recipes h2', {fontFamily: 'kellys'});
	Cufon.replace ('#content #container #recipes h3', {fontFamily: 'kellys'});
	Cufon.replace ('#content #container #recipes h4', {fontFamily: 'kellys'});
	Cufon.replace ('#content .sidepanel h4', {fontFamily: 'kellys', hover: true});
}

// Cornishness
function initCornishness () {
	replaceCornishnessFonts ();
	
	/*for (var i=0; i<$("#content #container h2 a").length; i++) {
		var tmp = $('#content #container h2 a')[i].href;
		//hash = tmp.split("/").pop();
		hash = path+"farm"+tmp.split("farm").pop();
		$($('#content #container h2 a')[i]).bind("click", {hash: hash}, loadPage);
		$($('#content #container h2 a')[i]).css ("cursor", "pointer");
		$($('#content #container img')[i]).bind("click", {hash: hash}, loadPage);
		$($('#content #container img')[i]).css ("cursor", "pointer");
	}
	$("#content #container h2 a").removeAttr("href");*/
}

function replaceCornishnessFonts () {
	Cufon.replace ('#content #container h2', {fontFamily: 'kellys'});
}

// Video / Ads Page
function initVideo (filename) {
	initVideoFonts ();
	
	var flashVars = { filename: filename };
	var flashParams = { menu: "false", wmode: "transparent", allowFullScreen: true };
	var flashID = { id : "videoplayerFlash" };
	swfobject.embedSWF (path+"swf/videoplayer.swf", "videoplayerFlash", "886px", "486px", "9.0.0", "swf/expressInstall.swf", flashVars, flashParams, flashID);
}

function initVideoFonts () {
	Cufon.replace ('#content #container #video h2', {fontFamily: 'kellys', hover: true});
	Cufon.replace ('#content #container #video h3', {fontFamily: 'kellys'});
}

function initAds () {
	Shadowbox.clearCache ();
	Shadowbox.setup ();
	initVideoFonts ();
	initVideo(path+"flv/clotted_cream_640x360.flv");
	
	$("#playflv1").removeAttr('href');
	$("#playflv2").removeAttr('href');
	$("#playflv3").removeAttr('href');
	
	$("#playflv1").click (function () {
		initVideo(path+"flv/TV_Strawberry_20.flv");
		$('#adname').text('Strawberry');
		initVideoFonts ();
	});
	
	$("#playflv2").click (function () {
		initVideo(path+"flv/TV_Honey_20.flv");
		$('#adname').text('Honeycomb');
		initVideoFonts ();
	});	
	
	$("#playflv3").click (function () {
		initVideo(path+"flv/clotted_cream_640x360.flv");
		$('#adname').text('Clotted Cream');
		initVideoFonts ();
	});
}

// Pageant
function initPageant () {
	replaceProductFonts ();
	
	/*var tmp = $('#content #container #page h4 a').attr ("href");
	//hash = tmp.split("/").pop();
	hash = path+"farm"+tmp.split("farm").pop();
	$($('#content #container #page h4 a')).bind("click", {hash: hash}, loadPage);
	$($('#content #container #page h4 a')).css ("cursor", "pointer");
	$("#content #container #page h4 a").removeAttr("href");*/
	
	initStars ();
}

function initStars () {
	$("#content #container #page .stars li").click (function () {
		var id = $(this).parent().attr("id");
		$.post (path + "php/rating.php", {id: $(this).parent().attr("id").replace ("cow", ""), rating: $(this).html()}, function (data) {
			$("#"+id).html (data);
		});
	});
	
	$("#content #container #page #pageant .pageantdetails").click (function () {
		var id = $(this).parent().attr("id");
		var num = id.replace ("li_", "");
		var row = Math.ceil (num/3);
		var start = ((row-1)*3)+1;
		
		var copy = "";
		
		for (i=start; i<start+3; i++)
			$("#li_"+i+" > .pageantextended").slideToggle ();
	});
}

// Suppliers
function initSuppliers () {
	replaceProductFonts ();
	
	/*var tmp = $('#content #container #page h4 a').attr ("href");
	//hash = tmp.split("/").pop();
	hash = path+"farm"+tmp.split("farm").pop();
	$($('#content #container #page h4 a')).bind("click", {hash: hash}, loadPage);
	$($('#content #container #page h4 a')).css ("cursor", "pointer");
	$("#content #container #page h4 a").removeAttr("href");*/
	
	var depth = 2;
	$("#content #container #page #pageant li").click (function () {
		Shadowbox.clearCache ();
		Shadowbox.setup ();
		var html = '<div class="suppliers-sb"><h3>'+$(this).children('img').attr('alt')+'</h3><img src="'+$(this).children('img').attr('src')+'" align="left" /><p>'+$(this).children('.biog').html()+'</p></div><script type="text/javascript">Cufon.replace(".suppliers-sb h3", {fontFamily: "kellys"})</script>';
		openShadowbox (html);
	});
}

function openShadowbox(content,title){
    Shadowbox.open ({
        content: content,
		player: "html",
		height: 420,
		width: 600
	});	
}

// Competition, What's On
function initCompetitions () {
	$.get(path + "php/safe/token.php",function(txt){
		$("#comp_left").append('<input id="comp_ts" type="hidden" name="ts" value="'+txt+'" />');
	});
	replaceSmallerPageFonts ();
	Shadowbox.clearCache ();
	Shadowbox.setup ();
	$("#comp_submit").click (validate);
}

function validate () {
	if ($("#comp_firstname").val()=="") {
		$(".error").html ("Your first name is invalid");
	} else if ($("#comp_lastname").val()=="") {
		$(".error").html ("Your last name is invalid");
	} else if (!checkEmail($("#comp_email").val())) {
		$(".error").html ("Your email address is invalid");
	} else if ($("#comp_answer").val()=="") {
		$(".error").html ("Please enter your answer");
	} else {
		var optin = 0;
		if ($("#comp_optin").attr('type') != 'hidden') optin = ($("#comp_optin").is(':checked') == true ? 1 : 0);
		var mailinglist = ($("#comp_mailinglist").is(':checked') == true ? 1 : 0);
		//alert ("optin: " + optin + ", mailinglist: " + mailinglist);
		
		$("#comp_submit").attr ("disabled", true);
		$(".error").html ("submitting information...");
		$.post (path+"php/competition.php", {id: $("#comp_id").val(), desc: $("#comp_desc").val(), firstname: $("#comp_firstname").val(), lastname: $("#comp_lastname").val(), answer: $("#comp_answer").val(), email: $("#comp_email").val(), optin: optin, mailinglist: mailinglist, ts: $("#comp_ts").val()}, function(data) {
			if (data == "1") {
				$(".error").html ("You have been entered into the competition!");
			} else {
				$("#comp_submit").attr ("disabled", false);
				$(".error").html ("There was an error, please try again.");
			}
		});
		
		if (mailinglist == 1) {
			//alert ("mailinglist sign up");
			$.post (path+"php/signup.php", {firstname: $("#comp_firstname").val(), lastname: $("#comp_lastname").val(), email: $("#comp_email").val(), dob: '0000-00-00'});
		}
	}
}
			
function checkEmail (email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) return (true);
	return (false);
}

function initWhatsOn () {
	replaceSmallerPageFonts ();
	var selectedID = 1;
	
	var source = path+"php/cowlandar.php";

	$(document).ready (function () {
		$('#calendar').fullCalendar ({
			events: source,
			viewDisplay: function(view) {
				Cufon.replace ('.fc-header-title', {fontFamily: 'kellys'});
			},
			eventMouseover: function (evt, jsEvent, view) {
				$("#calendarOptions p").html (evt.desc);
			},
			eventClick: function(event) {
				if (event.url) {
					window.open(event.url);
					return false;
				}
			}
		});
		
		$("#calendarOptions li").click (function () {
			var id = $(this).attr("id").replace ("cal_", "");
			var temp = selectedID;
			selectedID = id;
			$("#cal_"+temp).mouseout ();
			$('#calendar').fullCalendar ('removeEventSource', source);
			source = path + "php/cowlandar.php?id="+id;
			$('#calendar').fullCalendar ('addEventSource', source);
			console.log("source: " + source);
		});
		
		$("#calendarOptions li").mouseover (function () {
			var tabClass = $(this).html();
			var tabClass = tabClass.replace (/ /g, "_");
			$(this).addClass (tabClass);
		}).mouseout (function () {
			var id = $(this).attr("id").replace ("cal_", "");
			if (id != selectedID) $(this).removeClass ();
		});
	});
}

function replaceSmallerPageFonts () {
	Cufon.replace ('#content #container #smallerpage h2', {fontFamily: 'kellys'});
	Cufon.replace ('#content #container #smallerpage h3', {fontFamily: 'kellys'});
}
