if( !$('body').is('.js') ) { $('body').addClass('js'); }

$(document).ready(function(){
    $('.three-col.jsHeight .col').syncHeight({ updateOnResize: true }); 
	$(".accordion").createAccordion(); 
	$(".carousel").createCarousel();  //Carousel on the 'what we do' page
	
	//60s Slider
	$('#sliderContent').length ? sliderInit() : null;
	$('.content-conveyor').css('left','-800px').animate({left: '0px'}, 3000);
	$('.ui-slider-handle').css('left', '300px').animate({ left: '0px' }, 3000);
	
	//Home carousel
	$('#slides').length ? $('#slides').slides({ preloadImage: '/images/assets/loading.gif'}) : null;
	
	//Form validation
	$("#enquiryForm").length ? $("#enquiryForm").validate() : null;
	$("#loginForm").length ? $("#loginForm").validate() : null;
	$("#enquiryFormValidate").length ? $("#enquiryFormValidate").validate() : null;

	//Google map on contact us page
	if (typeof Gmap !== 'undefined') Gmap.init('.gmap');
});


/* ***************************************************************************************
 * syncHeight - jQuery plugin to automagically Snyc the heights of columns
 * Made to seemlessly work with the CCS-Framework YAML (yaml.de)
 * @requires jQuery v1.0.3
 *
 * http://blog.ginader.de/dev/syncheight/
 *
 * Copyright (c) 2007-2009 
 * Dirk Ginader (ginader.de)
 * Dirk Jesse (yaml.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Version: 1.1
 */
(function($) {
	$.fn.syncHeight = function(config) {
		var defaults = {
			updateOnResize: false	// re-sync element heights after a browser resize event (useful in flexible layouts)
		};
		var options = $.extend(defaults, config);		
		var e = this;
		
		var max = 0;
		var browser_id = 0;
		var property = [
			// To avoid content overflow in synchronised boxes on font scaling, we 
			// use 'min-height' property for modern browsers ...
			['min-height','0px'],
			// and 'height' property for Internet Explorer.
			['height','1%']
		];

		// check for IE6 ...
		if($.browser.msie && $.browser.version < 7){
			browser_id = 1;
		}
		
		// get maximum element height ...
		$(this).each(function() {
			// fallback to auto height before height check ...
			$(this).css(property[browser_id][0],property[browser_id][1]);
			var val=$(this).height();
			if(val > max){
			   max = val;
			}
		});
		
		// set synchronized element height ...
 		$(this).each(function() {
  			$(this).css(property[browser_id][0],max+'px');
		});
		
		// optional sync refresh on resize event ...
		if (options.updateOnResize == true) {
			$(window).resize(function(){ 
				$(e).syncHeight();
			});
		}
		return this;
	};	
})(jQuery);


/*
 * --------------------------------------------------------------------
 * Accordion drop-downs
 * --------------------------------------------------------------------
 */
