/*
* Copyright (c) 2010 Supercake Design
*/


// ***********************************************************************
// SUPERBOX
function SuperBox(links){
	/* ANIMATION HELPER */
	$.fn.wait = function(time, type) {
		time = time || 1000
		type = type || "fx"
		return this.queue(type, function() {
			var self = this
			setTimeout(function() {
				$(self).dequeue()
			}, time)
		})
	}
	
	/* INITIALISE */
	var current_link = 0
	var current_image = {}
	var box = {}
	var busy = false // prevents user from triggering multiple close and open events
	
	links.bind("click", function(e){
		e.preventDefault()
		
		// FIND LINK'S POSITION
		current_link = 0
		while (links[current_link].href != this.href) {
			current_link++
		}
	
		Update()
		Open()
	})
	Build()
	
	//$("a:first").trigger("click") // debug

	/* BUILD */
	function Build(){
		var html = '';
		
		html +=		'<div id="sb_bg"></div>' // box outside bg because it allows fading bg without fading box 
		
		html +=		'<div id="sb_box">'
		html +=			'<div id="sb_header">'
		html +=				'<a title="Close (esc key)" class="sb_close" href="javascript:;"><span>close</span></a>'
		html +=				'<h1>Encounters Film Festival: 2008</h1>'
		html +=		'</div>'
		
		html +=			'<div id="sb_image">'
		html +=				'<img src="" />'
		html +=				'<a class="sb_prev" href="javascript:;">prev</a>'
		html +=				'<a class="sb_next" href="javascript:;">next</a>'
		html +=				'<p id="sb_loading"><em>loading</em></p>'
		html +=			'</div>'
		
		html +=			'<div id="sb_footer">'
		html +=				'<a title="Prev (left arrow key)" class="sb_prev" href="javascript:;">&lt;&lt; <span>prev</span></a>'
		html +=				'<span id="sb_progress">1 of 4</span>'
		html +=				'<a title="Next (right arrow key)" class="sb_next" href="javascript:;"><span>next</span> &gt;&gt;</a>'
		html +=			'</div>'
		html +=		'</div>'
			
		
		$(html).appendTo("#page").hide() // !!!! comment out hide() for styling css
		
		// STORE ORIGINAL BOX PADDING & DIMENSIONS
		box.padding = {}
		box.padding.top =		parseInt($("#sb_box").css("padding-top"), 10)
		box.padding.bottom =	parseInt($("#sb_box").css("padding-bottom"), 10)
		box.padding.left =		parseInt($("#sb_box").css("padding-left"), 10)
		box.padding.right =		parseInt($("#sb_box").css("padding-right"), 10)
		
		box.width =				parseInt($("#sb_box").css("width"), 10) // !!!! dimensions aren't needed for variable sized images in the group - instead need to preload the image and use those dimensions 
		box.height =			parseInt($("#sb_box").css("height"), 10) //
	
		$("#sb_header, #sb_footer").hide() // default - they fade in after box reaches full size
		$("#sb_box").css({'width': 0,'height':0,'opacity':0,'padding': 0}) // !!!! comment out line for styling css
		
		// MAKE CLICKABLE
		$("#sb_box").bind("click", function(e){ // box click
			e.stopPropagation() // prevent #bg from triggering Close()
		})
		$("#sb_bg, #sb_box .sb_close").bind("click", Close)
		$("#sb_box .sb_prev").bind("click", Prev)
		$("#sb_box .sb_next").bind("click", Next)
		
		// HOVER HELPER
		$("#sb_box").bind("mouseenter", function(e){
			e.stopPropagation();
			$("#sb_box .close").removeClass("selected")
		})
		$("#sb_box").bind("mouseleave", function(e){
			e.stopPropagation();
			$("#sb_box .close").addClass("selected")
		})
		RemoteHover("#sb_bg", "#sb_box .sb_close")
		
		function RemoteHover(handle, target){
			$(handle).bind("mouseenter", function(e){
				e.stopPropagation();
				$(target).addClass("selected")
			})
			$(handle).bind("mouseleave", function(e){
				e.stopPropagation();
				$(target).removeClass("selected")
			})
		}
		RemoteHover("#sb_box #sb_image .sb_prev", "#sb_box #sb_footer .sb_prev")
		RemoteHover("#sb_box #sb_image .sb_next", "#sb_box #sb_footer .sb_next")
		
		// ADD KEYBOARD SHORTCUTS 
		$(document).bind("keydown.super", function(e) {
			if ($("#sb_box").is(':visible')){
				if (e.keyCode == 27) { // esc
					Close()
				
				} else if(e.keyCode == 37) { // left arrow
					Prev()
			
				} else if(e.keyCode == 39) { // right arrow
					Next()
				}
			}
		})
	}
	
	/* CENTER IMAGE */
	function CalcCenterCoords(){
		var webdesign_min_width = 0 // 1024 // !!!! centers document on design not window size
		var box_hmargins = 20 // !!!! distance from document bounds // should match shadow distance
		var box_vmargins = 20 //
		
		var win_h = $(window).height()
		var win_w = $(window).width()
		var win_w = (webdesign_min_width > win_w) ? webdesign_min_width : win_w
		
		var x = (win_w - box.width - box.padding.left - box.padding.right) / 2 // assumes box.width is smaller win_w
		var y = (win_h - box.height - box.padding.top - box.padding.bottom) / 2
		
		x = (x < box_hmargins) ? box_hmargins : x
		y = (y < box_vmargins) ? box_vmargins : y
		
		return {'left': x, 'top':y}
	}
	$(window).bind("resize", function(e){
		var coords = CalcCenterCoords()
		$("#sb_box").css(CalcCenterCoords())
	})
	
	/* OPEN */
	function Open(link){
		if (!busy){
			busy = true
			
			var orig = $(links[current_link]).offset()
			orig.top += - $(document).scrollTop() // converts pos to fixed position equivalent 
			orig.left += - $(document).scrollLeft() //
			
			$("#sb_box").css(orig).show() // move box to grow out of the link clicked
			var center = CalcCenterCoords()
			var options = {
				'top': center.top,
				'left': center.left,
				'opacity': 1,
				'width': box.width, // current_image.height,
				'height': box.height, // current_image.width,
				'paddingTop': box.padding.top,
				'paddingBottom': box.padding.bottom,
				'paddingLeft': box.padding.left,
				'paddingRight': box.padding.right
			}
			$("#sb_header, #sb_footer").show()
			
			if (!jQuery.browser.msie){
				$("#sb_bg").fadeIn(1) // fix for firefox - causing the bg to scale in from top right
			} else {
				$("#sb_bg").show() // fadeIn breaks IE opacity
			}
			//$("#sb_box").css(options)
			$("#sb_box").animate(options, 1) // fix for the fix - making sure everything appears at the same time
			
			busy = false
			
			/*
			// performance of animation is too bad - removing 
			// tried using css animations - no different
			$("#sb_box").animate(options, 500, "swing", function(){ // box grows out from original link
				busy = false
				$("#sb_header, #sb_footer").fadeIn(200)
			})
			$("#sb_bg").wait(200).fadeIn(300)
			*/
		}
	}
	
	/* CLOSE */
	function Close(){
		if (!busy){
			busy = true
			
			var orig = $(links[current_link]).offset()
			orig.top += - $(document).scrollTop() // converts pos to fixed position equivalent 
			orig.left += - $(document).scrollLeft() //
			
			var options = { // finshes fading and scaling out
				'top': orig.top,
				'left': orig.left,
				'opacity': 0,
				'width': 0,
				'height': 0,
				'paddingTop': 0,
				'paddingBottom': 0,
				'paddingLeft': 0,
				'paddingRight': 0
				//'padding': '0px 0px 0px 0px' // doesn't work
			}
			
			$("#sb_header, #sb_footer").fadeOut(200) // header and footer fade out
			$("#sb_box").animate(options, 500, function(){
				$("#sb_box").hide()
				busy = false	
			}) // box shrinks away to original link
			
			if (!jQuery.browser.msie){ // fadeOut breaks opacity in IE
				$("#sb_bg").fadeOut(300) // hide bg
			} else {
				$("#sb_bg").hide()
			}
		}
		// $(image_preloader).unbind();
	}
	
	/* NAVIGATION */
	function Step(pos, arr, increment){ // general array stepper
		pos += increment
		if (pos > arr.length - 1){
			pos = increment - 1 // e.g. 2 increment becomes pos 1
		} else if (pos < 0){
			pos = arr.length + increment // e.g. 15 items: -2 increment becomes pos 13 (second from last) 
		}
		return pos
	}
	function Prev(){ 
		current_link = Step(current_link, links, -1)
		Update() 
	}
	function Next(){ 
		current_link = Step(current_link, links, +1)
		Update()
	}
	
	/* UPDATE */
	function Update(){
		var link = $(links[current_link])
		var image_preloader = new Image
		var href = link.attr("href")
		image_preloader.src = href
		
		if (!ImageLoaded(href)){
			images_loaded.push(href)
		}
		
		
		$("#sb_progress").text((current_link+1)+" of "+links.length) // can see which image is being loaded
		
		if (image_preloader.complete && image_preloader.width != 0) { // firefox fix - 404 reports as complete
			Draw(link)
			
		} else {
			$("#sb_box").addClass("loading")
			
			$(image_preloader).bind('load', function() {
				Draw(link)
			})
		}
		
		function Draw(link){
			$("#sb_box").removeClass("loading")
	
			$("#sb_box #sb_image img").attr("src", link.attr("href"))
			
			$("#sb_box h1").text(link.attr("title"))
			
			current_image.width = image_preloader.width // need to store for FitToWindow on resize
			current_image.height = image_preloader.height //
		 
			PreloadNeighbourImages()
		}
	}
	
	/* PRELOAD NEIGHBOURS */
	var images_loaded = [] // loaded or loading, don't create a new image object if still loading
	function ImageLoaded(href){ // checks if href exists in images_loaded
		for (i=0; i<images_loaded.length; i++){
			if (href == images_loaded[0]){
				return true
			}
		}
		return false
	}
	function LoadImage(increment){
		var pos = Step(current_link, links, increment)
		var href = links[pos].href
		
		if (!ImageLoaded(href)){ // not loaded or loading
			img = new Image()
			img.src = href
			images_loaded.push(href)
		}
	}
	function PreloadNeighbourImages() {
		LoadImage(+1) // next image
		LoadImage(-1) // prev image
		LoadImage(+2) // aggressive - load next next image
		LoadImage(-2) // aggressive - load prev prev image
	}
}


