/**
 * Replace flash placeholders automatically
 */
var initFlash = function () {
	var validTags = new Array('img');//'div', (Not sure how to get the src / href from div)
	for (var i = 0; i < validTags.length; i++) {
		$(validTags[i] + '.dynamicFlash').each(function () {
			if (!this.id || this.id == '') {
				this.id = 'dynamicFlash_' + i;
			}
			var src = this.src.replace(/\.(gif|jpg|png|jpeg)$/i, '.swf');
			
			// Check if parent is an anchor
			var bannerLink = '';
			var elements = $(this).parents();
			for (var j in elements) {
				if (typeof elements[j] != 'function') {
					if (elements[j].tagName == 'A') {
						bannerLink = elements[j].href;
						break;
					}
				}
			}
			
			// embedSWF: function (swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn)
			swfobject.embedSWF(src, this.id, this.width, this.height, "9.0.0", null, { bannerLink: bannerLink }, {}, {});
		});
	}
};

/**
 * Activate show/hide links
 */
var initToggleLinks = function () {
	$('a.toggle').each(function () {
		var elementId = $(this).attr('class').match(/toggle([a-zA-Z0-9]+)/)
		if (elementId) {
			// Use camelCase id names
			elementId[1] = elementId[1].replace(/^[A-Z]/, function (a) { return a.toLowerCase(); });
			
			// Show this link
			$(this).show();
			
			// Initially hide the element
			$('#' + elementId[1]).hide();
			
			// Toggle element visibility on click
			$(this).click(function () {
				var that = this;
				
				$('#' + elementId[1]).toggle('fast', function () {
					if ($('#' + elementId[1]).css('display') == 'none') {
						$(that).html($(that).html().replace('Hide', 'Show'));
					} else {
						$(that).html($(that).html().replace('Show', 'Hide'));
					}
				});
				
				return false;
			});
		}
	});
};

/**
 * Initialise default/help text for input/textarea fields
 */
var initInputDefaultText = function (elementSelector) {
	if (!elementSelector) {
		elementSelector = 'input[type="text"]';
	}
	
	// Quick check to see if component is used
	if ($(elementSelector + '.defaultText').length < 1) {
		return false;
	}
	
	$(elementSelector + '.defaultText').each(function () {
		if ($(this).val() == '') {
			if ($(this).attr('class').indexOf('defaultTextIdle') == -1) {
				$(this).attr('class', $(this).attr('class') + ' defaultTextIdle');
			}
			
			$(this).val($(this).attr('title'));
		}
	});
	
	$(elementSelector + '.defaultText').focus(function () {
		$(this).attr('class', $(this).attr('class').replace(' defaultTextIdle', ''));
		
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
	});
	
	$(elementSelector + '.defaultText').blur(function () {
		if ($(this).val() == '') {
			if ($(this).attr('class').indexOf('defaultTextIdle') == -1) {
				$(this).attr('class', $(this).attr('class') + ' defaultTextIdle');
			}
			
			$(this).val($(this).attr('title'));
		}
	});
	
	$(elementSelector + '.defaultText').each(function () {
		var that = $(this);
		$(this).closest('form').submit(function () {
			if (that.val() == that.attr('title')) {
				that.val('');
			}
		});
	});
};

/**
 * Activate a javascript print link
 */
var initPrint = function () {
	if (window.print) {
		$('p.print').show();
		$('p.print a').click(function () {
			window.print();
			if (window.event) { window.event.cancelBubble = true; }
			return false;
		});
	}
};

/**
 * Initialise google analytics
 */
