
function validate_all_in(div_id) {
	var has_errors = false;
	var first_with_errors = null;
	$('#'+div_id+' :input').each(function(index,value) {
		if ($(this).attr('donotvalidate') == undefined && validate_input(this)) {
			has_errors = true;
			if (first_with_errors == null)
				first_with_errors = this;
		}
	});
	if (has_errors) {
		if (first_with_errors != null)
			$(first_with_errors).focus();
	}
	return !has_errors;
}

function validate_input(input_obj) {
	var input = $(input_obj);
	var has_errors = false;
	var a_minlen = input.attr('minlen');
	if (a_minlen != undefined) {
		var i_minlen = parseInt(a_minlen);
		if (i_minlen > 0) {
			if (input.val().length < i_minlen) {
				has_errors = true;
			}
		}
	}
	var a_maxlen = input.attr('maxlength');
	if (a_maxlen != undefined) {
		var i_maxlen = parseInt(a_maxlen);
		if (i_maxlen > 0) {
			if (input.val().length > i_maxlen) {
				has_errors = true;
			}
		}
	}
	if (input.attr('validate') != undefined && (input.val().length > 0)) {
		if (!validators[input.attr('validate')](input)) {
			has_errors = true;
		}
	}
	if (has_errors) {
		if (input.attr('autovalidate') == undefined) {
			input.change(function() {
				validate_input(this);
			});
		}
		input.attr('style','border:1px solid #FF0000;background-color:#FFDDDD');
		input.parent().children("label[name='validcheck']").removeClass('valid');
		input.parent().children("label[name='validcheck']").addClass('invalid');
	} else {
		input.attr('style','');
		input.removeAttr('style');
		if (input.attr('autovalidate') == undefined) {
			input.unbind('change');
		}
		input.parent().children("label[name='validcheck']").removeClass('invalid');
		input.parent().children("label[name='validcheck']").addClass('valid');
	}
	return has_errors;
}

var validators = new Array();
validators['email'] = validate_email;
validators['mobile'] = validate_phone;
validators['require'] = validate_require;

function validate_require(input) {
    var this_field = $(input);
    var other_field = $('#'+this_field.attr('required_field'));
    if (this_field.val().trim() != '') {
        return other_field.val().trim() != '';
    }
    return true;
}
function validate_email(input) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(input.val());
}

function validate_phone(input) {
	var num = input.val();
	if (num.substr(0,1) != '+') {
		num = default_prefix + num;
		input.val(num);
	}
	return valid_number(num);
}

jQuery.fn.sms_text = function(op) {
	if (op == 'clean') {
		_sms_text_clean_sms_text($(this),true,true);
		_sms_text_update_counters($(this));
		return;
	}
	this.keypress(function(e) {
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		// do now allow newline/enter key
		if(key == 10 || key == 13) {
			return false;
		}
		if(key == 32 && this.value.length == 0) {
			return false;
		}
		if (this.value.length==1000 && ((key > 31 && key < 127) || (key > 127 && key < 255) || key > 255)) {
			return false;
		}
	})
	.keyup(function() {
		_sms_text_clean_sms_text($(this),true,false);
		_sms_text_update_counters($(this));
	})
	.blur(function() {
		_sms_text_clean_sms_text($(this),true,false);
		_sms_text_update_counters($(this));
	})
	.change(function() {
		_sms_text_clean_sms_text($(this),true,false);
		_sms_text_update_counters($(this));
	});
	this.blur();
	return this;
};

function _sms_text_clean_sms_text(textfield,trim_start,trim_end) {
	var sms_text = $(textfield).val();
	sms_text = sms_text.substring(0,1000);
	var tmp_sms_text = '';
	for (i=0; i<sms_text.length && i<1000; i++) {
		if (sms_text.charAt(i)!='\n' && sms_text.charAt(i)!='\r' && sms_text.charAt(i)!='\t') {
			tmp_sms_text += sms_text.charAt(i);
		}
	}
	sms_text = tmp_sms_text;
	while (trim_start && sms_text.substr(0,1) == ' ') sms_text = sms_text.substring(1,sms_text.length);
	while (trim_end && sms_text.substr(sms_text.length - 1,1) == ' ')
		sms_text = sms_text.substring(0,sms_text.length-1);
	if (sms_text != textfield.val())
		textfield.val(sms_text);
}

