var minWidth = 960;
var minHeight = 760;

$(document).ready(function() {
  $('body').removeClass('no-js');

	$ageVerified = $.cookie('ageVerified');
	
	if ( !$ageVerified && !$('body').is("#page-gatekeeper") ) {
		// Cookie set, so set our dealer location
		window.location.href = "/gatekeeper.html";
	} else {
		$("body").css({"visibility": "visible"});

		if ($('body').is("#page-gatekeeper")) {
			$("#birthday-picker").birthdaypicker({
				maxAge: '123',
				dateFormat: 'littleEndian'
			});

			if ($restrictions) {
				$.each($restrictions, function() {
					$("#country-restrictions").append("<option value=\"" + this.age + "\">" + this.country + "</option>");
				});
			}

			$("a#do-login").bind("click", function(e) {
				canProceed = validateDOB();

				if (!canProceed) {
					e.preventDefault();
				} else {
					$.cookie('ageVerified', 'TRUE', { expires: 7, path: "/" });
				}
				
			});
		}

		if ($('body').is("#page-join-us")) {
			// $previouslySignedUp = $.cookie('signedUp');
			
			// if ($previouslySignedUp) {
			// 	$.cookie('signedUp', null, { expires: 7, path: "/" });
			// 	window.location.href = "home.html";
			// }
			
			$("form#subForm").bind("submit", function() {
				var name = $(this).find("#name").val();
				
				var email = $(this).find("#qhiai-qhiai").val();
				var emailCheck = $(this).find("#email-check").val();

				if ( !( name.length > 0 ) || !( email.length > 0 ) || !( emailCheck.length > 0 ) ) {
					alert("Please fill out all the fields.");
					return false;
				}

				if ( email != emailCheck ) {
					alert("Oops! Please make sure that your email address matches.");
					return false;
				}

				if ( !IsValidEmail(email) ) {
					alert("Oops! Please enter a valid email address.");
					return false;
				}

				// $.cookie('signedUp', 'TRUE', { expires: 7, path: "/" });
			});
		}

		if ($('body').is('#page-contact')) {
			$("span#email-1").replaceWith( decodeEmail('PEfh@vRrCfEO.Wf.Lv','4l5EdAur3WoDXxwKejHO2nTFRSgUftMZCaV7NyzLIBs1GQbh80YmJckiv69qPp','','') );
			$("span#email-2").replaceWith( decodeEmail('z42u2no@MbiNGfg.nG.2M', '13xhMRgnSLiQ9XqPj0eaKFkOfHYC26T4ZdwED7pouJWsVzAlcU8m5IrNyvtBGb') );
		}
		
		// Analytics
		window.analyticsID = (location.hostname.match('zumwohl.co.nz')) ? 'UA-18008027-1' : 'UA-18008027-2';
		window._gaq = window._gaq || [];
		window._gaq.push(['_setAccount', analyticsID]);
		window._gaq.push(['_trackPageview']);

		(function() {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		})();
	}

  $('.target-blank').click(function(e){
    e.preventDefault();
    window.open(this.href);
  });

	/* 
		Embed flash only if window is wide enough
	*/
	
	if($(window).width() >= 950) {
	  windowResizeHandler();
		embedFlash();

		$(window).bind('scroll', windowScrollHandler);
		$(window).bind('resize', windowResizeHandler);
		setTimeout("windowResizeHandler()",1000);

	} 
		
});




// Email obfuscator script 2.1 by Tim Williams, University of Arizona
// Random encryption key feature by Andrew Moulden, Site Engineering Ltd
// This code is freeware provided these four comment lines remain intact
// A wizard to generate this code is at http://www.jottings.com/obfuscator/
 
//Modified by Justin
function decodeEmail(coded, key, alternateText, linkClass) {
	var shift = coded.length;
	var link = '';

	var email = '';

	for (i=0; i<coded.length; i++) {
		if (key.indexOf(coded.charAt(i))==-1) {
			ltr = coded.charAt(i);
			link += (ltr);
		} else {
			ltr = (key.indexOf(coded.charAt(i))-shift+key.length) % key.length;;
			link += (key.charAt(ltr));
		}
	}
	if (alternateText) {
		if (linkClass) {
			email = "<a href='mailto:"+link+"' class='" + linkClass + "'>" + alternateText + "</a>";
		} else {
			email = "<a href='mailto:"+link+"'>" + alternateText + "</a>";
		}
	} else {
		if (linkClass) {
			email = "<a href='mailto:"+link+"' class='" + linkClass + "'>" + link + "</a>";
		} else {
			email = "<a href='mailto:"+link+"'>" + link + "</a>";
		}
	}

	return email;
}

function validateDOB() {
	var day = $("select.birth-day").val();
	var month = $("select.birth-month").val();
	var year = $("select.birth-year").val();
	var age = $("select#country-restrictions").val();

	if (day == 0 || month == 0 || year == 0) {
		alert("Please enter your date of birth");
		return false;
	} else {
		var mydate = new Date();
		mydate.setFullYear(year, month-1, day);

		var currdate = new Date();
		currdate.setFullYear(currdate.getFullYear() - age);

		if ((currdate - mydate) < 0) {
			alert("Sorry, only persons over the age of " + age + " may enter this site");
			return false;
		} else {
			return true;
		}
	}
}

function IsValidEmail(email) {
  var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
  return filter.test(email);
}


// FLASH STUFF
function windowResizeHandler() {
  var newW = $(window).width();
  var newH = $(window).height();

  if(newH < 760) {
    $('object').css('height', '760px');
  } else {
    $('object').css('height', '100%');
  };

	$('body').css('height', $(window).height());

  windowScrollHandler();
}

// Flash variable that positions the bottom menu in the Flash
function windowScrollHandler() {
  var obj = $('object')[0];
  if (!obj) return;
  obj.browserWindowScrollHandler($(window).height() + $(window).scrollTop());
}

function trackFlashPage(pageId) {
	try {
		_gaq.push(['_setAccount', analyticsID]);
		_gaq.push(['_trackPageview', pageId.toLowerCase()]);
	}
	catch(error){ }
}

// USes SWF Object to embed the flash
function embedFlash() {
  var flashvars = {};
  flashvars.xmlSrc = "/xml/zumwohl.xml?3";
  flashvars.mainSWF = "/zumwohl.swf?3";
  var params = {'quality': 'high', 'allowScriptAccess': 'sameDomain', 'wmode': 'direct'}; //opaque
  var attributes = {'id': 'main', 'name': 'main' };
  swfobject.embedSWF("/preloader.swf?3", "main", "100%", "100%", "10.0.0", "/expressInstall.swf", flashvars, params, attributes, function(){ $('body').css('height', $(window).height()); $('#main').css('display', 'block') });	
}

