// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(window).load(function () {
	
	window.setTimeout(function() {
		$("#body").height($("#content").height());
	}, 50);
	
	// show pop-up character
	window.setTimeout(function() {
		animateShowPopupCharacter();
	}, 500);
	
	$('#popup_loading').flash({
		swf: 'loading-indicator.swf',
		wmode: 'transparent',
		width: '420'
		// hasVersion: 10 // requires Flash 10
	});
	
	// preload gallery background
	PreloadImage("/images/gui/bg-content.png", function(){
	});
	window.isReady = true;
});
$(document).ready(function(){
	
	jQuery.fn.exists = function(){return jQuery(this).length>0;}
	
	jQuery.easing.def = "easeOutExpo";
	
	window.galleryWidth = 960;
	window.galleryGap = 10;
	window.maxPage = 0;
	window.characterHidden = false;
	
	window.isReady = false;
	
	var loadIndex = 0;

	if ($("#new_contact").exists()) {
		$("#new_contact").validate();
	}
	

	// Menu Animation
	$("#nav_portfolio a:not(.active)").mouseenter(function(){
		$(this).stop().animate({
			opacity: 1
		}, 600, 'easeOutCirc', function() {
			// Animation complete.
		});
	}).mouseleave(function(){
		$(this).stop().animate({
			opacity: 0
		}, 600, 'easeOutCirc', function() {
			// Animation complete.
		});
	});
	$("#nav_main a:not(.active)").mouseenter(function(){
		$(this).stop().animate({
			opacity: 1
		}, 600, 'easeOutCirc', function() {
			// Animation complete.
		});
	}).mouseleave(function(){
		$(this).stop().animate({
			opacity: 0
		}, 600, 'easeOutCirc', function() {
			// Animation complete.
		});
	});
	
	$("li.fade").hover(function(){$(this).fadeOut(100);$(this).fadeIn(500);});
	
	$(".show_post_link").click(function(){
		disablePost();
	});
	

	$("#body").ajaxComplete(function(event,request, settings){
	   // $(this).append("<li>Request Complete.</li>");
		if ($("#nav_main a.active").length > 0) {
			
			$(".date").corner();
			$(".index").corner();
			$(".comment .content").corner();
			$("#feature_posts").corner();
			
			// console.log("#posts_wrapper : "+$("#posts_wrapper").height());
			// resizeBody($("#posts_wrapper").height());
			// alert("#posts_wrapper : "+$("#posts_wrapper").height());
			// resizeBody($("#posts_wrapper").height());
			
		}else if($("#nav_portfolio a.active").length > 0){
			window.setTimeout(function() {
				animateOpen($("#nav_portfolio a.active"), $("#gallery").height(), function(){
					showContent("gallery");
				});
				window.setTimeout(function() {
					loadGalleryItem(0);
				}, 1000);
			}, 1500);
		}
	 });
	
	$('#nav_portfolio .character a').click(function(){
		var element = $(this);
		if (window.isReady) {
			animateHideContent();
			
			animateHidePopupCharacter(function(){
				window.isReady = false;
				makeActive(element);
				window.setTimeout(function() {
					$('#gallery').html('');
					$('#gallery_triggers').html('');
					animateClose();
					loadGalleryData('/characters.js');
				}, 50);
			
			});
			
		}
		return false;
		
	});
	
	$('#nav_portfolio .illustration a').click(function(){
		var element = $(this);
		if (window.isReady) {
			animateHideContent();
			animateHidePopupCharacter(function(){
			
				makeActive(element);
				window.isReady = false;
				window.setTimeout(function() {
					$('#gallery').html('');
					$('#gallery_triggers').html('');
					animateClose();
					loadGalleryData('/illustrations.js');
				}, 50);
		
			});
		}
		return false;
	});
	
	$('#nav_portfolio .print_identity a').click(function(){
		var element = $(this);
		if (window.isReady) {		
			animateHideContent();
			animateHidePopupCharacter(function(){
		
				makeActive(element);
				window.isReady = false;
				window.setTimeout(function() {
					$('#gallery').html('');
					$('#gallery_triggers').html('');
					animateClose();
					loadGalleryData('/printings.js');
				}, 50);
			
			});
		}		
		return false;
	});
	
	$('#nav_portfolio .web_design a').click(function(){
		var element = $(this);
		if (window.isReady) {		
			animateHideContent();
			animateHidePopupCharacter(function(){

				makeActive(element);
				window.isReady = false;
				window.setTimeout(function() {
					$('#gallery').html('');
					$('#gallery_triggers').html('');
					animateClose();
					loadGalleryData('/webdesigns.js');
				}, 50);

			});
		}		
		return false;
	});
	
	$('#nav_main .tutorial a').click(function(){
		var element = $(this);
		if (window.isReady) {
			makeActive(element);		
			animateHideContent();
			animateHidePopupCharacter(function(){
			
				window.setTimeout(function() {
					animateClose();
					window.setTimeout(function() {
						$("#tutorial_hidden_link").click();
					}, 1000);
				}, 50);
			
			});
		}
		return false;
	});
	
	$('#nav_main .blog a').click(function(){
		var element = $(this);
		if (window.isReady) {		
			makeActive(element);		
			animateHideContent();
			animateHidePopupCharacter(function(){
			
				window.setTimeout(function() {
					animateClose();
					window.setTimeout(function() {
						$("#blog_hidden_link").click();
					}, 1000);
				}, 50);
			
			});
		}
		return false;
	});
	
	$('#nav_main .download a').click(function(){
		var element = $(this);
		if (window.isReady) {
			makeActive(element);		
			animateHideContent();
			animateHidePopupCharacter(function(){
			
				window.setTimeout(function() {
					animateClose();
					window.setTimeout(function() {
						$("#download_hidden_link").click();
					}, 1000);
				}, 50);
			
			});
		}
		return false;
	});
	
	$('#nav_main .contact a').click(function(){
		var element = $(this);
		if (window.isReady) {
			makeActive(element);		
			animateHideContent();
			animateHidePopupCharacter(function(){
			
				window.setTimeout(function() {
					animateClose();
					window.setTimeout(function() {
						animateOpen(element, $("#contact").height()+50, function(){
							showContent("contact");
						});

					}, 1000);
				}, 50);
			
			});
		}
		return false;
	});
	
	
	
	$("#submit_comment_button").click(function(){
		$("#new_comment").submit();
		return false;
	});
	
	$("#submit_contact_button").click(function(){
		$("#new_contact").submit();
		return false;
	});
	
	
	$("#new_contact").submit(function(){
		if ($(this).valid()) {
			$("#contact_form_overlay").height($("#new_contact").height());
			$("#contact_form_loading").show();
			$("#contact_form_overlay").show();
			return true;
		}else{
			resizeBody($("#contact").height());
			return false;
		}
	});

	
});