function _sms_text_update_counters(textfield) {
	var sms_text = $(textfield).val();
	var total_used_chars = sms_length(sms_text);
	var current_sms_used_chars = sms_length(sms_text) <= 160 ? sms_length(sms_text) : ((sms_length(sms_text)-1)%153)+1;
	var current_needed_smss =  sms_length(sms_text) == 0 ? 0 : sms_length(sms_text) <= 160 ? 1 : Math.floor((sms_length(sms_text)-1)/153)+1;
	var chars_per_sms = current_needed_smss <= 1 ? 160 : 153;
	var available_chars = 1000 - total_used_chars;
	
	var tfid = textfield.attr('id');
	$('#'+tfid+'_count_smss').text(current_needed_smss);
	$('#'+tfid+'_count_sms_chars').text(current_sms_used_chars);
	$('#'+tfid+'_count_sms_size').text(chars_per_sms);
	$('#'+tfid+'_count_remaining_chars').text(available_chars);
}

function sms_length(smstext) {
	var smslen = 0;
	for (i=0;i<smstext.length;i++) {
		switch (smstext.charAt(i)) {
			case '\u000C': // form feed
			case '^':
			case '\u20AC': // euro sign
			case '{':
			case '}':
			case '[':
			case ']':
			case '~':
			case '|':
			case '\\': smslen++;
			default: smslen++;
		}
	}
	return smslen;
}


/*
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Version 1.0
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 */

jQuery.fn.phonenumber = function() {
	this.blur(function(e) {
		validate_phone($(this));
	});
	this.keypress(function(e) {
		return numeric_handle_keypress(e,this,19,true);
	});
	return this;
};
jQuery.fn.numeric = function(max_length) {
	this.keypress(function(e) {
		return numeric_handle_keypress(e,this,max_length,false);
	});
	this.blur(function(e) {
		var val = $(this).val();
		while (val.substring(0,1) == '0')
			val = val.substring(1);
		if (val.length == 0)
			val = '0';
		$(this).val(val);
	});
	return this;
};

function numeric_handle_keypress(e,input,max_length,allow_starting_plus) {
	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
	// allow enter/return key (only when in an input box)
	if(key == 13 && input.nodeName.toLowerCase() == "input") {
		return true;
	} else if(key == 13) {
		return false;
	}
	var allow = false;
	// allow Ctrl+A
	if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
	// allow Ctrl+X (cut)
	if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
	// allow Ctrl+C (copy)
	if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
	// allow Ctrl+Z (undo)
	if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
	// allow or deny Ctrl+V (paste), Shift+Ins
	if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ || (e.shiftKey && key == 45)) return true;
	// if a number was not pressed
	if(key < 48 || key > 57) {
		/* '+' only allowed at start */
		if(allow_starting_plus && key == 43 && input.value.length == 0) {
			return true;
		}
		// check for other keys that have special purposes
		if(
			key != 8 /* backspace */ &&
			key != 9 /* tab */ &&
			key != 13 /* enter */ &&
			key != 35 /* end */ &&
			key != 36 /* home */ &&
			key != 37 /* left */ &&
			key != 39 /* right */ &&
			key != 46 /* del */
		) {
			allow = false;
		} else {
			// for detecting special keys (listed above)
			// IE does not support 'charCode' and ignores them in keypress anyway
			if(typeof e.charCode != "undefined") {
				// special keys have 'keyCode' and 'which' the same (e.g. backspace)
				if(e.keyCode == e.which && e.which != 0) {
					allow = true;
				}
				// or keyCode != 0 and 'charCode'/'which' = 0
				else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0) {
					allow = true;
				}
			}
		}
	} else {
		if (input.value.length >= max_length)
			return false;
		allow = true;
	}
	return allow;
}

