var ajaxRequests = [];
var isMobile = false;
$(document).ready(function(){
		
    if($('#clientbox > div').length > 0){
			//Select Random Testimonial to animate
			var maxRand = $('#clientbox > div').length;
			var randNum = Math.floor(Math.random()*maxRand);
			$('#clientbox > div').hide();
			$('#clientbox > div').eq(randNum).show();
      var charLength = $('#clientbox > div:visible .testimonial').text().length;
      var readTime = charLength * 40;
      setTimeout(function(){ animateTestimonials(); }, readTime);
    }
		
		if($('#promocontainer').length > 0){
			initLoader();
			if(isMobile){
				$('#promocontainer').bind('swipeleft', function(){ changePromo('mobileLeft') });
				$('#promocontainer').bind('swiperight', function(){ changePromo('mobileRight') });
			}
		}
		
		$('#subnav a').each(function(){
				bindTooltip($(this));											 
		});		
		
		
		
});

function bindTooltip(aObj){

	var title = aObj.attr('title');
	aObj.data('title', title).removeAttr('title');
	 
	aObj.hover(function(){
			toggleTooltip(true, $(this));	
	}, function(){
			toggleTooltip(false, $(this));
	});
	
}

function toggleTooltip(active, aObj){
	
	var tempId = aObj.parent().index();
	var tempOffset = aObj.offset();
	var aTop = tempOffset.top;
	var aLeft = tempOffset.left;
	var aWidth = aObj.width();
	var tempTop = aTop + 40;
	
	
	if(active){

		var tempText = aObj.data('title');
		if($('#tooltip_'+tempId).length == 0){
			
		  var tempClass = 'subnavtooltip';
		
			var divTooltip = $('<div/>', {
												 'id': 'tooltip_'+tempId,
												 'class': 'tooltip '+tempClass
												 })
												 .text(tempText)
												 .append('<div class="tooltip_pointer tooltip_center"></div>');
			
			$('#content').append(divTooltip);
			
			var toolLeft = (aLeft + (aWidth/2) - (divTooltip.outerWidth() / 2)); 
			
			divTooltip.css({top: tempTop, left: toolLeft}).show();
			
		}
	
		//Animate In
		if(parseInt($('#tooltip_'+tempId).css('top')) == tempTop){
			$('#tooltip_'+tempId).css({top: tempTop + 10, opacity: 0, left: tempLeft});
		}
		
		var currLeft = parseInt($('#tooltip_'+tempId).css('left'));
		if(currLeft < 0){
			var tempLeft = currLeft + 9999;
			$('#tooltip_'+tempId).css({left: tempLeft});
		}
		
		if($.browser.msie && parseInt($.browser.version) < 9){
			$('#tooltip_'+tempId).css({top: tempTop, opacity: 1});
			$('#tooltip_'+tempId).find('div').show();
		}else{
			$('#tooltip_'+tempId).stop().animate({top: tempTop, opacity: 1}, 500);
		}
		
	
	}else{
		
		var currLeft = parseInt($('#tooltip_'+tempId).css('left'));
		var tempLeft = currLeft - 9999;
		//Animate Out
		if($.browser.msie && parseInt($.browser.version) < 9){
			$('#tooltip_'+tempId).css({top: tempTop, left: tempLeft, opacity: 0});
			$('#tooltip_'+tempId).find('div').hide();
		}else{
			$('#tooltip_'+tempId).stop().animate({top: tempTop + 10, opacity: 0}, 500, function(){ $('#tooltip_'+tempId).css({left: tempLeft})});
		}
		
		
	}
	
}

function animateTestimonials(){
	
	var maxLength = $('#clientbox > div').length;
	var charLength = $('#clientbox > div:visible .testimonial').text().length;
	var animTime = 750;
	var animOff = 250;
	var readTime = charLength * 40;
	
	//Fade out current item
	
	var currItem = $('#clientbox > div:visible');
	var currId = currItem.attr('id').split('_');
	var currNum = currId[1];
	
	$('#clientbox > div:visible .client-logo').delay(animTime-animOff).fadeTo(animTime-animOff, 0);
	$('#clientbox > div:visible .testimonial').fadeTo(animTime, 0);

  //Fade in next item
	
	var nextNum = (currNum == maxLength-1)? 0 : parseInt(currNum) + 1;
	var nextItem = $('#clientitem_'+nextNum);

	$('#clientitem_'+nextNum+' > .client-logo').hide();
	$('#clientitem_'+nextNum+' > .testimonial').hide();
	
	setTimeout( function() { 

	 currItem.hide();
	 $('#clientitem_'+currNum+' .client-logo').stop().removeAttr('style');
	 $('#clientitem_'+currNum+' .testimonial').stop().removeAttr('style');
	 
	 nextItem.show();
	 $('#clientitem_'+nextNum+' > .client-logo').delay(animTime-animOff).fadeIn(animTime-animOff);
	 $('#clientitem_'+nextNum+' > .testimonial').fadeIn(animTime);
	 
	}, animTime+animOff+100);
	
	setTimeout(function(){ animateTestimonials(); }, readTime);
	
}