function makeActive(element){
	$("#gallery").addClass('hidden');
	$('#nav_main a').removeClass('active');
	$('#nav_portfolio a').removeClass('active');
	element.addClass('active');
}

function showContent(key){
	if (key == "gallery") {
		$("#gallery").show();
		$("#gallery").removeClass("hidden");
		$("#gallery_triggers").show();
		$("#gallery_triggers").removeClass("hidden");
		$("#body").addClass("show_gallery");
	}else if (key == "post"){
		$("#gallery").html("");
		$("#posts_wrapper").show();
		$("#posts_wrapper").removeClass("hidden");
		$("#body").removeClass("show_gallery");
		// $("#body").addClass("show_post");
		$("#body .folder").hide();
		$("#gallery").hide();
	}else if (key == "contact") {
		// $("#body").addClass("show_contact_form");
		$("#gallery").html("");
		$("#gallery").hide();
		$("#contact").show();
		$("#contact").removeClass("hidden");
		$("#body").removeClass("show_gallery");
		$("#body .folder").hide();
		$("#gallery").hide();
		// $("#body").addClass("show_contact");
	}else{
		
	}
}

function animateHideContent(){
	$("#gallery").height(380);
	// $("#body").height(380);
	// $("#news").addClass("hidden");
	// $("#gallery").addClass("hidden");
	$("#gallery_triggers").hide();
	$("#posts_wrapper").addClass("hidden");
	$("#contact").addClass("hidden");
	window.setTimeout(function() {
		hideContent();
	}, 500);
}

function hideContent(){
	$("#news").hide();
	// $("#gallery").hide();
	$("#gallery_triggers").hide();
	$("#posts_wrapper").hide();
	$("#contact").hide();
}

