"use strict";

/* modernizr-test.js
 * Daniel Ott
 * 3 March 2011
 * Custom Tests using Modernizr's addTest API
 */

/* iOS
 * There may be times when we need a quick way to reference whether iOS is in play or not.
 * While a primative means, will be helpful for that.
 */
Modernizr.addTest('ipad', function () {
  return !!navigator.userAgent.match(/iPad/i);
});

Modernizr.addTest('iphone', function () {
  return !!navigator.userAgent.match(/iPhone/i);
});

Modernizr.addTest('ipod', function () {
  return !!navigator.userAgent.match(/iPod/i);
});

Modernizr.addTest('appleios', function () {
  return (Modernizr.ipad || Modernizr.ipod || Modernizr.iphone);
});

/* CSS position:fixed
 * Not supported in older IE browsers, nor on Apple's iOS devices.
 * Actually the token example on the Modernizr docs. http://www.modernizr.com/docs/
 */
Modernizr.addTest('positionfixed', function () {
    var test    = document.createElement('div'),
        control = test.cloneNode(false),
        fake = false,
        root = document.body || (function () {
            fake = true;
            return document.documentElement.appendChild(document.createElement('body'));
        }());

    var oldCssText = root.style.cssText;
    root.style.cssText = 'padding:0;margin:0';
    test.style.cssText = 'position:fixed;top:42px'; 
    root.appendChild(test);
    root.appendChild(control);
    
    var ret = test.offsetTop !== control.offsetTop;

    root.removeChild(test);
    root.removeChild(control);
    root.style.cssText = oldCssText;
    
    if (fake) {
        document.documentElement.removeChild(root);
    }
    
    /* Uh-oh. iOS would return a false positive here.
     * If it's about to return true, we'll explicitly test for known iOS User Agent strings.
     * "UA Sniffing is bad practice" you say. Agreeable, but sadly this feature has made it to
     * Modernizr's list of undectables, so we're reduced to having to use this. */
    return ret && !Modernizr.appleios;
});





