/*
	Copyright (c) 2006-2009, ePages GmbH
	All Rights Reserved.

	epages.cartridges.de_epages.content.widget.ShortUrlInput $Revision: 1.12 $

*/
dojo.provide("epages.cartridges.de_epages.content.widget.ShortUrlInput");
dojo.require("epages.widget.LocalizedWidget");
dojo.require('epages.html.element');
dojo.require('epages.event');
dojo.require('epages.lang.hash');
dojo.require('epages.lang.array');
dojo.require('epages.format');
dojo.require('epages.widget.FormElement');
dojo.require('epages.uimessagehandler');

dojo.declare(
	"epages.cartridges.de_epages.content.widget.ShortUrlInput",
	[epages.widget.LocalizedWidget, dijit._Container, dijit._Contained],
	{
		/**
		 * public properties
		 */
		url           : '?',                 // request url
		name          : '',                  // input name
		value         : '',                  // input value (shorturl)
		disabled      : '',                  // flag: input disabled
		nameInputId   : '',                  // string: id of name input
		parentObjectId: '',                  // epages parent ObjectID
		siteId        : epages.vars.SiteID,  // epages SiteID
		classAlias    : '',                  // epages ClassName of parent object
		languageId    : '',                  // language identifier
		contentObjectId: '',                 // epages ObjectID of current object
		formError     : '',                  // flag: 1 = form error occured
		saveButtonId  : '',                  // string: id of save button (register input node)

		/**
		 * private properties
		 */
		_inputTimeout     : undefined,       // save shorturl input timeout
		_nameInputTimeout : undefined,       // save name input timeout
		_isNew            : false,           // flag: indicates wether there was an inital value or not (don't overwrite inital values on name input changes)
		_lastNameValue    : '',              // save last name (to detect real changes / avoid requests)
		_lastValue        : '',              // save last shorturl (to detect real changes / avoid requests)
		_publishButton    : undefined,       // dom node of publish shortURL link

		/**
		 * widget properties
		 */
		templatePath:    dojo.moduleUrl('epages.cartridges.de_epages.content.widget', 'templates/ShortUrlInput.html'),
		translationName: dojo.moduleUrl('epages.cartridges.de_epages.content.widget', 'templates/translation'),
		widgetsInTemplate : true,

		/**
		 * widget life cycle
		 */
		postCreate: function() {
		// summary: initalize shorturl widget
			this.inherited("postCreate", arguments);
			if(this.siteId === undefined) {
				console.warn("epages.vars.SiteID not defined in "+this.declaredClass);
			}

			// create hash with temporary reserved short url (avoids duplicate shorturl on pages with multiple languages)
			if(epages.vars.TemporaryReservedShortUrl === undefined) {
				epages.vars.TemporaryReservedShortUrl = $H();
			}

			// update value in shorturl preview
			this._updateDisplayUrl(this.value);

			// update display of widget depending on its status
			if(this.value != "" && this.formError =="") {      // has inital value / no form error
				if(this.disabled != "disabled") {                // input is not disabled
					// show shorturl preview instead of shorturl input
					this.inputWrapperNode.style.display="none";
					this.displayUrlWrapperNode.style.display="";

					// (dirty) label formatting
					var labelNode = $('Label'+this.id);
					if(labelNode !== undefined && labelNode != null) {
						dojo.removeClass(labelNode, "InputLabelling");
						var tableNode = labelNode.parentNode.parentNode.parentNode;
						epages.html.replaceClass(tableNode, "InnerGrid", "FormGrid");
					}
				}
			} else if(this.formError =="1") {                  // set form error
				this._setError(true);
			} else {                                           // set flag _isNew
				this._isNew=true;
			}

			if(this.disabled=="disabled") {
				this.inputWidget.domNode.disabled= true;
			} else {
				// attach events
				this.connect(this.displayUrlWrapperNode, "onclick", "onClickEditLinkNode");
				this.connect(this.inputWidget.domNode, "onkeypress", "onKeypressInputNode");
				this.connect(this.inputWidget.domNode, "onchange", "onChangeInputNode");

				if(this.nameInputId != "") {
					var niNode=$(this.nameInputId);
					if(niNode) {
						this._lastNameValue = niNode.value;
						this.connect(niNode, "onchange", "onChangeNameInputNode");
						this.connect(niNode, "onkeypress", "onKeypressNameInputNode");
					}
				}

				// save the "publish short url" button
				var button = $('CommandLink-'+this.id);
				if(button) {
					this._publishButton = button;
				}
				this._updatePublishButton();

				// register input to specified save button
				dojo.addOnLoad(dojo.hitch(this, function() {
					var saveButton = $$(this.saveButtonId);
					if(saveButton !== undefined){
						saveButton.registerInput(this.inputWidget.domNode);
					} else {
						console.warn("Savebutton (id="+this.saveButtonId+") not found in "+this.declaredClass);
					}
				}));
			}
		},

		/**
		 * events
		 */

		onClickEditLinkNode : function(evt) {
		// summary: show short url input node and show info bubble
			this.inputWrapperNode.style.display="";
			this.displayUrlWrapperNode.style.display="none";
			this.inputWidget.domNode.focus();

			// (dirty) label formatting
			var labelNode = $('Label'+this.id);
			if(labelNode !== undefined) {
				dojo.addClass(labelNode, "InputLabelling");
				var tableNode = labelNode.parentNode.parentNode.parentNode;
				epages.html.replaceClass(tableNode, "FormGrid", "InnerGrid");
			}

			//display Info Bubble
				var position = $E(this.inputWidget.domNode).getAbsolutePosition();
				dojo.publish("uimessage/show", ["", this.translation.get('EditShortURLNotification'), "Bubble", {
					typeClass: "",
					sizeClass: "Small",
					x: position.x,
					y: (position.y + this.inputWidget.domNode.clientHeight + 4)
				}]);
		},

		onKeypressInputNode: function(evt) {
		// summary: handle keypress of shorturl input field - trigger onchange event after timeout
			dojo.publish("uimessage/hide", []);
			this._clearTimeouts();

			var _this = this;
			var iNode=this.inputWidget.domNode;
			this._inputTimeout = window.setTimeout( function() {
				epages.event.fire(iNode, "change");
			}, 100);
		},

		onKeypressNameInputNode: function(evt) {
		// summary: handle keypress of name input field - trigger onchange event after timeout
			this._clearTimeouts();

			var _this = this;
			var niNode=$(this.nameInputId);
			this._nameInputTimeout = window.setTimeout( function() {
				epages.event.fire(niNode, "change");
			}, 200);
		},

		onChangeInputNode: function(evt) {
		// summary: handle changes on input node - send request for a valid short url
			var v = this.getValue();
			this._clearTimeouts();
			this._updatePublishButton();
			if(this._lastValue != v) {                      // send request if there were real changes
				var orgName = this.getValue();

				var trimmedName = orgName.replace(/\s/g, ""); // check if string contains only space chars
				if(trimmedName != "") {
					var resShorturlString =	this._getTemporyReservedUrl();

					// build form data
					var request = new epages.io.Json();
					var formData = {
						'ViewAction' : 'JSONValidateShortURL',
						'ObjectID'   : this.siteId,
						'ParentID'   : this.parentObjectId,
						'ShortUrl'   : orgName,
						'ClassName'  : this.classAlias
					};

					// optinal form data
					if(this.contentObjectId != "") {
						formData['ContentObjectID'] = this.contentObjectId;
					}

					if(this.languageId != "") {
						formData['LanguageID'] = this.languageId;
					}

					if(resShorturlString != "") {
						formData['TemporaryReserved']=resShorturlString;
					}

					// send request
					request.loadAsync(this.url,
						epages.lang.hitch(this, function (result) { this._validateShortUrl_requestOk(result);}),
						formData,
						epages.lang.hitch(this, function (result, data) { this._getShortUrl_requestFailed(result, data);})
					);
				} else {
					this._setError(false);
				}
			}
		},

		triggerChangeNameInputNode: function() {
		// summary: public port to trigger new short URl suggest from outside
			this._clearTimeouts();
			this._updatePublishButton();

			var resShorturlString =	this._getTemporyReservedUrl();
			var orgName=$(this.nameInputId).value;

			// build form data
			var request = new epages.io.Json();
			var formData = {
				'ViewAction' : 'JSONGenerateShortURL',
				'ObjectID'   : this.siteId,
				'ParentID'   : this.parentObjectId,
				'Name'       : orgName,
				'ClassName'  : this.classAlias
			};

			// optinal form data
			if(this.languageId != "") {
				formData['LanguageID'] = this.languageId;
			}

			if(resShorturlString != "") {
				formData['TemporaryReserved']=resShorturlString;
			}

			// send request
			request.loadAsync(this.url,
				epages.lang.hitch(this, function (result) { this._getShortUrl_requestOk(result);}),
				formData,
				epages.lang.hitch(this, function (result, data) { this._getShortUrl_requestFailed(result, data);})
			);

			var niNode=$(this.nameInputId);
			this._nameInputTimeout = window.setTimeout( function() {
				epages.event.fire(niNode, "change");
			}, 2000);
		},

		onChangeNameInputNode: function(evt) {
		// summary: handle changes of name input field
			this._clearTimeouts();
			this._updatePublishButton();

			// send request only  if there were real changes and there were no initial value (don't overwrite current value)
			if((this.inputWidget.domNode.value == "" || this._isNew) &&
					this._lastNameValue != this.getNameValue()) {

				var resShorturlString =	this._getTemporyReservedUrl();
				var orgName=$(this.nameInputId).value;

				// build form data
				var request = new epages.io.Json();
				var formData = {
					'ViewAction' : 'JSONGenerateShortURL',
					'ObjectID'   : this.siteId,
					'ParentID'   : this.parentObjectId,
					'Name'       : orgName,
					'ClassName'  : this.classAlias
				};

				// optinal form data
				if(this.languageId != "") {
					formData['LanguageID'] = this.languageId;
				}

				if(resShorturlString != "") {
					formData['TemporaryReserved']=resShorturlString;
				}

				// send request
				request.loadAsync(this.url,
					epages.lang.hitch(this, function (result) { this._getShortUrl_requestOk(result);}),
					formData,
					epages.lang.hitch(this, function (result, data) { this._getShortUrl_requestFailed(result, data);})
				);
			}
		},

		/**
		 * getter, setter, other methods
		 */
		setValue: function(/* string */v, /* boolean? */ isValidated) {
		// summary: setter function - set value of input value
		// v: new value
		// isValidated: indicates if shorturl was validated (eg. proposal from server)
			this.inputWidget.domNode.value = v;
			this._lastValue = v;
			if(isValidated) {
				this._setTemporyReservedUrl();
				this._setError(false);
				dojo.publish("uimessage/hide", []);
			}
		},

		getValue: function() {
		// summary: returns short url input value
			return this.inputWidget.domNode.value;
		},

		getNameValue: function() {
		// summary: returns name input value
			var niNode=$(this.nameInputId);
			if(niNode) {
				return niNode.value;
			} else {
				return false;
			}
		},

		_clearTimeouts: function() {
		// summary: clear all timeouts
			if(this._inputTimeout !== undefined) {
				window.clearTimeout(this._inputTimeout);
			}

			if(this._nameInputTimeout !== undefined) {
				window.clearTimeout(this._nameInputTimeout);
			}
		},

		_setError : function(/* boolean */ setError) {
		// summary: set or remove error class on short url input
			if(setError) {
				dojo.addClass(this.inputWidget.domNode, "DialogError");
			} else {
				dojo.removeClass(this.inputWidget.domNode, "DialogError");
			}
		},

		_setTemporyReservedUrl: function() {
		// summary: set current value as temporaray reserved url
			var v = this.getValue();
			epages.vars.TemporaryReservedShortUrl.set(this.id, v);
		},

		_getTemporyReservedUrl: function() {
		// summary: returns a string with all reserved url (comma seperated)
				var resShorturl = [];
				var id = this.id;
				epages.vars.TemporaryReservedShortUrl.each(function(pair) {
					if(id != pair[0]) {
						resShorturl.push(pair[1]);
					}
				});
				return resShorturl.join(',');
		},


		_updateDisplayUrl : function(/* string */ v) {
		// summary: update shorturl preview div
			this.displayUrlNode.innerHTML = epages.format.scrunch(v,25, 0.4);
			this.displayUrlNode.title=v;
		},

		_validateShortUrl_requestOk : function(/* epages.io.json result */ result) {
		// summary: call back function (short url node change) - insert generated short url or display short url proposal bubble
			this._lastValue = this.getValue();
			this._setTemporyReservedUrl();
			if(result.data && result.data.Valid) {
				this._setError(false);
			} else {
				this.setValue(result.data.ShortURL,true);
			}
		},

		_updatePublishButton : function() {
		// summary: update commandlink "publish short url"
				if(this.getValue() == "") {
					if(this._publishButton){
						dojo.addClass(this._publishButton, "Disabled");
					}
				} else {
					if(this._publishButton && !dojo.hasAttr(this._publishButton, "title")){
						dojo.removeClass(this._publishButton, "Disabled");
					}
				}
		},

		_getShortUrl_requestOk : function(/* epages.io.json result */ result) {
		// summary: call back function (name input change) - insert generated short url and update
			if(result.data && result.data.ShortURL) {
				this.inputWidget.domNode.value=result.data.ShortURL;		// set short url
				// update display and status
				this._updateDisplayUrl(result.data.ShortURL);
				this._setError(false);
				this._setTemporyReservedUrl();
				this._lastNameValue = this.getNameValue();
				this._updatePublishButton();
			}
		},

		_getShortUrl_requestFailed : function(/* epages.io.json result */ result) {
		// summary: error handling request failed
			var errors = result.data.Errors;
			console.error("An error occured in request (function: onChangeNameInputNode, class: "+this.declaredClass+") ", result.data.Errors);
		}

	}
);