// ***********************************************************************
// PORTFOLIO PAGE
if ($("#page.portfolio")){
	// PRELOAD THUMBS
	$(".images ul").each(function(){ // for each portfolio project
		$(this).find("a:not(:first)").each(function(){
			var href = this.href
			href = href.replace(".jpg", "_thumb.jpg")
			var preload_thumbs = new Image()
			preload_thumbs.src = href // preload all links apart from the first one
		})
	})
	
	// MAKE LINK TITLES
	$(".images li a").each(function(){
		var project_name = $(this).parent().parent().parent().parent().find("h2").text()
		var title = ($(this).attr("title")) ? $(this).attr("title") : $(this).text()
		$(this).attr("title", project_name+": "+title)
	})
	
	// ADD IMAGE HOVER
	$(".images li a").hover(function(event){
		var link = $(this)
		var href = link.attr("href")
		href = href.replace(".jpg", "_thumb.jpg")
		var image = $(this).parent().parent().parent().find("img")
		image.attr("src", href) // change thumbnail
		
		image.parent().unbind().click(function(e){ // image link now triggers this link
			e.preventDefault()
			link.trigger("click")
		})
	})
	
	// SUPER BOX TO LINKS
	SuperBox($(".images ul a"))
	$(".images > a").unbind().click(function(e){ // initial state - every image link
		e.preventDefault()
		$(this).parent().find("ul a:first").trigger("click") // triggers first text link
	})
}