$.fn.createAccordion = function()	{
	return $(this).each(function() 	{
			
		var accordion = $(this),
			heading = $('.js-toggle',accordion),
			panel = $('.js-panel',accordion),
			activePanelClass = 'active',
			activeTabClass = 'selected',
			prefixWidget = 'widget', 
			prefixTab = 'tab',
			prefixPanel = 'panel',
			multiSelect = true, //option to open more than one tab
			defaultTab = 0, //Choose which tab to open first
			totalTabs = heading.length,
			cancelKeypress = false; //Opera problem with keydown/keypress 

				
		//add application role and js class to the HTML/BODY elemets
		if( !$('body').is('[role]') ) { $('body').attr('role','application'); }
		if( !$('html').is('.js') ) { $('html').addClass('js'); }		
		
		//add classes/id/ARIA
		if(multiSelect)	{
			accordion.attr('aria-multiselectable',true);
		}
		accordion.attr('role','tablist');
		
		heading.each(function(index)	{
			$(this).attr({'id':prefixTab+index, 'tabindex':-1, 'role':'tab', 'aria-controls':prefixPanel+index});
			$(this).next(panel).attr({'id':prefixPanel+index, 'role':'tabpanel', 'aria-labeledby':prefixTab+index, 'aria-hidden':true});
		});
			
		//on load open the 1st tab
		//heading.eq(defaultTab).addClass(activeTabClass).attr('tabindex',0);
		//panel.eq(defaultTab).addClass(activePanelClass).attr('aria-hidden',false);		
		
		//collapse/expand tabs function
		expandCollapse = function(tab)	{
			var $this = tab; 
			var index = $this.attr('id').replace(prefixTab,'');
			
			//close all previous tabs			
			if(multiSelect === false)	{
				//heading.removeClass(activeTabClass); //if at least one tab should be expanded
				panel.slideUp(500).removeClass(activePanelClass).attr('aria-hidden',true);
			}			
			
			if( $this.is('.'+activeTabClass) )	{
				$this.removeClass(activeTabClass);
				$('#panel'+index).slideUp(500).removeClass(activePanelClass).attr('aria-hidden',true);
			} else	{ 
				heading.attr('tabindex',-1);
				$this.addClass(activeTabClass).attr('tabindex',0);
				$('#panel'+index).slideDown(500).addClass(activePanelClass).attr('aria-hidden',false);	
			};
			return false;		
		};
		moveToTab = function(tab)	{
			//move to the tab, focus and index=0
			heading.attr('tabindex',-1);
			tab.attr('tabindex',0).focus();
		}
		
		//events
		heading
			.click(function(event)	{
				expandCollapse($(this));
				$(this).focus();
				event.stopPropagation(); 
				event.preventDefault() 
			})
			.keydown(function(event)	{
				var ret = true; 
				var currenttab = $(this);
				var id = Math.floor( currenttab.attr('id').replace(prefixTab,'') );
				if(event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40 || event.keyCode == 35 || event.keyCode == 36)	{
					// Left/Up arrow	 (movo to the previous tab)
					if(event.keyCode == 37 || event.keyCode == 38)	{
						(id-1 > -1) ? moveToTab( heading.eq(id-1) ) : moveToTab( heading.eq(totalTabs-1) );
					}
					// Right/Down arrow (move to the next tab)
					if(event.keyCode == 39 || event.keyCode == 40)	{ 
						(id+1 < totalTabs) ? moveToTab( heading.eq(id+1) ) :  moveToTab( heading.eq(0) );
					}
					// Home key
					if(event.keyCode == 36)	{ 
						moveToTab(heading.eq(0));
					}
					// End key
					if(event.keyCode == 35)	{ 
						moveToTab(heading.eq(totalTabs-1));
					}
					return false;
					event.preventDefault();
				}
				//check if enter or space was pressed on a tree node
				else if(event.keyCode == 13 || event.keyCode == 32){
					expandCollapse(currenttab);
					event.stopPropagation();
        			return false; 
				};

			});
			// If focus is on an element in a tab panel,
			//pressing Ctrl+Up/Left Arrows will move focus to the tab for that panel
			panel.keydown(function(event) {
				if( event.ctrlKey && (event.keyCode == 37 || event.keyCode == 38) )	{
					var thisId = Math.floor( $(this).attr('id').replace(prefixPanel,'') );
					heading.eq(thisId).focus();
				}
			});		
	});
}


/*
 * --------------------------------------------------------------------
 * 60s Slider
 * --------------------------------------------------------------------
 */
function sliderInit() {
	//vars
	var conveyor = $(".content-conveyor", $("#sliderContent")),
	item = $(".item", $("#sliderContent"));
	//set length of conveyor
	conveyor.css("width", item.length * parseInt(item.outerWidth(true)));
    //config
    var sliderOpts = {
	  max: (item.length * parseInt(item.outerWidth(true))) - parseInt($(".viewer", $("#sliderContent")).css("width")),
      slide: function(e, ui) { 
        conveyor.css("left", "-" + ui.value + "px");
      }
    };
    //create slider
    $("#slider").slider(sliderOpts);
}


/*
 * --------------------------------------------------------------------
 * jQuery carousel plugin
 * --------------------------------------------------------------------
 */
