/*
** Triggers the "rotate.orient" event on your element specified
**
** Argument 2 of your callback will be set to:
**   'portrait' - The screen is oriented vertically
**   'landscapeLeft' - The top of the device was rotated to the left
**   'landscapeRight' - The top of the device was rotated to the right
**
**
** This plugin is licensed under the Mit License.
**
** Copyright (c) 2010, Jesse Janzer - Tindr, LLC
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
** 
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
** 
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
*/
jQuery.fn.orient = function(fn){

	//have we already bound to all our events?
	if(!$(window).data('orientevent.orient')){

		var modePortrait = 'portrait';
		var modeLandscapeLeft = 'landscapeLeft';
		var modeLandscapeRight = 'landscapeRight';

		var fireOrient = function(mode){
			var stack = $(window).data('elements.orient');
			for(var k in stack){
				var el = stack[k];
				el.trigger('rotate.orient',mode);
			}
		}
		
		//which orientation method are we going to listen to?
		var nativeRotation = "onorientationchange" in window;
		if(nativeRotation){
			//this is an event support on android and iphone
			window.onorientationchange = function(){
				switch(window.orientation){
					case 0: //Portrait
						fireOrient(modePortrait);
						break;
					case 90: //Landscape (top turned left)
						fireOrient(modeLandscapeLeft);
						break;
					case -90: //Landscape (top turned right)
						fireOrient(modeLandscapeRight);
						break;
					case 180:
					case -180:
						fireOrient(modePortrait);
						break;
				}
			};
		} else {
			//in all other cases we'll emulate orientation by using the resize event
			$(window).resize(function(){
				if($(window).height()>$(window).width()){
					fireOrient(modePortrait);
				} else {
					fireOrient(modeLandscapeRight);
				}
			});
		}

	}

	return this.each(function(k,v){
		//push the element into the queue of listeners
		var el = $(v);
		el.bind('rotate.orient',fn);
		var stack = $(window).data('elements.orient');
		if(!stack){
			stack = [];
		}
		stack.push(el);
		$(window).data('elements.orient',stack);
	});
};

