var gallery = "";
var galWrap = "";
var visableRows = 12;
var itemWidth = 75
var galleryItem = {width:75};
var leftButton = "";
var rightButton ="";
var pos = 0;
var galLeft = 0;
var maxLeft = 0;
var gridWidth = 0;
	
	
// load/execute Scripts
function loadScript(path) {
	var js = document.createElement('script');
	js.setAttribute('language', 'javascript');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', path);
	window.document.body.appendChild(js);
	return true;
}

//Safeguard against other libs
(function($) {
// in place for validation - only validate on key up/change/blur if the form has been submitted once	
	var submittedOnce = false;
	
/** fieldClear
 * This will show/hide suggestions along with applying the initField class
 **/
	$.fn.fieldClear = function() {
		return this.focus(function() {
			if( this.value == this.defaultValue ) {
				this.value = "";
				$(this).removeClass("initField");
			}
		}).blur(function() {
			if( !this.value.length ) {
				this.value = this.defaultValue;
				$(this).addClass("initField");
			}
		});
	};
	
//show a loading screen over everything else in this container element	
	$.fn.showLoading = function( interval ){
		return this.each( function() {
			
			$height = $(this).height();
			$width = $(this).width();
			
			$("<div>", {
				'class': "overlay-loading",
				css: {height: $height, width:$width}
			}).appendTo( $(this) );
			
			$thisItem = $(this);
			
			setTimeout( function(){
				var ya = $thisItem.find("div.overlay-loading").fadeTo( 500, 0.00 );
				setTimeout( function(){ ya.remove(); }, 500);
			}, interval);
		});
	}
	
// move the gallery	
	$.fn.moveGallery = function( x ) {
		tempPos = pos + x;
		newLeft = tempPos * itemWidth;
		var ok = true;
		
		if( ok ) {
			pos = tempPos;
			galLeft = newLeft;
			return $(this).stop().animate({left: ( galLeft )}, 500);
		}
		
		return $(this);
	}
	
//get idea details for a given idea, and replace the contents of the object 'ajaxContent'
	$.fn.getIdeaDetails = function( my_id ){
		var ajaxContainer = $(this)
		$.ajax({
			type: "POST",
			url: "includes/ajaxController.php",
			data: "action=getIdeaDetails&id="+my_id,
			success: function(result) {
				ajaxContainer.empty().html( result );
			},
			error: function(x, y, z) {
				ajaxContainer.html( "Errormsg: "+y );
			}
		});
		return ajaxContainer;
	}
	
	
//Ideabook Gallery page
	function ideabookgallery(){
		//dom element cache
		gallery = $("#pictureGrid");
		galWrap = gallery.find(".wrap");
		ideaThumbLink = gallery.find("ul li a");
		
		//Show a loading overlay
		gallery.showLoading(5000);

		//move the gallery so you can see all rows to begin with
		galWrap.moveGallery(5);
		
		//nav buttons
		leftButton = gallery.find("#pictureNavLeft");
		rightButton = gallery.find("#pictureNavRight");
		
		//determine how many images there are and set width
		var lastUL = gallery.find(".wrap ul:last").attr('id');
		var numOfCols = Number( (lastUL).substring(4, lastUL.length ) ) + 1;
		
		//set globals
		gridWidth = numOfCols * itemWidth;
		maxLeft = (-1) * (gridWidth - (visableRows * itemWidth) ); 	//farthest left we can push the collection 
																	//[visableRows = number of visible cols, while itemWidth = width of col]
		//set grid width
		gallery.find(".wrap").css({width:gridWidth});
		
		//button click left
		leftButton.click( function(){
			//** enable the code below to limit people to the max and min values
			//if(galLeft >= 0){
			//	leftButton.addClass("hidden");
			//} else {
				galWrap.moveGallery(1);
			//	rightButton.removeClass("hidden");
			//}
			return false;
		});
		
		//button click right
		rightButton.click( function(){
			//** enable the code below to limit people to the max and min values
			//if( (galLeft-itemWidth) ==  maxLeft ){
			//	rightButton.addClass("hidden");
			//} else {
				galWrap.moveGallery(-1);
			//	leftButton.removeClass("hidden");
			//}
			return false;
		});
		
		//set action for clicking on a thumbnail
		function ajaxIdea(){
			//if its just a placeholder, dont try to load the details
			if( !$(this).hasClass('placeholder') ){
				//cache dom items
				var thisIdea = $(this).attr('id');
				var ajaxContent = $('.panel').first() //this is where the details will be loaded
				//make the ajax call
				$.ajax({
					type: "POST",
					url: "includes/ajaxController.php",
					data: "action=getIdeaDetails&id="+thisIdea,
					success: function(result) {
						ajaxContent.html( result );
					},
					error: function(x, y, z) {
						ajaxContent.html( "Errormsg: "+y );
						console.log( x );
						console.log( z );
					}
				});
				
			}else{
				alert('Submit your idea today and your photo could be included in the Idea Book');
			}
			return false;
		}
		ideaThumbLink.live('click', ajaxIdea);
		$("#weeklyWinners a").live('click', ajaxIdea);
		
	}

//Idea-book page
	function ideabookform(){	
		
		//Validate ideabook form
		function validateForm(){
		if(submittedOnce) {
			
			var ok = true;
			var idea_form = $("form[name=frm_idea]");
			var validFields = "";
			var invalidFields = "";
			
			if (idea_form.find("input[name=name]").hasClass("initField")) {
				ok = false;
				invalidFields += "input[name=name], ";
			} else {
				validFields += "input[name=name], ";
			}
			
			if (idea_form.find("textarea[name=myIdea]").hasClass("initField")) {
				ok = false;
				invalidFields += "textarea[name=myIdea], ";
			} else {
				validFields += "textarea[name=myIdea], ";
			}
			
			if (idea_form.find("input[name=city]").hasClass("initField") || idea_form.find("input[name=city]").val() == "") {
				ok = false;
				invalidFields += "input[name=city], ";
			} else {
				validFields += "input[name=city], ";
			}
			
			if (idea_form.find("select[name=state]").val() == "") {
				ok = false;
				invalidFields += "select[name=state], ";
			} else {
				validFields += "select[name=state], ";
			}
			
			if (!idea_form.find("input[name=CErelationship]:checked").length ) {
				ok = false;
				invalidFields += ".step4 strong, ";
			}else {	
				validFields += ".step4 strong, ";	
			}
			
			if (idea_form.find("input[name=email]").hasClass("initField")) {
				ok = false;
				invalidFields += "input[name=email], ";
			}else {
				validFields += "input[name=email], ";
			}
			
			if (!idea_form.find("input[name=agree]").is(":checked")) {
				ok = false;
				invalidFields += ".step7 strong, ";
			}else {
				validFields += ".step7 strong, ";
			}

			$(invalidFields+"").addClass("invalid");
			$(validFields+"").removeClass("invalid");
			
			return ok;
		}
		}
		
		// file upload via jquery plugin - the file automatically uploads after being chosen
		$("#uploadedPhoto").uploadify({
			'uploader'	: './script/uploadify.swf',
			'script'	: './script/uploadify.php',
			'cancelImg'	: './img/cancel.png',
			'folder'	: './upload',
			'fileDesc'	: 'Image Files Only (.png, .jpg, .jpeg, .gif)',
			'fileExt'	: '*.png;*.jpg;*.jpeg;*.gif',
			'sizeLimit'	: 6291456,
			'multi'		: false,
			'auto'		: true,
			'onSelect'	: function(event, ID, fileObj){
				//on select functions here
			}
		});
		
		$("form[name=frm_idea]").submit(function(){
			submittedOnce = true;
			var ok = validateForm();

			if(ok){ return true; }
			
			return false;
		});
		
		$('form[name=frm_idea] input, form[name=frm_idea] select, form[name=frm_idea] textarea')
			.keyup( function(){ setTimeout( validateForm(), 1000 ); })
			.blur ( function(){ $('input').trigger('keyup'); })
			.change ( function(){ $('input').trigger('keyup'); });
	}
	
	
//DOM Loaded
	$(document).ready( function(){
		
		//pictureGrid gallery scripting
		if( $("#pictureGrid").length ) { ideabookgallery(); }
		
		//ideabook form scripting
		if( $("form[name=frm_idea]").length ) { ideabookform(); }
		
		// Ideabook find form actions
		if( $("#frm_findPhoto").length ){
			//when submit clicked - replace form with idea details
			$("#frm_findPhoto").submit( function(){
				
				$(".panel").getIdeaDetails( $("input[name=photoNum]").val() );
				return false;
			});
		}
		
		// clear input on focus
		$("input[type=text], textarea").fieldClear();
		
	});
	
})(jQuery);

