// Instant win module
var instantWin = function () {
	var playElem = null; // Play area
	var oReq = new Request.HTML({evalScripts: true}); // Request object
	var firstname = null;
	var winner = false;
	var playSwf = null;
	var popup = new PopUp({windowOptions: {width: 960}});
	var defaultW = 500;
	var defaultH = 270;
	
	// Initialize the instantWin module
	function init () {
		var page = '/instant-win/play?'+new Date().getTime();
		
		if (window.location.href.indexOf('#') !== -1) {
			page = window.location.href.substr(window.location.href.indexOf('#')+1);
		}
		
		playElem = jQuery('#instantwin');
		
		jQuery.ajax({
			cache: true,
			type: "GET",
			url: page,
			success: update
		});
	};
	
	// Empty slot area and update with html
	function update() {
		var iw = jQuery('#instantwin');
		iw.html(arguments[2] ? arguments[2] : arguments[0]);
		
		Cufon.replace('h2, .text-replace');
		// createSuggest();
		
		jQuery('form', iw).each(function() {
			jQuery(this).validate({
				hideLabel: false,
				focusInvalid: false,
				labelsInInputs: true,
				submitHandler: ajaxFormSubmit,
				highlight: function(element, errorClass, validClass, msg) {
					errorHighlight(element, errorClass, validClass, msg);
					// createSuggest();
				}
			});
		});
	};
	
	function errorHighlight(element, errorClass, validClass, msg) {
		if (jQuery(element).prev().length > 0 && jQuery(element).prev().is(':visible')) {
			jQuery(element).prev().addClass(errorClass);
		} else {
			jQuery(element).next().addClass(errorClass);
		}
	}
	
	function injectHomeFlash() {
		// If slots elem is present inject flash
		var slots = playElem.find('#slots');
		
		if (slots.length > 0) {
			swfobject.embedSWF('/static/swf/homeflash.swf?'+new Date().getTime(), 'flash', defaultW, defaultH, '8', false, false, {wmode:'transparent'});
			playSwf = null;
		}
	}
	
	function injectPlayFlash() {
		var slots = playElem.find('#slots');
		
		if (slots.length > 0) {
			swfobject.embedSWF('/static/swf/instantwin.swf?'+new Date().getTime(), 'flash', defaultW, defaultH, '8', false, false, {wmode:'transparent', flashvars:'fname='+firstname, allowScriptAccess:'always'}, {id:'playFlash'});
			playSwf = swfobject.getObjectById('playFlash');
		}
	}
	
	function injectClosedFlash() {
		var slots = playElem.find('#slots');
		
		if (slots.length > 0) {
			swfobject.embedSWF('/static/swf/closedflash.swf?'+new Date().getTime(), 'flash', defaultW, defaultH, '8', false, false, {wmode:'transparent', flashvars:'fname='+winner, allowScriptAccess:'always'}, {id:'closedFlash'});
			playSwf = null;
		}
	}
	
	function ajaxFormSubmit() {
		var dataString = "";

		jQuery(this.currentForm).find('input, select, textarea').each(function(i, obj) {
			dataString += (i == 0) ? "" : "&";
			dataString += obj.name + "="+obj.value;
		});

		jQuery.ajax({
			cache: true,
			type: "POST",
			url: jQuery(this.currentForm).attr("action"),
			data: dataString,
			success: update
		});
	}
	
	function getUpdate() {
		jQuery.ajax({
			cache: true,
			type: "GET",
			url: '/instant-win/play?'+new Date().getTime(),
			success: update
		});
	}
	
	function getRegister() {
		jQuery.ajax({
			cache: true,
			type: "GET",
			url: '/instant-win/register',
			success: update
		});
	}
	
	/*
	 * Function called by flash to get result of user pressing play
	 *	example response: {"result":"lose","plays":2}
	 */
	function play() {
		// Ajax call sent to get result and spins left
		var getjson = jQuery.get('instant-win/play/json?'+new Date().getTime(), null, playSuccess);
	};
	
	/*
	 * Request.JSON onSuccess handler passes flash results and updates
	 * token with new plays left
	 */
	function playSuccess (data, text) {
		// If the data came back JSON formatted, then the code will execute past the first line in the try. Otherwise the data's not JSON formatted.
		try {
			var json = JSON.parse(data);
			if (json) {
				firstname = jQuery('#playername').html();
				var result = json.result.indexOf('win') != -1 ? 'win' : json.result;
				
				swfobject.getObjectById('playFlash').sendResult(result, json.plays, firstname);
				updateToken(json.plays);
			} else {
				update(data);
			}
		} catch (e) {
			update(data);
		}
	};
	
	function updateToken (plays) {
		jQuery('#plays-left-token').html(plays);
	};
	
	function createSuggest() {
		jQuery('input[type=text]').example(function() {
			return jQuery(this).parent().find('label[for='+this.id+']').html();
		});
	}
	
	/*
	 * Returns public methods and properties
	 */
	return {
		ajaxFormSubmit: ajaxFormSubmit,
		init: init,
		play: play,
		update:update,
		getRegister: getRegister,
		getUpdate: getUpdate,
		injectPlayFlash: injectPlayFlash,
		injectHomeFlash: injectHomeFlash,
		injectClosedFlash: injectClosedFlash,
		setWinner: function(name) {
			winner = name;
		},
		// Function to set the users name
		setName: function (name) {
			firstname = name;
		}
	};
}();

jQuery(function() {
	if (jQuery('instantwin')) {
		instantWin.init();
	}
	
	jQuery('.ajax').live('click', function() {
		jQuery.ajax({
			cache: true,
			type: "GET",
			url: this.href,
			success: instantWin.update
		});
		
		return false;
	});
	
	jQuery('.popup').live('click', function() {
		window.open(this.href, this.title, "location=0,width=600,height=800,scrollbars=yes,resizable=yes")
		return false;
	});
	
	var guiltyTeam = jQuery('img.guiltyTeam');
	
	if (guiltyTeam) {
		guiltyTeam.parent().empty().flash({
			src: '/static/swf/guiltyteam.swf',
			width: 545,
			height: 380
		}, { version: 8 });
	}
	
	var wuMachine = jQuery('.wuMachine');
	
	if (wuMachine) {
		wuMachine.parent().empty().flash({
			src: '/static/swf/wumachine.swf',
			width: 720,
			height: 400
		}, { version: 8 });
	}
});