jQuery.fn.slideImage = function(settings){
	settings = jQuery.extend({
		'baseUrl': null, //The prefix applied to the image path
		'imgs': [], //The list of images to toggle through
		'transitionDuration': 500, //The number of ms to transition the images
		'showDuration': 6000, //How long to show an image in ms
		'position': 0, //The current image position
		'direction': 1 //1 is forward, 0 is backward
	},settings);

	//let's find out if this browser supports transitions
	var testTransition = function(){
		if($.browser.msie){
			return false;
		}
		var slideImageEl = $('#slideImageTester');
		if(slideImageEl.length<=0){
			var slideImage = $('<div id="#slideImageTester" />');
			$('body').append(slideImage);
		}

		slideImage.css({
			'-webkit-transition': 'all',
			'-moz-transition': 'all',
			'-o-transition': 'all'
		});

		//do we have one of these stored?
		if(slideImage.css('-webkit-transition') == 'all'){ return true; }
		if(slideImage.css('-moz-transition') == 'all'){ return true; }
		if(slideImage.css('-o-transition') == 'all'){ return true; }

		slideImage.remove();

		return false;
	};

	//cache the value so we only call this once
	var canTransition = $(window).data('canTransition.slideImage');
	if(typeof(canTransition) == 'undefined'){
		var canTransition = testTransition();
		$(window).data('canTransition.slideImage',canTransition);
	}

	return this.each(function(k,v){
		//sanity check, do nothing if we aren't loaded with images
		if(settings.imgs.length <= 0){
			return;
		}

		var el = $(v);
		el.data('direction.slideImage',settings.direction);
		el.html('<div class="slideImageA"></div><div class="slideImageB"></div>');
		var slideA = el.find('.slideImageA');
		var slideB = el.find('.slideImageB');

		//start pre-loading our images now
		for(var i=0; i<settings.imgs.length; i++){
			var img = new Image();
			img.src = settings.baseUrl+settings.imgs[i];
		}

		//preserve our scope
		(function(){
			var imgs = settings.imgs;
			var cnt = 0;
			var position = settings.position;
			slideCurrent = slideA;
			slideNext = slideB;

			var imgCurrent = slideCurrent;
			var imgNext = slideNext;

			slideCurrent.addClass('slideImageActive');
			slideCurrent.css('background-image','url("'+settings.baseUrl + imgs[position]+'")');
			slideNext.css('background-image','url("'+settings.baseUrl + imgs[position+1]+'")');

			slideCurrent.find('img:first').attr('src',settings.baseUrl + imgs[position]);
			slideNext.find('img:first').attr('src',settings.baseUrl + imgs[position+1]);

			slideCurrent.css('left','0');
			position += 1;


			el.bind('next.slideImage',function(){
				var direction = el.data('direction.slideImage');
				position += direction == 1 ? 1 : -1;
				if(slideCurrent.hasClass('slideImageActive')){
					var tmp = slideCurrent;
					slideCurrent = slideNext;
					slideNext = tmp;
					slideCurrent.toggleClass('slideImageActive');
					slideNext.toggleClass('slideImageActive');
				}

				if(position > imgs.length-1){
					position = 0;
				} else if(position < 0){
					position = imgs.length -1;
				}

				urlNext = settings.baseUrl + imgs[position];

				slideNext.css('background-image','url('+urlNext+')');
				slideNext.find('img:first').attr('src',urlNext);

				var currentLeft = '-100%';
				var afterLeft = '100%';
				var nextLeft = '0%';

				if(direction == 0){
					//reverse
					currentLeft = '100%';
					afterLeft = '-100%';
				}

				//slide the current cell to the left, when done place it on the right
				if(!canTransition){
					slideCurrent.animate({'left':currentLeft},settings.transitionDuration,function(){
						$(this).css('left',afterLeft);
					});
					slideNext.animate({'left':nextLeft},settings.transitionDuration);
				} else {
					//if we can transform, let's do this instead of animating as this is much smoother
					var durationInSeconds = settings.transitionDuration / 1000;
					slideCurrent.css({
						'-webkit-transition': 'left '+durationInSeconds+'s ease-in-out',
						'-moz-transition': 'left '+durationInSeconds+'s ease-in-out',
						'-o-transition': 'left '+durationInSeconds+'s ease-in-out'
					});
					slideNext.css({
						'-webkit-transition': 'left '+durationInSeconds+'s ease-in-out',
						'-moz-transition': 'left '+durationInSeconds+'s ease-in-out',
						'-o-transition': 'left '+durationInSeconds+'s ease-in-out'
					});
					slideCurrent.css('left',currentLeft);
					slideNext.css('left',nextLeft);

					window.setTimeout(function(){
						//disable transitions and move this to the right
						slideCurrent.css({
							'-webkit-transition':'none',
							'-moz-transition':'none',
							'-o-transition':'none'
						});
						slideCurrent.css({'left':afterLeft});
					},settings.transitionDuration);
				}

				var timeout = el.data('timeout.slideImage');
				if(timeout){
					window.clearTimeout(timeout);
					timeout = null;
				}

				el.data('timeout.slideImage',window.setTimeout(function(){el.trigger('next.slideImage')},settings.showDuration));
				
			});

			var timeout = el.data('timeout.slideImage');
			if(timeout){
				window.clearTimeout(timeout);
				timeout = null;
			}

			el.data('timeout.slideImage',window.setTimeout(function(){
				var interval = window.setTimeout(function(){el.trigger('next.slideImage');},settings.showDuration+settings.transitionDuration);
			},settings.showDuration));
		})();

	});
};

