/*
General Javascript
*/

var current_industry = "";
var current_product = "ecs";

$(function() {
	// assign lightbox to prettyPhoto rel tags
	$("a[rel^='prettyPhoto']").prettyPhoto();

	bindToEmpty($('.landing .empty'));
	// handle contact modal
	$('#load_contact_modal, .ecs_new .load_contact_modal, .ppclanding .load_contact_modal').click(function() {
		// request page content
		$.get('http://www.themarlincompany.com/contact/ajax/', function(data) {
			//After modal is open, we want to run the validation code
			$.modal(data, {
				opacity:80,
				overlayCss: {backgroundColor:"#000"},
				overlayClose: true,
				onOpen: function (dialog) {
					dialog.overlay.fadeIn('normal', function () {
						dialog.data.show();
						dialog.container.show(1, function () {dialog.data.show(1);});
					});
				},
				onClose: function (dialog) {
					dialog.data.hide(1, function () {
						dialog.container.hide(1, function () {
							dialog.overlay.fadeOut('normal', function () {$.modal.close();});
						});
					});
				},
				onShow : function () {


if ( $("#modal_contact #sfp_referer").val() == "http://www.themarlincompany.com/products/electronic-message-boards" && $('body').hasClass('emsgboard')) {
	if ($("#sfj_referer").val() != "") {
		$("#modal_contact #sfp_referer").val($("#sfj_referer").val());
	}
}

if ($('body').hasClass('emsgboard')) {
	if ($("#sfp_source").val() == "Web contact") {
		$("#sfp_source").val("Electronic Message Boards LP");
	}
	if ($('body').hasClass('ebulletboard')) {$("#sfp_return").val("http://www.themarlincompany.com/contact/thank_you?f=modal&s=ebulletboard");} else if ($('body').hasClass('digimsgboard')) {$("#sfp_return").val("http://www.themarlincompany.com/contact/thank_you?f=modal&s=digimsgboard");} else {$("#sfp_return").val("http://www.themarlincompany.com/contact/thank_you?f=modal&s=emsgboard");}
}

					//Properly handle empties
					bindToEmpty($("#modal_contact .empty"));
					//Validate form
					$("#modal_contact").validate({
						rules: {
							first_name: {
								required: true,
								isFirstName: true
							},
							last_name: {
								required: true,
								isLastName: true
							},
							phone: {
								required: true,
								digits: true,
								rangelength: [10, 10]
							},
							email: {
								required: true,
								email: true
							},
							zip: {
								required: true,
								isZipCode: true
							}
						},
						messages: {
							first_name: "Please enter your first name",
							last_name: "Please enter your last name",
							phone: "Phone number must be 10 digits only (no punctuation).",
							email: "Please enter a valid email address",
							zip: "Please enter your zip/postal code"
						},
						errorClass: "fail" /*,
						submitHandler: function(form) {
							var queryString = $(form).serialize();
							$.post( 'https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8' , queryString , function (data) {
//							$.post( 'http://www.themarlincompany.com/contact/ajax/' , queryString , function (data) {
								if (data == "success") {$.get('http://www.themarlincompany.com/contact/ajax_thanks/', function(data) {
										$(".modal_header").html(data);
										$(".modal_content").html("");
										pageTracker._trackPageview('modal_contact');
									});
								} else {
									$("#modal_contact").html(data); // refresh the modal with the content returned from PHP
								}
							});
							return false; // make sure form uses ajax and not regular submission.
	  					} */


						/** BACKUP SUBMIT HANDLER IF SALEFORCE FAILS **/
						, submitHandler: function(form) {
							_gaq.push(['_trackEvent', 'Contact', 'Modal', $("#modal_contact input[name=lead_source]").val() ]);
							var queryString = $(form).serialize();
							queryString = queryString + "&phppost_email=digitalsurgeonstestrecip@gmail.com,info@themarlincompany.com&phppost_subject=%5BMarlin%5D%20Modal%20Form";
							$.post( '/email.php' , queryString , function (data) { /* goggles do nothing */ });
							form.submit();  // make sure the form still fires to salesforce
						}
						/** BACKUP SUBMIT HANDLER IF SALEFORCE FAILS **/


					});
				}
			});
		});

		// prevent link from firing
		return false;
	});

	$('li.industry_item').hover(
		function() { // mouseover
			if (current_industry) {
				$('p#ecs-' + current_industry).css({display:'none'});
				$('p#pcs-' + current_industry).css({display:'none'});
			} else {$('p#ecs').css({display:'none'});
				$('p#pcs').css({display:'none'});
			}			
			current_industry = $(this).attr('id');
			if (current_product == "ecs") {$('li.left_toggle').click();} else {$('li.right_toggle').click();}
		},
		function () { //mouseout
			var dummy = "data"; // function needs to do something
		}
	);

	$('li.industry_item').click(
		function() {$(this).find('a').click();}
	);

	$('li.left_toggle').click(
		function() {
			// toggle sprite states
			$(this).css(
				{ 'background-position': '0px -39px' }
			);
			$('li.right_toggle').css(
				{ 'background-position': '0px 0px' }
			);
			// toggle images
			if (current_industry) {
				$('p#ecs-' + current_industry).css({display:'block'});
				$('p#pcs-' + current_industry).css({display:'none'});
			} else {$('p#ecs').css({display:'block'});
				$('p#pcs').css({display:'none'});
			}
			// set current product
			current_product = "ecs";
		}
	);
	$('li.right_toggle').click(
		function() {
			// toggle sprite states
			$('li.left_toggle').css(
				{ 'background-position': '0px 0px' }
			);
			$(this).css(
				{ 'background-position': '0px -39px' }
			);
			// toggle images
			if (current_industry) {
				$('p#ecs-' + current_industry).css({display:'none'});
				$('p#pcs-' + current_industry).css({display:'block'});
			} else {$('p#ecs').css({display:'none'});
				$('p#pcs').css({display:'block'});
			}
			// set current product
			current_product = "pcs";
		}
	);

	$('a.close_modal').click(function() {
		$.modal.close();		
		return false;
	});

	//handle emptying fields initial value
	bindToEmpty($('.empty'));
	
	
	//handle featured / overview tabs on product pages
	if($('body.products').length) {
		var btnOver = $('a.tab_overview');
		var secOver = $('#overview');
		var btnFeat = $('a.tab_features');
		var secFeat = $('#features');
		
		secFeat.hide();
		
		btnOver.click(function() {
			$(this).parent().removeClass('active').addClass('active');
			btnFeat.parent().removeClass('active');
			
			secFeat.stop(true, true).fadeOut(150, function() {
				secOver.stop(true, true).fadeIn(150);
			});
			
			Cufon.refresh('#tertiary_nav ul li');
			
			return false;
		});
		
		btnFeat.click(function() {
			$(this).parent().removeClass('active').addClass('active');
			btnOver.parent().removeClass('active');
			
			secOver.stop(true, true).fadeOut(150, function() {
				secFeat.stop(true, true).fadeIn(150);
			});
			
			Cufon.refresh('#tertiary_nav ul li');
			
			return false;
		});		
	}
	
	//Home page carousel - reset interval when users click
	$('#carousel').not('body.issues #carousel').carousel('#carousel_previous', '#carousel_next', {onPrevious:function(event) {
		if(inter) {
			clearInterval(inter);
			inter = setInterval('$("#carousel_next").trigger("click")', 5000);
		}
	}, onNext:function(event) {
		if(inter) {
			clearInterval(inter);
			inter = setInterval('$("#carousel_next").trigger("click")', 5000);
		}
	}});
	//Timer for carousel
	var inter = setInterval('$("#carousel_next").trigger("click")', 5000);
	
	
	//Blog Archives
	$('select#archives').change(function() {
		href = $(this).val();
		if(href != '#') {
			window.location = href;
		}
	});


	/**** Form Validations ****/

	jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
	    phone_number = phone_number.replace(/s+/g, ""); 
		return this.optional(element) || phone_number.length > 9 &&
			phone_number.match(/^(1-?)?(([2-9]d{3})|[2-9]d{3})-?[2-9]d{3}-?d{4}$/);
	}, "Please specify a valid phone number");


	$.validator.addMethod("isFirstName", function(value, element) {
		return check_field_for_name(value, "First Name *");
	}, 'Please enter your first name.');
	$.validator.addMethod("isLastName", function(value, element) {
		return check_field_for_name(value, "Last Name *");
	}, 'Please enter your last name.');

	$.validator.addMethod("isZipCode", function(value, element) {
		return check_field_for_name(value, "Zip Code *");
	}, 'Please enter your zip/postal code.');
	
	jQuery.validator.addMethod("postalcode", function(postalcode, element) {
		return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
	}, "Please specify a valid postal/zip code");



	$("#newsletter_form").validate({
		rules: {
			"cm-hktjuh-hktjuh": {
				required: true,
				email: true
			}
		},
		messages: {
			email: "Please enter a valid email address"
		},
		errorClass: "fail",
		submitHandler: function (form) {
			_gaq.push(['_trackEvent', 'Contact', 'Newsletter Signup']);
			form.submit();
		}
	});

	$("#the_contact_form").validate({
		rules: {
			first_name: {
				required: true,
				isFirstName: true
			},
			last_name: {
				required: true,
				isLastName: true
			},
			phone: {
				required: true,
				digits: true,
				rangelength: [10, 10]
			},
			email: {
				required: true,
				email: true
			},
			zip: {
				required: true,
				isZipCode: true,
				postalcode: true
			}
		},
		messages: {
			first_name: "Please enter your first name",
			last_name: "Please enter your last name",
			phone: "Phone number must be 10 digits only (no punctuation)",
			email: "Please enter a valid email address",
			zip: "Please enter your zip/postal code"
		},
		errorClass: "fail"


		/** BACKUP SUBMIT HANDLER IF SALEFORCE FAILS **/
		, submitHandler: function(form) {
			_gaq.push(['_trackEvent', 'Contact', 'Contact Form', $("#the_contact_form input[name=lead_source]").val() ]);
			var queryString = $(form).serialize();
			queryString = queryString + "&phppost_email=digitalsurgeonstestrecip@gmail.com,info@themarlincompany.com&phppost_subject=%5BMarlin%5D%20Contact%20Form";
			$.post( '/email.php' , queryString , function (data) { /* goggles do nothing */ });
			form.submit();  // make sure the form still fires to salesforce
		}
		/** BACKUP SUBMIT HANDLER IF SALEFORCE FAILS **/


	});

	$("#free_offer_form").validate({
		rules: {
			first_name: {
				required: true,
				isFirstName: true
			},
			last_name: {
				required: true,
				isLastName: true
			},
			email: {
				required: true,
				email: true
			},
			zip: {
				required: true,
				isZipCode: true
			},
			phone: {
				required: true,
				digits: true,
				rangelength: [10, 10]
			}

		},
		messages: {
			first_name: "Please enter your first name",
			last_name: "Please enter your last name",
			phone: "Phone number must be 10 digits only (no punctuation)",
			email: "Please enter a valid email address",
			zip: "Please enter your zip/postal code"
		},
		errorClass: "fail"

		/** BACKUP SUBMIT HANDLER IF SALEFORCE FAILS **/
		, submitHandler: function(form) {
			_gaq.push(['_trackEvent', 'Contact', 'Free Offers', $("#free_offer_form input[name=lead_source]").val() ]);
			var queryString = $(form).serialize();
			queryString = queryString + "&phppost_email=digitalsurgeonstestrecip@gmail.com,info@themarlincompany.com&phppost_subject=%5BMarlin%5D%20Free%20Offers%20Form";
			$.post( '/email.php' , queryString , function (data) { /* goggles do nothing */ });
			form.submit();  // make sure the form still fires to salesforce
		}
		/** BACKUP SUBMIT HANDLER IF SALEFORCE FAILS **/

	});
			

});

//On Focus, clear text field of initial value
function bindToEmpty(obj) {
	if(obj.length) {
		obj.each(function() {
			$(this).data('initValue', $(this).val());
		});
		obj.focus(function() {
			if($(this).val() == $(this).data('initValue')) {$(this).val('');}
		}).blur(function() {
			if($(this).val() == '') {$(this).val($(this).data('initValue'));}
		});
	}
}

// returns true if value is DIFFERENT from check
function check_field_for_name(value, check) {
	if (value == check) {
		return false;
	} else {
		return true;
	}
}