$.fn.createCarousel = function(){
	return $(this).each(function(){
		
		var $tabs = $(this);
		var $tabNav = $tabs.find('.c-nav');
		var $tabContent = $tabs.find('.c-content');
		var $tabPanel = $tabContent.find('> div');
		var tabIDprefix = 'tab-';
		var tabIDsuffix = '-enhanced';
		var autoRotate = true; //Set tabs auto-ratating
		
		//Add class, attributes and ARIA to tab navigation
		$tabNav
			.find('li').each(function()	{
				var tabID = $(this).find('a').attr('href').replace('#','');
				$(this)
					.attr({'role':'tab','id':tabIDprefix + tabID, 'role': 'tabslist'})
					.find('a').attr('tabindex','-1');			
			})
			.end()
			.find('li:first').addClass('selected')
			.find('a').attr('tabindex',0);	
		
		//Add class and ARIA to tab panels	
		$tabPanel.each(function()	{			
			var tablistID = $(this).attr('id');
			$(this)
				.attr({'role':'tabpanel','aria-hidden':true, 'id':tablistID + tabIDsuffix, 'aria-labelledby':tabIDprefix + tablistID})
				.addClass('tabs-panel')
		});
		$tabContent
			.find('> div:first')
			.attr('aria-hidden',false)
			.addClass('tabs-panel-selected');
		
			
		//Generic select tab function
		function selectTab(tab)	{
			var $this = $(tab);
			var currentPanelID = ( $this.attr('href').replace('#','')) + tabIDsuffix;
			//change the tab navigation
			$tabNav
				.find('li.selected')
				.removeClass('selected')
				.find('a').attr('tabindex',-1);
			$this	
				.attr('tabindex',0)
				.parent('li')
				.addClass('selected');
			//change the tablist content
			$tabContent
				.find('.tabs-panel-selected')
				.fadeOut(1000)
				.removeClass('tabs-panel-selected')
				.attr('aria-hidden',true)
				.css('display','none');
			$('#' + currentPanelID)
				.fadeIn(1000)
				.addClass('tabs-panel-selected')
				.attr('aria-hidden',false)
				.css('display','block')
		}
			
		//Add events
		$tabNav.find('li a')
			.click(function()	{
				selectTab( $(this) );
				$(this).focus();
				return false;
			})
			.keydown(function(e)	{
				var currentTab = $(this).parent();
				//Find keyCode: http://asquare.net/javascript/tests/KeyCode.html
				var ret = true;
				switch(e.keyCode)	{
					//(select the previous tab)
					case 37: //Left arrow
					case 38: //Up arrow
						if(currentTab.prev().size() > 0)	{
							selectTab( currentTab.prev().find('a') );
							currentTab.prev().find('a').eq(0).focus();
							ret = false;
						} else {
							selectTab( currentTab.parent().find('a:last') );
							currentTab.parent().find('a:last').eq(0).focus();
							ret = false;
						}
					break;	
					//(select the next tab)
					case 39: //Right arrow
					case 40: //Down arrow
						if(currentTab.next().size() > 0)	{
							selectTab( currentTab.next().find('a') );
							currentTab.next().find('a').eq(0).focus();
							ret = false;
						} else {
							selectTab( currentTab.parent().find('a:first') );
							currentTab.parent().find('a:first').eq(0).focus();
							ret = false;
						}
					break;
					case 36: //Home key, select the first tab
						selectTab( currentTab.parent().find('a:first') );
						currentTab.parent().find('a:first').eq(0).focus();
						ret = false;
					break;
					case 35: //End key, select the last tab
						selectTab( currentTab.parent().find('a:last') );
						currentTab.parent().find('a:last').eq(0).focus();
						ret = false;
					break;
				}
				return ret;
			});
			
		//If focus is on an element in a tab panel:
		//Control + Up Arrow/Left Arrow: Set focus on the tab button for the currently displayed tab
		$tabPanel.keydown(function(e)	{
			if( e.ctrlKey && (e.keyCode == 37 || e.keyCode == 38) )	{
				$tabNav.find('li.selected a').focus();
			}
		});
			
		//Optional rotation
		if(autoRotate)	{
			var rotateTabs = setInterval(function()	{
				var currentTab = $tabNav.find('li.selected');
				if(currentTab.next().find('a').length)	{
					selectTab( currentTab.next().find('a') );
				} else {
					selectTab($tabNav.find('li:first a'));
				}
			}, 6000)
		};
		//Clear rotating after mouseover the tabs area
		if(autoRotate)	{
			$tabNav.find('a').bind('mouseover click keydown focus',function()	{
				clearInterval(rotateTabs);
			})	
				
		}
	});
}



