/*
 * jqForm - Various FORM jQuery plugins
 *
 * Copyright (c) 2008 Milan Andrejevic <milan.andrejevic@gmail.com>
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */
(function($) {
	/*
	* NOTE: source slightly changed to support enabledOnly=true!!! 
	* checkGroup - check all enabled checkboxes by class selector or by name
	* original work: http://plugins.jquery.com/project/checkgroup
	* $Version: 2008.05.29
	*
	* Example: $('#SelectAll').checkGroup({nameStartsWith: 'Submited_Tender'});
	*/
	$.fn.checkGroup=function(options) {
		//merge settings
		settings=$.extend({
			groupSelector:null,
			groupName:'group_name',
			enabledOnly:false
		},options || {});
		
		var ctrl_box=this;

		
		//allow a group selector override option
		var grp_slctr = (settings.groupSelector==null) ? 'input[name='+settings.groupName+']' : settings.groupSelector;
		
		//grab only enabled checkboxes if required
		if(settings.enabledOnly)
		{
			grp_slctr += ':enabled';
		}

		//attach click event to the "check all" checkbox(s)
		ctrl_box.click(function(e){
			chk_val=(e.target.checked);
			$(grp_slctr).attr('checked',chk_val);
			//if there are other "select all" boxes, sync them
			ctrl_box.attr('checked',chk_val);
		});
		//attach click event to checkboxes in the "group"
		$(grp_slctr).click(function(){
			if(!this.checked)
			{
				ctrl_box.attr('checked',false);
			}
			else
			{
				//if # of chkbxes is equal to # of chkbxes that are checked
				if($(grp_slctr).size()==$(grp_slctr+':checked').size()){
					ctrl_box.attr('checked','checked');
				}
			}
		});
		//make this function chainable within jquery
		return this;

	};

	/*
	 * passwordCheck - Check password and password reenter. Password strength meter.
	 * $Version: 2008.05.29
	 *
	 * Example: $('#Password').passwordCheck({against: $('#RePassword')});
	 */
	$.fn.passwordCheck = function(options) {
		var opts = $.extend({}, passwordCheckDefaults, options);
		
		var checkRepetition = function(pLen,str) {
			res = ""
			for ( i=0; i<str.length ; i++ ) {
				repeated=true
				for (j=0; j < pLen && (j+i+pLen) < str.length; j++)
					repeated = repeated && (str.charAt(j+i) == str.charAt(j+i+pLen))
				if (j < pLen) repeated = false
				if (repeated) {
					i += pLen - 1
					repeated = false
				}
				else {
					res += str.charAt(i)
				}
			}
			return res
		};
		
		var score = function(password) {
			var score = 0;
			//password contains spaces
			if (password.indexOf(' ') >= 0) { return opts.containsSpace }
			//password < opts.tooShort
			if (password.length < opts.tooShort ) { return opts.shortPass }
			//password length
			score += password.length * opts.tooShort
			score += (checkRepetition(1, password).length - password.length ) * 1
			score += (checkRepetition(2, password).length - password.length ) * 1
			score += (checkRepetition(3, password).length - password.length ) * 1
			score += (checkRepetition(4, password).length - password.length ) * 1
	
			//password has 3 numbers
			if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) score += 5 
			//password has 2 sybols
			if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5 
			//password has Upper and Lower chars
			if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) score += 10 
			//password has number and chars
			if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) score += 15 
			//password has number and symbol
			if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)) score += 15 
			//password has char and symbol
			if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)) score += 15 
			//password is just a nubers or chars
			if (password.match(/^\w+$/) || password.match(/^\d+$/) ) score -= 10 

			return score
		};
		
		var reenterMessage = $('<div class="' + opts.messageClass + '"><p></p></div>');
		var update = function(equal) {
			if (equal) {
				$("p", reenterMessage).text(opts.Match);
			} else {
				$("p", reenterMessage).text(opts.noMatch);
			}
		};
		
		return this.each(function() {
			var password = null;
			var reenter = null;
			
			var indicator = $('<div class="' + opts.indicatorContainerClass + '"><div></div></div>');
			var passwordMessage = $('<div class="' + opts.messageClass + '"><p></p></div>');
			$(this).after(indicator);
			$(indicator).after(passwordMessage);
			var reenterInput = opts.against;
			$(reenterInput).after(reenterMessage);
			
			$(this).keyup(function() {
				password = $(this).val();
				var strength = score(password);
				
				if (typeof(strength) == 'string') {
					$("p", passwordMessage).text(strength);
					$("div", indicator).css({'width': '0%'});
				} else {
					if (strength < 0) strength = 0
					if (strength > 100) strength = 100
					
					$("p", passwordMessage).text(opts.verystrong)
					if (strength < 67 ) $("p", passwordMessage).text(opts.strong)
					if (strength < 50 ) $("p", passwordMessage).text(opts.medium)
					if (strength < 34 ) $("p", passwordMessage).text(opts.normal)
					if (strength < 17 ) $("p", passwordMessage).text(opts.weak)
					
					$("div", indicator).css({'width': strength + '%'});
				}
			}).blur(function() {
				update((password == reenter));
			})
			
			$(reenterInput).keyup(function() {
				reenter = $(this).val();
				update((password == reenter));
			})
		});
	};
	
	passwordCheckDefaults = {
		indicatorContainerClass: 'indicatorContainer',
		messageClass: 'passwordMessage',
		tooShort: 6,
		shortPass: 'Too short!',
		containsSpace: 'No spaces!',
		weak: 'Weak',
		normal: 'Normal',
		medium: 'Medium',
		strong: 'Strong',
		verystrong: 'Very strong',
		noMatch: 'Doesn\'t match',
		Match: 'Passwords match'
	};
	
	/*
	 * addClearDate - Add Clear Date button
	 * $Version: 2008.05.26
	 *
	 * Example: $('input.Date').addClearDate();
	 */
	$.fn.addClearDate = function() {
		return this.each(function() {
			var clearTrigger = $('<input type="image" class="ACT" src="./images/action_clear.gif" title="Clear Date" />');
			var ID = this.id;
			$(this).after(clearTrigger);
			
			$(clearTrigger).click(function() {
				$('#' + ID).val('');
				return false;
			})
		});
	};
	
	/*
	 * prepareForm - Prepare form and adding events on Inputs to illustrate the input highlight
	 * $Version: 2008.06.02
	 *
	 * Example: $(element).prepareForm();
	 */
	$.fn.prepareForm = function(){
		var activeClass = "active";
		return this.each(function(){
			$(this).find("input:not(:button), textarea, select").each(function(){
				$(this)
					.focus(function(){
						if ($(this).hasClass("Radio")==true || $(this).hasClass("Check")==true){
						} else {
							$(this).addClass(activeClass);
						}
						$(this).parents("form").find("label[for='"+ $(this).attr("id") +"']").addClass(activeClass);
					})
					.blur(function(){
						if ($(this).hasClass("Radio")==true || $(this).hasClass("Check")==true){
						} else {
							$(this).removeClass(activeClass);
						}
						$(this).parents("form").find("label[for='"+ $(this).attr("id") +"']").removeClass(activeClass);
					});
			});
		});
	}

})(jQuery);
