/* 
   Author  : Andrew Webster
   Date    : Nov 2010
   Email   : andrew.webster@gmail.com
   Website : www.awebster.co.za   
*/


$.fn.accordion = function(settings) {
	
	settings = jQuery.extend({
		expander : 'reveal',
		toggler  : 'header',
		speed	 : 250,
		multiple : false
	}, settings);
	
	var $el = this;
	var expander = '.'+settings.expander;
	var toggler = '.'+settings.toggler;	

	// close expanders except any that are specified as open
	$el.find('li > a:not(".open")').each(function(){
		$(this).parent('li').children(expander).hide();
		$(this).toggleClass('closed');
	});
	
	$el.find('li > a'+toggler).click(function(){	
	
		clickedID = $el.find('li > a.open').index(this);
		
		// close open answers	
		if(!settings.multiple){			
			if ( $el.find('li a.open').length > 1 ){
				// close only clicked answers (if open)					
				if( $(this).hasClass('open') ){
					$(this).removeClass('open')
						.addClass('closed')
						.next(expander).slideUp(settings.speed);
						return;	
				}				
			} else {			
				// close all open answers		
				$el.children('li').each(function(){									
					$(this).children('a.open')
						.removeClass('open')
						.addClass('closed')
					$(this).children(expander).slideUp(settings.speed);				
				});
			}
		} else {
			// close only clicked answers (if open)					
			if( $(this).hasClass('open') ){
				$(this).removeClass('open')
					.addClass('closed')
					.next(expander).slideUp(settings.speed);
					return;	
			}			
		}
		
		// open clicked answer (unless it was open to begin with)		
		if(clickedID < 0){			
			$(this).nextAll(expander).slideDown(settings.speed);
			$(this).removeClass('closed')
				.addClass('open');
		}			
		return false;	
		
	});
	
	// enable expander controls
	$el.prev('.expander_controls').show();
	
	// show all
	$el.prev('.expander_controls').find('a.showall').click(function(){		
		$(this).parent('.expander_controls').next('ul.expander').children('li').each(function(){			
			$(this).children(expander).slideDown(settings.speed);
			$(this).children('a'+toggler).removeClass('closed')
				.addClass('open');
		});
		return false;
	});	
	
	// close all
	$el.prev('.expander_controls').find('a.closeall').click(function(){		
		$(this).parent('.expander_controls').next('ul.expander').children('li').each(function(){			
			$(this).children(expander).slideUp(settings.speed);
			$(this).children('a'+toggler).removeClass('open')
				.addClass('closed');
		});		
		return false;		
	});
	
	
}

