/*
 * Global JavaScript (requires jQuery)
 * 
 * Original Author: Chris Martin, Webexpectations
 */
 
/* - Initialisation (runs functions common to all pages) - */

$(document).ready(function() {
	attachInfoPopups();
	promoTabsAttach();
	headerSearch();
	headerLanguage();
	footerAlerts();
	centreSubnavs();
	attachPrint();
	attachSliders();
});

function attachSliders() {
	$('.slidehide').hide();
	$('.addshut').addClass('shut');
	$('.tach').css('cursor', 'pointer');
	$('.tach').click(function(e) {
		$(this).toggleClass('shut');
		$(this).next('.tac-slide').slideToggle('slow');
	});
}

function attachPrint() {
	$('.print').css('display', 'inline-block');
	$('.print').click(function(e) {
		e.preventDefault();
		window.print();
	});
}

(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
})(jQuery)
jQuery.preLoadImages(
	etGlobals.imagesPath + "back-langselect-open.png",
	etGlobals.imagesPath + "back-langselect-hover.png",
	etGlobals.imagesPath + "flag-fr.png",
	etGlobals.imagesPath + "flag-uk.png",
	etGlobals.imagesPath + "back-farefinder-button.png",
	etGlobals.imagesPath + "back-quicklinks-li-hover.gif",
	etGlobals.imagesPath + "back-alerts-button-l-hover.png",
	etGlobals.imagesPath + "back-alerts-button-r-hover.png",
	etGlobals.imagesPath + "back-quicklinks-groupe-li.gif");

function attachInfoPopups() {
	var width = 640;
	var height = 480;
  
  // TODO: Grab custom width and height from rel attribute.	Mootools version below to convert.
  /*
    if (rel = popup.getProperty('rel')) {
      var parts = rel.split(',');
      var dimensions = false;
      parts.each(function(part,j){
        if (part.trim().test("[0-9]+x[0-9]+", 'i')) { dimensions = j; }
      });
      if ($chk(dimensions)) {
        var dimensions = parts[dimensions].trim().split('x');
        width = dimensions[0];
        height = dimensions[1];
      }
    }
  */
  
  $('a.info').click(function(){
		window.open($(this).attr('href'),'_blank','width='+width+',height='+height+',resizable=yes,scrollbars=yes,toolbar=no,status=no,directories=no');
    if (window.focus) $(this).focus();
    return false;
	});

}

function promoTabsAttach() {
	// Set position
	this.position=$('div.promo-tabs ul.tabs li').length-1;
	// Start rotation of tabs
	var rotate = setInterval("promoTabsRotate()", 5000);
	// Remove the links from the tabs themselves.
	//$('div.promo-tabs ul.tabs li a').removeAttr('href');
	// Grab the sections
	var sections = $('.promo-tabs .section');
	// Placeholder: Clicking the tabs adjusts their classes to demonstrate style changes.
	$('div.promo-tabs ul.tabs li').each(function(i, el){
		$(this).click(function(event){
			event.preventDefault();
			$('div.promo-tabs ul.tabs li').removeClass('current');
			$(this).toggleClass('current');
			// Ensure all sections are not showing
			sections.css('display', 'none');
			// Fade in selected section
			sections.eq(i).fadeIn('slow');
			// End tabs rotation
			window.clearInterval(rotate);
		});
	});
}

function promoTabsRotate() {
	// Increment tab position
	if (this.position==$('div.promo-tabs ul.tabs li').length-1) this.position=0;
	else this.position++;
	// Show next tab
	$('div.promo-tabs ul.tabs li').removeClass('current');
	$('div.promo-tabs ul.tabs li').eq(this.position).toggleClass('current');
	$('.promo-tabs .section').css('display', 'none');
	$('.promo-tabs .section').eq(this.position).fadeIn('slow');
}

function headerSearch() {

    var searchString = etGlobals.searchPrompt;

	var search = $('div.langsearch input.text');
	if (!search.val() || search.val() == searchString) {
		search.val(searchString);
		search.addClass('empty');
	}
	
	// Set focus and blur events to insert/delete dummy text. Also toggle a class for adjusting the text colour.
	$('div.langsearch input.text').focus(function(){
		if ($(this).val() == searchString && $(this).hasClass('empty')) {
			$(this).val('');
			$(this).removeClass('empty');
		}
	});
	
	$('div.langsearch input.text').blur(function(){
		if ($(this).val() == '') {
			$(this).val(searchString);
			$(this).addClass('empty');
		}
	});
}

