// Vars
var photos 						= Array();				// Photos Array
var current_item				= null;					// Selected item
var total_items					= null;					// Total items in set
var loaded_items				= Array();				// Keeps track of what has been loaded
var req_item					= null;					// Requested item
var view_state					= null;					// Tracks view
var previous_view_state			= null;					// Keep track of previous view state
var window_height				= $(window).height();	// Width of window
var window_width				= $(window).width();	// Height of window

// Booking Form Vars For OpenTable
var RestaurantID				= '';
var SomersetHouseRestaurantID	= '48091';
var ChelseaRestaurantID			= '10228';

if (typeof console == "undefined") {
    this.console = {log: function() {}};
}

$(document).ready(function() {

	init();
	
	// Init change handlers
    $.address.init(function(event) {
 		// Defaults
		if(current_item == null || current_item == NaN) current_item = 0;
    }).change(function(event) {
        do_state_change();
    });
		
})

/*
	Init
*/
function init() {

	// Total Items
	total_items = photos.length;
	
	// Init date/time jquery plugin
	$('#startDate').datepicker({inline: true,dateFormat: 'dd/mm/yy',minDate: 0 });
	
	// Init drop jquery plugin
	$("SELECT").selectBox();
	
	// Show Gallery Buttons
	$('.pgpr').removeClass('hd');
	
	
	// Button Listeners
	button_listeners();	
}


/*
	Validate Mailing List Sign Up
*/


function validateNewsSignup()
{
	
	var e = $('#ue').val();
	var atpos=e.indexOf("@");
	var dotpos=e.lastIndexOf(".");
	if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
	  	alert("Please include a valid email address");
  		$("#ue").focus();
  		return false;
	}
  
  
  
}


/*
	Validate Bookings
*/


function validateBooking()
{
	
	var r = $('#restaurant option:selected').val();
	var d = $('#startDate').val();
	var p = $('#PartySize').val();
	
	// Check date
	if (d == null || d =="") {
  		alert("Please include a date");
  		$("#startDate").focus();
  		return false;
  	}
	
	// PartySize
	if (p == null || p =="") {
  		alert("Please let us know how many people will be dining");
  		return false;
  	}
	
	// Check restaurant
	if (r == null || r =="") {
  		alert("Please select a restaurant");
  		return false;
  	} else {
  		// Set the restuarantID so opentable knows which restaurant to book
  		$('#RestaurantID').val(r);
  	}
  	
}

/*
	State Changes
*/

function do_state_change() {

	console.log('state change');
	
	previous_view_state = view_state;
	
	// Get view state from url
	url_path = $.address.path();
	
	// View State
	if( url_path.search(/fullscreen/i) > -1) view_state = 'fullscreen';
	if( url_path.search(/website/i) > -1) view_state = 'website';
	
	// current_item
	items = $.address.pathNames(1);
	if (items.length >= 1) {
		current_item = parseInt(items[1]);
	}
	
	if(view_state == 'fullscreen') show_fullscreen_view();
	if(view_state == 'website') remove_fullscreen_view();	
	
}
	


/*
	Fullscreen
	everything below here is used to create full screen galleries
*/