jQuery.fn.emulateFixed = function(settings){
	settings = jQuery.extend({
		'top': false,
		'bottom': false,
		'left': false,
		'right': false,
		'emulate': false //if true will force emulation regardless if fixed works or not
	},settings);
	return this.each(function(k,v){
		//if we support fixed keep it fixed
		var el = $(v);
		
		var emulate = false;
		if(settings.emulate){
			//force emulation
			emulate = true;
		} else {
			//a quick sanity check if we're using an old version of ie
			if($.browser.msie && parseInt($.browser.version) <= 6){
				emulate = true;
			} else {
				//do we need to emulate?
				el.css('position','fixed');
				emulate = el.css('position') != 'fixed';
			}
		}

		if(emulate){
			//store the original values, in the event that the screen is resized we'll recalc
			var original = {
				'position': el.css('position'),
				'top': 'auto',
				'bottom': 'auto',
				'left': 'auto',
				'right': 'auto'
			};
			if(settings.top){
				original['top'] = el.css('top');
			}
			if(settings.bottom){
				original['bottom'] = el.css('bottom');
			}
			if(settings.left){
				original['left'] = el.css('left');
			}
			if(settings.right){
				original['right'] = el.css('right');
			}
			
			el.css('position','absolute');

			el.data('original.emulateFixed',original);
			
			var offset = el.offset();

			//whenever the window is resized, reorient our element
			$(window).resize(function(){
				el.css(el.data('original.emulateFixed'));
				offset = el.offset();
			});
			
			//which fields are we bound to?
			var top = parseInt(el.css('top'));
			var bottom = parseInt(el.css('bottom'));
			var left = parseInt(el.css('left'));
			var right = parseInt(el.css('right'));
			if(isNaN(top)){top=0;}
			if(isNaN(bottom)){bottom=0;}
			if(isNaN(left)){left=0;}
			if(isNaN(right)){right=0;}

			//console.log('el',offset,bottom,window.pageYOffset,$(window).height());

			var scroll = function(ev){
				var scrollTop = 0;
				var scrollLeft = 0;
				if(typeof(window.pageYOffset) == 'number'){
					scrollTop = window.pageYOffset;
					scrollLeft = window.pageXOffset;
				}else if(document.documentElement && typeof(document.documentElement.scrollTop) == 'number'){
					scrollTop = document.documentElement.scrollTop;
					scrollLeft = document.documentElement.scrollLeft;
				}else if(document.body && typeof(document.body.scrollTop) == 'number'){
					scrollTop = document.body.scrollTop;
					scrollLeft = document.body.scrollLeft;
				}else {
					//we don't know how to get the offset
					return;
				}

				var css = {};
				if(settings.top){
					css['top'] = scrollTop + top + 'px';
				}
				if(settings.bottom){
					css['top'] = offset.top + scrollTop + bottom + 'px';
				}
				if(settings.left){
					css['left'] = scrollLeft + left + 'px';
				}
				if(settings.right){
					css['left'] = offset.left + scrollLeft + right + 'px';
				}
				//window.alert(scrollTop + '|' + offset.top + '|' + bottom + '|' + css['top']);
				//window.alert(scrollTop + '|' + offset.top + '|' + top + '|' + css['top']);
				el.css(css);
			};

			$(window).bind('scroll.emulateFixed',scroll);
		}

	});
};


