// These variables have to be globals
var _interval;

$(document).ready(function() {
	
	/*** Begin home page carousel ***/
	
	$('#fma ul li').hover(
		function() {
			$(this).click();
		},
		function() {
		}
	);
	
	// Only run the carousel when the mouse is not inside #fma
	$('#fma').hover(
		function() {
			clearInterval(_interval);
		},
		function() {
			startCarousel();
		}
	);
	
	// This makes the li.active thumbnail elements links, but because we've overridden the click method so we need to use something else - mousedown is fine.
	// We call it using the live method because it needs to be bound to the current li.active element and any li elements that are assigned the active class in the future
	$('#fma ul li.thumbnail.active').live('mousedown', function() {
		var location = $(this).find('a').attr('href');
		if (typeof(location) != 'undefined' && location != '#') {
			window.location.href = location;
		}	
	});
	
	// When an li.thumbnail is clicked set the active class and swap the main image
	$('#fma ul li.thumbnail').click(function() {
		$('#fma ul li.thumbnail').removeClass('active');
		$(this).addClass('active');
		if (typeof($(this).attr('classForFMA')) != 'undefined') {
			additionalParameters = 'rel="' + $(this).attr('relForFMA') + '" class="' + $(this).attr('classForFMA') + '"';
			youtube = $(this).attr('youtubeForFMA');
		}
		else {
			additionalParameters = false;
		}
		$('#fma-large').html('<a href="' + $(this).find('a').attr('href') + '"' + additionalParameters + ' target="_blank"><img src="' + $(this).attr('src') + '"/></a>');
		if (additionalParameters) {
			$('.' + $(this).attr('classForFMA')).overlay({
				closeOnClick: true,
				top: 150,
				onBeforeLoad: function() {
					this.getOverlay().find(".contentWrap").html('<iframe width="640" height="360" src="http://www.youtube.com/embed/' + youtube + '" frameborder="0" allowfullscreen></iframe>');
				}
			});
		}
		return false;
	});
	
	// Right and left arrow functionality - we don't need to store any more information about where
	// we are in the carousel than what the DOM already holds. jQuery is great for this kind of work.
	$('#fma ul li .link-next').click(function() {
		// If we've reached the right arrow, go back to the first element
		if ($('#fma ul li.active').next().find('a').hasClass('link-next')) {
			$('#fma ul li.thumbnail:eq(0)').click();
		}
		else {
			$('#fma ul li.active').next().click();
		}
	});
	
	$('#fma ul li .link-prev').click(function() {
		// If we've reached the left arrow, go to the last element
		if ($('#fma ul li.active').prev().find('a').hasClass('link-prev')) {
			$('#fma ul li.thumbnail').last().click();
		}
		else {
			$('#fma ul li.active').prev().click();
		}
	});
	
	// The first li is active by default
	$('#fma ul li.thumbnail:eq(0)').click();

	startCarousel();
});

function startCarousel() {
	// Click the right arrow every 4 seconds
	_interval = setInterval(function() {
								$('#fma ul li .link-next').click();
					 		}, 4000);
}

//clear form
function initPage()
{
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
}
function clearFormFields(o)
{
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass) == -1) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}
if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);
// mobile browsers detect
browserPlatform = {
	platforms: [
		{ uaString:['symbian','midp'], cssFile:'symbian.css' }, // Symbian phones
		{ uaString:['opera','mobi'], cssFile:'opera.css' }, // Opera Mobile
		{ uaString:['msie','ppc'], cssFile:'ieppc.css' }, // IE Mobile <6
		{ uaString:'iemobile', cssFile:'iemobile.css' }, // IE Mobile 6+
		{ uaString:'webos', cssFile:'webos.css' }, // Palm WebOS
		{ uaString:'Android', cssFile:'android.css' }, // Android
		{ uaString:['BlackBerry','/6.0','mobi'], cssFile:'blackberry6.css' },	// Blackberry 6
		{ uaString:['BlackBerry','/7.0','mobi'], cssFile:'blackberry7.css' },	// Blackberry 7+
		{ uaString:'ipad', cssFile:'ipad.css', miscHead:'<meta name="viewport" content="width=device-width" />' }, // iPad
		{ uaString:['safari','mobi'], cssFile:'safari.css', miscHead:'<meta name="viewport" content="width=device-width" />' } // iPhone and other webkit browsers
	],
	options: {
		cssPath:'css/',
		mobileCSS:'allmobile.css'
	},
	init:function(){
		this.checkMobile();
		this.parsePlatforms();
		return this;
	},
	checkMobile: function() {
		if(this.uaMatch('mobi') || this.uaMatch('midp') || this.uaMatch('ppc') || this.uaMatch('webos')) {
			this.attachStyles({cssFile:this.options.mobileCSS});
		}
	},
	parsePlatforms: function() {
		for(var i = 0; i < this.platforms.length; i++) {
			if(typeof this.platforms[i].uaString === 'string') {
				if(this.uaMatch(this.platforms[i].uaString)) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			} else {
				for(var j = 0, allMatch = true; j < this.platforms[i].uaString.length; j++) {
					if(!this.uaMatch(this.platforms[i].uaString[j])) {
						allMatch = false;
					}
				}
				if(allMatch) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			}
		}
	},
	attachStyles: function(platform) {
		var head = document.getElementsByTagName('head')[0], fragment;
		var cssText = '<link rel="stylesheet" href="' + this.options.cssPath + platform.cssFile + '" type="text/css"/>';
		var miscText = platform.miscHead;
		if(platform.cssFile) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = cssText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(cssText);
			}
		}
		if(platform.miscHead) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = miscText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(miscText);
			}
		}
	},
	uaMatch:function(str) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(str.toLowerCase()) != -1;
	}
}.init();