/*
	Test less than IE 9
	Better to test an object exists but this
	is for cacheing issues with loading images
	
*/
var ie = (function(){

	var undef,
    v = 3,
    div = document.createElement('div'),
    all = div.getElementsByTagName('i');

	while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());


function show_fullscreen_view() {
	
	if(previous_view_state != 'fullscreen') {
	
		// Wrapper Div
		$('#fsw').append('<div id="fullscreen"><div class="photos"></div><div id="gnv"><a href="#" class="ir rta rt">Next</a><a href="#" class="ir lta lt">Previous</a><a href="#" class="cla ir cl">Close</a></div></div>');
		
		// Set interface for background overlay
		set_background();
		
		/*
			Button Listeners
		*/
		
		// Close
		$('#fullscreen, .cl').click(function(e) {
			nu = 'website/'+current_item;
			$.address.path(nu);
			e.preventDefault();
		})
		
		// Previous
		$('.lt').click(function(e) {
			set_photo_array_position('l');
			e.stopPropagation();
			e.preventDefault();
		})
		
		// Next
		$('.rt').click(function(e) {
			set_photo_array_position('r');
			e.stopPropagation();
			e.preventDefault();
		})
		
		// Keyboard Photographs
		$(document).keydown(function(e) {
			
			if(e.keyCode == 37) set_photo_array_position('l');
			if(e.keyCode == 39) set_photo_array_position('r');
			
		})
		
		// Show selected photo
		update_photo();
	
	
	} else { // Already in fullscreen
	
		// Show selected photo
		update_photo();
	}
}

function remove_fullscreen_view() {
	loaded_items = [];
	$('html').css('overflow', 'visible');
	$('#fsw').empty();
}


/*
	Button Listeners
*/

function button_listeners() {
		
	$('.tt').click(function(e) {
	
		// Get current id from link
		pid = $(this).attr('id');
		current_item = parseInt(pid.replace(/p/i, ''));
		nu = 'fullscreen/'+current_item;
		$.address.path(nu);
		e.preventDefault();
	});
}



/* 
	
	Update Photo

*/

function update_photo() {
	
	preload_photos();
	// fade out previous photo
	$('.photos .selected').hide();
	$('.photos .selected').removeClass('selected');
	// fade in new photos
	$('.photos .p'+current_item).addClass('selected');
	$('.photos .p'+current_item).fadeIn();
	// Position Fullscreen Photo
	position_photo();
}

function preload_photos() {

	

	if(current_item == null) {
		current_item = 0;
	}
	
	if(isNaN(current_item)) {
		current_item = 0;
	}
		
	load_next 		= true;
	load_previous 	= true;
	load_current	= true;
	target_class	= null;
		
	// Work out next and previous items
	prev_item = current_item - 1;
	next_item = current_item + 1;
	if(prev_item < 0) prev_item = total_items-1;
	if(next_item > (total_items-1)) next_item = 0;
	
	
	// Check for item in array with this value
	total_items_loaded = loaded_items.length;
	
	for (i = 0; i < total_items_loaded; i++) {
		// check next item loaded
		if (loaded_items[i] == next_item) {
			load_next = false;	
		}
		// Check previous item loaded
		if (loaded_items[i] == prev_item) {
			load_previous = false;	
		}
		// Check current item loaded
		if (loaded_items[i] == current_item) {
			load_current = false;	
		}
		
	}
	// Load next item
	if (load_next == true) {
		target_class = 'p'+next_item;
		// Create an anchor and img for the photo
		$('.photos').append('<a href="#" class="photo hd '+target_class+'"><img alt="'+photos[next_item][0]+'" /></a>');
		// Load in photo into img
		array_id = next_item;
		// Get the 800x600 photo
		url = photos[next_item][1];
		url = url.replace(/.jpg/i, '_la.jpg');
		ajax_photo(url, target_class, 85, 1, array_id);
		// Add item to loaded array
		loaded_items.push(next_item);
		// Add click listener
		add_photo_click_listener(target_class);
	}
	// Load previous item
	if (load_previous == true) {
		target_class = 'p'+prev_item;
		// Create an anchor and img for the photo
		$('.photos').append('<a href="#" class="photo hd '+target_class+'"><img alt="'+photos[prev_item][0]+'" /></a>');
		// Load in photo into img
		array_id = prev_item;
		// Get the 800x600 photo
		url = photos[prev_item][1];
		url = url.replace(/.jpg/i, '_la.jpg');
		ajax_photo(url, target_class, 85, 1, array_id);
		// Add item to loaded array
		loaded_items.push(prev_item);
		// Add click listener
		add_photo_click_listener(target_class);
	}
	
	// Load current item
	if (load_current == true) {
		target_class = 'p'+current_item;
		// Create an anchor and img for the photo
		$('.photos').append('<a href="#" class="photo hd '+target_class+'"><img alt="'+photos[current_item][0]+'" /></a>');
		// Load in photo into img
		array_id = current_item;
		// Get the 800x600 photo
		url = photos[current_item][1];
		url = url.replace(/.jpg/i, '_la.jpg');
		ajax_photo(url, target_class, 85, 1, array_id);
		// Add item to loaded array
		loaded_items.push(current_item);
		// Add click listener
		add_photo_click_listener(target_class);
	}
	
	
	
}

function add_photo_click_listener(target_class) {
	// 
	$('.photos .'+target_class).click(function(e) {
	
		// If homepage (only has one random photo)
		if (total_items == 1) {
			// Update url
			$.address.path('photographs/0');
			
		} else {
			// else show next item
			if (view_state == 'fullscreen') set_photo_array_position('r');
		}
		
		e.preventDefault();
		return false;
	})
	

}

function position_photo() {

	max_pc_of_window = 80;
	
	/*
		 Get original photo size and set this as a maximum
	*/

	photo_original_w = photos[current_item][2];
	photo_original_h = photos[current_item][3];
	max_width 		= photo_original_w;
	max_height		= photo_original_h;
	min_width 		= percentage_resize(photo_original_w, 20); // 50% of original
	min_height		= percentage_resize(photo_original_h, 20); // 50% of original

	/*
		Resize Photo
	*/
	
	// Set the hight based on the browser window size
	photo_height	= Math.round( (window_height / 100) * max_pc_of_window );
	
	// Constrain height
	if(photo_height < min_height) photo_height = min_height;
	if(photo_height > max_height) photo_height = max_height;
	
	/*
		Percentage of the photo_height compared to photo_original_h
		a[is the number]
		b[is the smaller number]
		a / b = %
	
	*/
	percentage_of_orginal = Math.round( ((photo_height / photo_original_h) * 100) );
	
	/*
	console.log('**** ');
	console.log('url: '+photos[current_item][1]);
	console.log('photo_height: '+photo_height);
	console.log('photo_original_h: '+photo_original_h);
	console.log('percentage_of_orginal: '+percentage_of_orginal);
	console.log('**** ');
	*/
	
	photo_width		= percentage_resize(photo_original_w, percentage_of_orginal);
	
	
	
	// Constrain width
	if(photo_width < min_width) photo_width = min_width;
	if(photo_width > max_width) photo_width = max_width;
	
	
	// Set a link to the same as the img child object
	$('.selected').width(photo_width);
	$('.selected').height(photo_height);
	
	$('.selected img').width(photo_width);
	$('.selected img').height(photo_height);
	
	$('.photos').width(photo_width);
	$('.photos').height(photo_height);
	
	
	/*
	
		Position Photo
	
	*/
	
	photo_y = ($(window).height() / 2) - (photo_height / 2) - 10 + $(window).scrollTop();
	photo_x = (window_width / 2) - (photo_width / 2) -30;
	
	$('.photos').css('position', 'absolute');
	$('.photos').css('top', photo_y);
	$('.photos').css('left', photo_x);
	
	
	/*
	
		Position Nav
		
	*/
	
	
	
	
	ny = ($(window).height() / 2) -125 + $(window).scrollTop();
	nx = ($(window).width() - 41);
	$('#gnv').css('position', 'absolute');
	$('#gnv').css('top', ny);
	$('#gnv').css('left', nx);
	
	
}

function ajax_photo(url, target_class, pc, opacity, array_id, load_another) { // url, id, size of image as percentage of original, opacity, array id, wether to load another item from an array of items
	

	// Target class
	target = '.'+target_class+' img';

	
	if (ie < 9) {
		unique = new Date().getTime()
		url = url+'?random='+unique;
		
	}
	

	$(target).attr('src', url).css('visibility', 'hidden').load( function() {
         	// Once loaded change size
			w = photos[array_id][2]; 
			h = photos[array_id][3];
			if(view_state == 'Photographs') {
				if(w > h) {
					orientation = 'landscape';
				} else {
					orientation = 'portait';
					pc = 89.5;
				}			}
		
			$('.'+target_class+' img').width( percentage_resize(w, pc) );
			$('.'+target_class+' img').height( percentage_resize(h, pc) );
			// Once loaded fade in photo (a element wrapping photo)
		 	$('.'+target_class).animate( { opacity: opacity }, 500);
		 	
		 	
		 	
		 	if(array_id == current_item) {
		 		// Position Fullscreen Photo
		 		position_photo();
		 	}
		 	
		 	$(this).hide().css('visibility', 'visible').fadeIn();
		
			if(load_another == true) {
				if(view_state == 'Thumbnails') {
					thumbnails_load_position++;
					if(thumbnails_load_position < total_items) {
						load_thumbnail();
					}
						}
			}
		
	});           
                      
}

function percentage_resize(n, p) {
	n = Math.round(((n/100) * p));
	return n;
}

function resize_photo(n, t) {
	n = n; // original number
	t = t; // resize to this 
	p = (((n - t)  / n ) * 100); // percentage difference between n and t
	p = 100 - p; // t is p% smaller than n
	return t;
}


/*
	Set photo array position

*/
function set_photo_array_position(req) {
	
	items = $.address.pathNames(1);
	if (items.length >= 1) {
		current_item = parseInt(items[1]);
	}

	next_item = null;
	
	next_item = requested_array_position(req);	

	// New URL
	nu = view_state.toLowerCase()+'/'+next_item
	
	// Set url
	$.address.path(nu);
	
}

function requested_array_position(req) {
	/*
		Pass this function l or r 
		and it will return the array position
		for the next or previous item in the array
	*/
	if (req == 'l') req_item = current_item - 1;
	if (req == 'r') req_item = current_item + 1;
	if(req_item < 0) req_item = total_items-1;
	if(req_item > (total_items-1)) req_item = 0;
	
	return req_item;
}



/*
	Resizing	
*/
$(window).resize(function() {
	if(view_state == 'fullscreen') {
		window_height	= $(window).height();
		window_width	= $(window).width();
		position_photo();
		set_background();
	}
});

// Sets fullscreen background
function set_background() {
	$('html').css('overflow', 'hidden');
	$('#fullscreen').css('width', '9000');
	$('#fullscreen').css('height', '9000');
}