function toggleBox(boxType, refObj){
	
	var boxObj = $('#'+boxType+'box');
	
	if(boxObj){
		
		var fadeTime = 650;
		var boxMask = $('#boxmask');
		
		if(boxObj.is(':visible')){
			
			boxObj.fadeOut(fadeTime)
			boxMask.delay(fadeTime / 2).fadeOut(fadeTime);
			
		}else{
			
			if(boxType == 'contact'){
				
				var topic = 0;
				
				if(refObj !== undefined){
					var tempVal = refObj.attr('id').split('icon');
					var topic = tempVal[1];
				}
				
				$('#contactname').val('');
				$('#contactemail').val('');
				$('#contacttopic').val(tempVal);
				$('#contactmessage').val('');
				$('#contactfeedback').hide();
			}
			
			boxMask.fadeIn(fadeTime);
			boxObj.delay(fadeTime / 2).fadeIn(fadeTime);
			
		}
		
	}
	
}


function sendMessage(){
	
	var formData = $('#contactfrm').serializeJSON();
	
	if($.inArray('sendMessage', ajaxRequests) < 0){
	
		var errorText = '';
		//if($.trim(formData['contactemail']).length == 0) errorText += 'Contact Email is required<br/>';
		//if($.trim(formData['contactmessage']).length == 0) errorText += 'Contact Message is required';
		
		if(errorText.length > 0){
			
			$('#contactfeedback').html(errorText).addClass('errorText').removeClass('successText').show();
			
		}else{
		
			ajaxRequests.push('sendMessage');
			
			//Ajax request to send data
			$.ajax({
			 type: "post",
			 url: templateDir+"/scripts/mailscript.php",
			 data: 'jsonData='+encodeURIComponent(JSON.stringify(formData)),
			 success: function(){			  
				 $('#contactfeedback').html('Thank you for contacting us.').addClass('successText').removeClass('errorText').show();	 
				 ajaxRequests.splice(ajaxRequests.indexOf('sendMessage'), 1);
			 },
			 error: function(){
				 $('#contactfeedback').html('Error sending message. Please try again.').addClass('errorText').removeClass('successText').show();	 
			 }
		 });
			
		}
		
	}
	
}

(function( $ ){
$.fn.serializeJSON=function() {
var json = {};
jQuery.map($(this).serializeArray(), function(n, i){
json[n['name']] = n['value'];
});
return json;
};
})( jQuery );