/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {
    
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
        
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/*
 * touchSwipe - jQuery Plugin
 * http://plugins.jquery.com/project/touchSwipe
 * http://labs.skinkers.com/touchSwipe/
 *
 * Copyright (c) 2010 Matt Bryson (www.skinkers.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * $version: 1.2.5
 *
 * Changelog
 * $Date: 2010-12-12 (Wed, 12 Dec 2010) $
 * $version: 1.0.0 
 * $version: 1.0.1 - removed multibyte comments
 *
 * $Date: 2011-21-02 (Mon, 21 Feb 2011) $
 * $version: 1.1.0 	- added allowPageScroll property to allow swiping and scrolling of page
 *					- changed handler signatures so one handler can be used for multiple events
 * $Date: 2011-23-02 (Wed, 23 Feb 2011) $
 * $version: 1.2.0 	- added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler.
 *					- If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object.
 * $version: 1.2.1 	- removed console log!
 *
 * $version: 1.2.2 	- Fixed bug where scope was not preserved in callback methods. 
 *
 * $Date: 2011-28-04 (Thurs, 28 April 2011) $
 * $version: 1.2.4 	- Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring.
 *
 * $Date: 2011-27-09 (Tues, 27 September 2011) $
 * $version: 1.2.5 	- Added support for testing swipes with mouse on desktop browser (thanks to https://github.com/joelhy)

 * A jQuery plugin to capture left, right, up and down swipes on touch devices.
 * You can capture 2 finger or 1 finger swipes, set the threshold and define either a catch all handler, or individual direction handlers.
 * Options:
 * 		swipe 		Function 	A catch all handler that is triggered for all swipe directions. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeLeft	Function 	A handler that is triggered for "left" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeRight	Function 	A handler that is triggered for "right" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeUp		Function 	A handler that is triggered for "up" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeDown	Function 	A handler that is triggered for "down" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 *		swipeStatus Function 	A handler triggered for every phase of the swipe. Handler is passed 4 arguments: event : The original event object, phase:The current swipe face, either "start?, "move?, "end? or "cancel?. direction : The swipe direction, either "up?, "down?, "left " or "right?.distance : The distance of the swipe.
 *		click		Function	A handler triggered when a user just clicks on the item, rather than swipes it. If they do not move, click is triggered, if they do move, it is not.
 *
 * 		fingers 	int 		Default 1. 	The number of fingers to trigger the swipe, 1 or 2.
 * 		threshold 	int  		Default 75.	The number of pixels that the user must move their finger by before it is considered a swipe.
 *		triggerOnTouchEnd Boolean Default true If true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
 *		allowPageScroll String Default "auto". How the browser handles page scrolls when the user is swiping on a touchSwipe object. 
 *										"auto" : all undefined swipes will cause the page to scroll in that direction.
 *										"none" : the page will not scroll when user swipes.
 *										"horizontal" : will force page to scroll on horizontal swipes.
 *										"vertical" : will force page to scroll on vertical swipes.
 *
 * This jQuery plugin will only run on devices running Mobile Webkit based browsers (iOS 2.0+, android 2.2+)
 */
(function($) 
{
	
	
	
	$.fn.swipe = function(options) 
	{
		if (!this) return false;
		
		// Default thresholds & swipe functions
		var defaults = {
					
			fingers 		: 1,								// int - The number of fingers to trigger the swipe, 1 or 2. Default is 1.
			threshold 		: 75,								// int - The number of pixels that the user must move their finger by before it is considered a swipe. Default is 75.
			
			swipe 			: null,		// Function - A catch all handler that is triggered for all swipe directions. Accepts 2 arguments, the original event object and the direction of the swipe : "left", "right", "up", "down".
			swipeLeft		: null,		// Function - A handler that is triggered for "left" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeRight		: null,		// Function - A handler that is triggered for "right" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeUp			: null,		// Function - A handler that is triggered for "up" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeDown		: null,		// Function - A handler that is triggered for "down" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeStatus		: null,		// Function - A handler triggered for every phase of the swipe. Handler is passed 4 arguments: event : The original event object, phase:The current swipe face, either "start?, "move?, "end? or "cancel?. direction : The swipe direction, either "up?, "down?, "left " or "right?.distance : The distance of the swipe.
			click			: null,		// Function	- A handler triggered when a user just clicks on the item, rather than swipes it. If they do not move, click is triggered, if they do move, it is not.
			
			triggerOnTouchEnd : true,	// Boolean, if true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
			allowPageScroll : "auto" 	/* How the browser handles page scrolls when the user is swiping on a touchSwipe object. 
											"auto" : all undefined swipes will cause the page to scroll in that direction.
 											"none" : the page will not scroll when user swipes.
 											"horizontal" : will force page to scroll on horizontal swipes.
 											"vertical" : will force page to scroll on vertical swipes.
										*/
		};
		
		
		//Constants
		var LEFT = "left";
		var RIGHT = "right";
		var UP = "up";
		var DOWN = "down";
		var NONE = "none";
		var HORIZONTAL = "horizontal";
		var VERTICAL = "vertical";
		var AUTO = "auto";
		
		var PHASE_START="start";
		var PHASE_MOVE="move";
		var PHASE_END="end";
		var PHASE_CANCEL="cancel";
		
	    var hasTouch = 'ontouchstart' in window,
        START_EV = hasTouch ? 'touchstart' : 'mousedown',
        MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
        END_EV = hasTouch ? 'touchend' : 'mouseup',
        CANCEL_EV = 'touchcancel';
		
		var phase="start";
		
		if (options.allowPageScroll==undefined && (options.swipe!=undefined || options.swipeStatus!=undefined))
			options.allowPageScroll=NONE;
		
		if (options)
			$.extend(defaults, options);
		
		var distance,direction; /* ADDED FOR use strict mode fixing*/
		/**
		 * Setup each object to detect swipe gestures
		 */
		return this.each(function() 
		{
            var that = this;
			var $this = $(this);
			
			var triggerElementID = null; 	// this variable is used to identity the triggering element
			var fingerCount = 0;			// the current number of fingers being used.	
			
			//track mouse points / delta
			var start={x:0, y:0};
			var end={x:0, y:0};
			var delta={x:0, y:0};
			
			
			/**
			* Event handler for a touch start event. 
			* Stops the default click event from triggering and stores where we touched
			*/
			function touchStart(event) 
			{
                var evt = hasTouch ? event.touches[0] : event; 
				phase = PHASE_START;
		
                if (hasTouch) {
                    // get the total number of fingers touching the screen
                    fingerCount = event.touches.length;
                }
				
				//clear vars..
				distance=0;
				direction=null;
				
				// check the number of fingers is what we are looking for
				if (fingerCount == defaults.fingers || !hasTouch) 
				{
					// get the coordinates of the touch
					start.x = end.x = evt.pageX;
					start.y = end.y = evt.pageY;
					
					if (defaults.swipeStatus)
						triggerHandler(event, phase);
				} 
				else 
				{
					//touch with more/less than the fingers we are looking for
					touchCancel(event);
				}

				that.addEventListener(MOVE_EV, touchMove, false);
				that.addEventListener(END_EV, touchEnd, false);
			}

			/**
			* Event handler for a touch move event. 
			* If we change fingers during move, then cancel the event
			*/
			function touchMove(event) 
			{
				if (phase == PHASE_END || phase == PHASE_CANCEL)
					return;
                
                var evt = hasTouch ? event.touches[0] : event; 
				
				end.x = evt.pageX;
				end.y = evt.pageY;
					
				direction = caluculateDirection();
                if (hasTouch) {
                    fingerCount = event.touches.length;
                }
				
				phase = PHASE_MOVE
				
				//Check if we need to prevent default evnet (page scroll) or not
				validateDefaultEvent(event, direction);
		
				if ( fingerCount == defaults.fingers || !hasTouch) 
				{
					distance = caluculateDistance();
					
					if (defaults.swipeStatus)
						triggerHandler(event, phase, direction, distance);
					
					//If we trigger whilst dragging, not on touch end, then calculate now...
					if (!defaults.triggerOnTouchEnd)
					{
						// if the user swiped more than the minimum length, perform the appropriate action
						if ( distance >= defaults.threshold ) 
						{
							phase = PHASE_END;
							triggerHandler(event, phase);
							touchCancel(event); // reset the variables
						}
					}
				} 
				else 
				{
					phase = PHASE_CANCEL;
					triggerHandler(event, phase); 
					touchCancel(event);
				}
			}
			
			/**
			* Event handler for a touch end event. 
			* Calculate the direction and trigger events
			*/
			function touchEnd(event) 
			{
				event.preventDefault();
				
				distance = caluculateDistance();
				direction = caluculateDirection();
						
				if (defaults.triggerOnTouchEnd)
				{
					phase = PHASE_END;
					// check to see if more than one finger was used and that there is an ending coordinate
					if ( (fingerCount == defaults.fingers  || !hasTouch) && end.x != 0 ) 
					{
						// if the user swiped more than the minimum length, perform the appropriate action
						if ( distance >= defaults.threshold ) 
						{
							triggerHandler(event, phase);
							touchCancel(event); // reset the variables
						} 
						else 
						{
							phase = PHASE_CANCEL;
							triggerHandler(event, phase); 
							touchCancel(event);
						}	
					} 
					else 
					{
						phase = PHASE_CANCEL;
						triggerHandler(event, phase); 
						touchCancel(event);
					}
				}
				else if (phase == PHASE_MOVE)
				{
					phase = PHASE_CANCEL;
					triggerHandler(event, phase); 
					touchCancel(event);
				}
				that.removeEventListener(MOVE_EV, touchMove, false);
				that.removeEventListener(END_EV, touchEnd, false);
			}
			
			/**
			* Event handler for a touch cancel event. 
			* Clears current vars
			*/
			function touchCancel(event) 
			{
				// reset the variables back to default values
				fingerCount = 0;
				
				start.x = 0;
				start.y = 0;
				end.x = 0;
				end.y = 0;
				delta.x = 0;
				delta.y = 0;
			}
			
			
			/**
			* Trigger the relevant event handler
			* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
			*/
			function triggerHandler(event, phase) 
			{
				//update status
				if (defaults.swipeStatus)
					defaults.swipeStatus.call($this,event, phase, direction || null, distance || 0);
				
				
				if (phase == PHASE_CANCEL)
				{
					if (defaults.click && (fingerCount==1 || !hasTouch) && (isNaN(distance) || distance==0))
						defaults.click.call($this,event, event.target);
				}
				
				if (phase == PHASE_END)
				{
					//trigger catch all event handler
					if (defaults.swipe)
				{
						
						defaults.swipe.call($this,event, direction, distance);
						
				}
					//trigger direction specific event handlers	
					switch(direction)
					{
						case LEFT :
							if (defaults.swipeLeft)
								defaults.swipeLeft.call($this,event, direction, distance);
							break;
						
						case RIGHT :
							if (defaults.swipeRight)
								defaults.swipeRight.call($this,event, direction, distance);
							break;

						case UP :
							if (defaults.swipeUp)
								defaults.swipeUp.call($this,event, direction, distance);
							break;
						
						case DOWN :	
							if (defaults.swipeDown)
								defaults.swipeDown.call($this,event, direction, distance);
							break;
					}
				}
			}
			
			
			/**
			 * Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
			 * This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
			 */
			function validateDefaultEvent(event, direction)
			{
				if( defaults.allowPageScroll==NONE )
				{
					event.preventDefault();
				}
				else 
				{
					var auto=defaults.allowPageScroll==AUTO;
					
					switch(direction)
					{
						case LEFT :
							if ( (defaults.swipeLeft && auto) || (!auto && defaults.allowPageScroll!=HORIZONTAL))
								event.preventDefault();
							break;
						
						case RIGHT :
							if ( (defaults.swipeRight && auto) || (!auto && defaults.allowPageScroll!=HORIZONTAL))
								event.preventDefault();
							break;

						case UP :
							if ( (defaults.swipeUp && auto) || (!auto && defaults.allowPageScroll!=VERTICAL))
								event.preventDefault();
							break;
						
						case DOWN :	
							if ( (defaults.swipeDown && auto) || (!auto && defaults.allowPageScroll!=VERTICAL))
								event.preventDefault();
							break;
					}
				}
				
			}
			
			
			
			/**
			* Calcualte the length / distance of the swipe
			*/
			function caluculateDistance()
			{
				return Math.round(Math.sqrt(Math.pow(end.x - start.x,2) + Math.pow(end.y - start.y,2)));
			}
			
			/**
			* Calcualte the angle of the swipe
			*/
			function caluculateAngle() 
			{
				var X = start.x-end.x;
				var Y = end.y-start.y;
				var r = Math.atan2(Y,X); //radians
				var angle = Math.round(r*180/Math.PI); //degrees
				
				//ensure value is positive
				if (angle < 0) 
					angle = 360 - Math.abs(angle);
					
				return angle;
			}
			
			/**
			* Calcualte the direction of the swipe
			* This will also call caluculateAngle to get the latest angle of swipe
			*/
			function caluculateDirection() 
			{
				var angle = caluculateAngle();
				
				if ( (angle <= 45) && (angle >= 0) ) 
					return LEFT;
				
				else if ( (angle <= 360) && (angle >= 315) )
					return LEFT;
				
				else if ( (angle >= 135) && (angle <= 225) )
					return RIGHT;
				
				else if ( (angle > 45) && (angle < 135) )
					return DOWN;
				
				else
					return UP;
			}
			
			

			// Add gestures to all swipable areas if supported
			try
			{

				this.addEventListener(START_EV, touchStart, false);
				this.addEventListener(CANCEL_EV, touchCancel);
			}
			catch(e)
			{
				//touch not supported
			}
				
		});
	};
	
	
	
	
})(jQuery);
var canfix = true; //browser supports fixed positioning?
var $preview = null;
var $into = null;
var $current = null;
var menuTimeout = null;

$(function(){

	/* INIT VARIABLES & SETUP */
	
	$preview = $('#preview');
	$into = $preview;
	var mobile = $('body').hasClass('mobile');
	
	canfix = (Modernizr.positionfixed && !mobile); //assume all mobile devices can't use position fixed
	
	if(!canfix) {	
		window.onorientationchange = updatePreview;
	
		$preview.html('<div></div>');	
		
		$preview.css({'position':'absolute','height':$(document).height()})
		
		$into = $preview.find('div');
		
		$preview.swipe( { swipe:swipe, click:closePreview } );
	}
		
	$('.lazy').each(function(){
		$(this).data('src',this.src);
		this.src = '/templates/2011/images/lazy.gif';
	});
	
	if(!mobile){ //desktop
		$('.product').each(function(){
			var $img = $(this).find('img');
			$img.wrap('<div class="reveal"></div>');
			$img.after('<div>'+$(this).find('img').attr('title')+'</div><a href="#" class="add">+ <span>ADD TO ENQUIRY</span></a><a href="#" class="enlarge">+ <span>ENLARGE</span></a>');
		})
	}

	/* EVENTS */
	
	$('#products').delegate('.product','click',function(){
		
		_gaq.push(['_trackEvent', 'Product', 'Preview']);
		
		var $img = $(this).find('img');
	
		if (Modernizr.touch && !mobile ){ //desktop version
			//reveal text on first click.. when revealed show preview
			if($img.css('top')=='auto' || parseInt($img.css('top'))>-150) {			
				$img.stop().animate({top:'-150px'},500);
				return false;
			} else {
				$img.stop().animate({top:'0px'},200);
			}
		}
	
		$preview.show();
		
		var src = $img.attr('src').replace('_thumb','_original');
		
		if(mobile || !$('#contact').is(':visible')) {		
			if($('#enquire').size()==0) {
				$('body').append('<a href="#" id="enquire">Enquire</a>');
				
				$('#enquire').click(function(e){
					e.stopImmediatePropagation();
					var m = $current.find('img').attr('src').match('\/([0-9]*)_thumb');
					$(this).attr('href',"mailto:mark@timelessinteriors.com.au?subject=Showroom%20Enquiry&body=Hi Mark, Please contact me regarding: http://s.timelessinteriors.com.au/"+m[1]+".jpg"); //Hi%20Mark,%0D%0A%0D%0APlease%20contact%20me%20regarding:%20"+encodeURIComponent(src));
				})

			} else {
				$('#enquire').show();
			}
			
		} else {
			$('#enquire').remove();
		}
		
		$current = $(this);
		
		$into.css({'background-image':'url(/templates/2011/images/loading.gif)','background-size':'auto'});
		
		var img = new Image();
		     
		img.onload=function(){
			$into.css({'background-image':'url('+this.src+')','background-size':'contain'});
		}
		
		img.src=src;
		
		if(!canfix) {		
			updatePreview();
		}
	});
	

	
	$into.click(closePreview);
	
	if(mobile) {
		$('select').change(function() {
			document.location.href = $(this).val();
		});
	}
	
	$(window).resize(function(){
		$(window).trigger('scroll');
		alignTop();
	});
	
	$(window).scroll(function(){
		
		var $lazy = $('.lazy');

		if($lazy.size()>0) {
		
			//load images between this range
			var showtop = $(this).scrollTop();
			var showbottom = showtop+$(this).height();

			$lazy.each(function(){
				
				var top = $(this).closest('.product').position().top;
				
				if(top >= (showtop-$(this).height()) && top <= showbottom) {
					$(this).attr('src',$(this).data('src'));
					$(this).removeClass('lazy'); 
				}
			})
			
		}		
	});
	
	if(!mobile) { //desktop
	
		$('#contact .controls').click(function(e){
			e.preventDefault();

			if($('#contact').hasClass('expand')) {
				$(this).parent().removeClass('expand').animate({left:'-400px'},250);
				$(this).attr('title','Expand');
			} else {
				$(this).parent().addClass('expand').animate({left:'0px'},500);
				$(this).attr('title','Collapase');
			}
		});
	
		$(window).on('keypress', function(e) {

	        if($preview.is(':visible')){
	        
	        	switch(e.keyCode) {
	        		case 27:
	        			closePreview(e);
	        		case 39:
	        		case 38:
	        		case 0:
	        			go('next');
	        		break;
	        		case 40:
	        		case 37:
	        			go('prev');
	        		break;
	        	}
	        	e.preventDefault();
	        }
		});
	
		$('#preview .next').on('click',function(e){
			e.stopImmediatePropagation();
			e.preventDefault();
			go('next');
		})
		$('#preview .previous').click(function(e){
			e.stopImmediatePropagation();
			e.preventDefault();
			go('prev');
		})
	
		$('#menu > ul > li > a').click(function(e){
			e.preventDefault();
		})
		$('#menu > ul > li > a').hover(function(e){
				clearInterval(menuTimeout);
				$('#menu li.expand').removeClass('expand');
				$(this).parent().addClass('expand');
			},function(){
				clearInterval(menuTimeout);
				menuTimeout = setInterval(function(){
					$('#menu li.expand').removeClass('expand');
				},300)
		})
		
		$('#menu li ul').hover(function(){ //submenu hover
				clearInterval(menuTimeout);
			},function(){
				clearInterval(menuTimeout);
				menuTimeout = setInterval(function(){
					$('#menu li.expand').removeClass('expand');
				},300)
			}
		)

		$('#products .reveal').hover(function(){
				var $img = $(this).find('img');
				if(parseInt($img.width())>100) {
					$img.stop().animate({top:'-150px'},500);
				}
			},function(){
				var $img = $(this).find('img');
				if(parseInt($img.width())>100) {
					$(this).find('img').stop().animate({top:'0px'},200);
				}
		});
		
		$('.add').click(function(e){
			e.stopImmediatePropagation();
			e.preventDefault();
			
			var enquiry_products = $.cookie('enquiry_products');
			
			var src = $(this).siblings('img').attr('src');
			
			var add = true;
			
			var products = [];
			
			if(enquiry_products != null) {
				var products = enquiry_products.split(',');
				for(var i=0,l=products.length;i<l;i++){
					if(products[i]==src) {
						add = false;
						alert('Product already in enquiry.');
						break;
					}
				}
			}
			
			if(add && products.length == 6) {
				alert('There is a maximum of 6 products per enquiry.');
				add = false;
			}
			
			if(add) {
				products.push(src);
				
				$.cookie('enquiry_products',products.join(','),{path: '/'});
			
				$('#selected').append('<a href="#"><img src="'+$(this).siblings('img').attr('src')+'" width="100" /><span></span></a>');
			
				$('#selected_preview').append('<img src="'+$(this).siblings('img').attr('src')+'" width="20" />');
				
				//if($('#contact').css('left') == '-400px') {
					//$('#contact').css({left:'-350px'}).stop().animate({left:'-400px'},250);
				//}
			}
			
			if($('#contact').css('left') == '-400px') {
				$('#contact .controls:last').trigger('click');
			}

		});
		
		$('.enlarge').click(function(e){
			e.preventDefault(); //stop default # event and bubble up to "preview event"
		})
		
		$('#selected a').live('click',function(e){
			e.preventDefault();
			
			var enquiry_products = $.cookie('enquiry_products');
			
			var src = $(this).find('img').attr('src');
			
			if(enquiry_products != null) {
				var p = enquiry_products.split(',');
				var products = [];
				for(var i=0,l=p.length;i<l;i++){
					if(p[i]!=src) {
						products.push(p[i]);
					}
				}
				$.cookie('enquiry_products',products.join(','),{path: '/'});
			}
			
			$(this).remove();
			$('#selected_preview img[src="'+src+'"]').remove();
			
			if($('#selected a').size()==0) {
				$('#contact').removeClass('expand').animate({left:'-400px'},250);
			}
			
		})
		
		$('#frm_enquiry').submit(function(e) {
			e.preventDefault();
			
			var valid = true;
			
			var email = $('#contact input[name=email]').val();
			var phone = $('#contact input[name=phone]').val();
			var comments = $('#contact textarea').val();
			
			if($('#selected a').size()==0) {
				alert('No Products Selected');
				valid = false;
			}
			if(valid && phone==0) {
				alert('Please enter a phone number');
				valid = false;
				$('#contact input[name=phone]').focus();
			}
			if(valid && email=='') {
				alert('Please enter an email address');
				valid = false;
				$('#contact input[name=email]').focus();
			}		
			if(valid) {
				
				$.cookie('enquiry_email',email,{path: '/'});
				$.cookie('enquiry_phone',phone,{path: '/'});
			
				$.post('/send_enquiry.php',{email:email,phone:phone,comments:comments},function(response){
					if(response=='sent') {
						alert('Thankyou for your enquiry. We will contact you as soon as possible.');
						$.cookie('enquiry_products',null,{path: '/'});
						$('#selected,#selected_preview').html('');
						$('#contact textarea').val('');
						
						$('#contact').removeClass('expand').animate({left:'-400px'},250);
						
						_gaq.push(['_trackEvent', 'Enquiry', 'Sent']);
					} else {
						alert('There was an error sending the email.');
						_gaq.push(['_trackEvent', 'Enquiry', 'Error']);
					}
				})
			}
		
		});
		
		$("#pagecurl").hover(function() { 
				$("img , .msg_block",this).stop().animate({ width: '307px',height: '319px'}, 500);
			}, function() {
				$("img",this).stop().animate({width: '120px',height: '126px'}, 220);
				$(".msg_block").stop().animate({width: '120px',height: '120px'}, 200);
		});
	}
	
	$(window).trigger('scroll');
	alignTop();
	
	//background-size not supported ... ie 7,8 etc
	if($('body').css('background-size')==undefined){
		$('body').css({'background-position':'top center','background-attachment':'fixed'});
	}
})

function swipe(e, direction)
{				

	if(direction == 'right') {
		go('prev');
	}
	
	if(direction == 'left') {
		go('next');
	}
	
	_gaq.push(['_trackEvent', 'Navigate', 'Swipe']);
	
	/* Moved to bottom of swipe function for android */
	e.stopImmediatePropagation();
	e.preventDefault();
}

function updatePreview() {

	var height = window.innerHeight ? window.innerHeight : $(window).height() 
	
	$('#enquire').css({top:$(document).scrollTop()+'px'});
	
	$into.css({'top':$(document).scrollTop()+'px','height':height+'px'});
	
	alignTop();
}

function alignTop() {
	var windowWidth = parseInt($(window).width());

	

	if($('#contact').is(':visible') && $('.product').size()>2 && windowWidth > 768) {

		$('#top').css('paddingLeft',$('#products .product:first').position().left+10+'px');
	} else {
		if($('#top').height()>60) {
			$('#top').css('paddingLeft',((windowWidth/2)-300)+'px');
		} else {
			$('#top').css('paddingLeft',((windowWidth/2)-440)+'px');
		}
	}
}

function closePreview(e){

	//for android - prevents clicking stuff under preview popup
	e.stopImmediatePropagation();
	e.preventDefault();
	
	$preview.hide();
	$('#enquire').hide(); //if it exists
}

function go(direction) {

	_gaq.push(['_trackEvent', 'Navigate', direction]);

	if(direction=='next') {
		var $prod = $current.next('.product');
	} else {
		var $prod = $current.prev('.product');
	}
	if($prod.size()>0) {
		$into.css({'background-image':'url(/templates/2011/images/loading.gif)','background-size':'auto'});

		var $img = $prod.find('img');
		
		if($img.hasClass('lazy')) {
			$img.removeClass('lazy');
			$img.attr('src',$img.data('src'));
		}

		var src = $img[0].src.replace('_thumb','_original');
	
		var img = new Image();
		     
		img.onload=function(){
			$into.css({'background-image':'url('+this.src+')','background-size':'contain'});
		}
		
		img.src=src;
		
		$current = $prod;
	}
}
