/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    script.js
    Scripts & jQuery goodness
    Created at: 2011-
    Created by: Adam Brewer for Outside Line
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
var cb = {};

/*
 * ---------------------------------------
 * Functions for flash background on Products page
 *
 */
function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function callToActionscript(flash, str) {
	getFlashMovie(flash).sendToActionscript(str);
}

function sendToJavaScript(val)
{
	document.getElementById('boxX').value = val;
}

$(function() {
	
	// VARS
	var productsList = $('#productsList');
	
	//$('#products').css({'z-index':'-1'})
	//$('#products').css({'display':'block', });

	


	/*
	 * --------------------------------------
	 * Decrease font-size is characters in form <input> exceeds a certian length
	 *
	 */
	var formInputs = $('#newsForm').find('input');
	var baseInputFontSize = formInputs.first().css('font-size');
	var charCount = 0;
	formInputs.keyup(function(e) {
		charCount = $(e.target).val().length;
		//console.log(typeof charCount);
		//console.log($(e.target).attr('name') + ': ', charCount);
		if (charCount <= 23) {
			$(e.target).css('font-size', baseInputFontSize);
		} else if (charCount > 23 && charCount <= 28) {
			$(e.target).css('font-size', '14px');
		} else if (charCount > 28 && charCount <= 33)  {
			$(e.target).css('font-size', '12px');
		} else {
			$(e.target).css('font-size', '10px');
		}
	})



	
	/*
	 * ---------------------------------------
	 * If JS is active in the browser
	 *
	 */
	if ($('#flash').length) {
		$('#flashFail').hide();
		var so = new SWFObject(cb.base_path+"assets/swf/as-js.swf", 'asjs', '100%', '100%', '10.0', "#000");
		so.addParam("wmode", "transparent");
		so.write("flash");
	}

	// hide the newsletter success message
	setTimeout(function() {
		$('#newsOverlay').fadeOut(800, function () {
			$(this).remove();
		});
	}, 4000);

	// fallback if js isn't enabled
	$('#products').css('position','absolute');
	$('#flash').show();

	$('.js-remove').remove();
	$('a[name^="!/"]').remove(); // remove all hash locations

	// Hide the cheese product images because they are hidden with .scrollable set to overflow:hidden
	// Here we grab the values of the position they should be set to in order to replace our placeholder with the correct values
	var cheeseImg = $('.cheeseImg').hide();

	// now create the image placeholder
	var imgPlaceholder = cheeseImg.first().clone().removeClass('cheeseImg').addClass('imgPlaceholder');
	imgPlaceholder.appendTo('#products').show();

	
	/*
	 * ---------------------------------------
	 * Special click events on the site
	 *
	 */
	// Show the social stuff on the home page when
	// clicking the "join us" nav item
	$('#joinUs').click(function(e) {
		e.preventDefault();
		$('#joinSocial').slideToggle(400, function() {
			// end of slide action
		});
		//return false;
	});

	// prevent default prev/next link action when
	// browsing between products
	$('.browse').live('click', function(e) {
		e.preventDefault();
		return false;
	});

	
	/*
	 * ---------------------------------------
	 * Scrollable setup stuff
	 *
	 */
	// Home page scrollable stuff
	var productImgsHome = $('#imgScroller').scrollable({
		circular: true,
		speed: 800,
		keyboard: false
	}).autoscroll({
		interval: 5000
	});
	var api2 = productImgsHome.scrollable();


	// init scrollable for the videos page
	$('#browsable').scrollable({
	
	});

	// setup ul.tabs to work as tabs for each div directly under div.panes
	$(".tabs").tabs(".panes > article");

	// initialize scrollable for products
	var root = $("#products .scrollable").scrollable({
		keyboard: true,
		speed: 600
	});

	// some variables that we need
	var api = root.scrollable({
	
	});

	/*
	 * ---------------------------------------
	 * Custom callbacks for the HOME SLIDER slider
	 *
	 */
	if ($('#imgScroller').length && api2) {
		api2.onBeforeSeek(function(event, i) {
			
			// only scroll if the scroller is hidden
			//if (!$('#imgScroller').is(':visible')) {
			//	return true;
			//}

			//$('#imgScroller').fadeOut(600, function () {
				//api2.seekTo(i);
				//console.log(i);
			//});
			//return false;
		}).onSeek(function(event, i) {
			if ($('html').hasClass('ie7')) {
				// ie7 doesn't handle the shadow on the cheese well when fading in/out
				//$('#imgScroller').show();
			} else {
				//$('#imgScroller').fadeIn(1000);
			}
		});
	}

	/*
	 * ---------------------------------------
	 * Custom callbacks before & after scrolling on the products page
	 *
	 */
	// callback before/after items have been scrolled
	var cheese = $('.cheese');
	var cheeseNum = 0; 
	if ($('#products .scrollable').length) {
		// remove the HTML background image
		document.body.style.backgroundImage = 'none';

		$('.tabs a').live('click', function(e) {
			var tabContentHeight = $(this).parents('.cheese').height();
			if (tabContentHeight) {
				if (tabContentHeight <= 350) tabContentHeight = 350;
				if (typeof updateScrollableHeight == 'function') updateScrollableHeight(tabContentHeight);
			}
		});


		// callback before the slider is triggered (jQuery Tools Scrollable plugin)
		api.onBeforeSeek(function(event, i) {			
			cheeseInView = i + 1;
			$('#products').fadeOut(100, function() {
				// find the location on the flash background			
				callToActionscript('asjs', cheeseInView);
			});

			// hash the location of the current product
			var hash = $(cheese[i]).attr('name');	
			if (typeof hash != 'undefined') {
				window.location.hash = '' + hash;
				
				// update the href's for the prev/next buttons on the products page.
				// this is so we can track in GA which cheeses have been viewed
				$('.prev').attr('href', 'products#' + $(cheese[i-1]).attr('name'));
				$('.next').attr('href', 'products#' + $(cheese[i+1]).attr('name'));
				
				// track the viewd cheeses on GA, if GA has loaded
				if (typeof _gaq != 'undefined') {
					_gaq.push(['_trackPageview', '/products#' + $(cheese[cheeseInView]).attr('name')]);
				} else {
					//console.log('Anlaytics not loaded. Cheese not tracked.');
				}
			}

			// adjust the height of the product window
			cheeseContentHeight = $(cheese[i]).height();
			if (cheeseContentHeight) {
				if (typeof updateScrollableHeight == 'function') updateScrollableHeight(cheeseContentHeight);
			}

			// remove the current placeholder image (replaced later)
			$('.imgPlaceholder').remove();

			// Hide the .browse nav links to prevent the script breaking during transition.
			// Not needed is #products is hidden during transition
			//$('.browse').hide();

		});

		api.onSeek(function(event, i) {
		
			$('#products').css({'left':'40%','z-index':'1000', visibility:'visible'}).delay(1000).fadeIn(800);

			// clone the product image and set as the image placeholder
			updatePlaceholder($(cheese[i]).find('img:first'));
			
			// Re-display all .browse nav buttons that should display.
			// Not needed is #products is hidden during transition
			//$('.browse').not('.disabled').show();

		});
	}

	
	/* 
	 * ---------------------------------------
	 * Load the cheese from the URI hash if it exists
	 *
	 */
	// function to test for flash loaded
	var hashOnload = window.location.hash;

	if (hashOnload.length && $('#products .scrollable').length) {
		// hide the products list
		//productsList().hide();
		
		var intervalCount = 0;
		var interval = setInterval(function() { 	
			intervalCount++;
			
			var flash = getFlashMovie('asjs');
			
			if (flash !== undefined && flash.sendToActionscript !== undefined) {
				// initiate the scroll-to from the integer in the hash location
				// console.log('swfobject loaded...selecting cheese from URI hash');
				clearInterval(interval);
				api.seekTo(parseInt(hashOnload.replace(/#/, ''), 10) - 1); // -1 important (ties in with flash zoomed-in product images)
			} else if (intervalCount >= 20) {
				// break the interval if a limit of 10 is reached
				// console.log('swfobject is taking too long to load.');
				clearInterval(interval);
			} else {
				// still in the loop, waiting for swfobject to be loaded
			}
		}, 100);
		
	} else {
		
		$('#products').css({'z-index':'-1'});
		

		// display the cheese products list
		var listWidth = productsList.show().width();
		// center the products list
		productsList.css({width: listWidth,	marginLeft: '-' + (listWidth / 2) + 'px', left: '50%'});
	}
	
	/* 
	 * ---------------------------------------
	 * Jump to a cheese if selected from the default products list
	 *
	 */
	productsList.find('a[href*="#"]') // find all hashed cheese url's
		.click(function(e) {
			e.preventDefault();
			var cheeseHash = this.hash;
			productsList.hide(200, function() {
				// -1 important (ties in with flash zoomed-in product images)
				// console.log(api);
				api.seekTo(parseInt(cheeseHash.replace(/#/, ''), 10) - 1);
			});
			return false;
		});


	$('#allProducts').click(function(e) {
		e.preventDefault();
		callToActionscript('asjs', 0);
		window.location.hash = '';
		// window.location.href = window.location.href.split('#')[0];
		// console.log(window.location);
		$('#products').css({visibility:'hidden'}, function(e) {
			
			productsList.css({width: listWidth,	marginLeft: '-' + (listWidth / 2) + 'px', left: '50%'});
		});
		var listWidth = productsList.fadeIn(400).width();
	});


	/*
	 * ---------------------------------------
	 * Functions
	 *
	 */
	// Check if a cheese product has an image and produces a clone to sit outside the "overflow:hidden" products box (as the placeholder image)
	var updatePlaceholder = function (cheeseObj) {
		var imageExists = false;
		if (typeof imgPlaceholder != 'undefined') {
		
			// only clone the cheese product in view and display the new placeholder if 
			// such an image exists for that cheese
			if (cheeseObj.length) {	
				var newImage = cheeseObj.clone().removeClass('cheeseImg').addClass('imgPlaceholder');
				imageExists = true;
				
				// only display the image if it has a valid src attribute
				if (imageExists) {
					newImage.appendTo($('#products')).fadeIn(400);
				}
			}
		}

	}

	// Adjusts the height of the product box according to the content.
	// CSS styles require the height to be fixed creating too much white-space, which is the reason for this work-around
	var updateScrollableHeight = function (height) {
		$('.scrollable').animate({
			height : height
		}, 400, function(){
			// finsihed animation
		});
	}


	

});



