var image_width = 0;
var image_height = 0;
var image_ratio = 0;

var current_image = 1;

var total_thumbs = 0;
var thumbnail_width = 0;
var thumbnail_margin = 0;
var total_thumbnail_width = 0;
var thumbnail_window_size = 0;
var visible_thumbnails = 0;
var thumbnails_wrapper_width = 0;
var ratio = 0;

var total_images = 0;
var sneakpeek = 0;
var just_clicked = false;

var tmp_title = "";
			
/* Slideshow Vars */
var slideshowplaying = false;
var slideval = "";

jQuery.fn.center = function () {
  this.css("position","absolute");
  this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
  this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
  return this;
}

$(document).ready(function(e) {
	// Thumbnail Placeholders
	$("#thumbnails-wrapper img").bind('load', function() {
		$(this).next().remove();
		$(this).removeClass("thumbnail-loading");
	});

	// Disable selection of elements
	// $("*").onselectstart = function() { return(false); };
	
	// Set the address history to not be strict (aka force /'s)
	$.address.strict(false);
	
	// Attach callbacks to the back/forward buttons
	$.address.externalChange(function() { handle_history_change(); });
	
	// Setup overlays and placeholders
	$(".placeholdme").each(function() {
		$(this).val($(this).attr('placeholder'));
	});
	$(".placeholdme").bind('focus', function() { if ($(this).val() == $(this).attr('placeholder')) { $(this).val(""); }}).bind('blur', function() { if ($(this).val() == "") { $(this).val($(this).attr('placeholder')); } });

	// Setup contact form validation
	$("#contactfrm").submit(function() {
		if ($("#contact-overlay-name").val() == "Name") { $("#contact-overlay-name").val(""); }
	});

	$("#contactfrm").validate({rules: {name: {required: true, minlength: 1}}, messages: {name: "Name is Required.", email: "Invalid Email Address."}, submitHandler: function(form) {
			$.post("/content/sendmail/", $(form).serialize(), function(data) {
				$("#contactfrm").hide(function() {
					$("#contactfrm-receipt").show();
				});
			});
	}});
	
	// Setup the movie thumbs
	$("[data-movie-id]").click(function() {
		var mid = $(this).attr("data-movie-id"),
				ifrm = $("<iframe/>", {
					src: 'http://player.vimeo.com/video/' + mid + '?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=' + video.autoplay,
					id: 'video-iframe',
					width: video.width,
					height: video.height,
					frameborder: '0',
					webkitAllowFullScreen: 'true',
					allowFullScreen: 'true'
				});

		$("#video-overlay").find('.video-content').append(ifrm);

		open_dialog($("#video-overlay"));
	});
});

function prev_image() {
	if (is_relaxed()) {
		just_clicked = true;
	
		if (current_image > 1) { load_image((parseInt(current_image) - 1), true); }
		else if (current_image <= 1) { load_image(parseInt(total_images), true);  }
	}
}

function next_image() {
	if (is_relaxed()) {
		just_clicked = true;

		if (total_images > current_image) { load_image((parseInt(current_image) + 1), true); }
		else if (total_images == current_image) { load_image(1, true); }
	}	
}

function toggle_slideshow(state) {
	if (slideshowplaying && state == null || state == "off") {
		// Stop the slideshow
		$("#slideshow-controls").removeClass('slideshow-pause').addClass('slideshow-play');
		clearInterval(slideval);
		slideshowplaying = false;
	} else if (!slideshowplaying && state == null || state == "on") {
		// Turn on the slideshow
		$("#slideshow-controls").removeClass('slideshow-play').addClass('slideshow-pause');
		slideval = setInterval(function() { $("#hotspot-right").trigger("click"); }, slideshow_interval);
		slideshowplaying = true;
	}
}

function is_relaxed() {
	var count = $("*:animated").size();
	
	if (count == 0) return true;	
	return false;
}

function handle_history_change() {
	// Bring up the history
	var photo = ($.address.parameter('photo')) ? $.address.parameter('photo') : 1;

	var imgint = setInterval(function() {
		if (is_relaxed()) { load_image(parseInt(photo)); clearInterval(imgint); }
	}, 200);
}

function toggle_galleries(state) {
	if (($("#galleries-window").css('display') == "block" && state == null) || state == "off") {
		$("#galleries-window").stop().animate({ width: 'hide' });
	} else if (($("#galleries-window").css('display') == "none" && state == null) || state == "on") {
		$("#galleries-window").stop().animate({ width: 'show' });
	} else if (state == "instant-off") {
		$("#galleries-window").stop().hide();
	}
}

function load_gallery(id) {
	if (id == null) return false;
	
	toggle_galleries("off");
	hide_clients();

	$("#thumbnails-window").stop().animate({ width: 'hide' }, 1500, function() {
		window.location = '/portfolio/' + id + '/';
	});
}

/* BEGIN Dynamic Sizing Functions */
function reset_view(zIndexer) {
	total_images = $(".slideshow-img").length;
	current_image = 1;

	zindexer();
	calculate_element_sizes();
	resizer();
}

function calculate_element_sizes() {
	// Thumbnail scroll specs
	total_thumbs = $("#thumbnails-wrapper img").length;
	thumbnail_width = parseInt($('#thumbnails-wrapper img:last').css('width'));
	thumbnail_margin = parseInt($('#thumbnails-wrapper img:last').css('margin-right'));
	total_thumbnail_width = (thumbnail_width + thumbnail_margin);
	thumbnail_window_size = (parseInt($('#thumbnails-window').width()) - parseInt($('#thumbnails-window').css('margin-left')));
	visible_thumbnails = Math.abs(thumbnail_window_size / total_thumbnail_width);
	thumbnails_wrapper_width = parseInt(((total_thumbs - visible_thumbnails) * total_thumbnail_width));
	if (thumbnails_wrapper_width < 0) { thumbnails_wrapper_width = 0; }
	ratio = thumbnails_wrapper_width / thumbnail_window_size;
}

