$(document).ready(function(){
	/* jquery commands here */
	
	
	// Press Releases Page Initialization
	if ($("#pr-ajax-content").length == 1) objPressReleases.init_page();
	
	// Photo Gallery Page Initialization
	if ($("#gallery-container").length == 1) {
		objPhotoGallery.init_page();
	} else {
		objPhotoGallery.update_image_count();
		objPhotoGallery.init_global_handlers();
	}
	
	// Photo Gallery Submit Request Form
	if ($("form#submit-request-form").length == 1) {
		objPhotoGalleryRequestForm.init_page();
	}
	
	// Preload Images
	objGlobals.preload_images();
	
	// Initialize fancybox for image selections sidebar
	objGlobals.init_fancybox_sidebar();
	
	
});


/**
 * Press Release Page
 *
 * @package default
 * @author Jesse Bunch
 * @since 1.0
 **/
var objPressReleases = {
	
	/* Private Properties
	------------------------------------------------------------------------- */
	_objKeyupTimer : '',
	
	
	/* Public Methods
	------------------------------------------------------------------------- */
	
	init_page : function() {
		
		// Load necessary scripts
		objGlobals.load_script(objGlobals.strjQueryEasingPath);
		
		// Hide the submit button if JS is enabled
		$("input#pr-submit-filter").hide();
		
		// Is there only one entry to display? If so, open it
		objPressReleases.check_for_single_entry();
		
		$("#pr-choose-category, #pr-choose-year").change(function() {
			
			objPressReleases.fetch_pr_content();
			
		});
		
		// Cancel submit on AJAX filter form
		$("#pr-filter-form").submit(function() { return false; });
		
		// Keyup handler for the keywords box
		$("#pr-choose-keywords").keyup(function() {
			
			// Wait 500ms before hitting the DB
			clearTimeout(objPressReleases._objKeyupTimer);
			objPressReleases._objKeyupTimer = setTimeout(function() {
				objPressReleases.fetch_pr_content();
			}, 500);
			
		});
		
		// Persistant Click Handler for "Hide/Show Links"
		$("a.btn-hideshow").live("click", function() {
			
			var elemEntry = $(this).next('div.pr-entry');
			
			if (elemEntry.is(":visible")) {
				
				elemEntry.slideUp(250, 'easeInOutQuint');
				$(this).html('Show');
				
			} else {
				
				$(".pr-entry:visible").slideUp(250, 'easeInOutQuint');
				$("a.btn-hideshow").html("Show");
				
				elemEntry.slideDown(250, 'easeInOutQuint');
				$(this).html('Hide');
				
			}
			return false;
		});
		
		
	},
	
	fetch_pr_content : function(strCategory, intYear, strKeywords) {
		
		// Show the loader
		$("#pr-ajax-content").html('Loading...');
		
		// Parse the URL
		$.post('/press-releases/ajax-content/',{
		 'category': $("#pr-choose-category").val(), 'year': $("#pr-choose-year").val(), 'search:general_content': $("#pr-choose-keywords").val()},
		 objPressReleases._insertLoadedPR , 'html');		
		
	},
	
	check_for_single_entry : function() {
		
		var elemEntries = $("#pr-ajax-content div.pr-entry");
		if (elemEntries.length == 1) {
			elemEntries.show();
			$("a.btn-hideshow").hide();
		} else {
			$("a.btn-hideshow").show();
		}
		
	},
	
	
	/* Private Methods
	------------------------------------------------------------------------- */
	_insertLoadedPR : function(strData) {
		
		$("#pr-ajax-content").html(strData);
		
		// Is there only one entry to display? If so, open it
		objPressReleases.check_for_single_entry();
		
	}
	
};

