// JavaScript Document

var $j=jQuery.noConflict();

var jsMCD6285 = window.jsMCD6285 || {};

var resetErrorArray = Array("name", "email", "confirm_email");

$j(function(){
	jsMCD6285.Common().init();

});


jsMCD6285.Common = function() {
	
	
	var init = function() {	
		$j('#btnGo').click(function() {
			sendForm();
			return false;
		});
		
		
		$j('#tcPopup').click(function() {
			window.open('terms.html','','scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
			return false;
		});
		
	}
	
	var sendForm = function(){
		
		resetErrors(resetErrorArray);
		
		if($j('#cbTC:checked').val() != 1){
			highlightErrors([]);
			return false;
		}
		
		var name = $j('#name').val();
		var email = $j('#email').val();
		var confirm_email = $j('#confirm_email').val();
		
		$j.ajax({
			dataType: 'json',
			type: 'POST',
			data:'json={"name":"' + name + '", "email":"' + email + '", "confirm_email":"' + confirm_email + '", "terms":"1"}',
			url: 'portal.php?json={}',
			success: function(data) {
				
				if(data.length != 0){
					highlightErrors(data);
				} else {
					showThanks();
				}
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("XMLHttpRequest: " + XMLHttpRequest);
				alert("textStatus: " + textStatus);
				alert("errorThrown: " + errorThrown);
			}
		});
		
	}
	
	var resetErrors = function(errorArray){
		$j('#formError').hide();
		
		for(var i = 0; i <= errorArray.length; i++) {
			$j('#' + errorArray[i]).css({backgroundPosition: "0 0px"} );
		}
	}
	
	var highlightErrors = function(errorArray){
		$j('#formError').show();
		
		for(var i = 0; i <= errorArray.length; i++) {
			$j('#' + errorArray[i]).css({backgroundPosition: "0 -42px"} );
		}
	}
	
	var showThanks = function() {
		$j("#content").html("<div id='thanksComp'><div id='thanksTitle'>Thank you for entering</div><div id='thanksCopy'>You've been entered into the prize draw. We'll send you an email if you're one of the lucky winners.</div><div id='btnFindMore'><a href='http://www.happymeal.co.nz' target='_blank'><img src='images/btnFindMore.png' alt='For more fun and games check out www.happymeal.co.nz' /></a></div></div>");
		
		$j('#bookSelection').css({top:"898px"} );
		$j('#footer').css({top:"1145px"} );
		
	}

	
	return {
		init : init
		
	}
}
