DreamGarage.resources = {

  enableForm: function(autoload)
  {
    autoload = autoload || false;

    // move form inside of screen
    var resourceForm = $(".resourceForm");
    $("#screen").after(resourceForm.clone());
    resourceForm.remove();

    // black out background and bring in modal message box
    $("#screen").fadeIn();
    $(".resourceForm").fadeIn().css("overflow","visible").css("height","auto");
    $("#resources select").css("visibility","hidden");
    jQuery.scrollTo("#header", 800);

    // bind actions after form appears
    $("#listing_category").bind("change", function() {
      var parent_category = $("#listing_category option:selected").val();
      DreamGarage.resources.getSubCategories(parent_category, function(sub_categories) {
        var arr = ['<option value="">SELECT SUB-CATEGORY</option>'];

        jQuery.each(sub_categories, function(e, i) {
          arr.push('<option value="' + e + '">' + e + '</option>');
         });

        $("#listing_subcategory").html(arr.join(" "));
      });
    });

    var toggle_inputs = function() {
      var value = $("p.adType input[type='radio']:checked").val();

      if (value == "Featured National" || value == "Standard National" ||
	  value == "Featured Local" || value == "Standard Local")
      {
        $("#listing_website, #listing_offer").css("background-color","").css("color","").attr("disabled","");

      }
      else
      {
        $("#listing_website, #listing_offer").css("background-color","#CCC")
                                             .css("color","#AAA")
                                             .attr("disabled","disabled");
      }

      if (value == "Standard Local" || value == "Featured Local")
      {
        $("#listing_address, #listing_city, #listing_state, #listing_zip, #listing_phone").css("background-color","").css("color","").attr("disabled","");

	if ($("div.zip p.label span.red").length == 0)
        {
	  $("div.zip p.label").append('<span class="red"> *</span>');
	}

      }
      else
      {
	$("#listing_address, #listing_city, #listing_state, #listing_phone").css("background-color","#CCC")
                                             .css("color","#AAA")
                                             .attr("disabled","disabled");

	if (value == "Classified")
	{
	  $("#listing_zip").css("background-color","").css("color","").attr("disabled","");

	  if ($("div.zip p.label span.red").length == 0)
          {
	    $("div.zip p.label").append('<span class="red"> *</span>');
	  }
	}
	else
	{
	  $("#listing_zip").css("background-color","#CCC").css("color","#AAA").attr("disabled","disabled");
	  $("div.zip p.label span.red").remove();
	}

      }


    };

    // bind disabling of certain inputs after certain selections are made
    $("p.adType input[type='radio']").bind("click", toggle_inputs);


    if (autoload)
    {
      toggle_inputs();
    }


    // bind validation for form
    $("#create_listing_form").submit(function() {
      var errors = [];

      // verify an ad type has been selected
      if ($("p.adType input[type='radio']:checked").length == 0)
      {
        errors.push({"div.adType div.errors": "You must choose an ad type."});
      }

      // verify that a category and sub-category has been selected
      if ($("#listing_category option:selected").val().length == 0)
      {
        errors.push({"div.selectCategories div.errors": "You must choose a category."});
      }

      if ($("#listing_subcategory option:selected").val().length == 0)
      {
        errors.push({"div.selectCategories div.errors": "You must choose a sub-category."});
      }

      // verify title
      if ($("#listing_title").val().length == 0)
      {
        errors.push({"div.createAd div.errors": "You must enter a title."});
      }

      // verify description
      if ($("#listing_description").val().length == 0)
      {
        errors.push({"div.createAd div.errors": "You must enter a description."});
      }
      else if ($("#listing_description").val().length > 130)
      {
        errors.push({"div.createAd div.errors": "You description is too long, please limit it to 130 characters."});
      }

      // check for errors
      if (errors.length > 0)
      {
        // clear existing errors
        $("div.errors").html("");

        // display errors
        for (error in errors)
        {
          for (key in errors[error])
          {
            $(key).append('<p class="red">' + errors[error][key] + '</p>');
          }
        }

        // scroll to first error
        jQuery.scrollTo($("div.errors:has(p):first"), 800);

        return false;
      }
      else
      {
        return true;
      }

    });

    // limit length of description

    $("#listing_description").bind("keyup", function() {
        var text = $("#listing_description").val();
        if (text.length > 130)
        {
          $("#listing_description").val(text.substring(0, 130));
        }
        else
        {
          $("#listing_description_character_count").text(130 - text.length);
        }
    });

    // limit length of offer

    $("#listing_offer").bind("keyup", function() {
      var text = $("#listing_offer").val();
      $("#listing_offer_character_count").text(50 - text.length);
    });

    // limit length of title

    $("#listing_title").bind("keyup", function() {
      var text = $("#listing_title").val();
      $("#listing_title_character_count").text(30 - text.length);
    });

    $("input.file").bind("change", function() {
      jQuery.ajax();
    });

    // bind cancel event
    $("#resourceForm span.link").bind("click", function() {
      $("#resourceForm").slideUp();

      var resourceForm = $(".resourceForm");
      $("#resources").after(resourceForm.clone());
      resourceForm.remove();

      $(".resourceForm").hide();

      $("#screen").fadeOut();
      $("#resources select").css("visibility","visible");


      if (autoload)
      {
        window.location = "/";
      }

    });

    if (autoload)
    {
      return false;
    }
    else
    {
      return true;
    }
  },

  // get search results

  getSearchResults: function(zipcode, term, resource_type)
  {
    $("#main_resources_" + resource_type).replaceWith('<div id="resources_are_waiting" class="resources centered"><img class="inline" src="/image/ajax_wait.gif" width="32" height="32" alt="ajax wait icon" /></div>');

    jQuery.get("/vehicles",

	       {
		 zip: zipcode,
		 distance: 25,
		 page: 1,
		 type: resource_type,
		 keyword: term,
		 parent: $("#resource_category_dropdown").val(),
		 category: "All",
		 mode: "ajax",
		 state: "on",
		 request: "resource-page"
	       },

	       function(response) {

		 $("#resources_are_waiting").replaceWith(response);

		 $("div.resources div.paging a").unbind();
		 $("select.resource_page_select").unbind();

		 $(".buttonResource").unbind();
		 $(".buttonResource").click(DreamGarage.resources.enableForm);

		 DreamGarage.resources.bindGetPage();

		 if (resource_type == "local")
		 {
		   DreamGarage.resources.bindLocalResults();
		 }
		 else if (resource_type == "classified")
		 {
		   DreamGarage.resources.bindClassifiedResults();
		   DreamGarage.resources.bindClassifiedSearchResults();
		 }

	       });

  },

  // get local results based on zip code and range
  getLocalResults: function(zipcode, range, resource_type)
  {
    $("#main_resources_" + resource_type).replaceWith('<div id="resources_are_waiting" class="resources centered"><img class="inline" src="/image/ajax_wait.gif" width="32" height="32" alt="ajax wait icon" /></div>');

    jQuery.get("/vehicles",

	       {
		 zip: zipcode,
		 distance: range,
		 page: 1,
		 type: resource_type,
		 parent: $("#resource_category_dropdown").val(),
		 category: "All",
		 mode: "ajax",
		 state: "on",
		 request: "resource-page"
	       },

	       function(response) {

		 $("#resources_are_waiting").replaceWith(response);

		 $("div.resources div.paging a").unbind();
		 $("select.resource_page_select").unbind();

		 $(".buttonResource").unbind();
		 $(".buttonResource").click(DreamGarage.resources.enableForm);

		 DreamGarage.resources.bindGetPage();

		 if (resource_type == "local")
		 {
		   DreamGarage.resources.bindLocalResults();
		 }
		 else if (resource_type == "classified")
		 {
		   DreamGarage.resources.bindClassifiedResults();
		   DreamGarage.resources.bindClassifiedSearchResults();
		 }

	       });


  },

  // get list of resource categories via ajax
  getCategories: function(func) {
    jQuery.getJSON('/vehicles/?mode=ajax&request=resource-categories',
	       function(response) { func(response); });
  },


  // get list of resource sub-categories via ajax
  getSubCategories: function(parent, func) {
    var name = (parent) ? '&name=' + parent : '';
    jQuery.getJSON('/vehicles/?mode=ajax&request=resource-sub-categories' + name,
    function(response) { func(response); });
  },


  bindSubCategorySelections: function() {
    $("#resource_subcategories a").unbind("click");
    $("#resource_subcategories a").bind("click", function() {

      var ajax_query = function(page_type, parent_category, page_category, onoff) {

	var options = {
	  page: 1,
	  type: page_type,
	  parent: parent_category,
	  category: page_category,
	  mode: "ajax",
	  request: "resource-page",
	  state: onoff
	};

	if (page_type == "local" && $("#local_zip").val().length > 0)
        {
	  options['zip'] = $("#local_zip").val();
          options['distance'] = $("#local_range option:selected").val();
	}
	else if (page_type == "classified" && $("#classy_zip").val() > 0)
	{
	  options['zip'] = $("#classy_zip").val();
	}

	jQuery.get("/vehicles", options,

		   function(response) {

		     $("#main_resources_" + page_type).replaceWith(response);

		     $("div.resources div.paging a").unbind();
		     $("select.resource_page_select").unbind();

		     $(".buttonResource").unbind();
		     $(".buttonResource").click(DreamGarage.resources.enableForm);

		     DreamGarage.resources.bindGetPage();

		     if (page_type == "local")
		     {
		       DreamGarage.resources.bindLocalResults();
		     }
		     else if (page_type == "classified")
		     {
		       DreamGarage.resources.bindClassifiedResults();
		       DreamGarage.resources.bindClassifiedSearchResults();
		     }
		   });
      };

      var category_name = jQuery.map($(this).attr("href").substr(1).replace(/\-/g, ' ').split(' '), function (n, i) {
	return n.slice(0,1).toUpperCase() + n.slice(1);
      }).join(" ");

      var parent_name = $("#resource_category_dropdown").val();

      var types = ["national", "local", "classified"];
      for (var i in types)
      {
	var visible = ($("#main_resources_" + types[i]).hasClass("on")) ? "on": "off";
	ajax_query(types[i], parent_name, category_name, visible);
      }

      $("#resource_subcategories a").removeClass("current");
      $(this).addClass("current");

      return false;
    });
  },


  // enable pagination for resources
  bindGetPage: function() {
    var operation = function(context) {
      var handle = $(context);

      if (handle.hasClass("resource_page_select"))
      {
	var page_number     = handle.find("option:selected").val();
	var parent_handle   = handle.parent().parent();
      }
      else
      {
	var page_number     = handle.attr("href").match(/\d+/);
	var parent_handle   = handle.parent();
      }

      var page_type       = parent_handle.find("input[name='resource_type']").val();
      var page_category   = parent_handle.find("input[name='resource_category']").val();
      var parent_category = parent_handle.find("input[name='parent_category']").val();

      var options = {
	page: page_number,
	type: page_type,
	parent: parent_category,
	category: page_category,
	mode: "ajax",
	request: "resource-page"
      };

      if (page_type == "local" && $("#local_zip").val().length > 0)
      {
	options['zip'] = $("#local_zip").val();
        options['distance'] = $("#local_range option:selected").val();
      }
      else if (page_type == "classified" && $("#classy_zip").val().length > 0)
      {
	options['zip'] = $("#classy_zip").val();
      }

      if (page_type == "classified" && $("#classy_keyword").val().length > 0 )
      {
	options['keyword'] = $("#classy_keyword").val();
      }

      if (handle.hasClass("resource_page_select"))
      {
	handle.parent().parent().parent().replaceWith('<div id="resources_are_waiting" class="resources centered"><img class="inline" src="/image/ajax_wait.gif" width="32" height="32" alt="ajax wait icon" /></div>');
      }
      else
      {
	handle.parent().parent().replaceWith('<div id="resources_are_waiting" class="resources centered"><img class="inline" src="/image/ajax_wait.gif" width="32" height="32" alt="ajax wait icon" /></div>');
      }

      jQuery.get("/vehicles", options,

		 function(response) {

		   $("#resources_are_waiting").replaceWith(response);

		   $("div.resources div.paging a").unbind();
		   $("select.resource_page_select").unbind();

		   $(".buttonResource").unbind();
		   $(".buttonResource").click(DreamGarage.resources.enableForm);

		   DreamGarage.resources.bindGetPage();

		   if (page_type == "local")
		   {
		     DreamGarage.resources.bindLocalResults();
		   }
		   else if (page_type == "classified")
		   {
		     DreamGarage.resources.bindClassifiedResults();
		     DreamGarage.resources.bindClassifiedSearchResults();
		   }
		 }
      );

      return false;
    };

    $("div.resources div.paging a").bind("click", function() { return operation(this); });
    $("select.resource_page_select").bind("change", function() { return operation(this); });

  },

  bindLocalResults: function() {
    var submit_function = function() {
      var zip = $("#local_zip").val();
      var range = $("#local_range option:selected").val();
      DreamGarage.resources.getLocalResults(zip, range, "local");
    };

    // bind local results "go" image button and enter key
    $("#local_submit").bind("click", submit_function);
    $("#local_zip_form").bind("submit", submit_function);
  },

  bindClassifiedResults: function () {

    var submit_function = function() {
      var zip = $("#classy_zip").val();
      var range = $("#classy_range option:selected").val();
      DreamGarage.resources.getLocalResults(zip, range, "classified");
    };

    // bind classified results "go" image button and enter key
    $("#classy_submit").bind("click", submit_function);
    $("#classy_zip_form").bind("submit", submit_function);
  },

  bindClassifiedSearchResults: function () {

    var submit_function = function() {
      var zip = $("#classy_zip").val();
      var keyword = $("#classy_keyword").val();

      if (keyword.length > 0)
      {
	DreamGarage.resources.getSearchResults(zip, keyword, "classified");
      }
      else
      {
	alert("Please enter a keyword you would like to search for in the classified listings.");
      }
      return false;
    };

    // bind classified results "go" image button and enter key
    $("#classy_search_form").unbind();
    $("#classy_search_form").bind("submit", submit_function);
  }

};

$(document).ready(function() {

  DreamGarage.resources.bindLocalResults();
  DreamGarage.resources.bindClassifiedResults();
  DreamGarage.resources.bindClassifiedSearchResults();

  // populate sub categories when parent category changed via dropdown
  $("#resource_category_dropdown").bind("change", function() {
    var category_name = $(this).val();

    DreamGarage.resources.getSubCategories(category_name, function(sub_categories) {
      var arr = [];
      jQuery.each(sub_categories, function(e, i) {
	arr.push('<a href="#' + e.replace(" ", "-").toLowerCase() + '">' + e + ' (' + i + ')</a>');
      });
      arr.push('<a href="#All">All</a>');

      // inject into DOM
      $("#resource_subcategories").html(arr.join(" "));

      // bind links to refresh resource area
      DreamGarage.resources.bindSubCategorySelections();
    });
  });

  DreamGarage.resources.bindSubCategorySelections();
  DreamGarage.resources.bindGetPage();

});