var objPhotoGallery = {
	
	_strPathToAPI : '/application/photo_handler.php',
	
	init_page : function() {
		
		// Load jQuery UI and jCarousel for this page
		objGlobals.load_script(objGlobals.strjQueryUIPath);
		objGlobals.load_script(objGlobals.strjQueryEasingPath);
		objGlobals.load_script(objGlobals.strjCarouselLitePath);
		
		objPhotoGallery.init_fancybox();
		
		// Handle "Add Selected Images" button clicks
		$("a#btn-add-selected-images").click(objPhotoGallery.add_to_cart);
		
		objPhotoGallery.init_global_handlers();
		
		// Set image selection text
		objPhotoGallery.update_image_count();
		
		// Override the filter form submit
		$("#pg-filter-form").submit(objPhotoGallery.submit_gallery_filter);
		
		// Set up the carousel
		objPhotoGallery.init_carousel();
		
		// Show all images link
		$("#pg-show-all").click(function() {
			$("#gallery-container").css('height', 'auto');
			$("#pagination").hide();
			return false;
		});
		
	},
	
	init_global_handlers : function() {
		
		// Handle "Remove Image" link clicks
		$("a.selection-remove-link").live("click", objPhotoGallery.remove_from_cart);
		
	},
	
	init_fancybox : function() {
		
		$("a.pg-image-thumb").fancybox(objGlobals.objFancyboxOptions);
		
		var objDetailFancyboxOptions = objGlobals.objFancyboxOptions;
		objDetailFancyboxOptions.padding = 0;
		objDetailFancyboxOptions.margin = 0;
		objDetailFancyboxOptions.transitionIn = 'fade';
		objDetailFancyboxOptions.transitionOut = 'fade';
		$("a.details").fancybox(objDetailFancyboxOptions);
		
	},
	
	init_carousel : function() {
		
		$("#gallery-container").jCarouselLite({
			circular: false,
			visible: 1,
			vertical: true,
			btnNext: '#pg-nav-next',
			btnPrev: '#pg-nav-prev',
			easing: 'easeOutQuint',
			speed: 1000,
			afterEnd: objPhotoGallery.calculate_gallery_page_numbers
		});
		
		objPhotoGallery.calculate_gallery_page_numbers($("#gallery-container ul li:first"));
		
		
	},
	
	calculate_gallery_page_numbers : function(objElement) {
		
		var intCurrentPage = $(objElement).index() + 1;
		var intTotalPages = $("#gallery-container ul li").length
		
		$("span#pg-page-numbers").html('Page ' + intCurrentPage + ' of ' + intTotalPages);
		
	},
	
	remove_from_cart : function() {
		
		var objLinkClicked = $(this);
		
		$.post(objPhotoGallery._strPathToAPI,{
		 'a': "remove_photo_by_id", 'id': $(this).attr('rel') },
		 function(){

			objLinkClicked.closest('li').slideUp(objPhotoGallery.update_image_count);
			
		
		});
		

		
		
		return false;
	},
	
	add_to_cart : function() {
		
		// Get a list of the checked photos
		var arrIDsToAdd = new Array();
		var objCheckedPhotos = $("input.pg-checkbox-add:checked");
		objCheckedPhotos.each(function(intIndex) {
			arrIDsToAdd.push($(objCheckedPhotos[intIndex]).val());
		});
		
		// Add the photos to the cart
		$.post(objPhotoGallery._strPathToAPI,
			{
				'a': "add_photos_by_comma_separated_ids",
				'ids': arrIDsToAdd.join(',')
			},
			function(){
				
				// Loop through the checked photos and add them to the view
				$(arrIDsToAdd).each(function(intIDIndex) {
					
					// Generate a list of photos already in the view
					var objCurrentIDs = $("a.selection-remove-link");
					var arrCurrentIDs = new Array();
					var arrCurrentIDObjects = new Array()
					objCurrentIDs.each(function(intLinkIndex) {
						arrCurrentIDs.push($(objCurrentIDs[intLinkIndex]).attr('rel'));
						arrCurrentIDObjects[$(objCurrentIDs[intLinkIndex]).attr('rel')] = $(objCurrentIDs[intLinkIndex]);
					});
					
					// Is this photo in the view?
					if ($.inArray(arrIDsToAdd[intIDIndex], arrCurrentIDs) != -1) {
						// Show it
						$(arrCurrentIDObjects[arrIDsToAdd[intIDIndex]]).closest('li')
							.slideDown(objPhotoGallery.update_image_count)
							.css('backgroundColor', '#E5D732')
							.animate({backgroundColor: '#F4EADB'}, 3500);
					} else {
						// Generate a new row from EE and add it to the view
						$.get('/photo-gallery/ajax-selection-row/' + arrIDsToAdd[intIDIndex], function(html){
							
							var elemToInsert = $(html);
							elemToInsert.hide();
							$("ul#image-selection li.first").after(elemToInsert);
							elemToInsert.slideDown(objPhotoGallery.update_image_count)
								.css('backgroundColor', '#E5D732')
								.animate({backgroundColor: '#F4EADB'}, 3500)
								.find("div.selection-image a")
								.fancybox(objGlobals.objFancyboxOptions);

						});
					}
				});
			 }
		);
		
		$("html,body").animate({scrollTop: 365}, 1000);
		$("input.pg-checkbox-add:checked").attr('checked', false);
		return false;
	},
	
	update_image_count : function() {
		
		var intNewCount = parseInt($("ul#image-selection li:visible").length - 1);
		
		if (intNewCount == 0) {
			$("ul#image-selection li.first").html('<p>You haven\'t selected any images.</p> <a href="/photo-gallery/" title="Add an image to your cart">Add Images...</a>');
		} else if (intNewCount == 1) {
			$("ul#image-selection li.first").html('You have selected ' + ($("ul#image-selection li:visible").length - 1).toString() + ' image');
		} else {
			$("ul#image-selection li.first").html('You have selected ' + ($("ul#image-selection li:visible").length - 1).toString() + ' images');
		}
		
	},
	
	submit_gallery_filter : function() {
		
		var strKeywords = $("#pg-choose-keywords").val();
		var strCategory = $("#pg-choose-category").val();
		
		$("#gallery-container").children().remove();
		$("#gallery-container").html("Searching...");
		
		$.post('/photo-gallery/ajax-image-gallery',{
		 'search:description': strKeywords, 'category': strCategory},
		 function(strHTML){
		
			var elemHTML = $(strHTML);
			$("#gallery-container").html(elemHTML);
			
			objPhotoGallery.init_carousel();
			objPhotoGallery.init_fancybox();
			
		
		}, 'html');
		
		return false;
		
	}
	
};

