/***********************************************************************************
************************************************************************************
********************************  Phone Splitter  **********************************
************************************************************************************
***********************************************************************************/

(function($) {

$.fn.phoneSplitter = function(options) {

	var defaults = {
		width: 'inherit',									// Defaults to letting it auto resize the phone fields
		spacers: null										// What delineators to use
	};
	
	$.extend(defaults, options);

	if($(this).attr('type') == 'text'){					// Only proceed if it's an existing visible form element

		var totalWidth = $(this).width();				// Gets the current element's width 
		var classes = $(this).attr('class');			// Gets the current element's classes
		var style = $(this).attr('style');				// Gets the current element's style rules
		var name = $(this).attr('name');				// Gets the current element's name
		var max = $(this).attr('maxlength');			// Gets the current element's maxlength
		var value = $(this).val().replace(/-/g,"");		// Gets the current element's value (removes dashes)
		
		
		if(defaults.spacers == 'parens')
			$(this).before('(');
		
		$(this).before($('<input>')
				.attr({ 
					'name': function(index) {return name + 'a';},					// Appends the letter A to the name and ID to distinguish it	
					'id': function(index) {return name + 'a';},
					'maxlength': '3',
					'class': function(index) {return classes;},					// Takes on all the classes of the element it's replacing
					'style': function(index) {return style;},						// Takes on all the classes of the element it's replacing
					'type': 'text'
				})
				.css({
					'width' : function(index) {
						if(defaults.width == 'inherit')
							return totalWidth * .30;
						else if(defaults.width == 'auto')
							return 30;
						else
							return defaults.width;
					}, 
					'margin-left' : '0px',
					'margin-right' : '0px',
					'padding-left' : '0px',
					'padding-right' : '0px'
				}).val(value.substring(0,3))
				//.addClass("text")
			);
		
		if(defaults.spacers == 'parens')
			$(this).before(') ');
		else if(defaults.spacers == 'dashes')
			$(this).before(' - ');
		
		$(this).before($('<input>')
				.attr({ 
					'name': function(index) {return name + 'b';},					// Appends the letter B to the name and ID to distinguish it	
					'id': function(index) {return name + 'b';},
					'maxlength': '3',
					'class': function(index) {return classes;},					// Takes on all the classes of the element it's replacing
					'style': function(index) {return style;},						// Takes on all the classes of the element it's replacing
					'type': 'text'
				})
				.css({
					'width' : function(index) {
						if(defaults.width == 'inherit')
							return totalWidth * .30;
						else if(defaults.width == 'auto')
							return 30;
						else
							return defaults.width;
					}, 
					'margin-left' : '0px',
					'margin-right' : '0px',
					'padding-left' : '0px',
					'padding-right' : '0px'
				}).val(value.substring(3,6))
				
			);
		
		if(defaults.spacers == 'parens' || defaults.spacers == 'dashes')
			$(this).before(' - ');
		
		$(this).before($('<input>')
				.attr({ 
					'name': function(index) {return name + 'c';},					// Appends the letter C to the name and ID to distinguish it	
					'id': function(index) {return name + 'c';},
					'maxlength': '4',
					'class': function(index) {return classes;},					// Takes on all the classes of the element it's replacing
					'style': function(index) {return style;},						// Takes on all the classes of the element it's replacing
					'type': 'text'
				})
				.css({
					'width' : function(index) {
						if(defaults.width == 'inherit')
							return totalWidth * .40;
						else if(defaults.width == 'auto')
							return 40;
						else
							return defaults.width;
					}, 
					'margin-left' : '0px',
					'margin-right' : '0px',
					'padding-left' : '0px',
					'padding-right' : '0px'
				}).val(value.substring(6,10))
			);
		
		$('input[name=' + name + 'a]').autotab({ target: name + 'b'});
		$('input[name=' + name + 'b]').autotab({ previous: name + 'a', target: name + 'c'});
		$('input[name=' + name + 'c]').autotab({ previous: name + 'b'});
		
		//$(this).before('<br />');
		
		$(this).before($('<input>')
				.attr({ 
					'name': function(index) {return name;},					// Appends the letter C to the name and ID to distinguish it	
					'id': function(index) {return name;},
					'maxlength': function(index) {return max;},
					'class': function(index) {return classes;},					// Takes on all the classes of the element it's replacing
					'style': function(index) {return style;},						// Takes on all the classes of the element it's replacing
					'type': 'hidden'
				}).val(value)
			);
		
		$(this).closest("form").submit(function() {
			$('input[name=' + name + ']').val(
				$('input[name=' + name + 'a]').val() + 
				$('input[name=' + name + 'b]').val() + 
				$('input[name=' + name + 'c]').val()
			);

			//alert($('input[name=' + name + ']').val());
			
			//return false;
		});
		
		$(this).remove();
		
	} else{
		alert("Error: " + $(this).attr('name') + " is either not the name of an element on the page, or is a hidden input element");
	}
	
};

})(jQuery);

