/*
 * The base class/namespace for all tagging_base shared javascript functions
 */

var CONTENT_TYPE_MEDIA = 1 << 0;
var CONTENT_TYPE_CONTENT = 1 << 1;
var CONTENT_TYPE_BLOG = 1 << 2;
var CONTENT_TYPE_MARKETPLACE = 1 << 3;
var CONTENT_TYPE_WALL = 1 << 4;


/* constructor */
var tagging_base = function(_element, _id, _key, _target, _callback) {
	this.tag_array 		= new Array();
	this.tag_element	= null; /* this element contains the rendered tag array */
	this.element		= _element;
	this.id				= _id;
	this.key			= _key;
	this.target			= _target;
	this.callback		= _callback;
	this.init();
};

tagging_base.prototype = {

	init : function() {
		var _this = this; // if we don't put this we lose scope.
		
		$(this.element).autocomplete('scripts.php?script=autocompleteall&mid=' + this.id,
				{
					width :300,
					max :50,
					minChars :2,
					cacheLength :0,
					multiple :false,
					matchContains :true,
					formatItem :this.formatItem,
					formatResult :this.formatResult
				});

		$(this.element).result( function(event, data, formatted) {
			/* push the data into the tag_array */
			_this.addTag(data);
			/* fire off the callback if there is one */
			if (_this.callback){
				_this.callback(event, data, formatted);
			}
		});
	},
	
	formatItem : function (row) {
		if (row[1]){
			return row[0] + " (<strong>" + row[1] + "</strong>)";
		} else {
			return row[0];
		}
	},
		
	formatResult : function (row) {
		return row[0].replace(/(<.+?>)/gi, '');
	},
	
	addTag : function(data){
		this.tag_array.push(data);
		this.createTagElement();
	},
	
	removeTag : function(index){
		this.tag_array.splice(index, 1);
		this.createTagElement();
	},
	
	createTagElement : function(){
		
		var _this = this;
		var _html = "";
		$(this.element).val("");
		$(this.target).html("");
		
		/* creates the tag elements with delete function */
		$.each(this.tag_array, function (key, value){
			var element = document.createElement("A");
			$(element).click( function () { _this.removeTag(key); } );
			$(element).text(" (x), ");
			$(_this.target).append( value[0] );
			$(_this.target).append( element );
		});
	},
	
	/* JSON Include needed */
	stringifyTags : function (_element) {
		if (_element){
			$(_element).val(JSON.stringify(this.tag_array));
		} else {
			return JSON.stringify(this.tag_array);
		}
	}
	

};


function _test(){
}
/* instantiate a singleton of this class for use */
// var tagger = new tagging_base();