// ***********************************************************************
// CONTACT PAGE
function ValidateForm(){
	var errors = []
	if (!$("input#name").val()){
		errors.push('Name')
	}
	if (!$("input#email").val()){
		errors.push('Email')
	}
	if (!$("textarea#message").val()){
		errors.push('Message')
	}
	
	var current_msg = $("form p.error").text()
	if (errors.length){
		var feedback_msg = 'Please complete all fields'
		
		if (current_msg != feedback_msg){
			$("form p.error").text(feedback_msg)
		}
		return false
	
	} else {
		if (current_msg != ""){
			$("form p.error").text("")
		}
		return true // send
	}
}
if ($("#page.contact form")){
	// PROTECTION
	var n = "info"
	var d = "supercake.co.uk"
	var e = n+'@'+d
	e = '<a href="mailto:'+e+'">'+e+'</a>'
	var txt = 'If you want to get in touch, please feel free to send an email to '+e+' or use the handy contact form.'
	$("#page.contact p.intro").html(txt).css("visibility","visible")
	
	// TRIGGER FOCUS OF INPUT WHEN CLICKING ON LABEL
	$('label').click(function(){
		var input = $(this).parent().find("#"+$(this).attr("for"))
		input.trigger("focus") // this is an iphone fix - label obstructs input from being focused
	})
	
	// CHANGE LABELS BASED ON INPUT
	$('input, textarea').blur(function(){ // checks if it should hide input on change 
		var label = $(this).parent().find("label[for='"+this.id+"']")
		if (!$(this).val()){ // no content
			$(label).css({"color":"#777777","text-indent":0}) // show label and change to default grey
		}
	}).focus(function(){
		var label = $(this).parent().find("label[for='"+this.id+"']")
		if (!$(this).val()){ // no content
			$(label).css({"color":"#CACACA"}) // change to light grey
		}
	}).keydown(function(){
		var label = $(this).parent().find("label[for='"+this.id+"']")
		if ($(label).is(':visible')){ // on the first key down
			$(label).css({"text-indent":-9999}) // hide
		}
	})
	
	
	$('input, textarea').trigger("keydown").trigger("blur") // set default state if browser has cached input
	
	// FORM VALIDATION
	if (!$("form p.error").length){ // server code may have created it
		$('<p class="error"></p>').appendTo("form fieldset")
	}
	
	$("form").submit(function() {
		return ValidateForm()
	})
	$("form").change(function() {
		if ($("form p.error").text()){ // remove error warning after user has tried to submit
			ValidateForm() 
		}
	})
}