(function($) {

$.fn.autotab = function(options) {

	var defaults = {
		maxlength: 2147483647,	// Defaults to maxlength value
		next: null,			// Where to auto tab to
		previous: null			// Backwards auto tab when all data is backspaced
	};
	
	$.extend(defaults, options);
	
	var check_element = function(name) {
		var val = null;
		var check_id = $('#' + name)[0];
		var check_name = $('input[name=' + name + ']')[0];

		if(check_id != undefined)
			val = $(check_id);
		else if(check_name != undefined)
			val = $(check_name);

		return val;
	};

	var key = function(e) {
		if(!e)
			e = window.event;

		return e.keyCode;
	};

	// Sets targets to element based on the name or ID passed
	if(typeof defaults.target == 'string')
		defaults.target = check_element(defaults.target);

	if(typeof defaults.previous == 'string')
		defaults.previous = check_element(defaults.previous);

	var maxlength = $(this).attr('maxlength');

	// defaults.maxlength has not changed and maxlength was specified
	if(defaults.maxlength == 2147483647 && maxlength != 2147483647)
		defaults.maxlength = maxlength;
	// defaults.maxlength overrides maxlength
	else if(defaults.maxlength > 0)
		$(this).attr('maxlength', defaults.maxlength)
	// defaults.maxlength and maxlength have not been specified
	// A target cannot be used since there is no defined maxlength
	else
		defaults.target = null;
	
	// IE does not recognize the backspace key
	// with keypress in a blank input box
	if($.browser.msie)
	{
		this.keydown(function(e) {
			if(key(e) == 8)
			{
				var val = this.value;

				if(val.length == 0 && defaults.previous)
					defaults.previous.focus();
			}
		});
	}

	return this.keypress(function(e) {
		if(key(e) == 8)
		{
			var val = this.value;

			if(val.length == 0 && defaults.previous)
				defaults.previous.focus();
		}
	}).keyup(function(e) {
		var val = this.value;

		/**
		 * Do not auto tab when the following keys are pressed
		 * 8:	Backspace
		 * 9:	Tab
		 * 16:	Shift
		 * 17:	Ctrl
		 * 18:	Alt
		 * 19:	Pause Break
		 * 20:	Caps Lock
		 * 27:	Esc
		 * 33:	Page Up
		 * 34:	Page Down
		 * 35:	End
		 * 36:	Home
		 * 37:	Left Arrow
		 * 38:	Up Arrow
		 * 39:	Right Arrow
		 * 40:	Down Arroww
		 * 45:	Insert
		 * 46:	Delete
		 * 144:	Num Lock
		 * 145:	Scroll Lock
		 */
		var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];
		var string = keys.toString();
		
		if(string.indexOf(key(e)) == -1 && val.length == defaults.maxlength && defaults.target)
			defaults.target.focus();
	});
};

})(jQuery);

function splitPhone(name, options){
	if($('input[name=' + name + ']').attr('type') == 'text'){			// Only proceed if it's an existing visible form element
		$('input[name=' + name + ']').phoneSplitter(options);	
	} else{
		alert("Error: " + name + " is either not the name of an element on the page, or is a hidden input element");
	}
}






