/**
 * jQuery Plugin for adding advanced forms behavior
 * 
 * @author Gabriel Lemonde-Labrecque
 * @copyright 2010, SchoolSuccess inc.
 */

var AdvancedForms = {
	pricePattern: /^\$?(\d?\d?\d?(?:(?:,\d\d\d)*|(?: \d\d\d)*|(?:\d\d\d)*))(?:\.(\d\d))?$/,
	
	simplifyPrice: function(price) {
		if (typeof price != 'string') alert('price is not a string');
		
		var matches = price.match(AdvancedForms.pricePattern);
		
		if (matches) {
			var dollars = matches[1].replace(/[ ,]/g, ''); //.replace(/\d?\d?\d((,\d\d\d)*/, '');
			var cents = matches[2];
			
			if (dollars == '')
				dollars = '0';
			
			if (typeof cents == 'undefined' || cents == '')
				cents = '00';
			
			return dollars + '.' + cents;
		}
		
		return '';
	},
	
	prettifyPrice: function(price) {
		if (typeof price != 'string') alert('price is not a string');
		
		var matches = price.match(AdvancedForms.pricePattern);
		
		var dollars = '0';
		var cents = '00';
		
		if (matches) {
			dollars = matches[1];
			
			if (dollars == '')
				dollars = '0';
			
			dollars = dollars.replace(/[ ,]/, '')
				.replace(/^0+/, '0')
				.replace(/^0(\d)/, '$1')
				.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
			
			cents = matches[2];
			
			if (typeof cents == 'undefined' || cents == '')
				cents = '00';
		}
		
		return '$' + dollars + '.' + cents;
	}
};

