// namespace
com.jobrapido.datatable = {};

com.jobrapido.datatable.DataTable = function(table, selector, options) {
	var clazz = "com.jobrapido.datatable.DataTable";
	var optionsDefaults = {
		"enableDefaultCss" : true,
		"enableHighlightRowOnMouseOver" : true,
		"refreshUrl": null,
		"refreshInterval": null,
		"scrollHeight":0
	}
	var options = jQuery.extend({}, optionsDefaults, options);
	var _this = this;
	var _table = table;
	var _selector = selector;
	
	// ---------------
	//   PUBLIC API
	// ---------------
	this.loadData = function(url) {
		log.debug(clazz+"|LOAD|");
		jQuery.get(url,function(data){_renderData(data)});
	}
	// ---------------
	//    PRIVATE
	// ---------------
	var _isValidTargetElement = function() {
		if (_table!=null && _table!=undefined && _table[0].tagName == "TABLE") {
			return true;
		} else {
			log.error(clazz+"|NEW|Not valid target element",_table);
			return false;
		}
	}
	
	var _applyDefaultCss = function() {
		log.debug(clazz+"|APPLY CSS|");
		if (!_table.hasClass("jrwt-datatable")) _table.addClass("jrwt-datatable");
		if (!jQuery("thead tr", _table).hasClass("jrwt-th")) jQuery("thead tr", _table).addClass("jrwt-th");
		_highlightOnRowMouseOver();
	}
	
	var _highlightOnRowMouseOver = function() {
		if (options.enableHighlightRowOnMouseOver) {
			jQuery("tbody>tr",_table).hover(
				function() {
					jQuery(this).addClass("highlight");
				},
				function() {
					jQuery(this).removeClass("highlight");
				}
			);
		}
	}
	
	var _renderData = function(data) {
		var tbody = jQuery("tbody",data);
		jQuery("tbody",_table).replaceWith(tbody);
		_resizeTBody();
		_highlightOnRowMouseOver();
	}
	
	var _resizeTBody = function() {
		var tbody = jQuery("tbody",_table);
		if (tbody[0]!=undefined && options.scrollHeight>0) {
			if (tbody[0].scrollHeight>options.scrollHeight)
			{
    			tbody.height(options.scrollHeight+"px");
			} else {
				tbody.height("auto");
			}
		}
	}
		
	// ---------------
	//   CONSTRUCTOR
	// ---------------
	var _new = function() {
		if (_isValidTargetElement.call()) {
			log.debug(clazz+"|NEW|");
			if (options.enableDefaultCss) _applyDefaultCss.call();
			if (options.refreshUrl!=null && options.refreshInterval!=null) {
				setInterval("jrt.$DataTable(\""+_selector+"\").loadData(\""+options.refreshUrl+"\")",options.refreshInterval);
			}
			_resizeTBody();
		}
	}
	_new.call();
}