function headerLanguage() {
	var select = $('div.langsearch select');
	var options = $('div.langsearch select option');
	
	// Hide the real select box and submit button, and add a class to adjust the box width.
	select.addClass('hide');
	$('div.langsearch input.button').addClass('hide');
	$('div.langsearch').addClass('langsearch-js');
	
	// Insert our fake box after.
	select.after($('<div class="langselect-bg"></div><div class="langselect"></div>'));
	
	$('div.langselect').hover(
	  function () {
	  	$('div.langselect-bg').addClass('langselect-bg-hover');
	  }, 
	  function () {
	    $('div.langselect-bg').removeClass('langselect-bg-hover');
	  }
	);
	
	// Use the select's options to build a series of anchors, placing them inside the fake box.
	/*options.each(function(){
		var option = $('<a class="' + $(this).val() + '">' + $(this).text() + '</a>');
		if ($(this).attr('selected')) {
			option.addClass('current');
			$('div.langselect').prepend(option);
		} else {
			$('div.langselect').append(option);
		}
	});*/
	
	options.each(function(){
		var option = $('<a class="' + $(this).text() + '">' + $(this).text() + '</a>');
		if ($(this).attr('selected')) {
			option.addClass('current');
			$('div.langselect').prepend(option);
		} else {
			$('div.langselect').append(option);
		}
	});
	
	// Set up click events for the anchors.
	// 1. If class is current, perform no action other than opening the box.
	// 2. If class is not current, adjust the select box value, move the current class over, close the box and trigger the parent form.
	$('div.langselect a').click(function(){
		if ($(this).hasClass('current') && !$('div.langselect').hasClass('open')) {
			$('div.langselect-bg').addClass('open-bg');
			$('div.langselect').addClass('open');
		} else {
			// If the value has changed...
			if ($(this).text() != $('div.langselect a.current').text()) {
				// Mark the clicked item as current and move to top.
				$('div.langselect a').removeClass('current');
				$(this).addClass('current');
				$('div.langselect').prepend($(this));
				
				// Adjust the value of the real select box.
				$('div.langsearch select option').removeAttr('selected');
				thetext = $(this).text();
				$('div.langsearch select option').each(function(){
					if ($(this).text() == thetext) {
						$('div.langsearch select').val($(this).val());
					}
				});
				
				// Close the box.
				$('div.langselect-bg').removeClass('open-bg');
				$('div.langselect-bg').removeClass('langselect-bg-hover');
				$('div.langselect').removeClass('open');

				var btn = document.getElementById('ctl00_ChangeLanguage');
				if (btn) btn.click();
			} else {
				// Value hasn't changed.
				$('div.langselect-bg').removeClass('open-bg');
				$('div.langselect').removeClass('open');
			}
		}
	});
}

function footerAlerts() {
	// Set initial values.
	var email = $('div.alerts input.text');
	if (!email.val() || email.val() == 'johnsmith@mail.com') {
		email.val('johnsmith@mail.com');
		email.addClass('empty');
	}
	
	// Hide label.
	$('div.alerts label').addClass('hide');
	
	// Set focus and blur events to insert/delete dummy text. Also toggle a class for adjusting the text colour.
	$('div.alerts input.text').focus(function(){
		if ($(this).val() == 'johnsmith@mail.com' && $(this).hasClass('empty')) {
			$(this).val('');
			$(this).removeClass('empty');
		}
	});
	
	$('div.alerts input.text').blur(function(){
		if ($(this).val() == '') {
			$(this).val('johnsmith@mail.com');
			$(this).addClass('empty');
		}
	});
}

function centreSubnavs() {
	// Adjust left position on subnavs based on parent width.
	$('div.subnav').parents('li').each(function(){
		// var left = -244;
		var left = -218;
		var menuwidth = $(this).width();
		left = left + (menuwidth/2);
		$(this).children().children('div.subnav').css('left',left + 'px');
	});
	
	// Exception for Inspiring Ideas.
	// $('ul#navbar li.ideas div.subnav').css('left','-219px');
	//$('ul#navbar li.ideas div.subnav').css('left','-166px');
}

