/*
*** Coded with loving care by Mat (Demotive) for Design UK ***
***	           "Toiling since '75" | Summer 2010           ***
*/

// Group attribute change
(function( $ ){
	$.fn.affectAttr = function(selector, attr, val) {
  		this.find(selector).attr(attr, val);
  		return this;
	};
})( jQuery );

var testPrefilled = function($el) {
	// check for prefilled details
	$el.find("li input").each(function() {
		if ($(this).val() != "") {
			$(this).prev().hide();
		}
	});
}

var toggleMemberArea = function() {
	if ($("#member_login").hasClass("open")) {
		$("#member_login")
			.removeClass("open")
			.affectAttr("input, button, a", "tabindex", "-1");
	} else {
		$("#member_login")
			.addClass("open")
			.affectAttr("input, button, a", "tabindex", "");
		// check for prefilled details
		testPrefilled($("#member_login"));
		// subsequent focus events on fields
		$("#member_login li input")
			.focus(function() {
				$(this).prev().hide();
			})
			.blur(function() {
				if ($(this).val() == "") {
					$(this).prev().show();
				}
			});
		$("body").bind("click.logintoggle", function(){
			$("#member_login")
				.removeClass("open")
				.affectAttr("input, button, a", "tabindex", "");
			$("body").unbind("click.logintoggle");
		});
		$('#member_login').click(function(event){
			event.stopPropagation();
		});		
	}
}