/*
 * --------------------------------------------------------------------
 * jQuery Homepage carousel plugin
 * --------------------------------------------------------------------
 */
$.fn.homeCarousel = function(){
	return $(this).each(function(){				
		var $el = $(this); 
		if ($el.length == 0) return;
		var $totalItems = $('li',$el).length;
		var imgId = 'img-';
		var autoRotate = true; //Set carousel auto-ratating. If used, remove focus from the image. Screen reader announce image all the time it rotates.
		var $interval = 5000;
		var pagination = false;
		

		/* carousel nav */
		var $nav = '';
		$nav += '<div class="nav" role="toolbar"><span class="stat">' + 1 + ' of ' + $totalItems + '</span>';
		$nav += '<div class="buttons" role="presentation">';
		$nav += '<span aria-controls="carousel" role="presentation"><button type="button" class="btn prev disabled" disabled="true" aria-disabled="true">Previous Image</button></span>';
		$nav += '<span aria-controls="carousel" role="presentation"><button type="button" class="btn next" aria-disabled="false">Next Image</button></span>';
		$nav += '</div>';
		$nav += '</div>';				
		$el.wrap('<div class="carousel-wrap"></div>');
		$('.carousel-wrap').prepend($nav);
		var $controls = $('.carousel-wrap .nav');
		
		/* Aria/classes/ids */
		$el.attr('role','listbox').find('li').each(function(i)	{
			$(this).attr({'role':'option','aria-selected':false,'tabindex':-1,'class':'item','id':'img-'+i});
		});
		
		$('li:first',$el).css('display','block').addClass('selected').attr({'aria-selected':true,'tabindex':0});
		
		/* function */
		function changeImg(img)	{
			//Chanage image and update pagination
			if(img > -1 && img < $totalItems)	{
				$('li.selected',$el).fadeOut(500).css('display','none').removeClass('selected').attr({'aria-selected':false,'tabindex':-1});
				$('li#img-'+img,$el).fadeIn(500).css('display','block').addClass('selected').attr({'aria-selected':true,'tabindex':0});
				$('li#img-'+img,$el).find('a').focus();
				$('span.stat',$controls).text(img+1 + ' of ' + $totalItems);
			}
			//update next/prev buttons
			$('.buttons .btn',$controls).removeClass('disabled').removeAttr('disabled');
			if(img <= 0)	{	
				$('.buttons .prev',$controls).addClass('disabled').attr({'disabled':true,'aria-disabled':true});
			}else if(img >= $totalItems-1)	{
				$('.buttons .next',$controls).addClass('disabled').attr({'disabled':true,'aria-disabled':true});
			}					
		}
		
		//Events
		$('.buttons .btn',$controls)
		.click(function()	{
			var currentImage = Math.floor( $('li.selected',$el).attr('id').replace('img-','') );
			if( $(this).is('.prev') )	{
				changeImg(currentImage -1)
			}else if($(this).is('.next'))	{
				changeImg(currentImage +1)
			}
			return false;
		});
		$('li',$el).keydown(function(e)	{
			var currentImage = Math.floor( $('li.selected',$el).attr('id').replace('img-','') );
			var ret = true;
			switch(e.keyCode)	{
				case 37: //Left arrow
				case 38: //Up arrow
					changeImg(currentImage -1);	
					ret = false;			
				break;	
				case 39: //Right arrow
				case 40: //Down arrow
					changeImg(currentImage +1);
					ret = false;			
				break;
			}
		return ret;
	});
	
	//autorotate option
	if(autoRotate)	{
		var rotateCarousel = setInterval(function()	{
			var currentImage = Math.floor( $('li.selected',$el).attr('id').replace('img-','') );
			if(currentImage < 0)	{
				changeImg(currentImage +1);
			}else if(currentImage === $totalItems-1)	{
				currentImage = 0;
				changeImg(currentImage);
			}else{
				changeImg(currentImage +1);
			}					
		},$interval);
	};
	//Clear rotating after mouseover the carousel area
	if(autoRotate)	{
		$el.bind('mouseover click keydown',function()	{
			clearInterval(rotateCarousel);
		});					
	}
		
		
	});
}