var promoDetails = [{'type': 'video', 'src' : 'telly', 'text' : '2011 Telly Awards Sizzler'},
											{'type': 'video', 'src' : 'fifa', 'text' : '"Edmonton is Festival City" - RED The Agency'},
											{'type': 'video', 'src' : 'bonton', 'text' : 'Ingredients for the Heart & Soul'},
											{'type': 'video', 'src' : 'education_math', 'text' : 'Math: It\'s everywhere'},
											{'type': 'video', 'src' : 'pab', 'text' : 'Alberta. Tell it like it is - Water Quality'}];
	


	function initLoader(){
			
			var images = new Array();
			var loadedCount = 0;
			
			for(x in promoDetails){
				images.push(templateDir+'/images/promo/'+x+'.jpg');
			}
			
			for(x in images){
				
				var img = new Image();
				
				$(img).load(function () {
						loadedCount++;
						if(loadedCount == images.length){
							initPlayer();
						}
				}).attr('src', images[x]);
				
			}
					
	}
	
	function initJWPlayer(){
		jwplayer("jwcontainer").setup({
			height: 360,
			width: 640,
			mute: "false",
			skin: templateDir+'/player/dyna/dyna.zip',
			modes: [
						{type: 'html5'},
						{type: 'flash', src: templateDir+'/scripts/player.swf'},
						{type: 'download'}
				]
			});
		
	}
	
	function initPlayer(){
		
		initJWPlayer();
		
		for(x in promoDetails){
			var imgPath = templateDir+'/images/promo/'+x+'.jpg';
			var Ptype = promoDetails[x].type;
			var Ptext = promoDetails[x].text;
			
			var Pclass = '';
			if(x == 0){ Pclass = 'item_selected'; }
			
			//Create Promo Area		
				var Phref = (Ptype == 'url')? promoDetails[x].src : 'javascript:void(0);';
				
				var promoLink = $('<a />', {
													'id': 'promo_'+x,
													'href': Phref,
													'html': '<img src='+imgPath+' />',
													'class': Pclass
													}).hide();

				if(Ptype == 'video'){
					
					var playicon = $('<div />', {
														 'class': 'playicon'
														});
					
					promoLink.append(playicon);
					
					promoLink.click(function(){ startVideo(); });
				}
			
			promoLink.appendTo('#videopromo');
			
			
			//Create Promo List
			var itemDiv = $('<div />', {
												'class': 'item '+Pclass,
												'id': 'item_'+x
											});
			
			var itemActionStatus = (Pclass.length > 0)? 'item_action_off' : 'item_action_on';
			var imgData = {width: imgDataDef.minWidth, height: imgDataDef.minHeight, bottom: imgDataDef.minBottom, opacity: imgDataDef.minOpac};
			var pHeadDisplay = 'display: none;';
			if(Pclass.length > 0){
				var imgData = {width: imgDataDef.maxWidth, height: imgDataDef.maxHeight, bottom: imgDataDef.maxBottom, opacity: imgDataDef.maxOpac};
				pHeadDisplay = '';
			}
			
			var itemImg = $('<img />', {
												'src': imgPath,
												'class': itemActionStatus
											}).css(imgData).click(function(){ changePromo($(this)) });
			
			itemDiv.append(itemImg);
			
			var promoHead = $('<div />', {
													'class': 'videohead',
													'style': pHeadDisplay
												});
				
			itemDiv.append(promoHead);
			
			var promoText = $('<p />',{
													'class': 'videotext',
													'style': pHeadDisplay
												}).text(Ptext);
			
			itemDiv.append(promoText);
			
			$('#scroll_container').append(itemDiv);
					
		}
		
		
	}
	
	function startVideo(){
		
		var tempId = $('.item_selected').attr('id');
		var promoId = tempId.split('_');
		promoId = promoId[1];
		
		var videoId = promoDetails[promoId].src;
		
		jwplayer().load({levels: [
			 { file: 'video/'+videoId+'.mp4' },
			 { file: 'video/'+videoId+'.webm' }
		]});
		
		setTimeout(function(){jwplayer().play();}, 1);
		$('#videoplayer').show();
		
	}
	
	var imgDataDef = {maxHeight: 360, maxWidth: 640, maxBottom: 5, maxOpac: 1,
										minHeight: 89, minWidth: 156, minBottom: 16, minOpac: .7};
	function changePromo(currObj){
		
		var scrollCont = $('#scroll_container');
		var videoPlayer = $('#videoplayer');

		if(currObj == 'mobileLeft'){
			var itemSelId = $('.item_selected').attr('id').split('_');
			var nextItemId = parseInt(itemSelId[1]) + 1;
			if($('#item_'+nextItemId).length > 0) currObj = $('#item_'+nextItemId+' img');
		}else if(currObj == 'mobileRight'){
			var itemSelId = $('.item_selected').attr('id').split('_');
			var prevItemId = parseInt(itemSelId[1]) - 1;
			if($('#item_'+prevItemId).length > 0) currObj = $('#item_'+prevItemId+' img');
		}
		
		if(!scrollCont.is(":animated") && currObj.parent().hasClass('item_selected')){
			
			//They are playing the selected item
			startVideo();
			
		}else{
			
			//They are switching items
			jwplayer().stop();
			videoPlayer.hide();
			
			var currSelected = $('.item_selected');
			var currSelectedImg = $('.item_selected img');
			
			var tempArr = currSelected.attr('id').split('_');
			var currId = parseInt(tempArr[1]);
			
			var tempArr = currObj.parent().attr('id').split('_');
			var selId = parseInt(tempArr[1]);
			
			var dir = (selId > currId)? 'next' : 'prev';
			
			var nextId = (dir == 'next')? currId + 1 : currId - 1;
		
			var tarItem = $('#item_'+nextId);
			var tarItemImg = $('#item_'+nextId+' img');
			
			if(tarItem.length > 0 && !scrollCont.is(":animated") && currObj.hasClass('item_action_on')){
			
			var animTime = 1000;
			
			//Animate images & containers
			currSelected.animate({width: imgDataDef.minWidth}, animTime, function(){ currSelected.removeClass('item_selected');});
			currSelectedImg.animate({width: imgDataDef.minWidth, height: imgDataDef.minHeight, bottom: imgDataDef.minBottom, opacity: imgDataDef.minOpac}, animTime);
			currSelected.find('.videohead').fadeOut(100);
			currSelected.find('.videotext').fadeOut(100);
			tarItem.animate({width: imgDataDef.maxWidth}, animTime, function(){ tarItem.addClass('item_selected')});
			tarItemImg.animate({width: imgDataDef.maxWidth, height: imgDataDef.maxHeight, bottom: imgDataDef.maxBottom, opacity: imgDataDef.maxOpac}, animTime);
			tarItem.find('.videohead').delay(animTime-100).fadeIn(250);
			tarItem.find('.videotext').delay(animTime-100).fadeIn(250);
			
			//Animate Appearing/Dissapearing items
			if(dir == 'next'){
				var tempHide = $('#item_'+(currId-1)+' img');
				var tempShow = $('#item_'+(selId+1)+' img');
			}else{
				var tempHide = $('#item_'+(currId+1)+' img');
				var tempShow = $('#item_'+(selId-1)+' img'); 
			}
			
			tempHide.animate({bottom: imgDataDef.minBottom+60, opacity: .3}, animTime);
			tempShow.animate({bottom: imgDataDef.minBottom, opacity: imgDataDef.minOpac}, animTime);
			
			//Move the container
			var currLeft = parseInt(scrollCont.css('left'));
			var animAmount = (dir == 'next')? currLeft - 170  : currLeft + 170;
			var animDir = {left: animAmount};
			
			scrollCont.animate(animDir, animTime, function(){
																						$('.item_action_off').removeClass('item_action_off').addClass('item_action_on');
																						tarItemImg.removeClass('item_action_on').addClass('item_action_off');
																				} );
			}
			
		}
				
	}
	
