/*
 * matches US phone number format 
 * 
 * where the area code may not start with 1 and the prefix may not start with 1 
 * allows '-' or ' ' as a separator and allows parens around area code 
 * some people may want to put a '1' in front of their number 
 * 
 * 1(212)-999-2345
 * or
 * 212 999 2344
 * or
 * 212-999-0983
 * 
 * but not
 * 111-123-5434
 * and not
 * 212 123 4567
 */
var searched=0;
var clients=0;
var market;

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    var pn=phone_number;
    pn=pn.replace(/[^\d]/g,""); 
    return this.optional(element) || pn.length > 9;
}, "Please specify a valid phone number");

function reset_field(f) {
	switch($(f).attr('type')) {
		case 'select-one':
		case 'text':
		case 'password':
			$(f).val('');
			break;
		case 'radio':
			$(f).attr('checked',false);
			break;
		default:
	}
}

function set_field(f,v) {
	switch($(f).attr('type')) {
		case 'select-one':
		case 'text':
		case 'password':
			$(f).val(v);
			break;
		case 'radio':
			$(f+'[value="'+v+'"]').attr('checked',true);
			break;
		default:
	}
}

function get_field(f) {
	switch($(f).attr('type')) {
		case 'select-one':
		case 'text':
		case 'password':
			return $(f).val();
			break;
		case 'radio':
			return $(f+':checked').val();
			break;
		default:
			return '';
	}
}

function market_changed() {
	// need to hide refine and criteria
	if ($('#Market').val()!=market) {
		$(".refine_search").hide();
		$('.criteria').hide();
		$('#marketinfo').empty();
		$('#map').css('display','none');
		$('#search_header').show();
		$('#search_msg').show();
		$('#postsearch_header').css('display','none');
		$('#postsearch_msg').css('display','none');
		// reset criteria fields -- all criteria fields must have an id for this to work
		$.each($('.criteria_1,.criteria_2'),function(i,v) {
			reset_field('#'+$(v).attr('id'));
		});
		market=$('#Market').val();
	}
	if ($('#Market').val()!=='') {
		$('#search_results').empty();
		$('#partner_results').empty();
		$('.partners_left').hide();
		$('.partners_right').hide();
		// if Zip set do search
		if ($('#Zip').val()) {
			var zip=$('#Zip').val();
			if (zip.length==5) perform_search();
		}
	} else {
		$_SESSION['market']=market;
		$('#search_results').empty();
		$('#other_results #google').empty();
		$('#other_results #yelp').empty();
		$('#other_results #yipit').empty();
		$('#partner_results').empty();
		$('.partners_left').hide();
		$('.partners_right').hide();
	}
}

function zip_changed(e) {
	// keep first 5 digits
	var zip=$('#Zip').val();
	zip=zip.substr(0,5);
	$('#Zip').val(zip);
	if (zip.length<5) {
		e.preventDefault();
		$('#Zip').trigger('focus');
		return;
	}
	// if Market set do search
	if ($('#Market').val()!=='') {
		perform_search();
	}
}

$(document).ready(function() {
	$('#rwd_tab').hide();
	$('#red_tab').hide();
	$('#reward_go').click(function(ev) {
		ev.preventDefault();
		$('#red_tab').trigger('click');
	});

	$("#tc1 label").inFieldLabels();

	// clear out map
	$('#map').css('display','none');
	
	// update session variables into form
	if ($_SESSION['market']) {
		$_SESSION['market']='';
//		$('#Market').val($_SESSION['market']);
//		$('#Market').trigger('change');
	}
	if ($_SESSION['zip']) {
		$('#Zip').val($_SESSION['zip']);
		$('#Zip').trigger('change');
	}
	if (
		($_SESSION['market'])&&
		($_SESSION['zip'])
	) {
		perform_search();
	}
	market=$('#Market').val();

	/* only allow numeric value for zipcode */
	$('#Zip').numeric();

	/* limit zipcode to 5 characters */
	$('#Zip').change(function(ev) {
		zip_changed(ev);
	});

	$('#Zip').keyup(function(ev) {
		var zip=$('#Zip').val();
		if (zip.length==5) {
			zip_changed(ev);
		}
	});
	
	$('#Market').change(function(ev) {
		market_changed();
	});

	$('#Market').keyup(function(ev) {
		market_changed();
	});

	// need to submit form if
	$("#re-search").submit(function(ev) {
		ev.preventDefault();
		// determine if any values have changed by comparing the values to those in $_SESSION
		if (
			(!$('#Market').val())||
			(!$('#Zip').val())||
			($('#Market')=='')||
			($('#Zip').val().length!=5)
		) {
			return;
		}
		perform_search();
	});

	$('.ts').click(function(ev) {
		ev.preventDefault();
		$('#Market').val($(ev.target).attr('href'));
		$('#Market').trigger('change');
		if ($('#Zip').val()=='') {
			$('#Zip').val($('#ip_ZipCode').val());
			$('#Zip').trigger('change');
		}
	});

	$.fn.extend({
		optionDisable:function() {
			var ths = $(this);
			if(ths.attr('tagName').toLowerCase() == 'option') {
				ths.before($('<optgroup>&nbsp;</optgroup>').css({'font':'bold 16px/16px "HelveticaNeue", Helvetica, Arial, sans-serif','font-style':'normal',color:'#cccccc',height:ths.height()}).attr({id:ths.attr('value'),label:''}));
				ths.before($('<optgroup>&nbsp;</optgroup>').css({'font':'bold 16px/16px "HelveticaNeue", Helvetica, Arial, sans-serif','font-style':'normal',color:'#cccccc',height:ths.height()}).attr({id:ths.attr('value'),label:ths.text()})).remove();
			}
			return ths;
		},
		optionEnable:function() {
			var ths = $(this);
			var tag = ths.attr('tagName').toLowerCase();
			if(tag == 'option') {
				ths.removeAttr('disabled');
			}
			else if(tag == 'optgroup') {
				ths.before($('<option />').attr({value:ths.attr('id')}).text(ths.attr('label'))).remove();
			}
			return ths;
		}
	});

	$.each($('#Market').children('[value=""]'),function(i,v) {
		if (i!=0) {
			$(v).optionDisable();
		}
	});
});

function perform_search() {
	var z=get_field('#Zip');
	var m=get_field('#Market');
	$_SESSION['zip']=z;
	$_SESSION['market']=m;
	clients=0;
	// need to invoke results page passing it a search param
	$.post('/wp-content/themes/zipsearch/save_search.php',
		{
			'zip':z,
			'market':m
		},
		function(data) {
			// since the information is in the session variables, we can just redirect the user
			window.location.href='/results';
		}
	);
}