function zindexer() {
	$(".slideshow-img").each(function() { $(this).css('zIndex', '198').css('display', 'none'); });	
	$(".slideshow-img").eq(current_image - 1).css('zIndex', '200').show();
}

// Window resizer function
function resizer(just_me) {
	// Default Vals
	if (just_me == null) { just_me = false; }
	
	//Define image ratio
	var el = $(".slideshow-img").eq(current_image-1);
	var co = $(".slideshow-img");
	var sp = el;
	var ratio = $(el).attr("ratio");
	
	//Gather browser and current image size
	var imagewidth = $(el).width();
	var imageheight = $(el).height();
	var browserwidth = $(window).width();
	var browserheight = $(window).height();
	var offset;

	//Resize Image Loaders
	$(".main-image-loader").css('height', browserheight).css('width', browserwidth);

	//Resize image to proper ratio

	// Horizontal Crop
	if (enable_full_vertical) {
		$(sp).height(browserheight);
		$(sp).width(browserheight / ratio);
		$(co).children().height(browserheight);
		$(co).children().width(browserheight / ratio);
		compensate = parseInt((browserheight / ratio) - browserwidth);

		if ((browserheight/browserwidth) > ratio){
			$(co).css('padding-left', '0').css('padding-right', '0');
		} else {
			var pad_left = Math.abs(compensate) / 2;
			if (just_me) {
				$(co).not($(".slideshow-img").eq(current_image-2)).css('padding-left', pad_left).css('padding-right', pad_left);			
			} else {
				$(co).css('padding-left', pad_left).css('padding-right', pad_left);
			}
		}	
	} else {
		if ((browserheight/browserwidth) > ratio){
			// Horizontal Crop
		    $(sp).height(browserheight);
		    $(sp).width(browserheight / ratio);
		    $(co).children().height(browserheight);
		    $(co).children().width(browserheight / ratio);
				compensate = parseInt((browserheight / ratio) - browserwidth);
		} else {
			// Vertical Crop
		    $(sp).width(browserwidth);
		    $(sp).height(browserwidth * ratio);
		    $(co).children().width(browserwidth);
		    $(co).children().height(browserwidth * ratio);
		    compensate = 0;
		}	
	}

	compensate = Math.abs(compensate);
}
/* END Dynamic Sizing Functions */

/* Begin Overlay Functions */
function open_dialog(obj) {
	$(obj).parent().show(function() {
		$(obj).center().fadeIn();
	});
}
function close_dialog(obj) {
	$(obj).fadeOut(function() {
		$(this).parent().hide();
	});
}
/* End Overlay Functions */

/* Begin Contact Form Functions */
function clear_contact_form() {
	$("#contactfrm-receipt").hide();
	$("#contactfrm").show();

	$(".placeholdme").each(function() {
		$(this).val($(this).attr('placeholder'));
	});	
}
/* End Contact Form Functions */

/* Begin Clients Functions */
function show_clients() {
	if($("#clientslist").is(":hidden")) {
		toggle_menubar("off");

		$.address.parameter("photo", "");
		$.address.parameter("clientlist", "1");

		$('#text').css({ top: '0px' });	
		$('#clients-text-arrow-up').hide();

		$('#icons').css({ top: '0px' });	
		$('#clients-icons-arrow-up').hide();

		$("#clientslist").fadeIn(function() {
			if ($("#text-wrapper").height() >= $("#text").height()) { $('#clients-text-arrow-down').hide(); }
			if ($("#icons-wrapper").height() >= $("#icons").height()) { $('#clients-icons-arrow-down').hide(); }		
		});

		tmp_title = document.title;
		document.title = page_title.replace('%portfolio%', 'Client List');
	}
	
	init_clients_nav();
}

function hide_clients() {
	if($("#clientslist").is(":visible")) {
		$.address.parameter("clientlist", "");
		$("#clientslist").fadeOut(function() {
			document.title = tmp_title;

			$(".clientswrapper #icons-wrapper").unbind('mousemove');
			$(".clientswrapper #text-wrapper").unbind('mousemove');
		});
	}
}
function toggle_clients() {
	if($("#clientslist").is(":hidden")) {
		show_clients();
	} else {
		hide_clients();
	}
}
function show_client(cid) {
	open_dialog($("#client-overlay"));
	$(".client-content").empty().append('<div class="ajax-loader"></div>').load("/classes/loadclient.php", {cid: cid}, function() {
		$(".client_images li:first").show();
		Cufon.refresh();
	});
}
function client_go_left() {
	if (!$(".client_images li:visible").is(":first-child")) {
		$(".client_images li:visible").hide().prev().show();	
	} 

	if (!$(".client_images li:visible").is(":first-child")) { $(".client_photo_left").show(); }	else { $(".client_photo_left").hide(); }
	if (!$(".client_images li:visible").is(":last-child")) { $(".client_photo_right").show(); } else { $(".client_photo_right").hide(); }
}
function client_go_right() {
	if (!$(".client_images li:visible").is(":last-child")) {
		$(".client_images li:visible").hide().next().show();	
	} 

	if (!$(".client_images li:visible").is(":first-child")) { $(".client_photo_left").show(); }	else { $(".client_photo_left").hide(); }
	if (!$(".client_images li:visible").is(":last-child")) { $(".client_photo_right").show(); } else { $(".client_photo_right").hide(); }
}
/* End Clients Functions */


function debug(text) {
	$("#info").text(text);
}
