var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var optin = false;
var optout = false;
var firstString = false;
var secondString = false;

$(document).ready(function() {
	
	//  ===========================================================================
	// 	ESS CALCULATOR Functions
	//  ===========================================================================

	/* 	This function calculates the ESS score by combining the values
	   	of all of the selected radio buttons in this form */
	$('.form.ess .calculate').click(function() {
		var essScore = 0;
		$('.form.ess input:radio:checked').each(function() {
			essScore = parseInt(essScore) +  parseInt($(this).val());
			$('.essvalue').html(essScore);
		});
	});
	

	//  ===========================================================================
	// 	FAQ Functions
	//  ===========================================================================

	/* 	This function determines whether the user is clicking an FAQ item
	   	or the 'back-to-top' link. */
	$('.p79 .pagecontent a.gafaq, .p79 .pagecontent a.backtotop').click(function() {
		$('.faqback').remove();
		var jumpID = $(this).attr("href").substr(4,2);
		
		/* Scrolls down the page to the FAQ item */
		if (jumpID > 0) {
			$('html,body').animate(
			{
				scrollTop: $("a[name=faq" + jumpID + "]").offset().top-10
			},500);
			$("a[name=faq" + jumpID + "]").before("<div class='faqback'></div>");
		}
		/* Scrolls back up the page */
		if ($(this).hasClass("backtotop")) {
			$('html,body').animate({scrollTop: $(".pagecontent").offset().top-10},500);
		}
		return false;
	});
	
	
	//  ===========================================================================
	// 	SEARCH BOX Functions
	//  ===========================================================================

	/* 	Search Box
		Clicking the search box will expand the search box and remove the default
		text within it (ie: "Search"). */
	$('#keyword').click(function() {
		if ($(this).val() == "Search") { 
			$(this).val(""); 
			$(this).parents(".search").addClass("clicked"); 
			$(this).animate({width: "+=30px"}, 500, "easeOutBack");
		}
	});
	/* 	On blur, the search box will shrink down to it's original size and then
		check if it should populate the searchbox with the default text (ie: "Search") */
	$('#keyword').blur(function() {
		if ($(this).val() == "") { 
			$(this).val("Search"); 
			$(this).parents(".search").removeClass("clicked"); 
			$(this).animate({width: "-=30px"}, 500, "easeOutBack");
		}
	});
	
	$('.searchform').submit(function() {
		var keywords = $('#keyword').val().replace(" ", "-");
		if (keywords != "" && keywords != "Search") { location.href = '/search/' + keywords; }
		return false;
	});
	
	
	//  ===========================================================================
	// 	SNIPE Functions
	//  ===========================================================================
	
	/* 	The snipe popup behavior inserts a DIV and the image within it which
		gets resized as it moves to the center of the page. It then calls the
		appropriate file and inserts the html into the fully expanded voucher
		form */

	function voucherPop(pageName, snipeObj, vsize) {

		if ($('body').hasClass('ie6')) {
			snipehtml = "<div id='snipecontent' class='pop'><img class='imagepop' src='/_assets/nuvigil2011/desktop/images/global/ie6/voucher-signup-back.gif' width='125'><div class='contentwrap'></div></div>";
			snipeext = "ie6";
		} else {
			snipehtml = "<div id='snipecontent' class='pop'><img class='imagepop' src='/_assets/nuvigil2011/desktop/images/con_standard/voucher-signup-back2.png' width='125'><div class='contentwrap'></div></div>";
			snipeext = "";
		}

		snipeFile = $(snipeObj).attr("id").split("snipe_")[1] + ".php?ext=" + snipeext;
		if (pageName == 'home') { voucherMarginTop = 40; } else { voucherMarginTop = 0; }
		$('body').append(snipehtml);
		offsetPos = $(snipeObj).offset();
		$('#snipecontent').css("top", offsetPos.top).css("left", "10px");
		$(snipeObj).fadeOut(250);
		$('body').prepend('<div id="backdrop" class="snipeback"></div>');
		$('#backdrop').css('filter', 'alpha(opacity=40)');
		$('#backdrop').fadeIn(500);
		$('#snipecontent').fadeIn(250).animate({
		   left: '50%',
		   marginLeft: -288,
		   marginTop: voucherMarginTop
		}, { duration: 500, queue: false });		
		$('#snipecontent .imagepop').animate({
			width: vsize
		}, 500, function() {
			$('#snipecontent .contentwrap').load('/_assets/nuvigil2011/desktop/snipe/' + snipeFile).fadeIn(500);
		});			
	}



	/* clicking the snipe will expand the voucher form' */
	$('.snipe').live("click", function() {
		if ($('body').hasClass('con_standard')) { vsize = 539; } else { vsize = 576; }
		google_track('_trackEvent', 'pat_rollover', 'open');
		voucherPop('interior', $(this), vsize);	
	});
	
	$('.inline-voucher').click(function() {
		$('html,body').animate({scrollTop: 0},500);
		$('.snipe').trigger('click');
	});

	if ( $('body').hasClass('ie6') ) { snipeAniPos1 = 125; snipeAniPos2 = 250; } else { snipeAniPos1 = 125; snipeAniPos2 = 250; }

	/* Snipe Animation (both mouseover and mouseout) */
	$('.snipe').live('mouseover', function() {
		$(this).animate({backgroundPosition:'0 -' + snipeAniPos1 + 'px'},0).delay(50);
		$(this).animate({backgroundPosition:'0 -' + snipeAniPos2 + 'px'},0);
	});
	
	$('.snipe').live('mouseout', function() {
		$(this).animate({backgroundPosition:'0 -' + snipeAniPos1 + 'px'},0).delay(50);
		$(this).animate({backgroundPosition:'0 0'},0)
	});
	

	//  ===========================================================================
	// 	VOUCHER Functions
	//  ===========================================================================

	/* 	Determines whether to include or remove the placeholder text within the 
		text boxes in the Voucher form. */
		
	$('.snipe-default input:text').live("click", function() {
			if ($(this).hasClass("email")) { var inputText = "Email"; }
			if ($(this).hasClass("emailconfirm")) { var inputText = "Confirm Email"; }
			if ($(this).hasClass("zipcode")) { var inputText = "ZIP Code"; }
			if ($(this).val() == inputText) { $(this).val(""); $(this).css("color", "#000"); }
	});

	$('.snipe-default input:text').live("blur", function() {
		if ($(this).val() == "") { 
			if ($(this).hasClass("email")) { var inputText = "Email"; }
			if ($(this).hasClass("emailconfirm")) { var inputText = "Confirm Email"; }
			if ($(this).hasClass("zipcode")) { var inputText = "ZIP Code"; }
			$(this).val(inputText); $(this).css("color", "#606060");
		}
	});	
	

	/* This function closes the Voucher by animating it back to its original state */
	$('#backdrop.snipeback, #snipecontent .close, #snipe_download').live("click", function() {

		if ($(this).attr("id") == 'snipe_download') {
			var email = $("#snipe_email").val();
			var email2 = $("#snipe_email2").val();
			var zip = $("#snipe_zip").val();
			
			if (email == '' || email2 == '' || zip == '' || email == 'Email' || email2 == 'Confirm Email' || zip == 'ZIP Code') {
				alert('Please enter values for all fields.');
				return false;	
			} else if (validateEmail(email) == false) {
				alert('Please enter a valid email address!');
				return false;
			} else if (email != email2) {
				alert('Your email addresses do not match!');
				return false;	
			}
			
			$.post('/forms/get_voucher_ids', { action: 'process_snipe_form', email: email, email2: email2, zip: zip, opt: $("#snipe_opt").val() },
			   function(data) {
					if(data){
						var newdata = data.split("|");
						gp1 = newdata[0];
						ch1 = newdata[1];
						gp2 = newdata[2];
						ch2 = newdata[3];
						
						google_track('_trackEvent', 'pat_rollover', 'download');
						window.location = '/forms/voucher/' + ch1 + '-' + ch2;

					}
					else console.log("Oh nooo!");
				}
			);
		} else {
			google_track('_trackEvent', 'pat_rollover', 'close');
		}
		$('#backdrop').fadeOut(500, function() {
			$(this).remove();
		});
		$('.snipe').fadeIn(1250);
		$('#snipecontent .contentwrap').fadeOut(200,function() {

			$('#snipecontent').animate({
			   marginLeft: 380
			}, { duration: 500, queue: false });
					
			$('#snipecontent .imagepop').animate({
				width: 150,
				opacity: 0
			}, 500, function() {
				$('#snipecontent').remove();	
			});
			
		});
	});
	

	//  ===========================================================================
	// 	LONG FORM Functions
	//  ===========================================================================

	$('.material .hoverwrap').mouseover(function() {
		var matID = $(this).attr('id');
		$('.' + matID).css("display", "block");
	});

	$('.material .hoverwrap').mouseout(function() {
		var matID = $(this).attr('id');
		$('.' + matID).css("display", "none");
	});

	
	//  ===========================================================================
	// 	GLOSSARY Functions
	//  ===========================================================================

	$('.glossary').click(function() {
		$('.gloswrap').remove();
		var glos = $(this);
		var term = $(this).text();
		google_track('_trackEvent', 'glossary', 'open', term);
		$.post('/forms/get_definition', { "term": term}, function(data) {
			if (data) {
				termdef = data.glossary_definition;			
				var gloshtml = "<div class='gloswrap ui-draggable'><div class='titlebar'><div class='x'>CLOSE X</div>Glossary</div><div class='glosbody'><div class='term'>" + term + "</div><div class='def'>" + termdef + "</div><div class='glinks'><a href='/glossary'>More Glossary Terms</a> | <a href='contact-nuvigil'>Contact Us</a></div></div></div>";
				$(glos).before(gloshtml);
				$(glos).prev().css("display","inline-block");
			}
		}, "json");	
	});
	
	$('.gloswrap .x').live('click', function() {
		google_track('_trackEvent', 'glossary', 'close', $(".term").text());
		$(this).parents(".gloswrap").fadeOut(250, function() {
			$(this).remove();
		});
	});
	

	//  ===========================================================================
	// 	FORM Functions
	//  ===========================================================================

	$('form').live("submit", function() {
		formPass = false;
		formError = false;
		alertMessage = "The following errors occurred: \n";
		firstString = ""; secondString = "";
		
		$(this).find('.required').each(function() {
			if( !$(this).val() ) {
				fieldName = $(this).siblings('label').html().replace(/(<.*?>)/ig,"").replace("*", "");
				alertMessage = alertMessage + "\n" + fieldName + " is a required field.";
				formError = true;
			} else {
				formError = false;
			}
		});
		
		$(this).find('.required.emailFormat').each(function() {
			if ( $(this).val() ) {
				if ( validateEmail( $(this).val() ) == false) {
					fieldName = $(this).siblings('label').html().replace(/(<.*?>)/ig,"").replace("*", "");
					alertMessage = alertMessage + "\n" + fieldName + " (" + $(this).val() + ") is not a valid email address.";
					formError = true;
				} else {
					if (formError != true) { formError = false };	
				}
			}
		});
		
		$(this).find('.required.matchString').each(function() {
			if (!firstString) { 
				firstString = $(this).val(); 
			} else { 
				secondString = $(this).val(); 
				if (firstString != secondString) { 
					formError = true;  
					alertMessage = alertMessage + "\nEmail addresses do not match."; 
				} else {
					if (formError != true) { formError = false };		
				}
			}
		});
		
		/* Required Long Form Buttons */
		if ($('#action').val() == 'submit_long') { 
			if ($('#SurveyName').val() == 'CARD-NUV0410') {
				alertMessage = alertMessage + "\nHave you been diagnosed... is a required field.";
				formError = true;
			}
			
			if (!validateRadio('DiscussedES')) {
				alertMessage = alertMessage + "\nHave you discussed ES... is a required field.";
				formError = true;
			}

			if (!validateRadio('Interfere')) {
				alertMessage = alertMessage + "\nHow much does your ES interfere... is a required field.";
				formError = true;
			}

			if (!validateRadio('WorkShifts')) {
				alertMessage = alertMessage + "\nDo you work shifts... is a required field.";
				formError = true;
			}
		}

		/* Required Share Form Checkbox */
		if ($('#action').val() == 'submit_share') { 
			if (!$('.q2').is(':checked')) {
				alertMessage = alertMessage + "\nWhat sleep disorder(s)... is a required field.";
				formError = true;				
			}
		}
				
		if (formError == true) {
			formPass = false;
			formError = false; 
			alert (alertMessage); 
			return false; 
		} else {
			formPass = true;	
		}
		
	});
	
	function validateRadio(ele) {
		var radioButton = document.getElementsByName(ele);
		var isSelected = false;
		for(i=0; i < radioButton.length; i++){
			if(radioButton[i].checked){
				isSelected = true;
				i = radioButton.length;
			}
		}
		return isSelected;
    }
	
	function validateEmail(email) {
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
   		return  emailPattern.test(email);  
	}

	



	//  ===========================================================================
	// 	PAGE Functions
	//  ===========================================================================

	/* Sends the user down the page using a smooth scrolling effect */
	$("#isilink").click(function() {
		$('html,body').animate({scrollTop: $("#isi").offset().top-20},1000);
	});
	
	//  ===========================================================================
	// 	GOOGLE TRACKING
	//  ===========================================================================

	/* google tracking -- print/email/recommend */
	$(".pagelinks a").click(function() {
		google_track('_trackEvent', 'actions', 'click', $(this).attr('class'));	
	});

	/* google tracking -- internal/external links */
	$(".internal_link, .external_link").click(function() {
		google_track('_trackEvent', ($(this).hasClass('internal_link') ? 'internal_link' : 'external_link'), 'click', $(this).attr("href"));	
	});
	
	/* google tracking -- callouts */
	$(".callbtns").children().click(function() {
		google_track('_trackEvent', 'left_callout', 'click', $(this).attr("href"));
	});
	
	/* google tracking -- pdfs */
	$(".pdf").click(function() {
		var url = $(this).attr("href");
		var array = url.split('/');
		var lastsegment = array[array.length-1];
		
		_gaq.push(['_trackPageview', lastsegment]);
	});
	
	/* google tracking -- faqs */
	$(".gafaq").click(function() {
		google_track('_trackEvent', 'faq', 'click', $(this).text());
	});

	/* google tracking -- top-right */
	$("#signup, #rash, #psi, #isilink").click(function() {
		google_track('_trackEvent', 'top-right', 'click', $(this).attr("id"));
	});
	
	/* google tracking -- snipe form */
	$("#snipe_email, #snipe_email2, #snipe_zip").live("focus", function() {
		google_track('_trackEvent', 'pat_rollover', 'click', $(this).attr("id").replace("snipe_", ""));
	});
	
	$("#snipe_opt").live("click", function() {
		if ($("#snipe_opt").is(':checked')) {
			if (!optin) {
				google_track('_trackEvent', 'pat_rollover', 'opt_in');
				optin = true;
			}
		} else {
			if (!optout) {
				google_track('_trackEvent', 'pat_rollover', 'opt_out');
				optout = true;
			}
		}
	});
	
});


	//  ===========================================================================
	// 	ADDITIONAL Functions
	//  ===========================================================================

	/* 	Sets the draggable effect for the glossary popup. This code allows us to apply
		the draggable behavior to 'live' items. */
	(function ($) {
	   $.fn.liveDraggable = function (opts) {
		  this.live("mouseover", function() {
			 if (!$(this).data("init")) {
				$(this).data("init", true).draggable(opts);
			 }
		  });
	   };
	}(jQuery));
	
	/* Glossary draggable code */
	$(function() {
		$( ".gloswrap" ).liveDraggable( {containment: "html", handle: ".titlebar"});
	});
		

	/* Easing effects for the Search Box */
	jQuery.extend( jQuery.easing,
	{
		easeInBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*(t/=d)*t*((s+1)*t - s) + b;
		},
		easeOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
		}
	});

	/* Debugging function for flash developers */
	function flashalert(msg) {
		alert(msg);	
	}



/**
 * function created for google tracking, just in case we need to make changes to
 * the google func call and/or we want to track these items ourselves
 */
function google_track(trackEvent, trackTitle, trackType, trackValue) {
	_gaq.push([trackEvent, trackTitle, trackType, trackValue]);
	//alert(trackEvent + ' ' + trackTitle + ' ' +  trackType + ' ' + trackValue);
	
}

function get_page_url(pageid) {
	$.post('/forms/get_page_url', { pageid: pageid },
	   function(data) {
			if(data){
				return data;
			}
		}
	);	
}