function initPortfolio(){
	
	initJWPlayer();
	
	$('#portfolio_items a').each(function(){
			
			$(this).data('name', $(this).attr('name')).removeAttr('name');
			$(this).data('title', $(this).attr('title')).removeAttr('title');
			
			$(this).hover(function(){
				animatePortfolio($(this), true);
			}, function(){
				animatePortfolio($(this), false);
			});
			
			$(this).click(function(){ playPortfolio($(this)) });
			
	});
	
}
	
function animatePortfolio(aObj, active){
	
	var tempId = aObj.attr('id');
	var tempOffset = aObj.offset();
	var aTop = tempOffset.top;
	var aLeft = tempOffset.left;
	var aWidth = aObj.width();
	var aHeight = aObj.height();
	var tooltipObj = $('#tooltip_'+tempId);
	var animDir = 10;
	
	if(tooltipObj.length > 0){
		if(tooltipObj.find('.tooltip_pointer').length > 0){
			var tempTop = aTop + aHeight + 15;
		}else{
			var tempTop = aTop - tooltipObj.outerHeight() - 15;
			animDir = -10;
		}
	}

	if(active){

		if(tooltipObj.length == 0){
			
			var tempHeader = aObj.data('name');
			var tempCat = aObj.data('category');
		  var tempClass = 'portfoliotooltip';
		
			var tempOrder = aObj.index();
			var tooltipClass = 'tooptip_pointer_down';
			
			if(tempOrder < 4) tooltipClass = 'tooltip_pointer';
			
			if($.inArray(tempOrder, [0, 4, 8]) >= 0){
				tooltipClass += ' tooltip_left';
			}else if($.inArray(tempOrder, [3, 7, 11]) >= 0){
				tooltipClass += ' tooltip_right';														 
		  }else{
			  tooltipClass += ' tooltip_center';
		  }
			
			var divTooltipPointer = $('<div />', {
																'class': tooltipClass
															});
		
			var divTooltipCat = $('<div />').append('<em>'+tempCat+'</em>');
		
			var divTooltip = $('<div/>', {
												 'id': 'tooltip_'+tempId,
												 'class': 'tooltip '+tempClass
												 })
												 .html(tempHeader)
												 .append(divTooltipCat)
												 .append(divTooltipPointer);
			
			$('#content').append(divTooltip);
			
			var toolTop = 0;
			var toolLeft = 0;
			
			if(divTooltipPointer.hasClass('tooltip_pointer')){
				toolTop = aTop + aHeight + 15;
			}else{
				toolTop = aTop - divTooltip.outerHeight() - 15;
				animDir = -10;
			}
			
			if(divTooltipPointer.hasClass('tooltip_left')){
			  toolLeft = aLeft;			
			}else if(divTooltipPointer.hasClass('tooltip_right')){
				toolLeft = (aLeft + aWidth) - divTooltip.outerWidth();
			}else{
				toolLeft = (aLeft + (aWidth/2) - (divTooltip.outerWidth() / 2)); 					
			}
			
			divTooltip.css({top: toolTop, left: toolLeft});
			
			tempTop = toolTop;
			
		}
	
		var tooltipObj = $('#tooltip_'+tempId);
	
		//Animate In
		if(parseInt(tooltipObj.css('top')) == tempTop){
			tooltipObj.css({top: tempTop + animDir, opacity: 0, left: tempLeft});
		}
		
		var currLeft = parseInt(tooltipObj.css('left'));
		if(currLeft < 0){
			var tempLeft = currLeft + 9999;
			tooltipObj.css({left: tempLeft});
		}
		
		if($.browser.msie && parseInt($.browser.version) < 9){
			tooltipObj.css({top: tempTop, opacity: 1});
			tooltipObj.find('div').show();
		}else{
			tooltipObj.stop().animate({top: tempTop, opacity: 1}, 500);
		}
		
	
		$('.imgbw').not('#'+tempId+' .imgbw').stop().fadeTo(500, 1);
	
	}else{
		
		var currLeft = parseInt(tooltipObj.css('left'));
		var tempLeft = currLeft - 9999;
		//Animate Out
		
		if($.browser.msie && parseInt($.browser.version) < 9){
			tooltipObj.css({top: tempTop, left: tempLeft, opacity: 0});
			tooltipObj.find('div').hide();
		}else{
			tooltipObj.stop().animate({top: tempTop + animDir, opacity: 0}, 500, function(){tooltipObj.css({left: tempLeft})});
		}
		
		
		$('.imgbw').stop().fadeTo(500, 0);
		
	}
	
}
	
