dojo.provide("epages.cartridges.de_epages.content.widget.JsonTagEditor");
dojo.require("epages.cartridges.de_epages.content.widget.TagEditor");
dojo.require('epages.string');

dojo.declare("epages.cartridges.de_epages.content.widget._JsonTagEditorStore",
			 epages.cartridges.de_epages.content.widget._TagEditorStore, {
	// parent needs to define a string which is used as subscribe/publish key
	unique:			null,

	constructor: function(unique){
		this.unique = unique;
		dojo.subscribe(this.unique + '/onNewSearchResults', this, "_handleJsonResult");
	},

	_fetchItems: function(	/* Object */ args,
							/* Function */ findCallback,
							/* Function */ errorCallback){
		// summary:
		//		See dojo.data.util.simpleFetch.fetch()
		if(!args.origKey){ args.origKey = ""; }
		// async call to json request function epages.cartridges.de_epages.content.widget.SmartSearchInput
		dojo.publish(this.unique + '/onEvaluateInput', [ args.origKey,dojo.mixin(args,{"findCallback":findCallback})]);
	},
	_handleJsonResult : function(items,args){
		// summary: recieve json result, sort and push it to callback
		if(args.sort){
			items.sort(dojo.data.util.sorter.createSortFunction(args.sort, this));
		}
		if (args.findCallback) {
			args.findCallback(items, args);
		}
	},
	getLabel: function(/* item */ item){
		return item.innerHTML;
	}
});

dojo.declare(
	"epages.cartridges.de_epages.content.widget.JsonTagEditor",
	epages.cartridges.de_epages.content.widget.TagEditor,
	{
		/**
		 * public properties
		 */
		//integer - limited by SMART_PRODUCT_SEARCH_RESULT_COUNT Perl constant
		pageSize:    10,

		// searchDelay: Integer
		//		Delay in milliseconds between when user types something and we start
		//		searching based on that value
		searchDelay: 0,
		// disable multiple tags
		delimiter: null,
		placeholder: '',
		storeType: "epages.cartridges.de_epages.content.widget._JsonTagEditorStore",
		labelType: "html",
    	submitOnEnter: true,	// flag that decides if the form is submitted by using the submit-Event (true) or
                          		// by trigger the event using the fire method (false)
		postCreate: function() {
			this.inherited('postCreate', arguments);
      this.submitOnEnter = epages.string.toBoolean(this.submitOnEnter);
    },
		_onKeyPress: function(/*Event*/ evt){
			var key = evt.charOrCode;
			if(evt.keyCode == dojo.keys.ENTER) {
				if(!this._isShowingNow){
          if(this.submitOnEnter){
					this.focusNode.form.submit();
          }else{
            epages.event.fire(dojo.query('input[type=submit]', this.focusNode.form)[0], "click");
          }
				}
			}
			this.inherited("_onKeyPress",arguments);
		}
	}
);