/***********************************************************************************
************************************************************************************
**********************************  Validation  ************************************
************************************************************************************
***********************************************************************************/




		function refreshTooltips(){	
			//$('input').unbind('mouseenter mouseleave onmouseover onmouseout');
			$('input[alt!=].error').tinyTips('custom', 'alt');
			
		}
		
		var waited = false;
		
		$(document).ready(function() {
			if (jQuery.isFunction(jQuery.fn.datepicker)) {
				$('#dob').datepicker({
					'showAnim': '', 
					'changeMonth': true, 
					'changeYear': true, 
					'yearRange': '1920:1995', 
					'dateFormat': 'yy-mm-dd', 
					'defaultDate': '-18y'
				});
			}
			
			$("form.offerForm").submit(function() {
				if(typeof optValidation == 'function') { 
					if(!optValidation()){
						return false;
					}					
				}
				
				$(".required[alt=]").removeClass('error');
				$("select.required").removeClass('error');
				
				$(".required[type!=hidden]").each(function() {
					if($(this).val() == ''){
						$(this).addClass('error');
					}
				});
				
				if($(".error").length > 0 ){
					alert('Please make sure you have filled in all required fields correctly');
					waited = false;
					return false;
				} else if($("#genderM").length > 0 && $("#genderF").length > 0){
					if(!$("#genderM").attr('checked') && !$("#genderF").attr('checked')){
						alert('Please indicate your gender');
						waited = false;
						return false;
					}
				} else if($('input[name=phone]').val().length != 10){
					if($('input[name=phonea]').val().length != 3)
						$('input[name=phonea]').addClass('error');
					
					if($('input[name=phoneb]').val().length != 3)
						$('input[name=phoneb]').addClass('error');
					
					if($('input[name=phonec]').val().length != 4)
						$('input[name=phonec]').addClass('error');
				
					alert('Please enter your 10 digit phone number');
					waited = false;
					return false;
				} else{
					if(waited){
						return true;
					} else{
						waited = true;
						setTimeout('$("form").submit()', 1500);
						return false;
					}
				}
			});
		
		
			$('#phone').wrapAll('<div class="phones" />');
			$('#phone').after('<div class="phoneStatus">&nbsp;</div>');

			if(typeof phoneDelim != 'undefined' && typeof phoneWidth != 'undefined'){	splitPhone('phone', { width: phoneWidth, spacers: phoneDelim	});	}
			else if(typeof phoneDelim != 'undefined'){	splitPhone('phone', { width: 'auto', spacers: phoneDelim	});	}
			else if(typeof phoneWidth != 'undefined'){	splitPhone('phone', { width: phoneWidth, spacers: 'dashes'	});	}
			else{	splitPhone('phone', { width: 'auto', spacers: 'dashes'	});	}

			refreshTooltips();
		
		
			$(".phones").focusout(function(){

				var filter_phone_npaxx = /^[0-9]{3}$/;
				var filter_phone_num = /^[0-9]{4}$/;
				var filter_phone = /^[0-9]{10}$/;
				
				if($("input[name=phonea], input[name=phoneb], input[name=phonec]").val() != ''){
						$('input[name=phone]').val(
							$('input[name=phonea]').val() + 
							$('input[name=phoneb]').val() + 
							$('input[name=phonec]').val()
						);
						//alert($('input[name=phone]').val());
						if($('input[name=phone]').val().length == 10 && filter_phone.test($("input[name=phone]").val())){
							$('.phoneStatus').removeClass('landline');
							$('.phoneStatus').removeClass('mobile');
							
							if(!$('.phoneStatus').hasClass('processing')){
								$('.phoneStatus').addClass('processing');
							
							
								$.getJSON('http://www.bpmimages.com/bluephoenixmedia/resources/validation/php/validate.php?callback=?', 
											'phone=' + $("#phone").val(), function(data) {
									if(data['result']['type'] == 'success' && data['result']['code'] != 'No Data Found'){
										$('input[name=phonea]').attr('alt','');
										$('input[name=phonea]').addClass('valid');
										$('input[name=phonea]').removeClass('error');
										$('input[name=phonea]').unbind('mouseenter mouseleave onmouseover onmouseout');
										
										$('input[name=phoneb]').attr('alt','');
										$('input[name=phoneb]').addClass('valid');
										$('input[name=phoneb]').removeClass('error');
										$('input[name=phoneb]').unbind('mouseenter mouseleave onmouseover onmouseout');
										
										$('input[name=phonec]').attr('alt','');
										$('input[name=phonec]').addClass('valid');
										$('input[name=phonec]').removeClass('error');
										$('input[name=phonec]').unbind('mouseenter mouseleave onmouseover onmouseout');
										
										$('.phoneStatus').removeClass('processing');
										$('.phoneStatus').addClass(data['listings'][0]['phonenumbers'][0]['type']);
										
									} else {
										$('input[name=phonea]').addClass('error');
										$('input[name=phoneb]').addClass('error');
										$('input[name=phonec]').addClass('error');
										
										$('input[name=phonea]').attr('alt','<div class="alertIcon"></div>Phone number cannot be found');
										$('input[name=phoneb]').attr('alt','<div class="alertIcon"></div>Phone number cannot be found');
										$('input[name=phonec]').attr('alt','<div class="alertIcon"></div>Phone number cannot be found');
										
										$('input[name=phonea]').removeClass('valid');
										$('input[name=phoneb]').removeClass('valid');
										$('input[name=phonec]').removeClass('valid');
										
										$('.phoneStatus').removeClass('processing');
										
										refreshTooltips();
									}
								});
							}
						} else if(!filter_phone.test($("input[name=phone]").val())){
							$('input[name=phonea]').addClass('error');
							$('input[name=phoneb]').addClass('error');
							$('input[name=phonec]').addClass('error');
							
							$('input[name=phonea]').attr('alt','<div class="alertIcon"></div>Not a valid number');
							$('input[name=phoneb]').attr('alt','<div class="alertIcon"></div>Not a valid number');
							$('input[name=phonec]').attr('alt','<div class="alertIcon"></div>Not a valid number');
							
							$('input[name=phonea]').removeClass('valid');
							$('input[name=phoneb]').removeClass('valid');
							$('input[name=phonec]').removeClass('valid');
							
							$('.phoneStatus').removeClass('processing');
							
							refreshTooltips();
						}
				} else{
					$('.phoneStatus').removeClass('processing');
					
					$('input[name=phonea]').removeClass('error');
					$('input[name=phoneb]').removeClass('error');
					$('input[name=phonec]').removeClass('error');
					
					$('input[name=phonea]').removeClass('valid');
					$('input[name=phoneb]').removeClass('valid');
					$('input[name=phonec]').removeClass('valid');
					
					$('.phoneStatus').removeClass('landline');
					$('.phoneStatus').removeClass('mobile');
				}
			});
			
			$("#zip").change(function(){
				var filter_us_zip = /^[0-9]{5}$/;
				
				$('#zip').addClass('processing');
				
				if($("#zip").val() != ''){
					if(!filter_us_zip.test($("#zip").val())){
						$('#zip').addClass('error');
						
						errorMsg = '<div class="alertIcon"></div>US Zip Codes must be in the form of 99999';
						$('#zip').attr('alt',errorMsg);
						
						$('#zip').removeClass('valid');
						$('#zip').removeClass('processing');
						
						$('#state').val('');
						$('#city').val('');
						
						refreshTooltips();
					
					} else {
						$.getJSON('http://www.bpmimages.com/bluephoenixmedia/resources/validation/php/validate.php?callback=?', 
									'zip=' + $("#zip").val(), function(data) {
							if((data['state'] && data['state'] != 'N/A') || data['response'] == 'emergency'){
								$('#state').val(data['state']);
								$('#city').val(data['city']);
								
								$('#zip').attr('alt','');
								$('#zip').addClass('valid');
								$('#zip').removeClass('error');
								$('#zip').removeClass('processing');
								$('#zip').unbind('mouseenter mouseleave onmouseover onmouseout');
							} else {
								$('#zip').addClass('error');
								$('#zip').removeClass('valid');
								$('#zip').removeClass('processing');
								
								$('#state').val('');
								$('#city').val('');
								
								errorMsg = '<div class="alertIcon"></div>Not a valid US zip code'
								$('#zip').attr('alt',errorMsg);
								
								refreshTooltips();
							}
						});
					}
				} else{
					$('#zip').removeClass('processing');
					$('#zip').removeClass('error');
					$('#zip').removeClass('valid');
				}
			});
			
			$("#email").change(function(){	
				var filter_email = /^[a-zA-Z0-9._%+-]{2,}@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
			
				$('#email').addClass('processing');
				
				if($("#email").val() != ''){
					if(!filter_email.test($("#email").val())){
						$('#email').addClass('error');
						
						errorMsg = '<div class="alertIcon"></div>Email address must be in the form of email@domain.com';
						$('#email').attr('alt',errorMsg);
						
						$('#email').removeClass('valid');
						$('#email').removeClass('processing');
						refreshTooltips();
					} else {
						$.getJSON('http://www.bpmimages.com/bluephoenixmedia/resources/validation/php/validate.php?callback=?', 
									'email=' + $("#email").val(), function(data) {
							if(data[$("#email").val()]['status']){
								$('#email').addClass('valid');
								$('#email').removeClass('error');
								$('#email').removeClass('processing');
								$('#email').attr('alt','');
								$('#email').unbind('mouseenter mouseleave onmouseover onmouseout');
							} else {
								$('#email').addClass('error');
								
								if(data[$("#email").val()]['error']){
									errorMsg = '<div class="alertIcon"></div>' + data[$("#email").val()]['error'];
									$('#email').attr('alt',errorMsg);
								}	else {	$('#email').attr('alt','<div class="alertIcon"></div>This email address is not valid');	}
								
								$('#email').removeClass('valid');
								$('#email').removeClass('processing');
								
								refreshTooltips();
							}
						});
					}
				} else{
					$('#email').removeClass('processing');
					$('#email').removeClass('error');
					$('#email').removeClass('valid');
				}
			});
		});
