//
// 
//  site.js
//
//  Created by  on 2010-12-05.
//  Copyright (c) 2010 murat n konar. All rights reserved.
//


var fotosite = function() {

	return {
	
		_current_gallery_index: undefined, 
		_current_entry_index: 	undefined,
		_overlay_id:			undefined,
		_galleries: 			undefined,
		_bio_scrollview:		undefined,
		_contact_scrollview:	undefined,
		_curve:					"easeInOutQuint",
		_arrow_timeout_id:		undefined,
		_mouse_is_inside_arrow: undefined,
				
				
		// ------------------------------------------------------------------------------------------------------------------------
		//	zeroPad 
		// ------------------------------------------------------------------------------------------------------------------------
		zeroPad: function (number, digit_count){
			var zeroPadded = number.toString();
			while(zeroPadded.length < digit_count) {
				zeroPadded = "0" + zeroPadded;
			}
			return zeroPadded;
		},		

		// ------------------------------------------------------------------------------------------------------------------------
		//	calcFotosHeight 
		// ------------------------------------------------------------------------------------------------------------------------
		calcFotosHeight: function(){
			return $("#container").height()
		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	applyFotoDimensions 
		// ------------------------------------------------------------------------------------------------------------------------
		applyFotoDimensions: function(){
			
			var new_sled_width 		= 0
			var new_fotos_height 	= this.calcFotosHeight()		
			
			$.each($("#bed img"), function(f, foto_element) { 
			
				var $foto_element = $(foto_element)

				var new_foto_width = Math.floor(foto_element.aspect_ratio*new_fotos_height)
				$foto_element.css("height", new_fotos_height);
				$foto_element.css("width", new_foto_width);
			
				new_sled_width += new_foto_width*1.25 // 25% margin of safety.
			})

 			$("#sled").css("width", new_sled_width + "px") 		
 		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	resizeHandler 
		// ------------------------------------------------------------------------------------------------------------------------
		resizeHandler: function () {
		
			var window_height = $(window).height()
					
			var new_container_height = Math.min(Math.max(window_height, 440), 1000)
		
			$('#container').css('height', new_container_height)
		
			this.applyFotoDimensions()
			this.alignEntry(this._current_entry_index)
			
			// adjust overlay geometries
			this.updateOverlayGeometry()
		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	wireUpArrows 
		// ------------------------------------------------------------------------------------------------------------------------
		wireUpArrows: function () {

			var self = this
			
			$(".fotosite-arrow").click(function (e){
		
				var is_left_arrow = $(this).attr('id') == "fotosite-arrow-left"				
				var entry_count = self._galleries[self._current_gallery_index].entries.length
				self.showEntryAtPath(self.pathObjectFromString(self._current_gallery_index + "." + (entry_count + Number(self._current_entry_index) + (is_left_arrow ? -1:1))%entry_count))
				e.preventDefault()
			})

			// rollover animation			
			$('.fotosite-arrow').hover(
				function(e){
					$(this).stop(true, true).addClass('fotosite-arrow-hovered', 500);
					self._mouse_is_inside_arrow = true
					e.preventDefault()
				}, 
				function(e){
					$(this).stop(true, true).removeClass('fotosite-arrow-hovered', 500);
					self._mouse_is_inside_arrow = false
					e.preventDefault()
				}
			)
			

			// setup auto-hide/show functionality
			$(window).mousemove(function (e){
			
				self.showArrows(true)
				
				if (self._arrow_timeout_id != undefined){
					window.clearTimeout(self._arrow_timeout_id);
					self._arrow_timeout_id = undefined; 
				}
				
				if (!self._mouse_is_inside_arrow){
					self._arrow_timeout_id = window.setTimeout(function (){
							self.showArrows(false)
					}, 2000)
				}
			})
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	showArrows 
		// ------------------------------------------------------------------------------------------------------------------------
		showArrows: function (show){
		
			var now_showing = $("#fotosite-arrow-left").calcCoords()["left"] == 0
			if (show != now_showing){
				var new_arrow_offset = show? 0 : ($("#fotosite-arrow-left").width()*-1)
				var easing = show ? "easeOutQuint":"easeInQuint"
				
				$("#fotosite-arrow-left").stop().animate({"left":new_arrow_offset}, 500, easing)
				$("#fotosite-arrow-right").stop().animate({"right":new_arrow_offset}, 500, easing)
			}
		},
		

		// ------------------------------------------------------------------------------------------------------------------------
		//	buildGalleryPicker 
		// ------------------------------------------------------------------------------------------------------------------------
		buildGalleryPicker: function () {
		
			var self = this
			var picker_list = $('#fotosite-gallery-picker-list')
		
			picker_list.empty()

			// add  gallery items
			$.each(this._galleries, function(g, gallery) {
				var itemHTML = '<li><a href="#' + g +'" path_string="' + g + '.0"' + ' class="fotosite-gallery-picker-item">' +  gallery.name + '</a></li>'
				picker_list.append(itemHTML)
			})

			// attach click handlers.
			$('.fotosite-gallery-picker-item').click( function(){			
					var path_string = $(this).attr('path_string')
					self.showEntryAtPath(path_string)
                    return false;
				}
			)

			// this bit makes the items fade on rollover
			$('.fotosite-gallery-picker-item').hover(
				function(){
					$(this).stop(true, true).addClass('hovered', 250);
				}, 
				function(){
					$(this).stop(true, true).removeClass('hovered', 1000);
				}
			)
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	buildOverlayPicker 
		// ------------------------------------------------------------------------------------------------------------------------
		buildOverlayPicker: function () {
		
			var self = this
		
			//add bio...
			var overlay_list = $('#fotosite-overlay-picker-list')
			overlay_list.empty()
			var bio_title 		= (this._site_details.bioTitle)?this._site_details.bioTitle:"Bio";
			var bioItemHTML 	= '<li><a href="#bio" path_string="bio" class="fotosite-overlay-picker-item">' + bio_title + '</a></li>'
			overlay_list.append(bioItemHTML)

			//...and contact
			var contactItemHTML = '<li><a href="#contact" path_string="contact" class="fotosite-overlay-picker-item">Contact</a></li>'
			overlay_list.append(contactItemHTML)

			// attach click handlers.
			$('.fotosite-overlay-picker-item').click( function(){			
					var path_string = $(this).attr('path_string')
					self.showEntryAtPath(path_string)
                    return false;
				}
			)
			
			// add blog after the above block
			var blogItemHTML = '<li><a href="http://decenzo-cordova.tumblr.com/" target="_empty" gallery_index="blog" class="fotosite-overlay-picker-item">Blog</a></li>'
			overlay_list.append(blogItemHTML)

			// this bit makes the items fade on rollover
			$('.fotosite-overlay-picker-item').hover(
				function(){
					$(this).stop(true, true).addClass('hovered', 250);
				}, 
				function(){
					$(this).stop(true, true).removeClass('hovered', 1000);
				}
			)
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	buildSocialPicker 
		// ------------------------------------------------------------------------------------------------------------------------
		buildSocialPicker: function (){
		
			// add facebook and twitter items
			var social_list = $('#fotosite-social-picker-list')
			social_list.empty()

			var facebookItemHTML = '<li><a href="http://www.facebook.com/people/DeCenzo-N-Cordova/1412376103" target="_empty" gallery_index="facebook" class="social-badge-link"><img src="+images/facebook-badges.png"></a></li>'
			social_list.append(facebookItemHTML)
			
			var twitterItemHTML = '<li><a href="http://twitter.com/DeCenzoCordova" target="_empty" gallery_index="twitter" class="social-badge-link"><img src="+images/twitter-badges.png"></a></li>'
			social_list.append(twitterItemHTML)

			var blogspotItemHTML = '<li><a href="http://decenzo-cordova.blogspot.com/" target="_empty" gallery_index="blogspot" class="social-badge-link"><img src="+images/blogspot-badges.png"></a></li>'
			social_list.append(blogspotItemHTML)

		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	rebuildEntryPickerForGallery 
		// ------------------------------------------------------------------------------------------------------------------------
		rebuildEntryPickerForGallery: function (gallery_index) {
		
			var self = this
			var gallery = this._galleries[gallery_index];
			var picker_list = $('#fotosite-entry-picker-list')
			var digit_count = Number(gallery.entries.length).toString().length
		
			picker_list.empty()

			$.each(gallery.entries, function(e, entry) {
			
				var link_text = self.zeroPad(e, digit_count)
				var itemHTML = '<li><a href="#' + gallery_index + "/" + e +'" entry_index=' + e + ' class="fotosite-entry-picker-item">' +  link_text + '</a></li>'
				picker_list.append(itemHTML)
			})
			
			// Attach click handlers.
			$('.fotosite-entry-picker-item').click( function(){			
					var entry_index = $(this).attr('entry_index')
					self.showEntryAtPath(self.pathObjectFromString(gallery_index + "." + entry_index))
                    return false;
				}
			)

			// Attach hover handlers.
			$('.fotosite-entry-picker-item').hoverIntent( function(){			
					var entry_index = $(this).attr('entry_index')
					self.showEntryAtPath(self.pathObjectFromString(gallery_index + "." + entry_index))
                    return false;
				},
				function(){}
			)

			// Start out with entry picker items (nearly) invisible.
			$('.fotosite-entry-picker-item').css('opacity', 0.1)
		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	pathObjectFromString 
		// ------------------------------------------------------------------------------------------------------------------------
		pathObjectFromString: function (path_string)
		{
			// path_string should be of the form:
			// 3.12.bio
			
			// the corresponding path object would be:
			// { 'gallery_index':3, 'entry_index':12, 'overlay_id':'bio'}
			
			var g = this._current_gallery_index?this._current_gallery_index:0
			var e = this._current_entry_index?this._current_entry_index:0
			
			var path_object = {'gallery_index':g, 'entry_index':e} // default result

				
			if (path_string && path_string.length > 0) {
				var path_components = path_string.split('.')
			
				if (path_components.length == 3 && !isNaN(path_components[0]) && !isNaN(path_components[1]) && isNaN(path_components[2])) {
				
					path_object['gallery_index'] 	= Number(path_components[0])
					path_object['entry_index'] 		= Number(path_components[1])
					path_object['overlay_id'] 		= path_components[2]
				}
				else if (path_components.length == 2 && !isNaN(path_components[0]) && !isNaN(path_components[1])) {
				
					path_object['gallery_index'] 	= Number(path_components[0])
					path_object['entry_index'] 		= Number(path_components[1])
				}
				else if (path_components.length == 1){
					if (isNaN(path_components[0])) {					
						path_object['overlay_id'] = path_components[0]
					}
					else {
						path_object['gallery_index'] = Number(path_components[0])
					}
				}
			}
			
			return path_object
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	alignEntry 
		// ------------------------------------------------------------------------------------------------------------------------
		alignEntry: function (f, duration, epilog){


			var foto_image = $("#foto-" + f)
			if (foto_image.length) {
			
				var delta = foto_image.offset()["left"] - $("#nav").calcCoords()['right']
				var new_sled_left = $("#sled").offset()["left"] - delta
	 	
	 			if (duration != undefined && duration > 0){
		 			$("#sled").stop()
		 			$("#sled").animate({'left': "-="+delta+"px"}, duration, this._curve, epilog)				
				}
				else {
					$("#sled").css("left", new_sled_left + "px")				
				}
			}
		},
		
						
		// ------------------------------------------------------------------------------------------------------------------------
		//	syncGalleryPicker 
		// ------------------------------------------------------------------------------------------------------------------------
		syncGalleryPicker: function () {
			
			var self = this
			$('.fotosite-gallery-picker-item.current').stop(true, true).removeClass('current');
				
			$('.fotosite-gallery-picker-item').each(function (index, item){
			
				var item_path_object = self.pathObjectFromString($(item).attr('path_string'))
				if (item_path_object['gallery_index'] == self._current_gallery_index) {
					$(item).stop(true, true).removeClass('hover').addClass('current');
				}
			})
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	syncEntryPicker 
		// ------------------------------------------------------------------------------------------------------------------------
		syncEntryPicker: function () {
			
			var self = this
			$('.fotosite-entry-picker-item.current').stop(true, true).removeClass('current');	
			
			$('.fotosite-entry-picker-item').each(function (index, item){

				if ($(item).attr('entry_index') == self._current_entry_index) {
					$(item).stop(true, true).addClass('current');
				}
			})
		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	syncDocumentTitle 
		// ------------------------------------------------------------------------------------------------------------------------
		syncDocumentTitle: function () {
		
			var new_window_title = ""

			if (this._overlay_id) {
				
				var overlay_name = "overlay"
				if (this._overlay_id == "bio") {
					overlay_name = (this._site_details.bioTitle)?this._site_details.bioTitle:"Bio";
				}
				else if (this._overlay_id == "contact") {
					overlay_name = "Contact"
				}

				new_window_title = this._site_details.pageTitle + " : " + overlay_name
			}
			else {
				var gallery_name = this._galleries[this._current_gallery_index].name
				new_window_title = this._site_details.pageTitle + " : " + gallery_name
			}
			
			document.title = new_window_title
		},
				
		// ------------------------------------------------------------------------------------------------------------------------
		//	showEntryAtPath 
		// ------------------------------------------------------------------------------------------------------------------------
		showEntryAtPath: function (new_path) {
		
			if (typeof new_path == "string"){
				new_path = this.pathObjectFromString(new_path)
			}

			var self = this
			var bed = $("#bed")		
			var new_gallery_index 	= new_path['gallery_index']
			var new_entry_index 	= new_path['entry_index']

			$("#gallery").fadeIn()
			$(".fotosite-arrow").fadeIn()
			$("#fotosite-entry-picker").fadeIn()
		
			if (new_gallery_index != this._current_gallery_index) {
				
				// New Gallery
						
				this._current_gallery_index = new_gallery_index
				this._current_entry_index = new_entry_index
				this.rebuildEntryPickerForGallery(new_gallery_index)
				this.syncGalleryPicker()
				this.syncEntryPicker()

				bed.fadeOut(500, self._curve, function(){		
							
					$("#sled").css("left", bed.calcCoords()['right'])
					self.setupEntries(new_gallery_index);
					bed.fadeIn(50, self._curve, function(){
						self.applyFotoDimensions();
						self.alignEntry(new_entry_index, 900);
					})							

				});
			}
			else {
				// new entry
				self._current_entry_index = Number(new_entry_index)
				self.syncEntryPicker()
				this.alignEntry(new_entry_index, 900)
			}
			
			// Overlay?
			this._overlay_id = new_path['overlay_id']
			if (this._overlay_id == undefined) {
				$("#fotosite-bio").fadeOut()
				$("#fotosite-contact").fadeOut()
			}
			else if (this._overlay_id == 'bio') {
				$("#fotosite-bio").fadeIn()
				$("#fotosite-contact").fadeOut()
				this.updateOverlayGeometry()
			}
			else if (this._overlay_id == 'contact') {
				$("#fotosite-bio").fadeOut()
				$("#fotosite-contact").fadeIn()
				this.updateOverlayGeometry()
			}
			
			this.syncDocumentTitle()

			// update address bar
			var new_hash = "#" + this._current_gallery_index + "." + this._current_entry_index
			if (this._overlay_id != undefined) {
				new_hash = new_hash + "." + this._overlay_id
			}
			if (window.location.hash != new_hash) {
				window.location.hash = new_hash
			}
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	setupEntries 
		// ------------------------------------------------------------------------------------------------------------------------
		setupEntries: function (gallery_index) {

			var self 		= this;
			var sled 		= $("#sled")
		
			sled.empty()
			
			$.each(this._galleries[gallery_index].entries, function(e, entry) { // for each entry in gallery

				var image = new Image()
				sled.append(image)
				
				var $image = $(image)

				var _epilog = function (){
		 			$image.delay(100).animate({"opacity" : 1.0}, 750, self._curve)
		 			
		 			// show the corresponding item in the entry picker
		 			$($(".fotosite-entry-picker-item")[e]).css("opacity", 1.0)
				}
				
				image.id="foto-" + e
				image.aspect_ratio = entry.fotowidth/entry.fotoheight

				$(image).css("opacity", 0.01) // Start it out invisible. We'll fade it in when it loads.
								
				image.src = entry.fotopath // This will start the load

				if (image.complete){
					_epilog()
				}
				else {
					$image.load(_epilog)
				}			
				
				$image.click(function (){
					self.showEntryAtPath(gallery_index + "." + e)
				})	
			})
		},			
	
		// ------------------------------------------------------------------------------------------------------------------------
		//	updateOverlayGeometry 
		// ------------------------------------------------------------------------------------------------------------------------
		updateOverlayGeometry: function () {
	
			var container_height = $('#container').height()
			var logo_top = $("#logo img").offset()['top']

			var new_height = container_height - 2*logo_top - 40;
			$(".fotosite-overlay .viewport").css('height', new_height)

			this._contact_scrollview.update();
			this._bio_scrollview.update();
		},			

		// ------------------------------------------------------------------------------------------------------------------------
		//	fillInOverlays
		// ------------------------------------------------------------------------------------------------------------------------
		fillInOverlays: function () {

			this._bio_scrollview = $("#fotosite-bio .scrollview")
			$("#fotosite-bio .fotosite-overlay-content .text").append(this._site_details.bioHTML)
			this._bio_scrollview.tinyscrollbar();

			this._contact_scrollview = $("#fotosite-contact .scrollview")
			$("#fotosite-contact .fotosite-overlay-content .text").append(this._site_details.contactHTML)
			this._contact_scrollview.tinyscrollbar();
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	exitOverlay 
		// ------------------------------------------------------------------------------------------------------------------------
		exitOverlay: function () {
			this.showEntryAtPath(self._current_gallery_index + "." + self._current_entry_index)
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	overlayClickHandler 
		// ------------------------------------------------------------------------------------------------------------------------
		overlayClickHandler: function (e){

			if (e.type == "click"){
				if ($(e.target).hasClass("fotosite-overlay") || $(e.target).hasClass("viewport")){			
					this.exitOverlay()
					event.preventDefault();
				}
			}
		},
		
		// ------------------------------------------------------------------------------------------------------------------------
		//	overlayIsVisible 
		// ------------------------------------------------------------------------------------------------------------------------
		overlayIsVisible: function (){
			
			var overlay_is_visible = false;
			
			$.each($(".fotosite-overlay"), function(i, overlay) {
				if (!overlay_is_visible && $(overlay).is(":visible")) {
					overlay_is_visible = true
				}
			})
			
			return overlay_is_visible
		},


		// ------------------------------------------------------------------------------------------------------------------------
		//	keydownHandler 
		// ------------------------------------------------------------------------------------------------------------------------
		keydownHandler: function (event){
			
			if (this.overlayIsVisible()) {
				if (event.keyCode == 27){
					this.exitOverlay()
				}
			}
			else if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40){
		
				var g = Number(this._current_gallery_index)
				var e = Number(this._current_entry_index)
		
				if (event.keyCode == 37 || event.keyCode == 38) {
					e = (this._galleries[g].entries.length + e - 1)%this._galleries[g].entries.length
	
				}
				else {
					e = (e + 1)%this._galleries[g].entries.length
				}
				
				var path_string = g + "." + e
				
				this.showEntryAtPath(this.pathObjectFromString(path_string))
	
				event.preventDefault();
			}
		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	initializeHistory 
		// ------------------------------------------------------------------------------------------------------------------------
		initializeHistory: function(){

			var self = this
			
			$.history.init(function (hash) {
				var path_object = self.pathObjectFromString(hash)
				self.showEntryAtPath(path_object)
			},
			{ unescape: ",/" }
			);
		},

		// ------------------------------------------------------------------------------------------------------------------------
		//	initialize 
		// ------------------------------------------------------------------------------------------------------------------------
		initialize: function () {

			var self = this

			// Start bio and contact sections out invisible.
			$("#fotosite-bio").fadeOut(0)
			$("#fotosite-contact").fadeOut(0)

			var _initialize = function () {			
						
				// Prevent scrolling on ios
				$('body').bind("touchmove", {}, function(event){
				  	event.preventDefault();
				});								

				$("#logo img").load(function(){}) // so we can't get called again.
				
				$("#nav").css("opacity", 0.05)				
								
				var data = fotosite_content();
				self._site_details = data.sitedetails
				self._galleries = data.galleries;
				
				$("#fotosite-banner").empty().append(self._site_details.bannerHTML)
				$("#fotosite-copyright").empty().append(self._site_details.copyrightHTML)
	
				// Build gallery navigation
				self.buildGalleryPicker()
				self.buildOverlayPicker()
				self.buildSocialPicker()
				
				self.wireUpArrows()
	
				// Build out contact and bio sections
				self.fillInOverlays()
				
				// Hook up event handlers for overlays
				$(".fotosite-overlay").click(function (e){self.overlayClickHandler(e)})
				
				// setup resize handling
				$(window).resize(function () {self.resizeHandler()})
	
	
				self.resizeHandler() // call once
	
				// setup keyboard shortcuts
				$(document).keydown(function (e){self.keydownHandler(e)})
				
	
				// History
				$.history.init(function (hash) {
					var path_object = self.pathObjectFromString(hash)
					self.showEntryAtPath(path_object)
				},
				{ unescape: ",/" }
				);

				$("#nav").animate({"opacity": 1.0}, 500)				
			}
									
			// This trick allows us to defer setup until 
			// the logo image is loaded.

			if ($("#logo img")[0].complete){
				_initialize()
			}			
			else {
	 			$("#logo img").load(_initialize)
			}
		}
	};
}();