function animateHidePopupCharacter(collback){
	if (!window.characterHidden) {
		
		$("#popup_character .fade").animate({
			bottom: -365
		}, 300, function(){

		});
		$("#popup_character").animate({
			opacity: 0
		}, 200, 'easeInOutExpo', function(){
			$("#popup_wrapper").removeClass("show_charactor");
			window.characterHidden = true;
			$("#popup_wrapper").hide();
		});
		$("#news").animate({
			// opacity: 0,
			top: -200
		}, 300, 'easeInOutExpo', function(){
			collback();
		});
	}else{
		console.log("character already hidden!");
		collback();
	}
	// collback();
}
function animateShowPopupCharacter(){
	$("#popup_wrapper").addClass("show_charactor");
	
	// $("#popup_character").css({'opacity': 1});
	
	$("#popup_character").animate({
		opacity: 1
	}, 300, 'easeInOutExpo', function(){
		// $("#popup_character").css({'opacity': 1});
	});
	
	$("#popup_character .fade").animate({
		bottom: 0
	}, 400, 'easeInOutExpo', function(){
		window.isReady = true;
	});
	
	$("#news").animate({
		// opacity: 1,
		top: 0
	}, 1000, 'easeInOutExpo', function(){
		
	});
}

function animateClose(){
	
	// show loading indicator
	$("#popup_loading").show();
	$("#popup_wrapper").show();
	$("#popup_wrapper").addClass("show_loading");
	$("#popup_character").hide();
	
	if ($("#body.show_gallery").exists()) {
		$("#body .folder.bottom_cap").show();
	}
	$("#body .folder.bottom").hide();
	
	resizeBody(0);
	
	window.setTimeout(function() {
		// $("#body .folder.bottom_cap").fadeOut(150);
		// $("#body .folder").fadeOut(150);
		$("#body .folder.bottom_cap").hide();
		$("#body .folder").hide();
		$("#body").removeClass("show_gallery");
		$("#gallery").hide();
	},480);
	
	// $("#top_animate_helper").addClass("expand");
	
	$("#top_animate_helper").stop().animate({
	    height: '135px',
	  }, 800, 'easeInOutQuint', function() {
	    // Animation complete.
	});
	
}

function animateOpen(element, height, callback){

	// $("#gallery").removeClass('hidden');
	// $("#gallery").show();
	// $("#gallery_triggers").fadeIn(300);
	
	$("#popup_wrapper").removeClass("show_loading");
	$("#popup_loading").hide();
	$("#popup_character").hide();
	// $("#popup_wrapper").hide();
	
	var offset = element.offset();
	$("#body .folder.top").css("background-position", ((offset.left+25) +"px")+ " 0");
	$("#body .folder.bottom_cap").css("background-position", ((offset.left+25) +"px") + " -50px ");
	
	// $("#top_animate_helper").removeClass("expand");	
	$("#top_animate_helper").stop().animate({
	    height: '0'
	  }, 800, 'easeOutExpo', function() {
	    // Animation complete.
	});
	
	// resizeBody(height);
	// $("#body").animate({
	//     height: newHeight
	//   }, 800, function() {
	//     // Animation complete.
	// });
	
	// $("#body .folder.top").fadeIn(100);
	// $("#body .folder.bottom").fadeIn(100);
	
	$("#body").stop().animate({
	    height: 50
	  }, 50, 'easeInOutExpo', function() {
	    $("#body .folder.top").show();
		$("#body .folder.bottom").show();
		$("#body .folder.bottom_cap").show();
		callback();
		window.setTimeout(function() {
			// $("#body .folder.bottom_cap").fadeOut(100);
			$("#body .folder.bottom_cap").hide();
		},150);
		
		$("#body").animate({
		    height: height
		  }, 700, 'easeOutExpo', function() {
			window.isReady = true;
		});
	});
	
	
}


function resizeBody(newHeight){
	// $("#body").height(newHeight);
	$("#body").stop().animate({
	    height: newHeight
	  }, 800, 'easeInOutQuint', function() {
	    // Animation complete.
		
	});
}


function disablePost(){
	$("#post_overlay").height($("#posts").height()+20);
	$("#post_overlay").fadeIn(300);
	$("#post_loading").fadeIn(300);
}

function enablePost(){
	$("#post_overlay").fadeOut(300);
	$("#post_loading").fadeOut(300);
}

