$(document).ready(function() {
	//Gallery
	$('#gallery a').lightBox();
	//GalleryStrip
	$('#galleryStrip a').lightBox();	
	// Slider
    $('#heroSlider').nivoSlider({
    	effect: 'sliceUp',
   		directionNav:false, 
        controlNav:true
    });
	// SlideToggle for Gallery text
	$('.galleryExpandableLink').click(function() {
		$('.galleryExpandable').slideToggle();
		if ($('#changeExpandableText').html()=='Read More About This Project') {
			$('#changeExpandableText').html('Hide Text');
		}
		else if ($('#changeExpandableText').html()=='Hide Text'){
			$('#changeExpandableText').html('Read More About This Project');
		};
	});
	//show contact form
	$('#contactFormBtn').click(function() {
		$('#overlayForm').fadeIn();
	});
	$('.overlayCloseBtn').click(function() {
		$('#overlayForm').fadeOut();
	});


	//Contact Us
	$("#contactSubmit").live('click',function(){
		$(".contactError").hide();
		var name = $("#contactName").val();
		var email = $("#contactEmail").val();
		var comment = $("textarea#contactComments").val();
		var error = 0;
		var contactNameError = errorMessage('Name',name,'required');
		var contactEmailError = errorMessage('Email',email,'required');
		if(contactEmailError === ''){contactEmailError  = validateEmail(email);}
		var contactCommentError = errorMessage('Comment',comment,'required');
		if(contactNameError !== ''){
			$("#contactNameError").html(contactNameError);
			$("#contactNameError").slideDown('slow');
			error = 1;
		}
		if(contactEmailError !== ''){
			$("#contactEmailError").html(contactEmailError);
			$("#contactEmailError").slideDown('slow');
			error = 1;
		}
		if(contactCommentError !== ''){
			$("#contactCommentsError").html(contactCommentError);
			$("#contactCommentsError").slideDown('slow');
			error = 1;

		}
		if(error === 1)
			return false;
		else{
			var parameter = "name="+name+"&email="+email+"&comment="+comment;
			$.ajax({
				type: "POST",
				url: "landing_page/send_form",
				data: parameter,
				dataType: "json",
				beforeSend: function(){
					$("#contactMessage").html("Please wait while we process your request");
				},
				success: function(data){
					$("#contactMessage").html(data.message);
					$("#contactName").val("");
					$("#contactEmail").val("");
					$("textarea#contactComments").val("");
				}
			});
			setTimeout(function(){
				$("#contactMessage").fadeOut('fast');
			},2000);
			return false;

		}

	});
	
	// iPad Give Away
	$("#giveawaySubmit").live('click',function(){
		$(".giveawayError").hide();
		var firstName = $("#giveawayFirstName").val();
		var lastName = $("#giveawayLastName").val();
		var email = $("#giveawayEmail").val();
		var company = $("#giveawayCompany").val();
		var department = $("#giveawayDepartment").val();
		var phone = $("#giveawayPhone").val();
		var comment = $("textarea#giveawayComments").val();
		
		var error = 0;
		var giveawayFirstNameError = errorMessage('First Name',firstName,'required');
		var giveawayLastNameError = errorMessage('Last Name',lastName,'required');
		var giveawayEmailError = errorMessage('Email',email,'required');
		var giveawayCompanyError = errorMessage('Company',company,'required');
		var giveawayPhoneError = errorMessage('Phone',phone,'required');
		if(giveawayEmailError === ''){giveawayEmailError  = validateEmail(email);}
		
		//var giveawayCommentError = errorMessage('Comment',comment,'required');

		if(giveawayFirstNameError !== ''){
			$("#giveawayFirstNameError").html(giveawayFirstNameError);
			$("#giveawayFirstNameError").slideDown('slow');
			error = 1;
		}
		if(giveawayLastNameError !== ''){
			$("#giveawayLastNameError").html(giveawayLastNameError);
			$("#giveawayLastNameError").slideDown('slow');
			error = 1;
		}
		if(giveawayEmailError !== ''){
			$("#giveawayEmailError").html(giveawayEmailError);
			$("#giveawayEmailError").slideDown('slow');
			error = 1;
		}
		if(giveawayCompanyError !== ''){
			$("#giveawayCompanyError").html(giveawayCompanyError);
			$("#giveawayCompanyError").slideDown('slow');
			error = 1;
		}
		if(giveawayPhoneError !== ''){
			$("#giveawayPhoneError").html(giveawayPhoneError);
			$("#giveawayPhoneError").slideDown('slow');
			error = 1;
		}
		
		/*
		if(giveawayCommentError !== ''){
			$("#giveawayCommentsError").html(giveawayCommentError);
			$("#giveawayCommentsError").slideDown('slow');
			error = 1;

		}
		*/
		if(error === 1)
			return false;
		else{
			$.ajax({
				type: "POST",
				url: "landing_page/input_giveaway",
				data: {
					firstName : firstName,
					lastName : lastName,
					email : email,
					company : company,
					department : department,
					phone : phone,
					comment : comment,
				} 
				,
				dataType: "json",
				beforeSend: function(){
					$("#giveawayMessage").html("Please wait while we process your request");
				},
				success: function(data){
					$("#giveawayMessage").html(data.message);
					$("#giveawayFirstName").val('');
					$("#giveawayLastName").val('');
					$("#giveawayEmail").val('');
					$("#giveawayCompany").val('');
					$("#giveawayDepartment").val('');
					$("#giveawayPhone").val('');
					$("textarea#giveawayComments").val('');
				}
			});
			setTimeout(function(){
				$("#giveawayMessage").fadeOut('fast');
			},5000);
			return false;

		}

	});


});