var objPhotoGalleryRequestForm = {
	
	init_page : function() {
		
		// Load jQuery UI for this page
		objGlobals.load_script(objGlobals.strjQueryUIPath);
		
		// Initialize date picker
		$(".datepicker").datepicker();
		
		// Form validation
		$("form#submit-request-form").submit(objPhotoGalleryRequestForm.form_validation);
		
		// Remove error class on focus
		$("form#submit-request-form input, form#submit-request-form textarea").focus(function() { $(this).removeClass('error'); });
		
	},
	
	form_validation : function() {
		
		var boolShouldAllowSubmit = true;
		
		if ($("input#first_name").val() == '') {
			$("input#first_name").addClass('error');
			boolShouldAllowSubmit = false;
		}
		
		if ($("input#last_name").val() == '') {
			$("input#last_name").addClass('error');
			boolShouldAllowSubmit = false;
		}
		
		if ($("input#email").val() == '') {
			$("input#email").addClass('error');
			boolShouldAllowSubmit = false;
		}
		
		if ($("textarea#how_used").val() == '') {
			$("textarea#how_used").addClass('error');
			boolShouldAllowSubmit = false;
		}
		
		if ($("input#captcha").val() == '') {
			$("input#captcha").addClass('error');
			boolShouldAllowSubmit = false;
		}
		
		if (!boolShouldAllowSubmit) {
			
			$("html,body").animate({scrollTop: 365}, 1000);
			$("p#error-description").fadeIn();
			
		}
		return boolShouldAllowSubmit;
		
	}
	
};

var objGlobals = {
	
	strjQueryUIPath : '/js/jqueryui-1.8.5.js',
	strjQueryEasingPath : '/js/jquery.easing-1.3.pack.js',
	strjCarouselLitePath : '/js/jquery.jcarousel.min.js',
	
	
	arrImagesToPreload : new Array(
		
		'/css/img/btn-add-selected-images-over.jpg'
		
	),
	
	objFancyboxOptions : {
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true
	},
	
	load_script : function(strPath) {
		
		$.ajax({async: false,type: "POST", url: strPath, data: null, success: null, dataType: 'script', error: function() { alert('There was an error loading: ' + strPath); }});
		
	},
	
	get_segment : function(num) {

	    num += 2;
	    var segments = [window.location.href].toString();
	    segments = segments.split('/');
	    if (segments[num] != undefined) {
	        return segments[num];
	    }
	    return '';
	
	},
	
	preload_images : function() {
		
		for(intIndex in objGlobals.arrImagesToPreload) {
			var objImg = new Image();
			objImg.src = objGlobals.arrImagesToPreload[intIndex];
		}
		
	},
	
	init_fancybox_sidebar : function() {
		
		$("div.selection-image a").fancybox(objGlobals.objFancyboxOptions);
		
	}
	
};
