/*
 * Title Caps
 * 
 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
 * License: http://www.opensource.org/licenses/mit-license.php
 */

(function(){
	var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
	var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
  
	this.titleCaps = function(title){
		var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0;
		
		while (true) {
			var m = split.exec(title);

			parts.push( title.substring(index, m ? m.index : title.length)
				.replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){
					return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
				})
				.replace(RegExp("\\b" + small + "\\b", "ig"), lower)
				.replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word){
					return punct + upper(word);
				})
				.replace(RegExp("\\b" + small + punct + "$", "ig"), upper));
			
			index = split.lastIndex;
			
			if ( m ) parts.push( m[0] );
			else break;
		}
		
		return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
			.replace(/(['Õ])S\b/ig, "$1s")
			.replace(/\b(AT&T|Q&A)\b/ig, function(all){
				return all.toUpperCase();
			});
	};
    
	function lower(word){
		return word.toLowerCase();
	}
    
	function upper(word){
	  return word.substr(0,1).toUpperCase() + word.substr(1);
	}
})();


//CONTROLLING EVENTS IN jQuery
jQuery(function($){
	
	/***************************/
	//@Author: Adrian "yEnS" Mato Gondelle
	//@website: www.yensdesign.com
	//@email: yensamg@gmail.com
	//@license: Feel free to use it, but keep this credits please!					
	/***************************/

	//SETTING UP OUR POPUP
	//0 means disabled; 1 means enabled;
	var popupStatus = 0;

	//loading popup with jQuery magic!
	function loadPopup(){
		//loads popup only if it is disabled
		if(popupStatus==0){
			$("#popupContact").fadeIn("slow");
			popupStatus = 1;
		}
	}

	//disabling popup with jQuery magic!
	function disablePopup(){
		//disables popup only if it is enabled
		if(popupStatus==1){
			$("#popupContact").fadeOut("slow");
			popupStatus = 0;
		}
	}

	//centering popup
	function centerPopup(){
		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#popupContact").height() + 20;
		var popupWidth = $("#popupContact").width();
		//centering
		$("#popupContact").css({
			"position": "absolute",
			"top": windowHeight/2-popupHeight/2,
			"left": windowWidth/2-popupWidth/2
		});

	}

	var allMonthsSelected;

	function validateMonths() {
		$('form#cal_chooser input').each(function (i) {
			if(this.value == "") {
				allMonthsSelected = false;
				return false;
			} else {
				allMonthsSelected = true;
				return true;
			}
		});
	}
	
	function getImageName(imagePath) {
		var regX = new RegExp("[0-9]+_");	
		var image = imagePath.substring(imagePath.lastIndexOf('/')+1,imagePath.length);
		var design = image.substring(0,image.lastIndexOf('.'));
		design = design.replace(regX,"");
		//design = design.replace(/-/g," ");  // jud
		design = design.replace(/-/g,"");  // jud
		design = titleCaps(design);
		return design;
	}
	
	function getImageNameSpaces(imagePath) {
		var regX = new RegExp("[0-9]+_");	
		var image = imagePath.substring(imagePath.lastIndexOf('/')+1,imagePath.length);
		var design = image.substring(0,image.lastIndexOf('.'));
		design = design.replace(regX,"");
		design = design.replace(/-/g," ");  // jud
		design = titleCaps(design);
		return design;
	}
	
	var currentMonth;
	// var currentMonthSrc = $("div.galleria_wrapper img").attr("src");

		
	//LOADING POPUP
	
	$("#months li").hover(
		function(){
			$(this).addClass('month_over');},
		function(){
			$(this).removeClass('month_over');
		}
	);
	
	//Click the button event!
	$("#months li").click(function(){
		currentMonth = $(this);
		currentMonthClass = $(this).children("img").attr('class');

		//centering with css
		centerPopup();
		//load popup
		loadPopup();
		var month = $(this).children("p").text();
		$("#month").text(month);
		
		var monthImage = $(this).find("img").attr("src");
		if(monthImage == "choose-image.png"){
			
		} else {
			$("div.galleria_wrapper img").attr("src", monthImage);
			var monthImageName = $(this).children("img").attr('src');
			monthImageName = getImageNameSpaces(monthImageName);
			$(".caption").text(monthImageName);
			currentMonthSrc = $("div.galleria_wrapper img").attr("src");
		}
	});
				
	//CLOSING POPUP
	//Click the x event!
	$("#popupContactClose").click(function(){
		disablePopup();
		currentMonth.children('img').attr('src', currentMonthSrc);
		var design = getImageName(currentMonthSrc);
		currentMonthClass = "input." + currentMonthClass + 'Img';  // jud
		$(currentMonthClass).val(design);
	});
	
	$("#choose").click(function(){
		disablePopup();
		currentMonth.children('img').attr('src', currentMonthSrc);
		var design = getImageName(currentMonthSrc);
		currentMonthClass = "input." + currentMonthClass + 'Img';  // jud
		$(currentMonthClass).val(design);
	});

	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
	
	// $('#choose').click(function() {
	// 	var currentMonthSrc = $("li.active img").attr('src');
	// 	disablePopup();
	// 	currentMonth.children('img').attr('src', currentMonthSrc);
	// 	
	// 	var design = getImageName(currentMonthSrc);
	// 	currentMonthClass = "input." + currentMonthClass + 'Img';  // jud
	// 	$(currentMonthClass).val(design);
	// });
	
	// Validate that all the month's images have been selected
	
	$('form#cal_chooser').submit(function() {
		validateMonths();
		if(!allMonthsSelected) {
			alert("Please Choose an Image for Each Month");
		}
		return allMonthsSelected;
	});
	
	
	
	// =========== Gallery Functionality =============
	
	
	// $('.gallery_unstyled').addClass('gallery'); // adds new class name to maintain degradability
	$('.nav').css('display','none'); // hides the nav initially
	
	var fadeSpeed = 'fast';  // Can be set to 'slow', 'normal', 'fast' or a time in milliseconds. Set to 0 for no fade. 
	var fadeValue = 0.6;     // They opacity to fade the image to from 0.0 to 1
	
	$('ul.gallery').galleria({
		history   : false, // deactivates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable.
		insert    : '#main_image',
	 							// the containing selector for our main image. 
							  // If not found or undefined (like here), galleria will create a container 
							  // before the ul with the class .galleria_container (see CSS)
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes

			$('.nav').css('display','block'); // shows the nav when the image is showing

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// fade in inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(fadeSpeed,1);

			// fade out active thumbnail
			thumb.fadeTo(fadeSpeed,fadeValue).addClass('selected');
			
			currentMonthSrc = $("div.galleria_wrapper img").attr("src");
		},
		
		onThumb : function(thumb) { // thumbnail effects goes here
			// fetch the thumbnail container
		
			var _li = thumb.parents('li');

			// if thumbnail is active, fade it out.
			var _fadeTo = _li.is('.active') ? "'" + fadeValue + "'" : '1';

			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
			
			
			// click effects
			// thumb.click(
			// 				function(){ 
			// 					currentMonthSrc = $(this).attr('src');
			// 				}
			// 			)
			// hover effects
			thumb.hover(
				function() { thumb.fadeTo(fadeSpeed, fadeValue); },
				function() { _li.not('.active').children('img').fadeTo(fadeSpeed, 1); } // don't fade out if the parent is active
			)
		}
		
	});
		
	
	// =========== Collections Functionality =============
		
	for (i=0; i<collectionNames.length; i++)
	{
		$("select#collections").append("<option value='" + i +"'>"+ collectionNames[i].name +"</option>");
	}
		
	$("select#collections").change(function () {
		var collectionIndex = $(this).find("option:selected").val();
		if(collectionIndex != '') {
	      	$("ul#months li img").each(function(n) {
				this.src = "calendar_images/" + collectionNames[collectionIndex].list[n];
				var design = this.src;
				design = getImageName(design);
				var monthClass = this.className;
				monthClass = "input." + monthClass + 'Img';  // jud
				$(monthClass).val(design);
				
			});
		} else {
			$("ul#months li img").attr('src', 'choose-image.png')
			$("ul#months li img").each(function(n) {
				var monthClass = this.className;
				monthClass = "input." + monthClass + 'Img';  // jud
				$(monthClass).val("");
			});
		}
    });
	
	
});