function playPortfolio(aObj){
	
	var videoId = aObj.attr('id');
	
	$('.tooltip').hide();
	$('#portfoliobox_text').html('');
	var boxText = aObj.data('name') + '<strong>' + aObj.data('client')+ '</strong><br/><em>' + aObj.data('category') + '</em><p>'+aObj.data('title')+'</p>';
	$('#portfoliobox_text').html(boxText);
	
	if($.browser.msie && parseInt($.browser.version) < 9){
		$('#portfoliobox').show();
	}else{
		$('#portfoliobox').fadeIn(500);
	}
	
	jwplayer().load({levels: [
		 { file: '/video/'+videoId+'.mp4' },
		 { file: '/video/'+videoId+'.webm' }
	]});
		
	setTimeout(function(){jwplayer().play();}, 650);

}

function stopPortfolio(){
	
	if($.browser.msie && parseInt($.browser.version) < 9){
		$('#portfoliobox').hide();
	}else{
		$('#portfoliobox').fadeOut(500);
	}
	
	$('.tooltip').show();
	jwplayer().stop();	
	
}

function getDirections(directionType){
	
	var locationObj = $('#location_'+directionType);
	var contactLnk = $('#contact_section_'+directionType+' .contact_dirlink');
	var contactHeader = $('#contact_section_'+directionType+' h1');
	
	if(!locationObj.is(':animated')){
	
		if(parseInt(locationObj.css('left')) == 0){
			locationObj.animate({left: -767}, 1000);
			contactHeader.animate({'margin-bottom': 20}, 1000);
			contactLnk.delay(500).fadeTo(500, 1);
		}else{
			locationObj.animate({left: 0}, 1000);
			contactHeader.animate({'margin-bottom': 280}, 1000);
			contactLnk.fadeTo(500, 0);
		}
	
	}
	
}
	
