/**
 * @author paul
 */
$(document).ready(function(){
  //Modify the form for ajax to function
  if ($("#clients_price_min").html() == null) return;
  //Hide city and the row it is in
  $("#clients_city").parent().parent().css("display","none");
  $("#clients_send_time_minute").after("<br/><small>Mountain Time Zone</small>");
  
  //Get county ready
  $("#clients_county").parent().attr('id', 'county_div');
  $("#clients_county").css("display","none");
  $("#county_div").append("<div id='county_select'></div>");

  //Now zipcodes
  $("#clients_zip").parent().attr('id', 'zip_div');
  $("#clients_zip").css("display","none");
  $("#zip_div").append("<div id='zip_select'></div>");
  
  //And Day Of Week
  $("#clients_send_dow").parent().attr('id', 'dow_div');
  $("#clients_send_dow").css("display","none");
  $("#dow_div").append("<input type='button' id='dAll' value=' Everyday ' onclick='toggleDay()'/>");
  $("#dow_div").append("<input type='checkbox' id='d0' value=0>Sunday ");
  $("#dow_div").append("<input type='checkbox' id='d1' value=1>Monday ");
  $("#dow_div").append("<input type='checkbox' id='d2' value=2>Tuesday ");
  $("#dow_div").append("<input type='checkbox' id='d3' value=3>Wednesday ");
  $("#dow_div").append("<input type='checkbox' id='d4' value=4>Thursday ");
  $("#dow_div").append("<input type='checkbox' id='d5' value=5>Friday ");
  $("#dow_div").append("<input type='checkbox' id='d6' value=6>Saturday ");
  days = $("#clients_send_dow").val();
  for (i=0; i<7; i++)
  {
	if (days.indexOf(i) != -1)
	{
		$("#d" + i).attr('checked','checked');
	}
  }
    
  //Set up the chain if state changes
  $("#clients_state_id").change(loadCounties);
  loadCounties();
  
  $("#clients_email").change(updateFlagged);
  $("#clients_email1").change(updateFlagged);
  $(":submit").click(closeForm);
});

function toggleDay()
{
	for(i=0; i<7; i++)
	{
		$("#d" + i).attr('checked', '1');
	}
}

function updateDOW()
{
	days = "";
	for(i=0; i<7; i++)
	{
		if ($("#d" + i).attr('checked'))
		{
			days += "" + i;
		}
	}
	$("#clients_send_dow").val( days );
}

function updateFlagged(){
	$("#clients_flagged").attr( 'value', 'N' );
}

function closeForm() {
	updateDOW();
	$("#county_select").remove();
	$("#zip_select").remove();
}

function loadCounties() {
  var state = $("#clients_state_id :selected").val();
  var id = $("#clients_id").val();

  $("#county_select").html("<div id='county_select'><img src='/images/wait1.gif'></div>");
  $("#county_select").load("/search/getCounties?id=" + id + "&state=" + state);
}

function loadZips() {
  var state = $("#clients_state_id :selected").val();
  var id = $("#clients_id").val();

  $("#zip_select").html("<div id='zip_select'><img src='/images/wait1.gif'></div>");
  $("#zip_select").load("/search/getZipcodes?id=" + id + "&state=" + state + "&counties=" + $("#clients_county").val());
}