//Poorly emulates the "background-size" cover (aka scaling an image)
jQuery.fn.emulateCover = function(settings){
	settings = jQuery.extend({
		'width': 0,
		'height': 0,
		'threshold':1.25,
		'resizeTimeout': 50 //how frequently do we update on resize, low values will thrash the cpu
	},settings);

	//do we need emulation?
	var testCover = function(){
		if($.browser.msie){
			return false;
		}
		var testEl = $('#emulateCoverTester');
		if(testEl.length<=0){
			var testEl = $('<div id="#emulateCoverTester" />');
			$('body').append(testEl);
		}

		testEl.css({
			'-webkit-background-size': 'cover',
			'-moz-background-size': 'cover',
			'-o-background-size': 'cover'
		});

		//do we have one of these stored?
		if(testEl.css('-webkit-background-size') == 'cover'){ return true; }
		if(testEl.css('-moz-background-size') == 'cover'){ return true; }
		if(testEl.css('-o-background-size') == 'cover'){ return true; }

		testEl.remove();

		return false;
	};


	//cache the value so we only call this once
	var canCover = $(window).data('canCover.emulateCover');
	if(typeof(canCover) == 'undefined'){
		var canCover = testCover();
		$(window).data('canCover.slideImage',canCover);
	}

	settings.ratio = (settings.width*1.0) / settings.height;
	return this.each(function(k,v){
		var el = $(v);
		if(canCover){
			el.css({
				'-webkit-background-size': 'cover',
				'-moz-background-size': 'cover',
				'-o-background-size': 'cover'
			});
			return;
		}
		el.data('computing.emulateCover',true);

		if(!el.hasClass('emulateCover')){
			var src = el.css('background-image');
			src = src.replace(/^url\(['"]+/,'').replace(/['"]+\)$/,'');
			var img = $('<img />');
			img.attr('src',src);
			el.html(img);
			el.addClass('emulateCover');
			$(window).bind('resize.emulateCover',function(){
				var timeout = el.data('timeout.emulateCover');
				if(timeout){
					window.clearTimeout(timeout);
					timeout = null;
				}
				el.data('timeout.emulateCover',window.setTimeout(function(){
					el.emulateCover(settings);
				},settings.resizeTimeout));
			});
		} else {
			var img = el.find('img:first');
		}

		//reset the images to 0 so the outer element doesn't "expand"
		img.css({
			'width': 0,
			'height': 0
		});
		var width = el.width();
		var height = el.height();
		img.css('display','none');

		var ratio = (width*1.0)/height;
		if(ratio> (settings.ratio*settings.threshold)){
			ratio = settings.ratio*settings.threshold;
		}
		if(ratio>settings.ratio){
			//wider
			var imgWidth = width*(ratio/settings.ratio);
			var imgHeight = height*(ratio/settings.ratio);
		} else {
			//taller
			var imgWidth = width/(ratio/settings.ratio);
			var imgHeight = height/(ratio/settings.ratio);
		}
		img.css({
			'width': imgWidth - 10 + 'px',
			'height': imgHeight - 10 + 'px'
		});
		img.css('display','inline');
		
		el.data('computing.emulateCover',false);
	});
};

$(document).ready(function(){
	$('body').orient(function(ev,orientation){
		var el = $(this);
		if(orientation == 'portrait'){
			el.addClass('portrait').removeClass('landscape');
		} else {
			el.addClass('landscape').removeClass('portrait');
		}
	});


	//trigger the initial rotation so we know which way to render the page
	var nativeRotation = "onorientationchange" in window;
	if(nativeRotation){
		window.onorientationchange();
	}

	var scrollWrapper = null;
	//if we're using a mobile webkit, let's use iscroll instead of emulation, as control to js is only returned when scrolling is done
	if($.browser.webkit){
		var wrapper = $('#wrapper');
		wrapper.wrap('<div id="scroll_wrapper" />');
		var scrollWrapper = $('#scroll_wrapper');

		scrollWrapper.css({
			'position': 'relative',
			'height':$(window).height()-$('#nav').outerHeight(),
			'z-index': 1,
			'overflow': 'hidden'
		});

		document.addEventListener('touchmove',function(ev){ev.preventDefault(); });
		
		myScroll = new iScroll('wrapper',{desktopCompatibility:true});

		$('.scrollto').click(function(){
			var href = $(this).attr('href');
			myScroll.scrollToElement(href);
			return false;
		});
	} else {
		//let's use emulation for fixed when available
		$('#background').emulateFixed({'top':true,'left':true});
		$('#nav').emulateFixed({'bottom':true,'left':true});
	}


	//whenever the screen resizes, adjust the background holder
	$(window).resize(function(){
		var background = $('#background');
		background.css({
			'width': $(window).width()+'px',
			'height': $(window).height()+'px'
		});
		//if we're using iscroll recalc the height of the scroll
		if(scrollWrapper){
			scrollWrapper.css('height',$(window).height()-$('#nav').outerHeight());
		}
		
	});
	$(window).resize();
	

	//we push these via javascript so we don't need to load them during the normal page load
	var imgs = ['alicia_keys.jpg','fugitive.jpg','skullcandy1.jpg','skullcandy2.jpg','superheroes.jpg','there_really_is_a_way.jpg','underpass.jpg','unicorns.jpg','yamaha.jpg','rkr_1.jpg','rkr_2.jpg','rkr_3.jpg'];
	//var imgs = ['alicia_keys.jpg','fugitive.jpg'];
	$('#background').slideImage({
		//'baseUrl':'http://qktract.subculture.org/sandbox/rain/img/bg_ls/',
		'baseUrl':'/img/bg_ls/',
		'imgs':imgs
	});
	
	$('#background div').emulateCover({'width':960,'height':640});
	
	$('#next').click(function(){
		$('#background').data('direction.slideImage',1).trigger('next.slideImage');
		return false;
	});
	$('#previous').click(function(){
		$('#background').data('direction.slideImage',0).trigger('next.slideImage');
		return false;
	});
});