function loadGalleryData(url){
	// console.log("loadGalleryData");
	
	$.getJSON(url, function(data) {
		var items = [];
		var elements = [];
		items = data['gallery']['items']['item'];
		
		$("#gallery_prev_button").remove();
		$("#gallery_next_button").remove();
		
		// $('<div/>', {
		//   'id' : 'gallery',
		//   'class': data['gallery']['type'],
		//   html: ""
		// }).appendTo('#content');
		
		$('<div/>', {
		  'class': 'gallery-container',
		  'style': 'width: ' + (items.length*(window.galleryWidth+window.galleryGap)) + 'px;',
		  html: ""
		}).appendTo('#gallery');
		
		$('<a/>', {
			'id': 'gallery_prev_button',
			'href': '#',
			html: 'Prev'
		}).bind('click', function() {
			galleryPrevPage();
			return false;
		}).appendTo('#gallery_wrapper');
		
		$('<a/>', {
			'id': 'gallery_next_button',
			'href': '#',
			html: 'Next'
		}).bind('click', function() {
			galleryNextPage();
			return false;
		}).appendTo('#gallery_wrapper');
		
		$('<li/>', {
			'class': 'prev-nav',
			html: $('<a/>', {
					'id': 'prev-item-nav',
					'class': '',
					'href': '#',
					html: 'Prev'
				}).bind('click', function() {
					galleryPrevPage();
					return false;
				})
		}).appendTo('#gallery_triggers');
		
		$.each(items, function(index){
			
			$('<div/>', {
				'id': 'gallery-item-'+index,
				'class': 'item loading',
				'data-image-url': items[index]['path'],
				html: ""
			}).bind('click', function() {
				// alert('Hello');
			}).append(
				$('<div/>', {
					'class': 'photo_loading_indicator',
				}).append(
					$('<img/>', {
						'src': '/images/gui/loading-3.gif',
						'class': 'loading',
						'width': '43'
					})
				)
			).appendTo('#gallery .gallery-container');
			
			
			
			$('<li/>', {
				'class': 'item-nav',
				html: $('<a/>', {
						'id': 'item-' + index + '-nav',
						'class': '',
						'href': '#',
						html: index
					}).bind('click', function() {
						galleryGoPage(index);
						return false;
					})
			}).appendTo('#gallery_triggers');
			
		});
		
		$('<li/>', {
			'class': 'next-nav',
			html: $('<a/>', {
					'id': 'next-item-nav',
					'class': '',
					'href': '#',
					html: 'Next'
				}).bind('click', function() {
					galleryNextPage();
					return false;
				})
		}).appendTo('#gallery_triggers');
		
		
		if (items.length == 1) {
			window.setTimeout(function() {
				$("#next-item-nav").parent().addClass("disabled");
				$("#gallery_next_button").addClass("disabled");
			}, 200);
		}else{
			
		}
		
		// $(".photo_loading_indicator").each(function(){
		// 	$(this).flash({
		// 		swf: 'loading-indicator.swf',
		// 		wmode: 'transparent',
		// 		width: '420'
		// 	})
		// });
		
		window.maxPage = $('#gallery .item').length;
		activeGalleryNav(0);
		
		// $.each(data, function(key, val) {
		//   items.push('<li id="' + key + '">' + val + '</li>');
		// });
		
		// window.setTimeout(function() {
		// 	loadGalleryItem(0);
		// }, 1500);
		
		
	});
	return true;
}

function galleryGoPage(page){
	var cWidth = parseInt($('#gallery .gallery-container').css('width'));
	var left = parseInt($('#gallery .gallery-container').css('left'));
	var currentPage = Math.floor(left/((window.galleryWidth+window.galleryGap)*(-1)));
	if (page >= 0) {
		var nextHeight = pageHeight(page);
		var currentHeight = pageHeight(currentPage)
		// console.log("nextHeight : "+nextHeight);
		// console.log("currentHeight : "+currentHeight);
		
		if (nextHeight < currentHeight) {
			// resize gallery then slide
			activeGalleryNav(page);
			// $("#body").height(nextHeight);
			$("#body").animate({
			    height: nextHeight
			  }, 400, 'easeOutExpo', function() {
				$("#gallery").height(nextHeight);
				$('#gallery .gallery-container').animate({
				    left: (page*(window.galleryWidth+window.galleryGap)*(-1))
				  }, 800, 'easeOutExpo', function() {
				  });

			  });
		}else if (nextHeight >= currentHeight){
			// slide then resize gallery
			activeGalleryNav(page);
			$('#gallery .gallery-container').animate({
			    left: (page*(window.galleryWidth+window.galleryGap)*(-1))
			  }, 800, 'easeOutExpo', function() {
				$("#gallery").height(nextHeight);
				$("#body").animate({
				    height: nextHeight
				  }, 400, 'easeOutExpo', function() {

				  });
				
			  });
			
		}
		
	}
}

