/**
* Application Javascripts
*/

/**
* Unobtrusive Javascript
* - Keep the views clear of javascripts by 
*   working on the DOM when ready
*/
$(document).ready(function() {
  new filterRegion.init(
    $('.region-country[name*=country_id]'), 
    $('.region-province[name*=province_id]'), 
    $('.region-city[name*=city_id]')
  );
});

/**
 * Filter a list of states/provinces/counties based on the Country selected
 *
 * @access public
 */
var filterRegion = new function() {
  this.zoneNodes = null;

  this.region = null;
  this.zone = null;
  this.city = null;

  this.init = function($regionObj, $zoneObj, $cityObj) {
    var $class = this;
    
    this.region = $regionObj;
    this.zone = $zoneObj;
    this.city = $cityObj;
    
    this.zoneNodes = new Object();

    $(this.region).children(':not(:empty)').each(function(e) {
      var optionID = $(this).val();
      var optionName = $(this).text();
      
      $class.zoneNodes[optionID] = $($class.zone).children('optgroup[label="'+ optionName +'"]');
    });

    // handle changing of regions
    if ($($class.zone).length > 0) {
      $(this.region).change(function(e) {
        var optionID = $($class.region).children(":selected").val();
        var optionName = $($class.region).children(":selected").text();

        // always clear the contents of the region select menu
        $($class.zone).empty();

        // determine if results are filtered
        if (optionID == "") {
          $($class.region).children(':not(:empty)').each(function(e) {
            var optionID = $(this).val();
            var optionName = $(this).text();

            // wrap the html in an optgroup
            var formattedHtml = $class.zoneNodes[optionID].wrap('<optgroup label="'+ $class.zoneNodes[optionName] +'"></optgroup>');

            $($class.zone).append(formattedHtml);
          });
        } else {

          // wrap the html in an optgroup        
          var formattedHtml = $class.zoneNodes[optionID].wrap('<optgroup label="'+ $class.zoneNodes[optionName] +'"></optgroup>');

          // inject formatted node
          $($class.zone).html(formattedHtml);
        }

        $($class.zone).hide();
        $($class.zone).fadeIn("normal");
      }); 
    }
    
    // handle changing of zones
    if ($($class.city).length > 0) {
      $($class.zone).change(function(e) {
        var optionName = $(':selected', $class.zone).text();

        // since we need to allow a closest major city selection, only select the first city in the group
        $('optgroup[label='+ optionName +'] option:first', $class.city).attr('selected', true);

        $($class.city).hide();
        $($class.city).fadeIn("normal");
      }); 
    }
  };
};

/**
 * Plugin to insert value into field at caret position
 *
 * @access public
 */
$.fn.insertAtCaret = function(insertValue) {
  return this.each(function() {
    if (document.selection) {
      // IE Support
      this.focus();
      sel = document.selection.createRange();
      sel.text = insertValue;
      this.focus();
      
    } else if (this.selectionStart || this.selectionStart == '0') {
      // Mozilla/Netscape/Safari Support
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      
      this.value = this.value.substring(0, startPos)
        + insertValue
        + this.value.substring(endPos, this.value.length);
        
      this.focus();
      this.selectionStart = startPos + insertValue.length;
      this.selectionEnd = startPos + insertValue.length;
      this.scrollTop = scrollTop;
      
    } else {
      // Everything else
      this.value += insertValue;
      this.focus();
    }
  });
};