(function($) {
	if ($.validator) {
		// Add a rule to jquery.validator for names
		$.validator.addMethod(
			"validName",
			function(value, element, param) {
				return (this.optional(element) || value.match(/^[^0-9`~!@#$%^&*()_+=\?\[\]\{\}|";:><,\/]+$/)) && (value.match(/^[A-Za-z'\-\s]+$/) ? ! (value.toUpperCase() == value || value.toLowerCase() == value) : true)
			},
			"Name cannot contain symbols. It must contain both Upper case and lower case letters."
		);
		
		// Add a rule to jquery.validator for usernames
		$.validator.addMethod(
			"validUsername",
			function(value, element, param) {
				return (this.optional(element) || (value.match(/^[A-Za-z][A-Za-z0-9\-\_]+$/) && value.length >= 4));
			},
			"Username must start with a letter and contain at least 4 characters. It can contain letters, numbers, dashes and underscores."
		);

		// Add a rule for dashed dates to jquery.validator
		$.validator.addMethod(
			"dashedDate",
			function(value, element) {
				return this.optional(element) || value.match(/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/);
			},
			"Please enter a date in the format yyyy-dd-mm"
		);
		
		// Add a rule for dashed dates to jquery.validator
		$.validator.addMethod(
			"isPhone",
			function(value, element) {
				return this.optional(element) || value.match(/^(?:\+?\d{1,3}?[-\.\s]?)?[-\.\s]?\(?\d{2,4}\)?[-\.\s]?\d{3,4}[-\.\s]?\d{4}.*?$/);
			},
			"Please enter a valid phone number"
		);

		// Add a rule to jquery.validator for prices
		$.validator.addMethod(
			"price",
			function(value, element, param) {
				return this.optional(element) || value.match(/^\$?(\d?\d?\d((,\d\d\d)*|( \d\d\d)*|(\d\d\d)*))(\.(\d\d))?$/);
			},
			"Please enter a valid price"
		);
		
		// Add a rule to jquery.validator for comparing prices greater than some value
		$.validator.addMethod('priceGreaterThan', function(value, element, param) {
			var simplifiedPrice = parseFloat(AdvancedForms.simplifyPrice(value));
			
			return this.optional(element) || (simplifiedPrice > param);
		}, 'Must be greater than start');
		
		// Add a rule to jquery.validator for comparing prices greater than or equal to some value
		$.validator.addMethod('priceGreaterThanOrEqualTo', function(value, element, param) {
			var simplifiedPrice = parseFloat(AdvancedForms.simplifyPrice(value));
			
			return this.optional(element) || (simplifiedPrice >= param);
		}, 'Must be greater than or equal to start');
		
		// Add a rule to jquery.validator for comparing numbers greater than some value
		$.validator.addMethod('greaterThan', function(value, element, param) {
			return this.optional(element) || value > param;
		}, 'Must be greater than start');
		
		// Add a rule to jquery.validator for comparing numbers greater than or equal to some value
		$.validator.addMethod('greaterThanOrEqualTo', function(value, element, param) {
			return this.optional(element) || value >= param;
		}, 'Must be greater than or equal to start');
		
		// Add a rule to jquery.validator for comparing numbers or strings not equal to some value
		$.validator.addMethod('notEqualTo', function(value, element, param) {
			return this.optional(element) || value != param;
		}, 'Must be not equal to specified value');
		
		$.validator.addMethod('phone', function(){
				var pattern = '/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/';
				if (pattern.test($('#request_phone').val()))
					return true;
							
				return false;
		}, 'Wrong phon number');
	}
	
	$.fn.enter = function(callback) {
		$(this).keydown(function(event) {
			if(event.keyCode == 13 || event.keyCode == 10) {
				callback(event);
			}
		});
	};
	
	$.fn.tripleClick = function(callback) {
		if (typeof callback == 'undefined')
			callback = function() {};
		
		$(this).click(function() {
			var numberOfClicks = $(this).data('numberOfClicks') || 0;
			numberOfClicks++;
			$(this).data('numberOfClicks', numberOfClicks);
			
			if (numberOfClicks == 1) {
				$(this).css({ color: 'orange' });
			}
			else if (numberOfClicks == 2) {
				$(this).css({ color: 'red' });
			}
			else {
				callback();
			}
		});
	}
	
	$.fn.prettifyPrice = function() {
		var prettiedPrice = AdvancedForms.prettifyPrice(TC.string.trim($(this).text()));
		
		if (prettiedPrice != '')
			$(this).html(prettiedPrice);
	};
	
	/**
	 * defaultText
	 * 
	 * Initialize the default text of a text input.
	 * Clears a text input whenenever user focus on a it while it still contains its default text.
	 * Sets the default text back in the text input whenever user blurs it while it still contains an empty value.
	 */
	$.fn.defaultText = function(text) {
		$(this).each(function() {
			var $this = $(this);
			
			$this.focus(function () {
				if ($this.val() == text) {
					$this.val('');
					$this.css('color', 'black');
				}
				
				$this.css('color', 'black');
			});
			
			$this.blur(function () {
				if ($this.val() == '') {
					$this.val(text);
					$this.css('color', '#999');
				}
				else {
					$this.css('color', 'black');
				}
			});
			
			if ($this.val() == '' || $this.val() == text) {
				$this.val(text);
				$this.css('color', '#999');
			}
			else {
				$this.css('color', 'black');
			}
			
			$this.closest('form').submit(function() {
				if ($this.val() == text)
					$this.val('');
			});
		});
	};
	
	function floatKeypress(event) {
		var code = (event.keyCode ? event.keyCode : event.which);
		
		if (code != 46 && ((code >= 32 && code < 35) || (code > 40 && code < 48) || code > 57)) {
			event.preventDefault();
		}
	}
	
	$.fn.dateInput = function(initValue) {
		$(this).focus(function() {
			$(this).select();
		});
		
		if (typeof initValue != 'undefined') {
			$(this).val(initValue);
		}
		$(this).blur();
	};
	
	$.fn.floatInput = function(initValue) {
		$(this).keypress(floatKeypress);
		
		$(this).focus(function() {
			$(this).select();
		});
		
		$(this).val(initValue);
		$(this).blur();
	};
	
	$.fn.priceInput = function(initValue) {
		var that = $(this);
		$(this).keypress(floatKeypress);
		
		$(this).focus(function() {
			$(this).val(AdvancedForms.simplifyPrice($(this).val()));
			$(this).select();
		});
		
		$(this).blur(function() {
			$(this).val(AdvancedForms.prettifyPrice($(this).val()));
		});
		
		$(this).val(initValue);
		$(this).blur();
		
		$(this).enter(function() {
			that.blur();
		});
	};
	
	$.fn.aSwitch = function(textOn, textOff) {
		var $this = $(this);
		var $el = $('<p class="field switch"><label class="cb-enable"><span>' + textOn + '</span></label><label class="cb-disable"><span>' + textOff + '</span></label></p>');
		$this.after($el);
		$this.detach();
		$el.append($this);
		
		
		
		function updateView() {
			if ($this.is(':checked')) {
				$el.find(".cb-enable").addClass('selected');
				$el.find(".cb-disable").removeClass('selected');
			}
			else {
				$el.find(".cb-enable").removeClass('selected');
				$el.find(".cb-disable").addClass('selected');
			}
		}
		
		
		$el.find(".cb-enable, .cb-disable").click(function(){
			
				$this.click();
				updateView();
				if ($this.closest('input').attr('checked') == 'checked')
					$this.closest('input').removeAttr('checked');
				else
					$this.closest('input').attr('checked', 'checked');
			
		});
		
		updateView();
	};
	
	$.centerimage = {
		styles: {},
		defaults: {
			width: 100,
			height: 100
		}
	};
	
	$.fn.extend({
		center: function(options) {
			// Merge user options with defaults options
			options = $.extend({}, $.centerimage.defaults, options);
			
			var styleId = 'Width' + options.width + 'Height' + options.height;
			var wrapperClass = 'centerimage' + styleId;
			
			function getStyle() {
				var $style = $(
					'<style type="text/css">' + "\n" +
					'	.' + wrapperClass + ' {' + "\n" +
					'		display: table-cell;' + "\n" +
					'		text-align: center;' + "\n" +
					'		vertical-align: middle;' + "\n" +
					'		width: ' + options.width + 'px;' + "\n" +
					'		height: ' + options.height + 'px;' + "\n" +
					'	}' + "\n" +
					'	.' + wrapperClass + ' * {' + "\n" +
					'		vertical-align: middle;' + "\n" +
					'	}' + "\n" +
					/*/
					.wraptocenter {
						display: block;
					}
					.wraptocenter span {
						display: inline-block;
						height: 100%;
						width: 1px;
					}
					//*/
					'</style>' + "\n" +
					'<!--[if lt IE 8]>' + "\n" +
					'<style>' + "\n" +
					'	.' + wrapperClass + ' span {' + "\n" +
					'		display: relative;' + "\n" + // display: inline-block
					'		height: 100%;' + "\n" +
					'	}' + "\n" +
					'</style>' + "\n" +
					'<![endif]-->');
				
				return $style;
			}
			
			if ( ! $.centerimage.styles[styleId]) {
				var $style = getStyle();
				
				$.centerimage.styles[styleId] = $style;
				$('head').eq(0).append($style);
			}
			
			return this.each(function() {
				var $this = $(this);
				
				// Get native image coordinates
				var nativeimage = new Image();
				
				nativeimage.onload = function() {
					var width = nativeimage.width;
					var height = nativeimage.height;
					
					// Set CSS to preserve ratio
					if (width > height)
						$this.css({ width: options.width, height: 'auto' });
					else
						$this.css({ width: 'auto', height: options.height });
					
					var wrapper = $('<div></div>').addClass(wrapperClass);
					
					$this.wrap(wrapper);
					$this.before('<span></span>');
				};
				
				nativeimage.src = $this.attr('src');
			});
		}
	});
})(jQuery);

