// Instant win module
var instantWin = function () {
	var playElem = null; // Play area
	var firstname = null;
	var winner = false;
	var playSwf = null;
	var popup = new PopUp({windowOptions: {width: 960}});
	var defaultW = 935;
	var defaultH = 543;
	
	// Initialize the instantWin module
	function init () {
		var page = false;
		
		if (window.location.href.indexOf('#') !== -1) {
			page = window.location.href.substr(window.location.href.indexOf('#')+1);
		}
		
		playElem = jQuery('#instant-win');
		
		if (page) {
			jQuery.ajax({
				cache: true,
				type: "GET",
				url: page,
				success: update
			});
		}
	};
	
	// Empty slot area and update with html
	function update() {
		var iw = jQuery('#instant-win');
		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,
				highlight: function(element, errorClass, validClass, msg) {
					errorHighlight(element, errorClass, validClass, msg);
					// createSuggest();
				}
			});
		});
	};
	
	function errorHighlight(element, errorClass, validClass, msg) {
		jQuery(element).addClass(errorClass);
		if (jQuery(element).prev().length > 0) {
			jQuery(element).prev('label:visible').addClass(errorClass);
		} else {
			jQuery(element).parent().find('label:visible').addClass(errorClass);
		}
	}
	
	function errorUnhighlight(element, errorClass, validClass, msg) {
		jQuery(element).removeClass(errorClass);
		if (jQuery(element).prev().length > 0) {
			jQuery(element).prev('label').removeClass(errorClass);
		} else {
			// if the element has more than one label (ie: the regular one, and an error one)
			if (jQuery(element).parent().find('label').length > 1) {
				// Remove the error label;
				jQuery(element).parent().remove(jQuery(element).parent().find('label').get(0));
			}
			
			jQuery(element).parent().find('label').removeClass(errorClass);
		}
	}
	
	function injectPlayFlash() {
		var slots = playElem.find('#slots');
		
		if (slots.length > 0) {
			swfobject.embedSWF(
				/* swfUrl				*/ '/static/flash/gameflash.swf?'+new Date().getTime(),
				/* id					*/ 'slots',
				/* width				*/ defaultW,
				/* height				*/ defaultH,
				/* version				*/ '8',
				/* expressInstallSwfurl	*/ '/static/script/swfobject2.2/expressInstall.swf',
				/* flashvars			*/ false,
				/* params				*/ {wmode:'transparent', flashvars:'fname='+firstname, allowScriptAccess:'always'},
				/* attributes			*/ {id:'playFlash'},
				/* callbackFn			*/ function() {
												// Show the fire the gun copy
												jQuery('h2.fire-gun').show();
										   }
			);
			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: '/snail-race/play?'+new Date().getTime(),
			success: update
		});
	}
	
	function getRegister() {
		jQuery.ajax({
			cache: true,
			type: "GET",
			url: '/snail-race/register',
			success: update
		});
	}
	
	function getTellFriend() {
		jQuery.ajax({
			cache: true,
			type: "GET",
			url: '/snail-race/friend',
			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('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, 'http://ooh.comps.bigfish.co.uk/snail-race');
				updateToken(json.plays);
			} else {
				console.log('not json');
				update(data);
			}
		} catch (e) {
			console.log(e);
			update(data);
		}
	};
	
	function updateToken (plays) {
		jQuery('.plays-left').html(plays);
	};
	
	function createSuggest() {
		// jQuery('input[type=text]').example(function() {
		// 	return jQuery(this).prev('label').hide().html();
		// });
	}
	
	function showGunMessage() {
		jQuery('.fire-gun').show();
	}
	function hideGunMessage() {
		jQuery('.fire-gun').hide();
	}
	
	/*
	 * Returns public methods and properties
	 */
	return {
		ajaxFormSubmit: ajaxFormSubmit,
		init: init,
		play: play,
		update:update,
		getRegister: getRegister,
		getTellFriend: getTellFriend,
		getUpdate: getUpdate,
		injectPlayFlash: injectPlayFlash,
		injectClosedFlash: injectClosedFlash,
		errorHighlight: errorHighlight,
		errorUnhighlight: errorUnhighlight,
		showGunMessage: showGunMessage,
		hideGunMessage: hideGunMessage,
		setWinner: function(name) {
			winner = name;
		},
		// Function to set the users name
		setName: function (name) {
			firstname = name;
		}
	};
}();

jQuery(document).ready(function() {
	instantWin.init();
	
	jQuery('input[type=text]').example(function() {
		return jQuery(this).prev('label').html();
	});
	jQuery('form label:not(.checkbox label):visible').hide();
	
	jQuery('form').each(function() {
		jQuery(this).validate({
			hideLabel: true,
			focusInvalid: false,
			labelsInInputs: true,
			highlight: instantWin.errorHighlight,
			unhighlight: instantWin.errorUnhighlight
		});
	});
	
	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;
	});
	
	try{ DD_belatedPNG.fix('img, a, .container, .fire-gun, .plays-left, .col1, .col2'); } catch(e) {}
});
