/* Globals */
var didResize 				= false,
	$browserWindow 			= false,
	$contentWrapper			= false,
	topVideo				= false,
	inPageVideo				= false,
	page 					= 1,
	$more					= false,
	ie						= false;	


/**
 * DOM Load
 */
$(document).ready(function() {
	if ($.browser.msie) {
		ie = parseInt($.browser.version);	
	}
	pageEnhance();		
});



function pageEnhance() {
	
	$contentWrapper = $("#wrapper");
	
	/* Nice page loading */
	$("a.page,.tags a,#tagCloud a").click(function() {
		var href = $(this).attr("href");
	  	$("#wholeSite").fadeOut(300,function(){			
			window.location = href;
		});
		return false
	});	

	
	/* Get top vimeo */
	if($('#topVideoIFrame').size()>0) {
		Froogaloop($('#topVideoIFrame')[0]).addEvent('ready', function() {															
	       	topVideo = Froogaloop('topVideoIFrame'); 	
		    topVideo.addEvent('play', function() {							
		       	$(".videoThumb iframe").remove();
				if(inPageVideo) {
					inPageVideo.api("api_pause");	
				}
			}) 
			if(!$("#topVideo").hasClass("hide") && !$("html").hasClass("iphone") && !$("html").hasClass("android") && !$("html").hasClass("blackberry") && !$("html").hasClass("ipod")) {	
				
				topVideo.api("play");
				topVideo.api("api_setVolume", 0.2);
			} 
		})
	}
	
	/* Get top vimeo */
	if($('#inPageVideoIFrame').size()>0) {
		Froogaloop($('#inPageVideoIFrame')[0]).addEvent('ready', function() {								
	       	inPageVideo = Froogaloop($('#inPageVideoIFrame')[0]); 	
		    inPageVideo.addEvent('play', function() {
				if(topVideo) {
					topVideo.api("api_pause");
				}						

			}) 			
			inPageVideo.api("play");
		})
	}
	
	
	
	

	/* Video show/hide */
	$("#showVideo").live("click",function(){
		$("#hideVideo").css({display:"block"});
		$(this).hide();
		var targetHeight = $("#topVideo .width").outerHeight() + 20;	
		$("#topVideo").show().animate({height:targetHeight+"px"},{
			duration:1500,
			step: function() {
				layout();
			},
			complete: function() {
				$(this).css({height:"auto"}).find("iframe").fadeIn(1800,function(){
					if(!topVideo) {					
						Froogaloop($('#topVideoIFrame')[0]).addEvent('ready', function() {							
					       	topVideo = $f( $('#topVideoIFrame')[0] );  							
							topVideo.addEvent('play', function() {							
						       	$(".videoThumb iframe").remove();
							})		
							topVideo.api("play");
							topVideo.api("api_setVolume", 0.2);		     
						})	
					} else {
						topVideo.addEvent('play', function() {							
					       	$(".videoThumb iframe").remove();
						})
						topVideo.api("play");		
						topVideo.api("api_setVolume", 0.2);				
					}				
				});				
			},
			easing: "easeOutCirc"
		})
		return false;
	})
	$("#hideVideo").live("click",function(){
		$("#showVideo").css({display:"block"});
		$(this).hide();
		if(!topVideo) {
			Froogaloop($('#topVideoIFrame')[0]).addEvent('ready', function() {						
		       	topVideo = $f( $('#topVideoIFrame')[0] );   
				topVideo.api("api_pause");							     
			})
		} else {
			topVideo.api("api_pause");	
		}
		$("#topVideo").animate({height:"0"},{
			duration:1000,
			step: function() {
				layout();
			},
			complete: function() {
				$(this).hide()
				if(inPageVideo) {
					inPageVideo.api("api_play");	
				}
			}
		})
		return false;
	})
	
	
	/* Toggle View */
	$("#listView").click(function(){
		$('.grid').masonry('destroy');	
		$(".videoThumb iframe").remove();
		$("#toggleWrapper").removeClass("grid").addClass("list")
		$("#listView").hide();
		$("#gridView").show();
		return false;
	})
	$("#gridView").click(function(){
		$("#toggleWrapper").removeClass("list").addClass("grid");
		$('.grid').masonry({
		  itemSelector: 'li.post',
			columnWidth: 150,
			gutterWidth: 18
		});			
		$("#listView").show();
		$("#gridView").hide();
		return false;
	})
	
	
	$(window).resize(function(){
		didResize = true;
	})
	//layout();
	setInterval(function() {	
		if(didResize) {
	        didResize 			= false;	
			layout();
	    }
	}, 15);
	
	loadImages();
	
	// Pagination
	var p = $("#pagination");
	if(p.size()>0 && (!ie || ie>=9)) {		
		var moreURL = p.find(".older").attr("href");
		$more = $('<div id="loadingMore"></div><div id="loadMore">Load more posts</div>').click(function(){
			
			$("#loadingMore").css({height:"200px"}).show()
			
			$.ajax({
				type: "GET",
				url: moreURL,
				success: function(msg){
					
					
				
					// Append list items
					var $result = $(msg),
						$items = $result.find("#toggleWrapper li");
						
						
					$("#loadingMore").hide()	
						
					if($("#toggleWrapper").hasClass("list")) {
						$("#toggleWrapper").append($items);
					} else {
						$("#toggleWrapper").append($items).masonry( 'reload' );
					}							
					
					loadImages()
			
					// update load button
					$older = $result.find(".older");
					if($older && $older!=null && $older.size()>0) {
						moreURL = $older.attr("href");
					} else {
						$more.remove();
					}
				}
			});
		})			
		p.before($more);
	}
	
	$(".videoThumb").live("click",function(){
		
		if($(this).closest("#toggleWrapper").hasClass("list")) {
			$(this).closest("li").find(".moreLink").click()
		} else {
				var data = $(this).attr("data-vimeo");		
				$(".videoThumb iframe").remove();		
				$(this).append('<iframe id="vimeoThumb" src="http://player.vimeo.com/video/'+data+'?title=0&amp;byline=0&amp;color=cc1719&amp;autoplay=1" width="318" height="240" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>');

				if(!topVideo) {
					Froogaloop($('#topVideoIFrame')[0]).addEvent('ready', function() {						
				       	topVideo = $f( $('#topVideoIFrame')[0] );   
						topVideo.api("api_pause");				     
					})
				} else {
					topVideo.api("api_pause");	
				}
		}
		
	
		
	})
	
	$('#galleryNav a').live("click",function(){
		var href = $(this).attr("href");
		//var loader = $("#full .loader");
		$('#galleryNav a').removeClass("selected");
		$("#largeImageWrapper .ldr img").fadeOut(300,function(){
			$(this).css({visibility:"hidden"}).show();
			$(this).addClass("selected");
			//loader.stop().fadeTo(0,1);
			//var to = setTimeout(function(){ loader.stop().fadeTo(300,.8); },500);
			$.imgpreload(href,{
				all: function() {
					//clearTimeout(to);			
					var newImg = new Image();
				    	newImg.src = href;
				    	var height = newImg.height;
						var width = newImg.width;
				    	$(newImg).ready(function(){						
							$("#largeImageWrapper .ldr").animate(
								{height:newImg.height+"px",width:newImg.width+"px"},
								{
									"duration": 600,
									"easing": "easeOutCirc",
									"complete": function(){
										$("#largeImageWrapper .ldr img").attr("src",href).hide().css({visibility:"visible",height:newImg.height+"px",width:newImg.width+"px"}).fadeIn(1000);
									},
									"step": function() {
										layout();
									}
								}							
							)
				    	});				
				}
			});
		});
	
		return false
	})
	
	
	// New windows
	newWindowLinks();
	
	// Default text
	defaultText();
	
	// Forms
	$("#checkoutBtn").click(function(){
		$(this).removeClass("greenButton").addClass("greyButton")
		$("#basketForm").submit()
		return false;
	})
	$(".submitButton").each(function(){
		var text 				= $(this).val();
		var $targetBtn			= $(this);
		var $relacementButton 	= $('<span class="moreLink">'+text+'</span>');
			$relacementButton.click(function(){
				$targetBtn.click()
			})
		$(this).before($relacementButton)
	})
	
	if(!Modernizr.input.placeholder) {
		$('input').each(function() {
			if($(this).val()=="") {
				var placeholder = $(this).attr("placeholder");				
				$(this).val(placeholder);
				$(this).removeAttr("placeholder");				
				$(this).focus(function() {				
					if ($(this).val() == placeholder) { 
						$(this).val(''); 
					}
				})
				$(this).blur(function() {				
					if ($.trim($(this).val()) == '') { 
						$(this).val(placeholder); 
					}
				});
			}
				
		});
	}
	
	if(Modernizr.rgba) {	
		$('#evilcredit').hover(function(){
			$(this).addClass("hover");
			spectrum();
		},function() {
			$(this).removeClass("hover");
			$('#evilcredit strong').stop().animate( { color: "#4b4a4a" }, {
				duration: 1000
			});
		})
	}
			
}