$(function(){

	function changeDate(el) {
		var monthYear = $(el).parent('.row').children('.month').attr('value');
		if (monthYear.length == 3) {
			var month = monthYear.substr(0,1);
			var year = monthYear.substr(1,2);
		} else {
			var month = monthYear.substr(0,2);
			var year = monthYear.substr(2,2);
		}
		var day = $(el).parent('.row').children('.day').attr('value');
		var theDate = month + '/' + day + '/' + year;
		
		return theDate;	
	}

	if ($('select[name*="SelectedLanguage"] option:selected').val() == '1036') {
		$.datepicker.setDefaults($.datepicker.regional['fr']);
	}
			
	//$.datepicker.setDefaults($.datepicker.regional['fr']);

	$('.fFDatePicker').each(function(i, el) {								

		//$(el).datepicker($.datepicker.regional['fr']);
		
		$(el).datepicker({
			changeMonth: true,
			changeYear: true,
			minDate: '0',
			maxDate: '+1y +5m',
			showOn: 'button',
			buttonImage: '/templates/commercial/images/icon-calendar.png',
			buttonImageOnly: true,
			dateFormat: 'm/d/y',
			altFormat: 'y-m-d',
			showButtonPanel: true,
			/*closeText: 'Close',*/
			onClose: function() {

				var theDate = $(this).val().split('/');
				
				$(el)
					.parent('.row')
					.children('.month')
					.val(theDate[0]+theDate[2]);
				
				$(el)
					.parent('.row')
					.children('.day')
					.val(theDate[1]);				
				
			}
		});
		
		$(el)
			.parent('.row')
			.children('.month, .day')
			.change(function() {
				var date = changeDate($(this));
				$(el).datepicker( "setDate" , date );
			});
		
		
		
	});
	
	/*$('.fFDatePicker').css({
		padding: '0px',
		margin: '0px',
		border: 'none',
		position: 'absolute'
	});*/
	
	$("img.ui-datepicker-trigger").before('<a href="#" class="calendar"></a>');
	
	$('a.calendar').click(function(e){
		e.preventDefault();
		$(this).next().trigger('click');
	});
	
	$("img.ui-datepicker-trigger").css({
		visibility: 'hidden'
	});
	
	$("img.ui-datepicker-trigger").hover(
	  function () {
	    $(this).attr('src','/templates/commercial/images/icon-calendar-hover.png');
	  }, 
	  function () {
	    $(this).attr('src','/templates/commercial/images/icon-calendar.png');
	  }
	);

});

$(document).ready(function() {
	$('.formholder .row').each(function(i, el) {
		var value = $(el).children('.hint').text();
		if (value!='') {
			$(el).children('.text').val(value).focus(function() {
				if ($(this).val() == value) $(this).val('');
			});
		}
	});
	$('.formholder .text, .formholder .select, .formholder .selectmultiple, .formholder .area')
		.css('color','#777');
	$('.formholder .text, .formholder .select, .formholder .selectmultiple, .formholder .area').focus(function(i, el){
		$(this).css('color','#333');
	});
});

$(document).ready(function() {

	function toolTips() {
	    this.xOffset = -10; // x distance from mouse
	    this.yOffset = -50; // y distance from mouse       
	    
	    $(".tip").unbind().hover(    
	        function(e) {
	            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
	            
	            $('body').append( '<div class="tooltip"><div class="tooltiparrow"></div>' + $(this).attr('title') + '</div>' );
	                        
	            $('.tooltip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
	            
	        },
	        function() {
	            $(".tooltip").fadeOut("slow").remove();
	        }
	    ).mousemove(
	        function(e) {
	            this.top = (e.pageY + yOffset);
	            this.left = (e.pageX + xOffset);
	                         
	            $(".tooltip").css("top", this.top+"px").css("left", this.left+"px");
	        }
	    );    
	}
	toolTips();	
	$(".tip").click(function(e) {
		e.preventDefault();
	});
	
	$('.slide li').addClass('shut');
	$('.slide li .text').hide();
	$('.slide li').each(function(i, el) {
		$(this).children('h3').css('cursor','pointer').click(function(e) {
		//$(this).children('h3').wrapInner('<a />').click(function(e) {
			$(el).children('.text').slideToggle();
			$(el).toggleClass('shut');
		});
	});
	
});

