// JavaScript Document

var play;
var currentTime = new Date();

jQuery.fn.exists = function () {
	return jQuery(this).length > 0;
}

$(document).ready(function () {

	jQuery.fn.exists = function () {
		return jQuery(this).length > 0;
	}

	// primary nav drop down
	$("ul.main li").hover(function () {
		$(this).addClass("hover");
		$('ul:first', this).css('visibility', 'visible');
	}, function () {
		$(this).removeClass("hover");
		$('ul:first', this).css('visibility', 'hidden');
	});

	$("ul.main li ul li:has(ul)").find("a:first").append(" &raquo; ");



	//Cufon Text replacement
	Cufon.replace('h2');
	Cufon.replace('h3');
	Cufon.replace('.survey-title');
	Cufon.replace('.order-process ul li a', { hover: true });

	$("#quickLinksContent").hide();
	$("#quickLinksContent").slideUp();

	//Quick links
	$('#quickLinks').toggle(
		function () {
			$(".quick-links-container").slideDown();
			//$("#quickLinksContent").show();
			//$("#quickLinksContent").show();
		},
		function () {
			$(".quick-links-container").slideUp();
		});



	//Slider
	$(function () {
		$("#accordion").accordion({ autoHeight: false });
	});


	$(function () {
		$("#accordion, #accordion1i, #accordion2i").accordion({ autoHeight: false, active: -1, collapsible: true });
	});


	//Homepage Hero Slider

	//Set Default State of each portfolio piece
	$(".paging").show();
	$(".paging a:first").addClass("active");

	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".window").width();
	var imageSum = $(".image_reel img").size();
	var imageReelWidth = imageWidth * imageSum + 200;

	//Adjust the image reel to its new size
	//$(".window").height($(".image_reel").find('div.hero').height());
	$(".image_reel").css({ 'width': imageReelWidth });

	//Paging + Slider Function
	rotate = function () {
		window.clearTimeout(play);
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".paging a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

		//Slider Animation
		$(".image_reel").animate({
			'margin-left': -image_reelPosition
		}, 1000, rotateSwitch);
	};

	//Rotation + Timing Event
	var rotateSwitch = function () {
		currentTime = new Date();
		play = window.setTimeout(function () { //Set timer - this will repeat itself every 3 seconds
			$active = $('.paging a.active').next();
			if ($active.length === 0) { //If paging reaches the end...
				$active = $('.paging a:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 7000); //Timer speed in milliseconds (3 seconds)
	};

	rotateSwitch(); //Run function on launch

	//On Hover
	$(".image_reel a").hover(function () {
		window.clearTimeout(play); //Stop the rotation
	}, function () {
		rotateSwitch(); //Resume rotation
	});

	//On Click
	$(".paging a").click(function () {
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		window.clearTimeout(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		return false; //Prevent browser jump to link anchor
	});

	//Main Navigation menu jquery
	function megaHoverOver() {
		$(this).find(".sub").stop().fadeTo('fast', 1).show();

		//Calculate width of all ul's
		(function ($) {
			jQuery.fn.calcSubWidth = function () {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function () {
					rowWidth += $(this).width();
				});
			};
		})(jQuery);

		if ($(this).find(".row").length > 0) { //If row exists...
			var biggestRow = 0;
			//Calculate each row
			$(this).find(".row").each(function () {
				$(this).calcSubWidth();
				//Find biggest row
				if (rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({ 'width': biggestRow });
			$(this).find(".row:last").css({ 'margin': '0' });

		} else { //If row does not exist...

			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({ 'width': rowWidth });

		}
	}

	function megaHoverOut() {
		$(this).find(".sub").stop().fadeTo('fast', 0, function () {
			$(this).hide();
		});
	}


	var config = {
		sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		interval: 200, // number = milliseconds for onMouseOver polling interval    
		over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		timeout: 0, // number = milliseconds delay before onMouseOut    
		out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	//$(".main ul li .sub").css({ 'opacity': '0' });
	/*$(".main ul li").hoverIntent(config);*/

	$(".main ul li").hover(megaHoverOver, megaHoverOut);


	// initialise video carousel
	initVideos();

	// initialise forms and polls
	initForms();
	initPolls();

	// initialise facebook feed
	initFacebook();
});

function initVideos() {

	//var iframe = $("#videoIframe");
	var mediaItem = $("#mediaItem");
	if (mediaItem.exists()) {
		$("p.link a, div.video img", "#videoCarousel").click(function () {
			var mediaUrl = $(this).parents('div.video').find('p.link a').attr("href");
			var v = mediaUrl.substr(1);
			var videoUrl = 'http://www.youtube.com/v/' + v + "?autoplay=1";
			var objectTag = '<object width="669" height="411" id="mediaItem"><param name="movie" value="' + videoUrl + '"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><param name="autoplay" value="1"></param><param name="wmode" value="transparent"></param><embed src="' + videoUrl + '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" wmode="transparent" autoplay="1" width="669" height="411"> </embed></object>';
			$('#mediaItem').html(objectTag);
			return false;
		});
		$('div.mediaImage a').click(
			function () {
				var imageTag = '<img src="' + $(this).attr('href') + '" alt=""/>';
				$('#mediaItem').html(imageTag);
				return false;
			}
		);
	}

	/*if (iframe.exists()) {
		$("p.link a, div.video img", "#videoCarousel").click(function () {
			var v = $(this).parents('div.video').find('p.link a').attr("href").substr(1);
			iframe.attr("src", "http://www.youtube.com/embed/" + v + "?autoplay=1");
			return false;
		});
	}*/
}

//
// polls
//
function initPolls() {
	var polls = $(".poll");
	if (polls.exists()) {
		polls.addClass("customise");
		initRadioButtons(polls);
	}
}



function setupOtherFieldVisibility() {

	$("div.scfDropListBorder").each(function () {


		var $container = $(this);

		var classes = $container.attr("class").toString();
		if (classes.indexOf("name.Country")) {

			$next = $container.next("div[class*=name.Other+Country]");

			$next.hide(); // hide the other field below
			$next.find("div.scfSingleLineGeneralPanel").hide();

			$container.find("ul.sbOptions li a").click(function () {
				if (this.rel == "-") { // by using a hyphen we can easily make the field multi lingual.
					$next.slideDown('fast', function () {
						$next.find("div.scfSingleLineGeneralPanel").fadeIn('fast');
					});
				} else {
					$next.slideUp('medium');
					$next.find("div.scfSingleLineGeneralPanel").hide();
				}
			});


			var currentValue = $container.find("select option").filter(":selected").val();
			if (currentValue == "-") {
				$next.show();
				$next.find("div.scfSingleLineGeneralPanel").fadeIn('fast');
			}

		}
	});
}


//
// form customisation
//
function initForms() {
	var scfForm = $(".scfForm");
	if (scfForm.exists()) {
		scfForm.addClass("customise");


		$("select", scfForm).selectbox();

		

	    var zIndex = 2000;

	    setupOtherFieldVisibility();


	    $(".scfDateOfBirth,.sbHolder", scfForm).each(function () {
	    	$(this).css("z-index", zIndex);
	    	zIndex--;
	    });
		initTextAreas(scfForm);
		initRadioButtons(scfForm);
		initCheckBoxes(scfForm);
	}
}

function initTextAreas(form) {
	$("textarea", form).wrap("<div class=\"textarea\"></div>");
}

function initCheckBoxes(form) {
	function setChecked(span, checkbox, checked) {
		checkbox.prop("checked", checked);
		if (checked)
			span.addClass("checked")
		else
			span.removeClass("checked");
	}
	//var form = $(".form");
	$("input[type=\"checkbox\"]", form).wrap("<span class=\"checkbox curvyIgnore\" />");
	var spans = $("span.checkbox", form);
	spans.each(function () {
		var span = this;
		var checkbox = $("input", span);
		setChecked($(span), checkbox, checkbox.prop("checked"));
		$("label[for=\"" + checkbox.attr("id") + "\"]", form).click(function () {
			setChecked($(span), checkbox, !checkbox.prop("checked"));
		});
	});
	spans.click(function () {
		var checkbox = $("input", this);
		setChecked($(this), checkbox, !checkbox.prop("checked"));
		return false;
	});
}


function initRadioButtons(forms) {

	var map = {};

	forms.each(function () {
		var form = $(this);

		$("input[type=\"radio\"]", form).wrap("<span class=\"radio curvyIgnore\" />");

		var allSpans = $("span.radio", form);

		allSpans.each(function () {
			var span = this;
			var radio = $("input", span);
			//var group = radio.attr("name");
			$(this).attr("data-radio-name", radio.attr("name"));

			//setChecked($(span), radio, radio.prop("checked"));
			$("label[for=\"" + radio.attr("id") + "\"]", form).click(function () {
				setChecked(radio);
			});
		});

		allSpans.click(function () {
			var radio = $("input", this);
			setChecked(radio);
			return false;
		});

		allSpans.each(function () {
			var span = $(this);
			var group = span.attr("data-radio-name");
			if (!map[group])
				map[group] = $("span[data-radio-name=\"" + group + "\"]", form);
		});
		updateChecked(allSpans);
	});

	function setChecked(radio) {
		if (!radio.prop("checked")) {
			radio.prop("checked", true);
			updateChecked(map[radio.attr("name")]);
		}
	}

	function updateChecked(spans) {
		spans.each(function () {
			var r = $("input", this);
			if (r.prop("checked"))
				$(this).addClass("checked")
			else
				$(this).removeClass("checked");
		});
	}
}


function initFacebook() {
	var $container = $(".facebook-feed");
	var $template = $("#facebookFeedTmpl");
	if ($container.exists() && $template.exists()) {
		$container.facebookFeed(4, $template, "/Services/FacebookPosts.ashx",
		function () {
			$(".jScrollbar").jScrollbar({
				allowMouseWheel: true,
				scrollStep: 10
			});
		}
		);
		$container.fadeIn('slow');
	}
}

$(document).ready(
	function () {
		$('.scfDateOfBirth input').datepicker({
			changeMonth: true,
			changeYear: true,
			constrainInput: true,
			yearRange: 'c-90Y:c',
			minDate: '-90Y',
			maxDate: '-16Y',
			defaultDate: '-18Y',
			dateFormat: 'dd/mm/yy'
		});
		$('.scfDateOfBirth input').keydown(function () { return false; })
	}
);
