/*
	Authored by Phillip Parr
	August 2010
		
	Setup playslip client side interactivity
	
	I fixed missing semicolons and !== and === etc.
	Robert
*/

(function($){
		  
	$.fn.extend({
				
		playslip: function(options) {
			
			var self = this; // create a pointer to internal functions
			var defaults = { 
				luckyDip: "LD"
			};
			var o = $.extend(defaults, options); // merge the defaults into passed values
			o.numbersPerBoard = o.mainNumsPerBoard + o.specialNumsPerBoard;

			
			this.updateAmount = function(){
				var numBoards = CoreForms.fullBoards($(this).find('input[name="dummy"]'), o.noOfBoards, o.numbersPerBoard);
				var numWeeks = $(this).find('select[name="numberOfWeeks"]').val();
				var numDays = ($(this).find('select[name="daysOfWeek"]').length) ? (($(this).find('select[name="daysOfWeek"]').val()).replace(/_/g,'')).length : 1;
				o.totamount = (o.costPerBoard * numBoards * numWeeks * numDays);
				$(this).find('#totalAmount').html(self.currencyFormat(o.totamount));
			}
			
			this.currencyFormat = function(x) {
				var t, s=new String(Math.round(x*100));
				while (s.length<3) {
					s='0'+s;
				}
				return s.substr(0, t=(s.length-2)) + '.' + s.substr(t, 2);
			}


			this.removeAllBoardErrors = function(){
				clearErrorMessage();
				$(this).find('ol, input').removeClass('error');
			}
			
			
			this.validateEmptyOrLD = function(lineNumber) {  
				var empty = true;
				$(this).find('#pl'+lineNumber+' input').each(function() {
					var val = $(this).val();
					if(val !== null && val !=='' && val !== o.luckyDip) {
						empty = false;
					}
				});
				return empty;
			}		
			
			
			this.luckyDipReplace = function(playline) {
				$('#' + playline + ' > li > input:text').val(o.luckyDip);
				$('#' + playline).parents('fieldset').find('input[name="drawGameBoards['+playline.substr(2,1)+'].luckyDip"]').val('true'); // set hidden luckydip field to true
				self.removeAllBoardErrors(); 
				self.updateAmount();
			}
			
			
			this.displayErrorWithButton = function(errorMessage, buttonMessage, buttonUrl, callback){
				var error = "<a href='"+buttonUrl+"' class='primary'><span>"+buttonMessage+"</span></a>";
				if (typeof(callback) == "function") {
					error = '<a class="primary error_button"><span>'+buttonMessage+'</span></a>';
				}
				setErrorMessage(errorMessage +  error, function(container) {
					container.find('.error_button').click(function() {
						callback();
					});
				});
			}
			
			
			this.setupHelpBoxContainer = function() {
				$('a.lottohelpboxcontainerOpen').click(function() {
					if(!$('.cloned_help').length) {
						$('#lottoHelpOverlay').clone(true).addClass('cloned_help').css({ display: 'block', left: '257px', top: '9px' }).appendTo('#primarycontent'); 
					}
					$('a.lottohelpboxcontainerClose').click(function() {
						$(this).parents('.cloned_help').remove();
					return false;
				});
					return false;
				});	
			}
			
			
			this.attachNumericBoxesRules = function(thisInput, extraBoxes) {
				thisInput.data('validation', { maxVal: o.maxValue, minVal: o.minValue, ld: o.luckyDip });
				thisInput.rules("add", {
					requiredIfSiblingsHaveValue: true,
					mustBeUniqueOnDrawLineMatrix: { "min":0, "max":o.mainNumsPerBoard - 1, "ld":o.luckyDip },
					greaterThan: { "val":o.minValue - 1, "ld":o.luckyDip },
					lessThan: { "val":o.maxValue + 1, "ld":o.luckyDip },
					isLDAndNumber: { "ld":o.luckyDip },
					isNumericAndTwoDigits: { "val":true, "ld":o.luckyDip },
					messages: {
						mustBeUniqueOnDrawLineMatrix: o.messages.duplicatedNumberMsg,
						requiredIfSiblingsHaveValue: o.messages.tooFewNumbersMsg,
						greaterThan: o.messages.invalidNumberMsg,
						lessThan: o.messages.invalidNumberMsg,
						isLDAndNumber: o.messages.clearConfirmMsg,
						isNumericAndTwoDigits: o.messages.invalidNumberMsg
					}
				});
				thisInput.addClass("hiValParent2-playslip");
				if(extraBoxes) {
					thisInput.data('validation', { maxVal: o.specialMaxValue, minVal: o.specialMinValue, ld: o.luckyDip });
					thisInput.rules("add", {
						requiredIfSiblingsHaveValue: true,
						mustBeUniqueOnDrawLineMatrix: { "min":o.mainNumsPerBoard, "max":o.numbersPerBoard - 1, "ld":o.luckyDip },
						greaterThan: { "val":o.specialMinValue - 1, "ld":o.luckyDip },
						lessThan: { "val":o.specialMaxValue + 1, "ld":o.luckyDip },
						isLDAndNumber: { "ld":o.luckyDip },
						isNumericAndTwoDigits: { "val":true, "ld":o.luckyDip },
						messages: {
							greaterThan: o.messages.specialInvalidNumberMsg,
							lessThan: o.messages.specialInvalidNumberMsg,
							isLDAndNumber: o.messages.clearConfirmMsg,
							isNumericAndTwoDigits: o.messages.specialInvalidNumberMsg
						}
					});
				} 	
			}	
			
			
			// setup playslip
			return this.each(function() {
				
				// added to allow us to check for full lines on form submission. Is there a better way to do this?
				$(this).append('<input type="hidden" name="dummy" value="" />');
				
				// clearing a line
				CoreForms.setupClearThisLine(function(playline) {
					self.updateAmount();
					playline.find('input[name="drawGameBoards['+playline.find('ol').attr('id').substr(2,1)+'].luckyDip"]').val('false'); // set hidden luckydip field to false
				});
				
				self.setupHelpBoxContainer();	// setup help link
				
				CoreValidationMethods.setupValidation(this); // attach main validation events to form
				
				CoreForms.setupTotalContainer(this, self.currencyFormat(o.totamount));	// insert the total calculation
				CoreForms.setupLuckyDipLink(this, o.inputGameName.toLowerCase());	// swap lucky dip checkboxes for buttons

				// fix LD buttons for IE6 users
				if ($.browser.msie && $.browser.version < 7) {
					$('.luckydipimg').each(function() {
						var src = $(this).attr('src').replace('.png', '.gif');
						$(this).attr({ 'src': src });
					});
				}

				// setup validation on number inputs
				$(this).find('#playsliplist input[type="text"]').each(function() {
					var line = $(this).attr('id').substr(2, 1);
					var slot = $(this).attr('id').substr(3, 1);
					if(slot >= o.mainNumsPerBoard) {
						self.attachNumericBoxesRules($(this), true);
					} else {
						self.attachNumericBoxesRules($(this), false);
					}
				});

				// if the game is unavailable the form is empty and we can't calculate anything
				if($(this).find('#totalAmount').length) {
					self.updateAmount();
				}
				
				// last numbers link
				$(this).find('.confirm_last_numbers').click(function() {
					var blank = true;
					$(self).find('#playsliplist input[type="text"]').each(function() {
						if($(this).val()) {blank = false;}
					});
					if(!blank) {
						var error1 = "<a class='primary transparent' href='javascript:document.playslipForm.submit();'><span>Continue</span></a>";
						var error2 = "<a class='primary transparent remove_errors' href=''><span>Cancel</span></a>";
						var error = error1 + error2;
						setErrorMessage(o.messages.confirmLastNumberOverwriteMsg + error); 
						$('.remove_errors').click(function() { self.removeAllBoardErrors(); return false; });
						return false;
					} else {
						$('form[name="playslipForm"]').submit();
					}
					return false;
				});
				
				$(this).find('#playnow').click(function() {
					// add validation rules for draw selection drop downs
					if($(this).parents('form').find("select[name='daysOfWeek']").length) {
						$(this).parents('form').find("select[name='daysOfWeek']").addClass('drawselect').rules("add", { 
							isDaySelected: true,
							messages: { 
								isDaySelected: o.messages.daysErrorMsg
							}
						});
					}
					$(this).parents('form').find("select[name='numberOfWeeks']").addClass('drawselect').rules("add", { 
						areWeeksSelected: true,
						messages: { 
							areWeeksSelected: o.messages.weeksErrorMsg
						}
					});
					$(this).parents('form').find('input[name="dummy"]').rules("add", {
						hasWholeBoard : { 
							"boards" : o.noOfBoards, 
							"numbers" : o.numbersPerBoard 
						},
						messages: {
							hasWholeBoard : o.messages.noBoardsErrorMsg
						}
					});
					$(this).parents('form').find('#playsliplist input[type="text"]').change(function() {
						$(this).parents('form').find('input[name="dummy"]').valid();
					});				
				});
				$(this).find('select[name="daysOfWeek"], select[name="numberOfWeeks"], #playsliplist input[type="text"]').change(function() {
					self.updateAmount();
				});
				
				
				// update number of weeks available based on selected days for countdown
				var now = $(this).find('select[name="numberOfWeeks"]').clone();
				$(this).find('select[name="daysOfWeek"]').change(function() {
					var millisecondDay = 1000 * 60 * 60 * 24;
					var days = $(this).val();
					var date = new Date();
					var today = date.getDay();
					var lastPlayDate = new Date();

					if(days.replace(/_/g, '').length > 1) {
						// more than one day selected, more calculation...
						var found = false;
						var pointer = today - 2; // convert to 1 based array and prev day
						if(pointer < 0) pointer += 7;
						while(found === false) {
							if(days[pointer] != '_') { // lil face
								day = pointer + 1;
								found = true;
							}
							pointer--;
							if(pointer < 0) {pointer += 7;}
						}
					} else {
						day = days.length - days.replace(/^_*/, '').length + 1;
					}
					if(day >= today) {
						lastPlayDate.setDate(lastPlayDate.getDate() + day - today);
					} else {
						lastPlayDate.setDate(lastPlayDate.getDate() + day - today + 7);
					}
					
					if(days.replace(/^_*/, '').length) {					
					var validWeeks = Math.ceil((Date.parse(o.lastDrawDate) + millisecondDay - Date.parse(lastPlayDate)) / millisecondDay / 7);
					} else {
						var validWeeks = o.maxWeeks;
					}
					
					
					var val = $(this).parents('form').find('select[name="numberOfWeeks"]').val();
					
					// IE doesn't like us splurging the options back into the select with html(), so we have to rebuild them individually, manually.
					$(this).parents('form').find('select[name="numberOfWeeks"]').html('');
					var dow = $(this);
					$(now).find('option').each(function() {
						$('<option>').val($(this).val()).text($(this).html()).appendTo($(dow).parents('form').find('select[name="numberOfWeeks"]'));
					});
					$(this).parents('form').find('select[name="numberOfWeeks"] option').each(function() {
						if($(this).val() > validWeeks) {
							$(this).remove();
						}
					});
					
					// if the previously selected number of weeks is no longer available, select the maximum number of weeks available
					if($(this).parents('form').find('select[name="numberOfWeeks"] option[value="'+val+'"]').length) {
						$(this).parents('form').find('select[name="numberOfWeeks"]').val(val);
					} else {
						//$(this).parents('form').find('select[name="numberOfWeeks"]').val($(this).parents('form').find('select[name="numberOfWeeks"] option:last').val())
					}
				});
			
				
				// clear notice if shown - introduced for star number limit change
				$(this).find('#playsliplist input[type="text"]').focus(function() {
					if($(this).parents('li').hasClass('notice')) {
						$(self).find('.notice').removeClass('notice');
					}
				});				

				// luckydip click
				$(this).find('.luckydiplink').click(function(){
					var obj = $(this);
					var playline = $(this).parent().parent().attr('id');
					if(self.validateEmptyOrLD(playline.substring(2,3))) {
						self.luckyDipReplace(playline);
						$(this).parents('form').find('input[name="dummy"]').valid();
					} else {
						self.displayErrorWithButton(o.messages.luckyDipConfirmMsg, "OK", "#", function() { self.luckyDipReplace(playline); obj.parents('form').find('input[name="dummy"]').valid(); });
					}
					return false;
				});
				
				// set luckydip checkbox if form line already populated with LD values (ideally this would have been in the backend)
				$('#playsliplist ol').each(function() {
					if($(this).find('input[value="'+o.luckyDip+'"]').length == o.mainNumsPerBoard + o.specialNumsPerBoard) {
						$(this).parent().find('input[name$="luckyDip"]').val('true');
					}
				});
				
				$('#addToBasketFirst').click(function() {
					$(self).unbind('submit');
				});
			});
		}
	});
})(jQuery);