function errorMessage(Subject,Field,Required){
	if(Field == "" && Required=='required'){
		return Subject+" is required";
	}
	else{
		return "";
	}
}

// function to validates an email address
function validateEmail(thisEmail)
{
	//initiate returnMessage variable
	var returnMessage="";

	if(thisEmail == '')
	{
		// alert the user
		returnMessage = "Please type in a valid email address.";
	}
	else
	{
		// function to check email address vilidity
		function emailCheck(emailStr)
		{
			/* The following pattern is used to check if the entered e-mail address
			   fits the user@domain format.  It also is used to separate the username
			   from the domain. */
			var emailPat=/^(.+)@(.+)$/
			/* The following string represents the pattern for matching all special
			   characters.  We don't want to allow special characters in the address.
			   These characters include ( ) < > @ , ; : \ " . [ ]    */
			var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
			/* The following string represents the range of characters allowed in a
			   username or domainname.  It really states which chars aren't allowed. */
			var validChars="\[^\\s" + specialChars + "\]"
			/* The following pattern applies if the "user" is a quoted string (in
			   which case, there are no rules about which characters are allowed
			   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
			   is a legal e-mail address. */
			var quotedUser="(\"[^\"]*\")"
			/* The following pattern applies for domains that are IP addresses,
			   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
			   e-mail address. NOTE: The square brackets are required. */
			var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
			/* The following string represents an atom (basically a series of
			   non-special characters.) */
			var atom=validChars + '+'
			/* The following string represents one word in the typical username.
			   For example, in john.doe@somewhere.com, john and doe are words.
			   Basically, a word is either an atom or quoted string. */
			var word="(" + atom + "|" + quotedUser + ")"
			// The following pattern describes the structure of the user
			var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
			/* The following pattern describes the structure of a normal symbolic
			   domain, as opposed to ipDomainPat, shown above. */
			var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


			/* Finally, let's start trying to figure out if the supplied address is
			   valid. */

			/* Begin with the coarse pattern to simply break up user@domain into
			   different pieces that are easy to analyze. */
			var matchArray=emailStr.match(emailPat);
			//alert(emailStr);
			var checkMatch='-' + matchArray + '-';
			if (checkMatch == "-null-")
			{
			  /* Too many/few @'s or something; basically, this address doesn't
				 even fit the general mould of a valid e-mail address. */
				returnMessage = "The email address seems incorrect (check @ and .'s).";
			}
			else
			{
				var user=matchArray[1];
				var domain=matchArray[2];

				// See if "user" is valid
				if (user.match(userPat)==null)
				{
					// user is not valid
					returnMessage = "The email's username doesn't seem to be valid (before the @).";
				}

				/* if the e-mail address is at an IP address (as opposed to a symbolic
				   host name) make sure the IP address is valid. */
				var IPArray=domain.match(ipDomainPat)
				if (IPArray!=null) {
					// this is an IP address
					  for (var i=1;i<=4;i++) {
						if (IPArray[i]>255) {
							returnMessage = "The email's destination IP address is invalid.";
						}
					}
				}

				// Domain is symbolic name
				var domainArray=domain.match(domainPat)
				if (domainArray==null) {
					returnMessage = "The email's domain name doesn't seem to be valid (after the @).";
				}

				/* domain name seems valid, but now make sure that it ends in a
				   three-letter word (like com, edu, gov) or a two-letter word,
				   representing country (uk, nl), and that there's a hostname preceding
				   the domain or country. */

				/* Now we need to break up the domain to get a count of how many atoms
				   it consists of. */
				var atomPat=new RegExp(atom,"g")
				var domArr=domain.match(atomPat)
				var len=domArr.length
				if (domArr[domArr.length-1].length<2 ||
					domArr[domArr.length-1].length>4) {
				   // the address must end in a two letter or three letter word.
				   returnMessage = "The email must end in a four-letter domain, three-letter domain, or two letter country.";
				}

				// Make sure there's a host name preceding the domain.
				if (len < 2) {
				   returnMessage="This email is missing a hostname!";
				}
			}
		}
		// call the validation function and return its result
		val=emailCheck(thisEmail);
		// if it returns val=no_submit, stop form
	}

	return returnMessage;
}