$(document).ready(function(){

	/****************************************************************************************************************
	CHUNK: global elements
	*/
		
	// watcher for Shift key
	document.shiftDown = false;
	$(document)
		.keydown(function(event) {
			if (event.keyCode == 16) {
				document.shiftDown = true;
			}
		})
		.keyup(function(event) {
			if (event.keyCode == 16) {
				document.shiftDown = false;
			}
		});
	
	/****************************************************************************************************************/
	
	// grab megamenu elements
	var $menuEls = $('#navigation_primary .submenu');
	$menuEls.each(function(i) {
		$(this).css('display', 'block');	// (this will occur before IE6 iframe script, enabling iframe measurement)
		// over/out adds/removes class of .over here: #navigation_primary > li upon hover (class shifts both submenu div and iframe (ie6))
		$(this).parents('li').hover(
			function() {
				$(this).addClass('over');
			},
			function() {
				$(this).removeClass('over');
			}
		)
		// keyboard handling (tabbing)
		// top level link (ie womens) - on focus, show menu, on shift-tab (backwards) hide menu
		$(this).parents('li')
			.keyup(function(event) {
				/*if (event.keyCode == 9 && document.shiftDown != true) {
					$(this).parents('li').addClass('over');
				}*/
				if (event.keyCode == 9 && document.shiftDown == true) {
					$(this).parents('li').removeClass('over');
				}
			});
		// all links within menu upon focus, show the menu (catches mouse-out followed by keyboard tabbing if focus is still within menu)
		$(this).find('a')
			.keyup(function(event) {
				if (event.keyCode == 9) {
					$(this).parents('.submenu').parents('li').addClass('over');
				}
			});
		// last occuring link within a menu on tab-out, hide the menu
		$(this).find('a:last')
			.keydown(function(event) {
				if (event.keyCode == 9 && document.shiftDown != true) {
					$(this).parents('.submenu').parents('li').removeClass('over');
				}
			});
		// first occuring link within a menu on shift-tab-out, hide the menu
		$(this).find('a:first')
			.keydown(function(event) {
				if (event.keyCode == 9 && document.shiftDown == true) {
					$(this).parents('.submenu').parents('li').removeClass('over');
				}
			});
	});
	
	/****************************************************************************************************************/
	
	// login form setup
	if ($("#header #member_login").length > 0) {
		// header member form setup
		$("#member_login").affectAttr("input, button, a", "tabindex", "-1");
		
		// toggle show / hide
		$("#member_controls > a[href*='member_login']").click(function(event) {
			toggleMemberArea();
			return false;
		});
	}
	
	/****************************************************************************************************************/
	
	// global top level nav links highlighting
	if ($("#page").hasClass("errorpage") == false) {
		if ($("#page").hasClass("home")) {
			$("#navigation_primary > li:first > a:first").addClass("current");
		} else {
			var $menuEls = $("#navigation_primary > li > a");

			journey_loop:
			for (var i = 0; i < journey.length; i++)
			{
				for (var c = 0; c < $menuEls.length; c++)
				{
					var link = $menuEls.eq(c).attr('href');

					if (link.indexOf(journey[i]) > -1)
					{
						$menuEls.eq(c).addClass('current');

						break journey_loop;
					}
				};
			}
		}
	}
	
		// left hand subnav links highlighting
	var $navigation_secondary = $(".navigation_secondary");

	if ($navigation_secondary.length > 0) {
		if (journey.length == 2) {
			$navigation_secondary.find("h6 a").addClass("selected");
		} else {
			var $groupedLinks = $navigation_secondary.find("li a");

			for (var i=0; i<journey.length-2; i++) {
				$groupedLinks.each(function() {

					var $this = $(this);

					if ($this.attr("href").indexOf(journey[i]) != -1) {

						if (window.archiveYear) { // Let's get lame...

							var $text = $this.text(),
							    $match = $text.match(/^News Archive ([0-9]+)$/);

							if ($match != null && $match.length > 1 && $match[1] == window.archiveYear) $this.addClass("selected");
						}
						else $this.addClass("selected");
					}
				});
			}
		}
	}
	
	/****************************************************************************************************************
	CHUNK: homepage specific
	*/
	
	if ($('.home').length > 0) {
	
		DEMOTIVE.tabs.init($('.dem-tabbed'));
	
		$('.home #hero .item').each(function(index, element) {
			$(this)
				.click(function(event) {
					window.location.href = $(this).find('.pullthrough a').attr('href');
					return false;
				})
				.hover(
					function() {
						$(this).addClass('over');
					},
					function() {
						$(this).removeClass('over');
					}
				);
		});
		
		/**************** NOTE: See "load" event scripts lower down for slideshow setup ******************/
		
		// homepage accordion
		var $_el = $('.home #hero .aside ul');
		var unitHeight = $_el.find('div:first').css('min-height');
		$_el.find('div').css({
				'height' : '0px',
				'min-height' : '0px',
				'overflow' : 'hidden'
			});
		$_el.find('div:first').css({
				'height' : unitHeight
			});
		$_el.find('li > a')
			.click(function(e) {
				e.preventDefault();
				$_targetDiv = $(this).next();
				if ($_targetDiv.height() > 0) {
					$_el.find('div:not(:first)').animate({ height: '0px' }, 250);
					$_el.find('div:first').animate({ height: unitHeight }, 250);
				} else {
					$_targetDiv.animate({ height: unitHeight }, 250);
					$_el.find('div').not($_targetDiv).animate({ height: '0px' }, 250);
				}
			})
			.each(function() {
				$(this).next().append('<p><a href="' + $(this).attr('href') + '">Find out more</a></p>')
			});
		
		$('.home .puff').each(function(index, element) {
			$(this)
				.click(function(event) {
					window.location.href = $(this).find('a.lead_in').attr('href');
					return false;
				})
				.hover(
					function() {
						$(this).addClass('over');
					},
					function() {
						$(this).removeClass('over');
					}
				);
		});

		// homepage news ticker
		function newsTicker () {

			this.speed = 700;
			this.pause = 5000;

			this.removeFirst = function() {
				var item = $('#latest ol').find('li').first();
				    next = item.next(),
				    copy = item.clone();

				next.css('display', 'none');

				item
					.parent()
					.append(copy);
				
				item
					.animate({opacity: 0}, self.speed)
					.fadeOut('slow', function() {
						$(this).remove();
						next.fadeIn('slow');
					});
			};

			if ( $('#latest ol').find('li').length > 1 ) var interval = setInterval(this.removeFirst, this.pause);
		}
		newsTicker();
		
	}
	
	/****************************************************************************************************************
	CHUNK: "aside" specific
	*/
	
	if ($('#page:not(.home) .aside').length > 0) {
		
		DEMOTIVE.tabs.init($('.aside .dem-tabbed'), { matchHeight:'false' });
		
		$('.puff_alt .tint')
			.hover(
				function() {
					$(this).addClass('over');
				},
				function() {
					$(this).removeClass('over');
				}
			)
			.click(function(event) {
				window.location.href = $(this).find('a').attr('href');
				return false;
			});
		
	}
	
	/****************************************************************************************************************
	CHUNK: Jobsearch results page
	*/
	
	if ($('#jobsearch_subscribe').length > 0) {
		// focus events on fields
		$("#jobsearch_subscribe input")
			.focus(function() {
				$(this).prev().hide();
			})
			.blur(function() {
				if ($(this).val() == "") {
					$(this).prev().show();
				}
			});
	}
	
	
	/****************************************************************************************************************
	CHUNK: Job advertiser login page
	*/
	
	/*if ($('#advertiser_login').length > 0) {
		// focus events on fields
		$("#advertiser_login input")
			.focus(function() {
				$(this).prev().hide();
			})
			.blur(function() {
				if ($(this).val() == "") {
					$(this).prev().show();
				}
			});
	}*/
	
	
	/****************************************************************************************************************
	CHUNK: Enhanced styling for Newsletter listing
	*/
	
	if ($('.newsletter_listing').length > 0) {
		// focus events on fields
		var $containers = $(".newsletter_listing ol");
		$containers.each(function() {
			var $els = $(this).find("li");
			for (var i=0; i<$els.length; i++) {
				if (i==4) {
					$els.eq(i).addClass("c");
				}
				if (i>=4) {
					$els.eq(i).addClass("r");
				}
			}
		});
	}
	
	
	/****************************************************************************************************************
	CHUNK: tab-select-mech: tabs used as selections for forms (basically offscreen radio button control)
	*/
	
	if ($('.tab-select-mech').length > 0) {
		$('.tab-select-mech li:first-child').addClass('dem-active');
		$('.tab-select-mech li').each(function() {
			$(this)
				.append('<a href="#">' + $(this).find('label').text() + "</a>")
				.find('label').remove();
			$(this)
				.find(':radio').attr('tabindex', '-1');
		});
		$('.tab-select-mech a').click(function(event) {
			$(this).parents('.tab-select-mech').find('li').removeClass('dem-active');
			$(this).parent().addClass('dem-active');
			$(this).siblings('input').click();
			event.preventDefault();
		});
	}

});


/****************************************************************************************************************
CHUNK: Loaded events - homepage slideshow etc. Waits for all areas to load, inc images etc.
*/

$(window).load(function(){
	if ($('.home').length > 0) {
		// hero slideshow
		var $_heroEls = $('.home #hero .item');
		var heroCounter = 0;
		var heroLimit = $_heroEls.length - 1;
		var heroIntervalID = 0;
		heroIntervalID = setInterval(function() {
			if (heroCounter < heroLimit) {
				$_heroEls.eq(heroCounter).fadeOut();
				heroCounter++;
			} else {
				heroCounter = 0;
				$_heroEls.eq(heroCounter).fadeIn(function() {
					$_heroEls.show();
				});
			}
	    },
	    5000);
	}
	
	/****************************************************************************************************************/
	
	// advertiser form setup
	if ($("#member_login_article").length > 0) {
		testPrefilled($("#member_login_article"));
		// subsequent focus events on fields
		$("#member_login_article li input")
			.focus(function() {
				$(this).prev().hide();
			})
			.blur(function() {
				if ($(this).val() == "") {
					$(this).prev().show();
				}
			});
	}
});


