/*
	Calabash - Site JavaScript
	Created: 29/03/2010 - @paulmsmith
*/

/* configuring the playing field
--------------------------------------------- */

	var $j = jQuery.noConflict();

	// handle firebug console issues
	var sitedebug = true;
	if (typeof console == "undefined") {
		var console = { log: function() {} };
	} 
	else if (!sitedebug || typeof console.log == "undefined") console.log = function() {};

/* airfront.co.uk js - ol
--------------------------------------------- */

	var site = {
		
		// site-wide constants
		constants : {
			flashLoading : '<div class="flash-loading"></div>',
			scanImage : '<div class="overlay overlay-scan"></div>',
			selectors : {
				scanImage : "scan-image",
				requiredClass : ".required",
				tabbedContent : "js-tabbed-content",
				tabs : "js-tabs",
				panes : "js-tab-pane",
				featuredItem : "featured-item" // contains featured content (generally the flash player)
			},
			sections : {
				currentSection : "not-set", // default
				home : "home",
				work: "work",
				about : "about",
				blog : "blog",
				services : "services"
			}
		},
		
		// this function shows the video player if the youtube API returns initial state var
		_showPlayer : function(state, id) {
			if(state == -1) {
				$j("div.flash-loading", "." + site.constants.selectors.featuredItem).remove();
			}
		},
		
		// return "current" section which is ID on bodyTag
		_getCurrentSection : function() {
			var currentSection = $j("body").attr("id");
			return currentSection;
		},
		
		// attach events to tab markup, etc
		_handleTabs: function() {
			_self = this;
			
			// find all tab sets - the tabs and the panels
			jTabbedContent = $j("." + _self.constants.selectors.tabbedContent);
			
			// for each set of tabs do the following
			jTabbedContent.each(function(index, elm){
				
				currentTabs = this;
				
				// on click of the tab
				$j("." + _self.constants.selectors.tabs + " li a").click(function(e){

						e.preventDefault();
						
						// hide all panes
						$j(elm).find("." + _self.constants.selectors.panes).hide();
						
						// grad href from tab anchor to be used as pointer to pane we'd like to show
						paneToShow = $j(this).attr("href");
						
						// remove active class from all tab buttons
						$j(elm).find("." + _self.constants.selectors.tabs  + " li a").removeClass("active");
						
						// add active class the tab button just clicked
						$j(this).addClass("active");
						
						// show the pane linked to by tab just clicked
						$j(paneToShow).show();

				});
				
				// here we are showing the first pane and setting the first tab to active
				$j("." + _self.constants.selectors.tabs  + " li a:first").addClass("active");

				$j("." + _self.constants.selectors.panes, elm).each(function(i){
					
					if(i == 0) {
						$j(this).css("display", "block");
					}
					
				});
				
			});

			
		},
		
		// grabs the video code from a YouTube URL. This might need work if they change the URL structure in future.
		_grabYouTubeCode : function(fullUrl) {
			var ytCode = fullUrl.substring(31,42);
			return ytCode;
		},
		
		// calabash embed video function. Uses swfObject and has a defaults object that can be overridden by passing object
		_embedVideo : function(passedArgsObj) {
			
			var self = this;

			/* defaults */
			settings = {
				align: "left",
				author: "",
				autoplay: false,
				bgcolor: null,
				color: "#dedb00",
				hd: false,
				width: 510,
				height: 355,
				image: false,
				path: "http://calabashfilms.com/script/",
				skin: "player/default.swf?nocache=" + new Date().getTime(),
				target : "videoPlayer",
				title: "",
				video: "gE1KGHUb9zw"
			};
			
			// $j("#" + settings.target).text("_");

			/* override the defaults if necessary */
			for (var argName in passedArgsObj) {
				settings[argName] = passedArgsObj[argName];
			}
			
			if(settings.autoplay == true) {
				// settings.skin = "player/autoplay.swf?nocache=" + new Date().getTime();
				settings.video += "&autoplay=1";
			}
			
			var id = settings.target + "swf";
			
			// jqTools flash embed plugin instead of nasty swfObject
			flashembed(settings.target,
				// flashEmbed Configuration Object
				{ 
					src: "http://www.youtube.com/v/" + settings.video,
					cachebusting : true,
					bgcolor: "#000000",
					width: settings.width,
					height: settings.height,
					wmode: "opaque",
					allowfullscreen: true,
					allowscriptaccess: "always",
					quality: "high",
					scale: "noscale",
					menu: "false",
					id: id,
					name: id
				},
				// flash vars 
				{
					align: settings.align,
					author: settings.author,
					color: settings.color,
					hd: settings.hd,
					id: id,
					image: settings.image,
					title: settings.title, 
					video: settings.video + "&ap=%2526fmt%3D18&showinfo=0&iv_load_policy=3&rel=0&fs=1"
				}
			);
			
			
			// $j("." + site.constants.selectors.featuredItem).append(site.constants.flashLoading);
			
		},
		
		// site-wide init function - all this to happen on each and every page of the site
		_init : function() {
			var self = this;
			
			// jQuery objects
			jScanImages = $j("." + self.constants.selectors.scanImage);
			jRequiredLabels = $j("span." + self.constants.selectors.requiredClass);
			
			// if there are "scan images" append the non-semantic div to overlay div
			if(jScanImages.length) {
				$j(self.constants.scanImage).appendTo(jScanImages);
			}
			
			// if there are any required spans for forms here, swap text to * for js enabled
			if(jRequiredLabels.length) {
				jRequiredLabels.text("*");
			}
			
			// find the current section based on body#
			var currentSection = self._getCurrentSection();		
			self.constants.sections.currentSection = currentSection;
			
			// if home fire the home init
			if (currentSection == self.constants.sections.home) {
				self.home._init();
			}
			
			// if blog fire the blog init
			if (currentSection == self.constants.sections.blog) {
				self.blog._init();
			}
			
			// if work fire the work init
			if (currentSection == self.constants.sections.work) {
				self.work._init();
			}

			// if work fire the work init
			if (currentSection == self.constants.sections.services) {
				self.services._init();
			}
			
		},
		
		// homepage specific js
		home : {
			showreelCode: "GHM4HkFUORg",
			showreelReplaced : false,
			selectors : {
				showreelContainer : "videoPlayer",
				showreelPlayButton : "overlay-play",
				showreelCTA : "showreel-cta",
				testimonials : "js-testimonials",
				colsToEqual : "col-equal",
				blogPost : "sample-blog-post"
			},
			
			_init : function() {
				var self = this; // the home object
				
				// instantiate some jQuery objects
				var jShowReel = $j("#" + self.selectors.showreelContainer);
				var jTestimonials = $j("." + self.selectors.testimonials);
				
				// if we find the showreel. add the button and fancy non-semantic elements.
				// attach the event to the play button;
				if(jShowReel.length) {	
					
					jShowReel.each(function(){
						$j(this).append(site.constants.scanImage + '<div class="overlay ' + self.selectors.showreelPlayButton + '"></div>');
						$j("." + self.selectors.showreelPlayButton, this).click(function(){
							
							self.showreelReplaced = true;
							console.log("clicky");
							
							site._embedVideo({ video: self.showreelCode, autoplay: true });
							
						});
					});
					
					// trigger the attached stuff for the play button
					$j("." + self.selectors.showreelCTA).click(function(e){
						// if we've not swapped out place-holder for the showreel lets do that!
						if (self.showreelReplaced == false) {
							$j("." + self.selectors.showreelPlayButton).trigger('click');
						// if we have then lets get the state of the player
						} else {
							if(getPlayerState() == 1) {
								pause();
							} else if (getPlayerState() == 2 || getPlayerState() == 0) {
								play();
							}
						}
						e.preventDefault();
					});
					
				} // if jShowReel
				
				// if testimonials exists run as carousel
				if(jTestimonials.length) {
					
					$j("." + self.selectors.testimonials).carousel({ loop: true });
					
				} // if jTestimonials
				
				$j("." + self.selectors.colsToEqual).equalHeights();
				$j("." + self.selectors.blogPost + " p").append("...");
				
			} // home init
		
		}, // home obj
		
		// about page specific js
		about : {
			_init : function() {
				var self = this; // the about object
				console.log("site.about._init() has fired!");
			}
		},
		
		// work page specific js
		work : {
			selectors : {
				workDescriptions : "js-work-desc",
				workThumbs : "js-work-thumbs",
				workThumbTitle : "work-thumb-title"
			},
			_init : function() {
				var self = this;
				
				var jWorkDescriptions = self.selectors.workDescriptions;
				var jWorkThumbs = self.selectors.workThumbs;
				
				if(jWorkDescriptions.length) {
					$j("." + self.selectors.workDescriptions).carousel({ loop: true, pagination: true });
				}
				
				if(jWorkThumbs.length) {
					$j("." + self.selectors.workThumbs).carousel({ loop: true, pagination: false });
				}
				
				// on click of each link within the PromoSelector carousel we trigger the corresponding pagination link within the featurePromo carousel
				$j("." + self.selectors.workThumbs + " li a").each(function(i){
					var that = this;
					
					var videoURL = $j(this).attr("href");
					// var ytCode = videoURL.substring(31,42);
					var ytCode = site._grabYouTubeCode(videoURL);
					
					// console.log(videoURL);
					// console.log(ytCode);
					
					$j(this).click(function(e){
						e.preventDefault();
						var ii = i + 1;
						$j("." + self.selectors.workDescriptions + " .carousel-pagination a:nth-child(" + ii + ")").trigger('click');
						site._embedVideo({ video: ytCode });
					});
					
					$j(this).hover(
						function () {
							$j("." + self.selectors.workThumbTitle, $j(this).parent()).fadeTo("fast", 0.80);
						  },
						  function () {
						    $j("." + self.selectors.workThumbTitle, $j(this).parent()).fadeOut();
						}
					);
					
					// here I'm grabbing the latest piece of work and embedding it.
					var LatestWork = $j("." + self.selectors.workThumbs + " li a").first().attr("href");
					site._embedVideo({ video: site._grabYouTubeCode(LatestWork) });
					
				});
				
				// console.log("site.work._init() has fired!");
			}
		},
		
		// services page specific js
		services : {
			_init : function () {
				var self = this;
				
				jTabbedContent = $j("." + site.constants.selectors.tabbedContent);
				// if tabs are on the page run tabs function
				if(jTabbedContent.length) {
					site._handleTabs();
				}
				
				// console.log("site.services._init() has fired!");
				
			}
		},
		
		// services page specific js
		blog : {
			selectors : {
				blogLandingEntry : "#blog .columnset-blog-l .col",
				blogLandingEntriesRowTop: "#blog .columnset-blog-l .col:nth-child(-n+5)"
			},
			_init : function () {
				var self = this;
				console.log("bloggggggg");
				// if find blog entries on landing page - remove the padding and top border from top row of entries
				jLandingEntriesTopRow = $j(self.selectors.blogLandingEntriesRowTop);
				if (jLandingEntriesTopRow.length) {
					jLandingEntriesTopRow.css({'padding-top' : '0px', 'border-top' : 'none'});
				}
				
			}
		}
		
	};
	
	// onDomReady
	$j(function() {
		var self = this;
		site._init();
	});