// JavaScript Document
var formContent;
var sending=false;
var fileUploading=false;
//var photoVideo=false;
var requiredFields=true;
var photoUploadLabel = $("#photoUpload").html();
var video = $("form #video").val();
var videoLabel=$("label[for=video]").html();
//submit the form
function sendForm() {
	if(!sending) {
		sending=true;
		//all the form elements
		var submitElements = $('form').serializeArray();
		var postString='';
		$.each( submitElements, function(i, v){
			postString+='&'+v.name+"="+escape(v.value);
		});
		//removes the first &
		postString=postString.substr(1);
		
		//ajax query.
		var submitContact = $.ajax({
			type: "POST",
			url: "scripts/submitContest.php",
			data: postString,
			async: false,
			success: function(data){//add the content to the page
				//remove the loader
				$('#popCenter').css({'background-image' : 'none'});
				//thank you
				if(data==1) {
					$('.contactForm').replaceWith('<div class="thankYou" style="width:100%;"><h2>Thank you for entering the truwhip &#8220;CRACK THE WHIP&#8221; RECIPE CONTEST</h2><p>A confirmation has been sent to your email. If you do not receive it in 24 hours, please enter again or contact us directly with your entry @ <a href="mailto:truwhipthenatural@gmail.com" target="_blank">truwhipthenatural@gmail.com</a></p></div>');
					//tracks submit completions
					_gaq.push(['_trackEvent', 'Contest', 'Form', 'Submitted']);
				} else {
					$('.contactForm').replaceWith('<div class="thankYou" style="width:100%;"><h2>There was an error submitting your entry</h2><p>The following error was returned: '+data+'<br />Because we want to hear about your delicious recipe, please email us directly with your entry @ <a href="mailto:truwhipthenatural@gmail.com" target="_blank">truwhipthenatural@gmail.com</a></div>');
					//tracks submit failures at final stage
					_gaq.push(['_trackEvent', 'Contest', 'Form', 'SubmitFAIL']);
				}
				//$('.contactForm').fadeTo(0,1, function() {
					var new_position = $('#popCenter').offset();
					window.scrollTo(0,new_position.top);
					
					//change the size to fit the thank you content
					$('#popCenter').animate({
							'background-image' : 'none',
							'height' : 'auto',
							'width' : 'auto'
						}, {//wait a bit and then close
							duration : 200, 
							complete: function() {
								var t=setTimeout(function() {
									closePopUp(true);	
									sending=false;
								},5000);
							}
					});
				//});
			}
		}).responseText;
		return false;
	}
}
//show/hide the contest
function closePopUp(clear) {
	$('#popCenter').css("top",$(document).scrollTop()+40);
	$('#blackBack').height($(document).height());
	$('#popContainer').fadeToggle(500, function() {
		if(clear) {
			$('.thankYou').parent().html(formContent);
		}										
	});
	$('#blackBack').fadeToggle(500);
	
}
function submitForm() {
	// Client side form validation
	$('form').submit(function(e) {
		requiredFields=true;
		_gaq.push(['_trackEvent', 'Contest', 'Form', 'SubmitClicked']);
		//validation
		//caputres the values saved in each field/label
		var firstName = $("form #firstName").val();
		var firstNameLabel=$("label[for=firstName]").html();
		
		var lastName = $("form #lastName").val();
		var lastNameLabel=$("label[for=lastName]").html();
		
		var email = $("form #email").val();
		var emailLabel=$("label[for=email]").html();
		
		var emailConfirm = $("form #emailConfirm").val();
		var emailConfirmLabel=$("label[for=emailConfirm]").html();
		
		var address = $("form #address").val();
		var addressLabel=$("label[for=address]").html();
		
		var city = $("form #city").val();
		var cityLabel=$("label[for=city]").html();
		
		var state = $("form #state").val();
		var stateLabel=$("label[for=state]").html();
		
		var zip = $("form #zip").val();
		var zipLabel=$("label[for=zip]").html();
		
		var recipeCategoryLabel=$("label[for=recipeCategory]").html();
		
		var recipe = $("form #recipe").val();
		var recipeLabel=$("label[for=recipe]").html();

		//first name
		if(firstName=='') {
			$("label[for=firstName]").html('Enter your First Name');
			$("label[for=firstName]").addClass('req');
			$('form #firstName').blur();
			$('form #firstName').focus(function() {
				$("label[for=firstName]").html(firstNameLabel);
				$("label[for=firstName]").removeClass('req');
			});
			requiredFields=false;
		}
		//last name
		if(lastName=='') {
			$("label[for=lastName]").html('Enter your Last Name');
			$("label[for=lastName]").addClass('req');
			$('form #lastName').blur();
			$('form #lastName').focus(function() {
				$("label[for=lastName]").html(lastNameLabel);
				$("label[for=lastName]").removeClass('req');
			});
			requiredFields=false;
		}
		//email
		var pattern = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/);
		if(email=='') {
			$("label[for=email]").html('Enter your Email');
			$("label[for=email]").addClass('req');
			$('form #email').blur();
			$('form #email').focus(function() {
				$("label[for=email]").html(emailLabel);
				$("label[for=email]").removeClass('req');
			});
			requiredFields=false;
		} else if(!pattern.test(email)){//validates email
			$("label[for=email]").html('Enter a Valid Email');
			$("label[for=email]").addClass('req');
			$('form #email').blur();
			$('form #email').focus(function() {
				$('form #email').focus(function() {
					$("label[for=email]").html(emailLabel);
					$("label[for=email]").removeClass('req');
				});
			});
			requiredFields=false;
		} else if(email!=emailConfirm){//validates email
			$("label[for=emailConfirm]").html('Your emails do<br />not match');
			$("label[for=emailConfirm]").addClass('req');
			$('form #emailConfirm').blur();
			$('form #emailConfirm').focus(function() {
				$('form #emailConfirm').focus(function() {
					$("label[for=emailConfirm]").html(emailConfirmLabel);
					$("label[for=emailConfirm]").removeClass('req');
				});
			});
			requiredFields=false;
		}
		//address
		if(address=='') {
			$("label[for=address]").html('Enter your Address');
			$("label[for=address]").addClass('req');
			$('form #address').blur();
			$('form #address').focus(function() {
				$("label[for=address]").html(addressLabel);
				$("label[for=address]").removeClass('req');
			});
			requiredFields=false;
		}
		//city
		if(city=='') {
			$("label[for=city]").html('Enter your City');
			$("label[for=city]").addClass('req');
			$('form #city').blur();
			$('form #city').focus(function() {
				$("label[for=city]").html(cityLabel);
				$("label[for=city]").removeClass('req');
			});
			requiredFields=false;
		}
		//state
		if(state=='') {
			$("label[for=state]").html('Select your State');
			$("label[for=state]").addClass('req');
			$('form #state').blur();
			$('form #state').focus(function() {
				$("label[for=state]").html(stateLabel);
				$("label[for=state]").removeClass('req');
			});
			requiredFields=false;
		}
		//zip
		if(zip=='') {
			$("label[for=zip]").html('Enter your Zip');
			$("label[for=zip]").addClass('req');
			$('form #zip').blur();
			$('form #zip').focus(function() {
				$("label[for=zip]").html(zipLabel);
				$("label[for=zip]").removeClass('req');
			});
			requiredFields=false;
		}
		//recipe Category
		var recipeCategoryID = $("input[@name='recipeCategory']:checked").attr('id');
		if(!recipeCategoryID || recipeCategoryID=='undefined') {
			$("label[for=recipeCategory]").html('Please choose a Recipe Category');
			$("label[for=recipeCategory]").addClass('req');
			$("input[name='recipeCategory']").change(function(){
				$("label[for=recipeCategory]").html(recipeCategoryLabel);
				$("label[for=recipeCategory]").removeClass('req');
			});
		} 
		//recipe
		if(recipe=='') {
			$("label[for=recipe]").html('Enter your recipe');
			$("label[for=recipe]").addClass('req');
			$('form #recipe').blur();
			$('form #recipe').focus(function() {
				$("label[for=recipe]").html(recipeLabel);
				$("label[for=recipe]").removeClass('req');
			});
			requiredFields=false;
		}
		//valid URL
		var validURL = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		$('#video').change(function() {
			var videoURL = $(this).val();
			if(validURL.test(videoURL)){
				$("label[for=video]").html(videoLabel);
				$("#photoUpload").html('Photo upload');
				$("#photoUpload, label[for=video]").removeClass('req');
        		//photoVideo=true;
			}else{
				$("label[for=video]").html('Invalid URL. Please copy and Paste from your browser.');
			}				   
		});
		var videoURL = $('#video').val();
		/*if(validURL.test(videoURL)){
			photoVideo=true;
		}*/
		
		
		var uploader = $('#uploader').plupload('getUploader');
		// Files in queue upload them first
		/*if(!photoVideo) {
			$("#photoUpload, label[for=video]").html('Please Upload at least one Photo or Video');
			$("#photoUpload, label[for=video]").addClass('req');
			requiredFields=false;
		}*/
		//if any field isn't filled out correctly, return false
		if(requiredFields==false) {
			var new_position = $('#popCenter').offset();
			window.scrollTo(0,new_position.top);
			return false;
		}
		if(requiredFields/* && photoVideo*/) {
			if(!fileUploading) {
				sendForm();
			} else {
				$("#photoUpload").addClass('req');
				$("#photoUpload").html('Finish Uploading your file before submitting');
			}
		}
		/*********** END VALIDATION **********/
		return false;
	});	
}
/************* UPLOADER **************/
//gets the previous label for the upload object
var photoUploadLabel = 'Photo upload (Max 3MB per file, 3 total files.)';
function uploaderEnable() {
	//uploader
	// Convert divs to queue widgets when the DOM is ready
	$(function() {
		$("#uploader").plupload({
			// General settings
			runtimes : 'flash,html5,html4',
			url : 'scripts/plupload/examples/upload.php',
			max_file_size : '5mb',
			max_file_count: 3, // user can add no more then 20 files at a time
			chunk_size : '1mb',
			unique_names : true,
			multiple_queues : true,
			
			// Rename files by clicking on their titles
			rename: true,
			
			// Sort files
			//sortable: true,
	
			// Specify what files to browse for
			filters : [
				{title : "Image files", extensions : "jpg,gif,png,tiff,raw"},
			],
	
			// Flash settings
			flash_swf_url : 'scripts/plupload/js/plupload.flash.swf'
		});
	});		
	//gets the uploader object
	
		
	var video = $("form #video").val();
	var videoLabel=$("label[for=video]").html();
	var uploader = $('#uploader').plupload('getUploader');
	//stops submit if a file is uploading
	
	uploader.bind('FilesAdded', function(up, files) {
		$("#photoUpload, label[for=video]").removeClass('req');
		//$("label[for=video]").html('Video Link');
		$("#photoUpload").addClass('req');
		$("#photoUpload").html('Upload your file before submitting');
		 $('#button').attr('disabled', 'disabled');
		 $('#button').addClass('disabled');
		photoAdded = true;
		fileUploading=true;
		_gaq.push(['_trackEvent', 'Contest', 'File', 'FileAdded']);
	});
	
	uploader.bind('UploadProgress', function(up, file) {
		fileUploading=true;
	});
	uploader.bind('QueueChanged', function() {
		uploader.start();
	});
	uploader.bind('StateChanged', function() {
		if(!fileUploading) {
			$("#photoUpload").html(photoUploadLabel);
		}
		if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
			$('#button').removeAttr('disabled');
			$('#button').removeClass('disabled');
			//if(requiredFields) {
				//photoVideo=true;
				//adds a loader image
				//$('#popCenter').css({'background-image' : 'url(/media/loading.gif)'});
				//$('.contactForm').fadeTo(100,0.33);
					//var t=setTimeout(function() {
						//alert('send form after uploaded');
						//sendForm();				  
					//},250);
			//}
		}
	});
	uploader.bind('UploadComplete', function(up, file) {
		fileUploading=false;
		$("#photoUpload").html(photoUploadLabel);
		$("#photoUpload").removeClass('req');
		//photoVideo=true;
		_gaq.push(['_trackEvent', 'Contest', 'File', 'UploadComplete']);
	});
}
/************* ON LOAD ***************/
$(document).ready(function(){
	formContent=$('.contactForm').parent().html();
	//enter the contest!
	$('.contestEntry, #contestEntryMain, #contestEntryLink').click(function(){
		_gaq.push(['_trackEvent', 'Contest', 'Opened', 'formOpened']);
		submitForm();
		uploaderEnable();
		closePopUp();
		return false;
	});
	//hide the popup
	$('#closeX, #popClose, #blackBack').click(function() {
		closePopUp(true);
		return false;
	});
});