function defaultText() {
	$(".defaultText").unbind("focus,blur").focus(function () {		
		if ($(this).val() == $(this)[0].defaultValue) {
        	$(this).val("");
        }
	 }).blur(function() {
        if ($(this).val() == "") {
        	$(this).val($(this)[0].defaultValue);
     	}
	 });
}



/**	
 * Target new windows
 */
function newWindowLinks(){
	$('a[rel=external],#tweets a').live("click",function(){
		window.open($(this).attr('href'));
		return false;
	});
}


/* Un-obfuscate email */
function fnE(inarr,text) {
	inarr = inarr.split(",");
	var out = "";
	for(i=inarr.length-1;i>=0;i--) {
		out += inarr[i];
	}
	if(text==false || text=="" || text==undefined) {
		text = out;
	}
	document.write('<a href="mailto:'+out+'" class="email">'+text+'</a>');
}



function jsdebug(message) {
	try {
		if(window.console) {
			console.log(message);			
		}
	} catch(e) {}	
}



// Main layout and resizing
function layout() {	
	var windowHeight	= $(window).height(),
		headerHeight 	= $("#header").outerHeight(),
		bottomHeight	= $("#bottom").height(),
		topVideoHeight	= $("#topVideo").is(":visible") ? $("#topVideo").height() : 0,
		contentHeight	= $("#contentInner").outerHeight(),
		siteHeight 		= headerHeight+bottomHeight+contentHeight+topVideoHeight,	
		diff 			= windowHeight-headerHeight-bottomHeight-topVideoHeight;

	if(siteHeight<windowHeight) {
		$contentWrapper.css({"height":diff+"px"});
	} else {
		$contentWrapper.css({"height":"auto"});
	}
}

function loadImages() {
	$(".ldr img:not(.loaded)").imgpreload({
		each: function() {		
			$(this).hide().css({visibility:"visible"}).fadeIn(1000).addClass("loaded")
		}
	});
}


function spectrum(){  
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  
	if($("#evilcredit").hasClass("hover")) {
	 	$('#evilcredit strong').animate( { color: hue }, {
			duration: 1000,
			complete: function() {
				spectrum();
			}
		});
	}      
}