$(function(){

	Cufon.replace('#main h1, #main h2.blue, #main h2.primary, #main .title, #content .img_std p.stats, #content .module .digits', { 
			fontFamily: 'AvantGarde'
	});	
	
	
	/** Homepage slideshow
	*************************/
	$('#slideshow .slides').cycle({ 
		fx:     'scrollLeft', 
		speed:  900, 
		timeout: 6000, 
		pager:  '#slideshow_nav, #slideshow_nav2', 
		pagerAnchorBuilder: function(idx, slide) { 
			return '#slideshow_nav li:eq(' + idx + ') a, #slideshow_nav2 li:eq(' + idx + ') a'; 
			
			
		} 
		
		
		
	});
	
	
	

	
	
	/** Services slideshow
	*************************/
	$('#intro_carousel .slides').cycle({ 
		fx:     'scrollLeft', 
		speed:  600, 
		timeout: 5000   
	});
	
	
	/** Video modal
	*************************/	
	var myLoad = function(){ 		
		
		
		
		/** Carousel
		**************************/
//		function carousel_initCallback(carousel){			
//			
//			// listen for vid thumb click events
//			$('#carousel ul li a').click(function(){
//				vidID = $(this).attr('rel');
//				
//				// update video embed		
//				$('#video_wrap param:eq(0)').attr('value','http://www.youtube.com/v/'+vidID);
//				$('#video_wrap embed').attr('src','http://www.youtube.com/v/'+vidID);
//				
//				videoEmbed = $('#video_wrap').html();
//				$('#video_wrap').empty();
//				$('#video_wrap').html(videoEmbed);				
//					
//				return false;
//			});				
//			
	    //		}		

	    function carousel_initCallback(carousel) {

	        $('#video_wrap .movieHolder').hide();

	        // on click of 'play holding image'
	        $('#video_wrap .playHolder').click(function () {

	            var vidID = $(this).attr('rel');

	            // update video embed        
	            $('#video_wrap .movieHolder param:eq(0)').attr('value', 'http://www.youtube.com/v/' + vidID + '?autoplay=1');
	            $('#video_wrap .movieHolder embed').attr('src', 'http://www.youtube.com/v/' + vidID + '?autoplay=1');

	            videoEmbed = $('#video_wrap .movieHolder').html();
	            $('#video_wrap .movieHolder').empty();
	            $('#video_wrap .movieHolder').html(videoEmbed);


	            $(this).hide();
	            $('#video_wrap .movieHolder').show();

	            return false;
	        });

	        // listen for vid thumb click events
	        $('#carousel ul li a').click(function () {

	            var videoID = $(this).attr('rel');

	            // updade 'play holding image'
	            $('#video_wrap a.playHolder').attr('href', 'http://www.youtube.com/v/' + videoID);
	            $('#video_wrap a.playHolder').attr('rel', videoID);
	            $('#video_wrap a.playHolder img').attr('src', $(this).attr('href'));

	            $('#video_wrap .movieHolder').hide();
	            $('#video_wrap .playHolder').show();

	            return false;
	        });

	    }        

		
		$('#carousel').jcarousel({
			scroll : 1,
			wrap: 'both',
			initCallback: carousel_initCallback,
			itemFallbackDimension: '117px'
		});		
		
	}; 	
	
	
	$('#videoModal').jqm({
		 trigger: 'a.launchVideo',
		 ajax:'@href',
		 onLoad:myLoad
	});
	
	
	
	
	/** Form default value show/hide
	*************************/	
	if( !($('#contact_form').length > 0) ){		
		$(function() {
		  $('input[type="text"]:not(".noblur")').add('textarea')	  
		  .focus(function() {
			var $this = $(this);
			
			if (!$this.data('default')) {
			  $this.data('default', $this.val());
			}
			
			if ($this.val() == $this.data('default')) {
			  $this.val('');
			}
		  })	  
		  .blur(function() {
			var $this = $(this);
			
			if ($this.val() == '') {
			  $(this).val($this.data('default'));
			}
		  })	  
		});
	}
	
	
	/** Nav bleeds
	**************************/	
	function addBleeds(el){
		$el = el;
		$el.parent('td').prev('td').addClass('bleed-l');
		$el.parent('td').next('td').addClass('bleed-r');
	}	
	function removeBleeds(el){
		$el = el;
		if( !($el.hasClass('active')) ){
			$el.parent('td').prev('td').removeClass('bleed-l');
			$el.parent('td').next('td').removeClass('bleed-r');
		}
		$('#nav td a.active').each(function(){
			addBleeds($(this));
		});
		
	}
	$('#nav td a.active').each(function(){
		addBleeds($(this));
	});
	$('#nav td a').hover(function(){
			addBleeds($(this));
	},function(){
			removeBleeds($(this));	
	});		
	
	
	/** Sitemap expand
	**************************/	
	$(function(){
		var $sitemap = $('#footer > .sitemap_row');
		var sitemapHeight;
		var destination;
		
		$('#footer a.sitemap').click(function(){
			
			sitemapHeight = $sitemap.height();
			destination = $('body').height() + sitemapHeight;		
			
			if( $sitemap.is(':hidden') ){				
				$sitemap.slideToggle(250);				
				$('html:not(:animated),body:not(:animated)').animate({	scrollTop: destination	}, 250);				
			} else {			
				$sitemap.slideToggle(250);
			}			
			
			return false;
		});
	});
	
	/** Table row highlight
	**************************/	
	$('#content table.share_docs tr:not(".year") td, #content table.news_announce td').hover(function(){
		$(this).parent('tr').addClass('hilite');
	},function(){
		$(this).parent('tr').removeClass('hilite');	
	});
	
	/** Intro listings highlight
	**************************/	
	$('#content ul.intro_listings li').hover(function(){
		$(this).addClass('hilite');
	},function(){
		$(this).removeClass('hilite');	
	});
	
	
	/** Service expander
	**************************/	
	$('#content ul.expander:eq(0)').accordion();
	$('#content ul.expander:eq(1)').accordion();
	
	/** Panel expander
	**************************/	
	$('#content ul.panels').accordion({ multiple:true });
	
	
/** Map overlays
	**************************/	
	if( $('#worldmap').length > 0 ){
		function closeListener(){
			$('#map_lb .map_overlay .close').click(function(){
				$('#map_lb').empty();
			});
			$(document).keyup(function(e){
				if (e.keyCode == 27) $('#map_lb .map_overlay .close').click();
			});		
		}
		
		/* on click */
		$('#worldmap area').click(function(){
			$('#map_lb').empty();	
			$($(this).attr('href')).clone().appendTo('#map_lb');		
			$('#map_lb .map_overlay').hide().fadeIn(250);			
			closeListener();		
			return false;	
		});
		/* */
		
		/* on hover */	
		(function(){
			var holdIt;
			$('#worldmap area').hover(function(){			
				function considerMeHovered(){
					clearTimeout(holdIt);
					if( $('#map_lb > div').length < 1){	
						$('#map_lb').empty();	
						$($(this).attr('href')).clone().appendTo('#map_lb');		
						$('#map_lb .map_overlay').hide().fadeIn(250);			
						closeListener();				
					}
				}
				holdIt = setTimeout(considerMeHovered, 400);			
			},function(){
				clearTimeout(holdIt);
			});
			
			$('#worldmap area').click(function(){
				return false;
			});
		})();
		/* */	
		
		// on hover
		$('#worldmap area').hover(function(){
			$('#map .hilite').empty();
			href = $(this).attr('href');
			if( href == '#shipbrokingsingapore' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/singapore-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokinguk' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/uk-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokingnny' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/newyork-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokinggreece' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/greece-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokingdubai' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/dubai-over.gif" />')
					.fadeIn(150);					
					
			}
		},function(){
			$('#map .hilite').empty();
		});
	}
	


/** Map overlays
	**************************/	
	if( $('#worldmap1').length > 0 ){
		function closeListener(){
			$('#map_lb .map_overlay .close').click(function(){
				$('#map_lb').empty();
			});
			$(document).keyup(function(e){
				if (e.keyCode == 27) $('#map_lb .map_overlay .close').click();
			});		
		}
		
		/* on click */
		$('#worldmap1 area').click(function(){
			$('#map_lb').empty();	
			$($(this).attr('href')).clone().appendTo('#map_lb');		
			$('#map_lb .map_overlay').hide().fadeIn(250);			
			closeListener();		
			return false;	
		});
		/* */
		
		/* on hover */	
		(function(){
			var holdIt;
			$('#worldmap1 area').hover(function(){			
				function considerMeHovered(){
					clearTimeout(holdIt);
					if( $('#map_lb > div').length < 1){	
						$('#map_lb').empty();	
						$($(this).attr('href')).clone().appendTo('#map_lb');		
						$('#map_lb .map_overlay').hide().fadeIn(250);			
						closeListener();				
					}
				}
				holdIt = setTimeout(considerMeHovered, 400);			
			},function(){
				clearTimeout(holdIt);
			});
			
			$('#worldmap1 area').click(function(){
				return false;
			});
		})();
		/* */	
		
		// on hover
		$('#worldmap1 area').hover(function(){
			$('#map .hilite').empty();
			href = $(this).attr('href');
			if( href == '#shipbrokingsingapore' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/singapore-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokinguk' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/uk-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokingnny' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/newyork-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokinggreece' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/greece-over.gif" />')
					.fadeIn(150);
			} else if( href == '#shipbrokingdubai' ){
				$('#map .hilite')
					.hide()
					.html('<img src="assets/images/content/map/dubai-over.gif" />')
					.fadeIn(150);					
			}
		},function(){
			$('#map .hilite').empty();
		});
	}



	
	
	
	
	/** Small World Map
	**************************/
	if( $('#smallmap').length > 0 ){		
		
		var $regionlist = $('#content .panels .listings ul.list');
		
		$('#smallmap area').hover(function(){			
			var region = $(this).attr('href');				
			region = region.substring(1, region.length);
			
			if( region == 'fareast' ){				
				$regionlist.children('li.'+region).animate({
					backgroundColor : '#83bf40',
					borderBottomColor: '#83bf40'
				}, 250);				
			} else if( region == 'cis' ){				
				$regionlist.children('li.'+region).animate({
					backgroundColor : '#00a4d6',
					borderBottomColor: '#00a4d6'
				}, 250);				
			} else if( region == 'uk' ){				
				$regionlist.children('li.'+region).animate({
					backgroundColor : '#e55825',
					borderBottomColor: '#e55825'
				}, 250);				
			} else if( region == 'gulf' ){				
				$regionlist.children('li.'+region).animate({
					backgroundColor : '#74277e',
					borderBottomColor: '#74277e'
				}, 250);				
			}			
			
			$regionlist.children('li.'+region).children('a').animate({
				color : '#ffffff'
			}, 250);
						
			
		},function(){
			$regionlist.children('li').each(function(){
				$(this).animate({
					backgroundColor : '#f1f0f1',
					borderBottomColor: '#bbbabb'
				}, 150);
				
				$(this).children('a').animate({
					color: '#265787'
				}, 150);
				
			});
		});		
		
	}
	
	
	
	/** Career profiles
	**************************/	
	
	// preload images
	if( $('#content .career_intro ul.people').length > 0 ){	
		var imgArray = new Array();
		var imgCount = 0;
		$('#content .career_intro ul.people li a').each(function(){
			imgCount++;
			imgArray[imgCount] = new Image();
			imgArray[imgCount].src = $(this).attr('href');	
		});	
	}	
	
	$('#content .career_intro .profile').hide();
	
	// on hover
	$('#content .career_intro ul.people li a').hoverIntent(function(){
		
		$profile = $('#content .career_intro .profile');		
		pic = $(this).attr('rel');
		name = $(this).attr('title');
		text = $(this).children('img').attr('alt');		
		
		$profile
			.hide()
			.css({ 'background-image': 'url('+pic+')'})
			.empty()
			.append('<div class="overlay"><strong>'+name+'</strong><p>'+text+'</p></div>')
			.fadeIn(250);

	},function(){
		$('#content .career_intro .profile')
			.css({ 'background-image': 'none'})
			.empty()
			.hide();
	});
	
	
	
	/** Expand application
	**************************/	
	$('#content .application').hide();	
	$('#content a.expand_app').click(function(){
		$($(this).attr('href')).slideDown(250);
		return false;
	});
	
	
	// Extend validation rules
	$.validator.addMethod("notEqual", function(value, element, param) {
	  return this.optional(element) || value != param;
	}, "Please specify a different (non-default) value");	
	
	
	$('#apply_form').validate(
		{
			errorElement: 'span',				
			rules: {
				app_name: {
					required: true,
					notEqual: 'Name*',
					minlength: 2
				},
				app_email: {
					required: true,
					notEqual: 'Email*',
					email: true
				},
				app_conf_email: {
					required: true,
					notEqual: 'Confirm Email*',
					equalTo: '#app_email'
				},
				app_phone: {
					minlength: 9
				},
				app_cv: {
					required: true
				}
			},
			messages: {
				app_name: {
					required: "Please enter your first name",
					notEqual: "Please enter your first name",
					minlength: "Your name must consist of at least 2 characters"
				},	
				app_email: {
					required: "Please enter a valid email address",
					notEqual: "Please enter a valid email address",
					email: "Please enter a valid email address"
				},			
				app_conf_email: {
					required: "Email addresses do not match!",
					notEqual: "Email addresses do not match!",
					equalTo: "Email addresses do not match!"
				},
				app_phone: {
					minlength: "Your phone number must consist of at least 9 characters"
				},
				app_cv: {
					required: "Please attach your CV"
				}
			}
		});
	
	
	/** Subscribe form
	**************************/	
	$('#subscribe_form').validate(
		{
			errorElement: 'span',				
			rules: {
				sub_firstname: {
					required: true,
					notEqual: 'Firstname*',
					minlength: 2
				},
				sub_surname: {
					required: true,
					notEqual: 'Surname*',
					minlength: 2
				},
				sub_email: {
					required: true,
					notEqual: 'Email address*',
					email: true
				},
				sub_jobtitle: {
					minlength: 2
				},
				sub_company: {
					minlength: 2
				},
				sub_cat: {
					notEqual: 'null'
				}
			},
			messages: {
				sub_firstname: {
					required: "Please enter your first name",
					notEqual: "Please enter your first name",
					minlength: "Your name must consist of at least 2 characters"
				},	
				sub_surname: {
					required: "Please enter your surname",
					notEqual: "Please enter your surname",
					minlength: "Your name must consist of at least 2 characters"
				},			
				sub_email: {
					required: "Please enter a valid email address",
					notEqual: "Please enter a valid email address",
					email: "Please enter a valid email address"
				},
				sub_jobtitle: {
					minlength: "Your job title must consist of at least 2 characters"
				},
				sub_company: {
					minlength: "Your company name must consist of at least 2 characters"
				},
				sub_cat: {
					notEqual: "Please select a category"
				}
			}
		});
	
		
	/** Register form
	**************************/	
	
		/** Multi-select control
		**************************/		
		function insertNode(nodeVal, nodeText, control){				
			// test if node already exists
			var nodeExist = false;			
			$('#' +  + control + ' option').each(function(){
				if( nodeVal == $(this).val() ) nodeExist = true;
			});			
			// if node doesn't exist, add it			
			if ( nodeExist == false ) $('#' + control).append('<option value="'+nodeVal+'">'+nodeText+'</option>');	
		}
		
		function removeNode(nodeVal, nodeText, control){	
			$('form .multi .col_2 select option[value='+nodeVal+']').remove();
		}
		
		// add node options
		$('#putType').click(function(){
			$('#jobtype option:selected').each(function(){
				insertNode($(this).val(), $(this).text() , 'jobselect');			
			});
			return false;
		});
		
		// remove node options
		$('#removeType').click(function(){
			$('#jobtype option:selected').each(function(){
				removeNode($(this).val(), $(this).text(), 'jobselect');			
			});
			return false;
		});
		
			$('#putLocation').click(function(){
				$('#jobtypeLocation option:selected').each(function(){
					insertNode($(this).val(), $(this).text(), 'jobselectlocation');		
				});
				return false;
			});

			// remove node options
			$('#removeLocation').click(function(){
				$('#jobtypeLocation option:selected').each(function(){
					removeNode($(this).val(), $(this).text(), 'jobselectlocation');			
				});
				return false;
			});
		
	
	

});