function galleryPrevPage(){
	var cWidth = parseInt($('#gallery .gallery-container').css('width'));
	var left = parseInt($('#gallery .gallery-container').css('left'));
	var currentPage = Math.floor(left/((window.galleryWidth+window.galleryGap)*(-1)));

	if(0 < currentPage){
		galleryGoPage(currentPage-1);
	}
}

function galleryNextPage(){
	var cWidth = parseInt($('#gallery .gallery-container').css('width'));
	var left = parseInt($('#gallery .gallery-container').css('left'));
	var currentPage = Math.floor(left/((window.galleryWidth+window.galleryGap)*(-1)));
	
	if((window.maxPage-1) > currentPage){
		galleryGoPage(currentPage+1);
	}
}

function activeGalleryNav(page){
	var navID = "#item-"+page+"-nav";
	$("#gallery_triggers a").removeClass("active");
	$(navID).addClass("active");
	if (0 == page) {
		$("#prev-item-nav").parent().addClass("disabled");
		$("#gallery_prev_button").addClass("disabled");
		$("#next-item-nav").parent().removeClass("disabled");
		$("#gallery_next_button").removeClass("disabled");
	}else if(page == (window.maxPage-1)){
		$("#prev-item-nav").parent().removeClass("disabled");
		$("#gallery_prev_button").removeClass("disabled");
		$("#next-item-nav").parent().addClass("disabled");
		$("#gallery_next_button").addClass("disabled");
	}else{
		$("#prev-item-nav").parent().removeClass("disabled");
		$("#gallery_prev_button").removeClass("disabled");
		$("#next-item-nav").parent().removeClass("disabled");
		$("#gallery_next_button").removeClass("disabled");
	}
}

function pageHeight(index){
	var pageImageID = '#gallery-item-'+index+" img.photo";
	var h = $(pageImageID).height();
	if(h == null){
		return 400;
	}else{
		return h;
	}
}

function resizeGallery(index){
	if (window.isReady) {
		var newHeight = pageHeight(index);
		var oldHeight = $("#gallery").height();
		// alert("photo height : "+h);
		if (oldHeight < newHeight) {
			// set #gallery height then animate #body
			$("#gallery").height(newHeight);
			$("#body").animate({
				height: newHeight
			}, 400, 'easeOutExpo', function() {
			
			});
		}else{
			// animate #body then set #gallery height
			$("#body").animate({
				height: newHeight
			}, 400, 'easeOutExpo', function() {
				$("#gallery").height(newHeight);
			});
		}
	}
}

function loadGalleryItem(index){
	
	if (index < window.maxPage) {
		var ele = $('#gallery .item')[index];
		var src = $(ele).attr('data-image-url');
		
		PreloadImage(src, function(){
			// $('.loading', ele).remove();
			$(".photo_loading_indicator", ele).fadeOut(100);
			$(ele).removeClass('loading');
			$(ele).addClass('complete');
			$('<img/>', {
				'class': 'photo',
				'src': src
			}).appendTo(ele);
			
			
			var cWidth = parseInt($('#gallery .gallery-container').css('width'));
			var left = parseInt($('#gallery .gallery-container').css('left'));
			var currentPage = Math.floor(left/((window.galleryWidth+window.galleryGap)*(-1)));
			// alert(currentPage);
			if (index == currentPage) {
				window.setTimeout(function() {
					resizeGallery(index);
				}, 100);
				// alert('xxx');
			}
			
			// if (index == 0) {
			// 	window.setTimeout(function() {
			// 		animateOpen($("#nav_portfolio a.active"), $("#gallery").height());
			// 		showContent("gallery");
			// 		window.setTimeout(function() {
			// 			resizeGallery(index);
			// 		}, 100);
			// 	}, 2000);
			// }
			
			loadGalleryItem(index+1)
		});
	}else{
		// remove main loadding indicator
	}
	
}

function PreloadImage(imgSrc, callback){
  var objImagePreloader = new Image();

  objImagePreloader.src = imgSrc;
  if(objImagePreloader.complete){
	window.setTimeout(function() {
		callback();
	}, 3000);
    objImagePreloader.onload=function(){};
  }else{
    objImagePreloader.onload = function() {
      callback();
      //    clear onLoad, IE behaves irratically with animated gifs otherwise
      objImagePreloader.onload=function(){};
    }
  }
}


function clearCommentForm(){
	$(':input','#new_comment')
	 .not(':button, :submit, :reset, :hidden')
	 .val('')
	 .removeAttr('checked')
	 .removeAttr('selected');
	$("#comment_form_loading").hide();
	$("#comment_form_overlay").hide();
	
}