var initGoogleAnalytics = function () {
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	
	//use jQuery to call the Google Analytics JavaScript
	$.getScript(gaJsHost + "google-analytics.com/ga.js", function() {
		//tell Analytics about the current page load using standard _trackPageview method
		try {
			var pageTracker = _gat._getTracker("TODO");
			pageTracker._trackPageview();
			
			//loop though each anchor element
			$('a').each(function() {
				var href = $(this).attr('href');
				var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
				
				//check for links starting with http or https, making sure that links to our own domain are excluded
				if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
					$(this).click(function() {
						var extLink = href.replace(/^https?\:\/\//i, '');
						pageTracker._trackEvent('External', 'Click', extLink);
					});
				}
				//check for links starting with mailto:
				else if (href.match(/^mailto\:/i)){
					$(this).click(function() {
						var mailLink = href.replace(/^mailto\:/i, '');
						pageTracker._trackEvent('Email', 'Click', mailLink);
					});
				}
				//check for links with file extension that match the filetypes regular expression:
				else if (href.match(filetypes)){
					$(this).click(function() {
						var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
						var filePath = href.replace(/^https?\:\/\/[^\/]+\//i, '');
						pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
					});
				}
			});
		} catch(err) {}
	});
};

/**
 * Enhance the header search form
 */
var initHeaderSearchForm = function () {
	$('form#searchForm').submit(function () {
		if ($('#searchString').val() == $('#searchString').attr('title') || $('#searchString').val() == '') {
			window.alert('Please enter a search string');
			$('#searchString').focus();
			return false;
		}
	});
	
	// TODO: add search hints
};

/**
 * Initialise the fancybox component
 */
var initFancybox = function () {
	var fancyboxSettings = {
		transitionIn: 'elastic',
		transitionOut: 'elastic',
		speedIn: 300, 
		speedOut: 200, 
		overlayShow: true,
		enableEscapeButton: true
	};
	
	$('a.fancyBox').each(function (index, autoLink) {
		var pos = autoLink.href.indexOf('?');
		if (pos != -1) {
			var extension = autoLink.href.substr(pos - 4, 4);
		} else {
			var extension = autoLink.href.substr(autoLink.href.length - 4);
		}
		
		switch (extension.toLowerCase()) {
			case '.jpeg':
			case '.jpg':
			case '.gif':
			case '.png':
			case '.bmp':
				$(autoLink).fancybox($.extend(true, {
				}, fancyboxSettings));
				break;
			case '.flv':
				// Video player not installed
				break;
				// Initialise the video player only if there are videos
				$(autoLink).fancybox($.extend(true, {
					width: 512,
					height: 288,
					type: 'swf',
					href: './.resources/flash/preloader.swf'
						+ '?assetLocation=' + window.encodeURIComponent('./.resources/flash/assets/')
						+ '&assetName=' + window.encodeURIComponent('videoplayer.swf')
						+ '&mediaURL=' + window.encodeURIComponent(autoLink.href)
						+ '&pictureURL=' + window.encodeURIComponent('images/beta_video_still.jpg'),
					swf: {
						allowFullScreen: "true",
						quality: "high",
						scale: "noscale",
						allowscriptaccess: "sameDomain"
					},
					onCleanup: function (a, b, c) {
						// Override a cleanup function that causes a js error in IE 6/7
						window.__flash__removeCallback = function (instance, name) {
							if (instance) {
								instance[name] = null;
							}
						};
					}
				}, fancyboxSettings));
				break;
			case '.swf':
				$(autoLink).fancybox($.extend(true, {
				}, fancyboxSettings));
				break;
			default:
				break;
		}
	});
};

/**
 * Initialise the tinyMCE editor
 */
var initTinymce = function () {
	$('textarea.tinymce').tinymce({
		// Location of TinyMCE script
		script_url : Site.baseUrl + 'tiny_mce/tiny_mce.js',

		// General options
		theme : "advanced",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,bullist,numlist,|,sub,sup,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		//theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		//theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		//theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
	});
};

/**
 * Initialise the datepicker plugin
 */
var initDatepicker = function () {
	$('input.datepicker').datepicker({
		inline: true,
		dateFormat: 'dd/mm/yy'
	});
};

/**
 * Make links marked as external open in a new window
 */
var initExternalLinks = function () {
	$('a[rel="external"]').attr('title', '(This link opens in a new window)');
	$('a[rel="external"]').click(function () {
		window.open(this.href);
		if (window.event) { window.event.cancelBubble = true; }
		return false;
	});
};

/**
 * Attach plus/minus buttons before and after a quantity input on a catalogue list item
 */
var initQuantityButtons = function () {
	// Add decrement button
	$('input.quantity').each(function (index, input) {
		if (!$(input).attr('disabled')) {
			var a = $(document.createElement('a'));
			a.attr('class', 'icon iconMinus');
			a.text('-');
			a.click(function () {
				var quantity = parseInt($(input).val());
				if (quantity > 1) {
					$(input).val(quantity - 1);
				}
				return false;
			});
			
			// Attach button
			$(input).before(a);
		}
	});
	
	// Add increment button
	$('input.quantity').each(function (index, input) {
		if (!$(input).attr('disabled')) {
			var a = $(document.createElement('a'));
			a.attr('class', 'icon iconPlus');
			a.text('+');
			a.click(function () {
				var quantity = parseInt($(input).val());
				$(input).val(quantity + 1);
				return false;
			});
			
			// Attach button
			$(input).after(a);
		}
	});
};

/**
 * Auto collapse list trees (definition lists)
 */
var initListTreeExpanding = function () {
	// Quick check to see if component is used
	if ($('dl.listTreeExpanding').length < 1) {
		return false;
	}
	
	$('dl.listTreeExpanding dd').hide();
	$('dl.listTreeExpanding dt').attr('class', 'closed');
	$('dl.listTreeExpanding dt').css('cursor', 'pointer');
	$('dl.listTreeExpanding dt').click(function () {
		if ($(this).next().is('dd')) {
			$(this).next().toggle('fast', function () {
				if ($(this).css('display') == 'none') {
					$(this).prev().attr('class', 'closed');
				} else {
					$(this).prev().attr('class', 'opened');
				}
			});
			return false;
		}
		return true;
	});
}

/**
 * Autocomplete the search box in the header
 */
var initAutocompleteSearch = function () {
	$('#searchString').autocomplete(Site.baseUrl + 'catalogue/search', {
		minChars: 3,
		formatItem: function (item) {
			return item[0];
		}
	}).result(function (event, data, formatted) {
		window.location.href = Site.baseUrl + 'catalogue/item/' + data[1];
	});
	$('#searchString').attr('autocomplete', 'off');
};

/**
 * Startup procedures
 */
$(document).ready(function () {	// Show elements that were hidden as they require javascript to be of use
	$('.jsRequiredShow').show();
	$('.jsRequiredHide').hide();
	
	initQuantityButtons();
	initListTreeExpanding();
	initInputDefaultText();
	initInputDefaultText('textarea');
	//initFlash();
	initToggleLinks();
	initPrint();
	//initGoogleAnalytics();
	//initHeaderSearchForm();
	initFancybox();
	initTinymce();
	initDatepicker();
	initExternalLinks();
	initAutocompleteSearch();
});

/**
 * Alert a variable
 */
var var_dump = function (onWhat, data) {
	var output = new Array();
	for (var i in data) {
		output.push(i + ' (' + typeof data[i] + '):' + data[i]);
	}
	window.alert(onWhat + ' ... ' + output.join("\n"));
};
