// Table of contents for flash beers
var toc = new Array();

// Beers Book
toc['intro']        = '2';
toc['kinggoblin']   = '6';
toc['hobgoblin']    = '4';
toc['wychcraft']    = '8';
toc['scarecrow']    = '10';
toc['goliath']      = '12';
toc['gingerbeard']  = '14';
toc['january']      = '16';
toc['dirtytackle']  = '18';
toc['paddystout']   = '20';
toc['hotchocolate'] = '22';
toc['elderwych']    = '24';
toc['gingerbeard2'] = '26';
toc['bountiful']    = '28';
toc['jesterjack']	= '30';
toc['dogsbol']      = '32';
toc['bahhumbug']    = '34';

// Legends Book
toc['forest']     = '4';
toc['stones']     = '6';
toc['hobgoblins'] = '8';
toc['lantern']    = '10';
toc['guardian']   = '12';
toc['dancers']    = '14';
toc['oak']        = '16';
toc['well']       = '18';
toc['beltaine']   = '20';
toc['trees']      = '22';

// History
toc['witney']    = '4';
toc['clinchs']   = '6';
toc['eagle']     = '8';
toc['star']      = '10';
toc['brakspear'] = '12';

function nl2br (str, is_xhtml) {   
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
$(document).ready(function() {
	
	if( $.cookie('lite') != 'true' && $.cookie('lite') != 'false' ) {
		$.cookie('lite', true, { expires: 365 });
	}
		
	var header = 'header';
	if(theme == 'christmas') header = 'header-xmas-signoff';
	if( $('#the-wychwood').length > 0 && ! ( $.browser.msie && $.browser.version < 7 ) && ( $.cookie('lite') == 'false' ) ) {
		swfobject.embedSWF(base_url+"/public/swf/"+header+".swf?time="+revision, "flash_header_object", "960", "391", "9.0.0", base_url+"/public/js/swfobject/expressInstall.swf", { }, { wmode: 'transparent', allowscriptaccess: 'true' }, { id: "flash_header_object", name: "flash_header_object", quality: "medium" }, function() { setTimeout(function() { header = swfobject.getObjectById('flash_header_object'); try { header.selectPage('home'); signsup = true; } catch(err) { } ;}, 5000); });
		swfobject.embedSWF(base_url+"/public/swf/footer.swf?time="+revision, "flash_footer", "960", "210", "9.0.0", base_url+"/public/js/swfobject/expressInstall.swf", { }, { wmode: 'transparent', allowscriptaccess: 'true' }, { id: "flash_footer_object", name: "flash_footer_object", quality: "medium" }, function() { setTimeout(function() { footer = swfobject.getObjectById('flash_footer'); }, 5000); });
	}

	// Set up the navigation
	$('.sub_nav').hide();
	
	// Hide any elements that need hiding
	$('.onLoadHide').hide();
	
	$('.has_sub_nav a').unbind('click');
	$('.has_sub_nav a').click(function() {
		var link = this;
		$('.sub_nav').each(function() {
			if($(this).is(':visible') && $(this).attr('id') != $(link).attr('rel') + '_nav') {
				$(this).hide('slide', {direction: 'up'}, 'slow');
			}
		});
	
		$('#' + $(this).attr('rel') + '_nav').show('slide', {direction: 'up'}, 'slow');
		return false;
	});

	$('#export_nav a').live('click', function(event) {
		$('#popup').removeClass('large').addClass('small');
		$('#popup_content').html($(event.currentTarget.hash).html());
		openPopup('#popup');
		event.preventDefault();
	});

	// Open links in external window
	$('a.external').live('click', function(event) {
		window.open(this.href);
		event.preventDefault();
	});

	// Do the popups on the news page
	$('#wychwood-times .readmore').live('click', function(event) {
		// Copy content from page holder
		$('#popup').removeClass('small').addClass('large');
		$('#popup_content').html($($(event.target).attr('rel')).html());
		openPopup('#popup');
		event.preventDefault();
	});

	// Do the popups on the links page
	$('#links .popup').live('click', function(event) {
		// Copy content from page holder
		$('#popup').removeClass('large').addClass('small');
		$('#popup_content').html($($(event.target).attr('rel')).html());
		openPopup('#popup');
		event.preventDefault();
	});

	// Do the interavtive FAQs
	$('#faq #questions .question').live('click', function(event) {
		var target = $(event.target).attr('rel');
		$('#answer .question').html($(event.target).html());
		$('#answer .answer').html($(target).html());
		event.preventDefault();
	});

	// Do the terms and conditions
	$('#terms_conditions #links a').live('click', function(event) {
		var target = $(event.target).attr('rel');
		$('.tcs').hide();
		$(target).show();
		$('#dynamic_content').css('height', ( $(target).height() + 50 > $('#links').height() + 150 ) ? $(target).height() + 50 : $('#links').height() + 150);
		event.preventDefault();
	});

	// Google map link for contact page
	$('#contact #google_map_link').live('click', function(event) {
		$('#google_map_link').html($('#google_map').html());
		event.preventDefault();
	});

	// Do the movies
	$('#movies_nav').live('click', function(event) {
		
		swfobject.embedSWF(base_url+'public/swf/flayr.swf?movie='+base_url+'/public/flv/'+$(event.target).attr('rel')+'.flv&autoplay=true&controls=seek', "video_object", "478", "269", "9.0.0", base_url+'public/js/swfobject/expressInstall.swf', { }, { wmode: 'transparent' }, { id: "video_object", name: "video_object" });
		
		event.preventDefault();
	});
		
	$('#buffer').html('');

	// Page loader for flash book
	$('.flashbook_page_link').live('click', flashTargetPage);

	$('#container_form #submit-button').live('click', function() {
		var f = $('#container_form form');
		var error = false;
		if( ! $('#newsletter_marketing').attr('checked') ) {
			error = "Please confirm your opt-in to<br/>our e-newsletter";
		}
		if( ! $('#newsletter_age').attr('checked') ) {
			error = "You must be over 18";
		}
		$('#newsletter_firstname,#newsletter_surname,#newsletter_email').each(function() {
			if( $(this).val() == '') {
				error = "Please ensure all the fields<br/>are completed correctly";
			}
		});
		$('#newsletter_age')
		if( error ) {
			competitions.flashNotification('', error);
		} else {
			$.post(f.attr('action'), f.serialize(), function() {
				$('#container_form').hide();
				$('#container_thanks').show();
			});
		}
		return false;
	});
	
	// Mischief popup windows
	$('#mischief .newwindow').live('click', function() {
		window.open( this.href );
		return false;
	});

	// Sound on/off button
	$('#footer_sound').click(function() {
		try {
			header = swfobject.getObjectById('flash_header_object');
			header.toggleSound();
		} catch(err) { }
		return false;
	});

	// Sound on/off button
	$('#footer_flash_toggle').click(function() {
		toggleFlash();
		return false;
	});

	$('#beers_movies').show();
	
	$('#bpny').find('.send-button').live('click', function(){
		var email = $('#bpny #email').val();		
		if(validate_email(email)) {
			// Do the post
			$.post($('#mid-spacer form').attr('action'), { email: email }, function() {
				$('#mid-spacer').html('Thanks for your support!');
			});
		} else {
			alert('Please enter a valid email address');
		}
		return false;
	});

});

function toggleFlash() {
	if($.cookie('lite') == 'false') {
		$.cookie('lite', 'true');
		window.location.href = site_url;
	} else {
		$.cookie('lite', 'false');
		window.location.href = site_url;
	}
	return false;
}

$('#add div button').live('click', function() {
	$(this).addClass('uploading');
});

var postload = new function() {
	this.run = function() {
		return this;
	};
	this.unload = function() {
		this.run = function() { return this; };
	};
	
};

// Functions for the wychwood main site navigation
var wychwood_nav = new function() {
	this.hide = function() {
		// $('#navigation').animate({ top: -70 }, 'slow', "easeInSine");
	};
	this.show = function() {
		// $('#navigation').animate({ top: 0 }, 'slow', "easeOutBounce");
	};
};

function flashTargetPage(event) {
	if( ! ( $.browser.msie && $.browser.version < 7) && $.cookie('lite') == 'false') {
		// Check for deep linking and process any request
		var fo = swfobject.getObjectById('flash_object');
		fo.jsPageFlip(toc[$(event.target).attr('rel')]);
		event.preventDefault();
	} else {
		window.location.href = site_url + event.target.href.replace(site_url, '')+'#noload'; 
		event.preventDefault();
	}

}

// Opens a modal window
function openPopup(id) {
	$(id).modal({opacity: 80, closeHTML: "<a href='#'>Close</a>", escClose: true, overlayClose: true, onOpen: function (dialog) {
		$('#popup_full_content').html(" ");
		$('#popup_full_content').css('display', 'none');
		$('#popup_content').css('display', 'inline');
		
		dialog.overlay.fadeIn('slow', function () {
			dialog.data.show();
			dialog.container.show();
			try {
				$('#popup.ifixpng').ifixpng();
			} catch(err) { }
		});
	}});
}

// Opens a modal window
function openImagePopup(id) {
	$(id).modal({opacity: 80, closeHTML: "<a href='#'>Close</a>", escClose: true, overlayClose: true, onOpen: function (dialog) {
		$('#popup_content').html(" ");
		$('#popup_content').css('display', 'none');
		$('#popup_full_content').css('display', 'inline');
		dialog.overlay.fadeIn('slow', function () {
			dialog.data.show();
			dialog.container.show();
			try {
				$('#popup.ifixpng').ifixpng();
			} catch(err) { }
		});
	}});
}




// Code for simple custom dropdown
function customDropdown(id) {
	$('select option', id).each(function(){
		// Build the options list
		if($(this).attr('value') != "") {
			$('.dropdown-options ul', id).append($('<li><div rel="'+$(this).attr('value')+'" class="checkbox"></div>&bull;&nbsp;&nbsp;'+$(this).html()+'</li>'));
		}
	});
	
	$('table', id).show();

	$('.dropdown-options', id).hide();

	$('.dropdown-options .checkbox', id).die('click');

	$('.dropdown-options .checkbox', id).live('click', function() {
		var option = $('option[value="'+$(this).attr('rel')+'"]', id);

		$('.checkbox', id).removeClass('selected');
		$(this).addClass('selected');

		$('.dropdown-select', id).html(option.html());

		$('.dropdown-options', id).slideUp();
		
		$('select', id).attr('value', $(this).attr('rel'));

	});

	$('.dropdown-select', id).html($('label', id).html());
	$('select', id).hide();
	$('label', id).hide();

	$('.dropdown-opener', id).die('click');

	$('.dropdown-opener', id).live('click', function(event){
		$('.dropdown-options', id).toggle('blind');
	});
}
function filterDropdown(id,action){
	customDropdown(id);
	$('.dropdown-opener', id).show();
	$('.dropdown', id).show();
	$('.dropdown-select', id).show();
	$('input', id).hide();
	$('.dropdown-options .checkbox', id).die();
	$('.dropdown-options .checkbox', id).live('click', function() {
		var option = $('option[value="'+$(this).attr('rel')+'"]', id);

		$('.checkbox', id).removeClass('selected');
		$(this).addClass('selected');
		
		$('select', id).attr('value', $(this).attr('rel'));
		
		$('form', id).attr('action',action+'/'+$('select', id).attr('value'));
	    window.location = $('form', id).attr('action');
	    window.location.reload();
		return false;
	});	
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
function validate_email(email) {
	var pattern=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if (pattern.test(email)) { return true; } else { return false; }
}

