﻿/// <reference path="jQuery.intellisense.js" />
/// <reference name "MicrosoftAjax.js" assembly="System.Web.Extensions" />

(function($) {

	// Debug
	if ( !$.browser.safari && typeof window.console !== 'undefined' && typeof window.console.log === 'function' )
	{	// Use window.console
		$.log = window.console.log;
	}
	else
	{	// Don't use anything
		$.log = function ( ) { };
	}
})(jQuery);

cascadeSelect = function(list, options) {
  this.list = list;
  this.options = options;
  this.init();
};

cascadeSelect.prototype = {

  init : function() {
    if (this.options.parent) {
      $(this.options.parent).bind('change', Function.createDelegate(this, this.parentChanged));
      
      parentSelectedValue = $(this.options.parent).val();
      this.list.disabled = (parentSelectedValue == null) || (parentSelectedValue == '');
    }
  },
  
  parentChanged : function(e) {
    this.dataBind();
  },
  
  clear : function() {
    $(this.list).removeOption(/./);
  },
  
  dataBind : function() {
    parentSelectedValue = $(this.options.parent).val();

    this.clear();    
    if (parentSelectedValue) {
      this.showLoadingIndicator();
      params = $.extend({}, this.options.postParams, {
        request: this.options.getItemsRequest,
        parentValue: parentSelectedValue      
      });      
      $.getMSJSON(this.options.serviceUrl, params, 
                  Function.createDelegate(this, this.dataBindHandler),
                  Function.createDelegate(this, this.errorRequestHandler));      
    }
    else {
      this.list.disabled = true;
    }
  },
  
  errorRequestHandler : function(response, result) {
    $.log('WARN', response.responseText);
  }, 
	          
  dataBindHandler : function(data, result) {
    if (result == 'success' && data) {
      list = this.list;
      if (this.options.defaultItemText != null && this.options.defaultItemValue != null) {
        $(list).addOption(this.options.defaultItemValue, this.options.defaultItemText);
      }
      $.each(data, function(i, x){
        $(list).addOption(x.Key, x.Value);
      });
      $(list).selectOptions('');
      $(list).change();
    }
    this.hideLoadingIndicator();
    this.list.disabled = false;    
  },
  
  showLoadingIndicator : function() {
  },
  
  hideLoadingIndicator : function() {
  }  
};

(function($) {

  $.fn.cascadeSelect = function(options) {
  
    var options = $.extend({}, $.fn.cascadeSelect.defaults, options);
    
    $(this).each(function() {
      new cascadeSelect(this, options);
    });
	};			
	
	$.fn.cascadeSelect.defaults = {
    serviceUrl : '',
    getItemsRequest : 'GetItems',
    parent: null,
    postParams : {},
    defaultItemText: null,
    defaultItemValue: null
	};

})(jQuery);
