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

	epages.cartridges.de_epages.content.widget.ToolNewPage $Revision: 1.24 $

*/
dojo.provide("epages.cartridges.de_epages.content.widget.ToolNewPage");
dojo.require("epages.widget.LocalizedWidget");
dojo.require("epages.html");
dojo.require('epages.io.translation');
dojo.require('epages.lang.sort');
dojo.require('epages.widget.FormElement');
dojo.require('epages.cartridges.de_epages.presentation.icon');

dojo.declare(
	"epages.cartridges.de_epages.content.widget.ToolNewPage",
	[epages.widget.LocalizedWidget],
	{
		/**
		 * public properties
		 */
		uri           : '?',
		objectTreeId  : 'contentExplorerObjectTree',
		classStoreId  : 'contentClassStore',
		imageUrl      : epages.vars.StoreRoot + '/BO/icons',
		widgetsInTemplate  : true,
		disabled      : false,

		/**
		 * private properties
		 */
		_classStore :   undefined,
		_currentClassId: undefined,					// current classid of selected element in tree
		_overloadClassId: undefined,				// overload currentClassId (to create a new page on different page) - temporary only
		_overloadObjectId : undefined, 			// overload current parent object - temporary only
		_newPageWidget:  undefined,
		_imageClickConnect: undefined,
		_selectedItemNoFeature: false,

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

		postCreate: function() {
			this.inherited("postCreate", arguments);
			dojo.subscribe(this.objectTreeId+'/select', this, '_onSelectObject');
			this._imageClickConnect = dojo.connect(this.imageNode.parentNode, 'click', this, '_onClick');
			this._classStore = dojo.getObject(this.classStoreId);
			this.isVisibleOffNode = new epages.widget.FormElement({}, this.isVisibleOffNode).elementNode;
			this.isVisibleOnNode = new epages.widget.FormElement({}, this.isVisibleOnNode).elementNode;
			this.selectNode = new epages.widget.FormElement({}, this.selectNode).elementNode;
			this.connect(this.selectNode,'onchange', '_onChangeType');
			this.connect(this.newNameWidget.domNode,'onkeyup', '_onChangeName');
		},

		_onSelectObject:function(node) {
			this._currentClassId = node.item.classId;
			this._overloadClassId = undefined;  // reset _overloadClassId
			this._overloadObjectId = undefined; // reset _overloadObjectId
			var item = this._classStore.fetchItemByIdentity(this._currentClassId);
			if(item.contentChildClasses.length == 0) {
				var parentNode = node.getParent();
				if(parentNode && parentNode.item && parentNode.item.classId){
					this._currentClassId = parentNode.item.classId;
					this._overloadClassId = parentNode.item.classId;
					this._overloadObjectId = parentNode.item.objectId;
				}
			}
				if (this._imageClickConnect === undefined) {
					this._imageClickConnect = dojo.connect(this.imageNode, 'click', this, '_onClick');
				}
				dojo.publish(this.id+"/enabled", []);
				this.disabled=false;
		},

		_onClick: function (/* event */ evt, /* object? */ opt) {
		// summary: init & open dialog
		//  event - event object
		//  opt - options object
		//    preselectedClass -> this ClassID will be preselected
		//    overloadClassId  -> ClassID overload parent object
		//    overloadObjectId -> ObjectID overload parent object
			if(opt) {
				if(opt.overloadClassId) {
					this._overloadClassId=opt.overloadClassId;
				}
				if(opt.overloadObjectId) {
					this._overloadObjectId = opt.overloadObjectId;
				}
			}

			if (this._newPageWidget === undefined) {
				this.createModalDialog();
			}
			this.refreshInputs(this._currentClassId, (opt && opt.preselectedClass) ? opt.preselectedClass : undefined );
			this._newPageWidget.show();

			setTimeout(dojo.hitch(this, function() {
				epages.event.fire( this.newNameWidget.domNode, 'focus' );
				this.newNameWidget.domNode.focus();
				this.newNameWidget.domNode.select();
			}), 200);
		},

		refreshInputs: function (/* string */ classId, preselectedClass) {
		// summary: load options in select field
		//  classId - ClassID of current page
			var item = this._classStore.fetchItemByIdentity(this._overloadClassId ? this._overloadClassId : classId);
			epages.html.removeChildren(this.selectNode);
			var classItems = [];
			var hasSel = false;
			dojo.forEach(item.contentChildClasses, function (el) {
				classItems.push(this._classStore.fetchItemByIdentity(el));
			}, this);
			dojo.forEach(classItems.sort(epages.lang.sort.position), function (optionItem) {
				var feature = optionItem.feature;
				var option = document.createElement('option');
				option.value=optionItem.objectId;
				option.innerHTML=optionItem.title;
				if(feature.currentValue != undefined && feature.maxValue != undefined && (
					parseInt(optionItem.feature.currentValue) >= parseInt(optionItem.feature.maxValue))){
					dojo.addClass(option, "FeatureDisabled");
				}
				if(!hasSel) {
					option.selected=true;
					hasSel = true;
				}
				this.selectNode.appendChild(option);
			}, this);

			this.newNameWidget.domNode.value='';
			dojo.removeClass(this._newPageWidget.buttons[0].domNode,'Active');
			dojo.addClass(this._newPageWidget.buttons[0].domNode,'Disabled');
			$$(this.isVisibleOffNode.id).setChecked(true);

			if(preselectedClass) {
				this.selectNode.value = preselectedClass;
				if(this.selectNode.value == preselectedClass) {
					this.newNameWidget.attr('value',this.selectNode[this.selectNode.selectedIndex].text);
				}
			} else {
				this.selectNode.startupIndex = 0;
			}

			this._onChangeType();

		},

		createModalDialog: function () {
			dojo.require("epages.widget.Modaldialog");
			var me = this;
			this._newPageWidget = new epages.widget.Modaldialog({
				options:{
					title : this.translate('CreateNewPage'),
					width : 700,
					scroll: "auto",
					content: this.dialogNode
				},
				buttons: [{
					label: this.translate('Insert'),
					cssClass: 'Disabled',
					onclick: function() {
						if(!dojo.hasClass(this.domNode,'Disabled')){
							dojo.addClass(this.domNode,'Disabled');
							dojo.removeClass(this.domNode,'Active');
							var isVisibleTemp = me.isVisibleOnNode.checked;
							var objectTree = $$(me.objectTreeId);
							var tmpObjectId = me._overloadObjectId;
							if(me._overloadObjectId) {
								objectTree.selectNodeByObjectId(me._overloadObjectId);
							}
							me._overloadClassId = undefined; 	// reset _overloadClassId
							me._overloadObjectId = undefined; // reset _overloadObjectId
							objectTree.createObject(me.selectNode, me.newNameWidget.domNode, me.translate('EnterAlias'),tmpObjectId,isVisibleTemp);
							this._modalDialogWidget.hide();
						}
					}
				},{
					label: epages.io.dictionary.get('Cancel'),
					onclick: function() {
						this._modalDialogWidget.hide();
					}
				}]
			});
			document.body.appendChild(this._newPageWidget.domNode);
			this.dialogNode.style.display="";
		},

		_setSaveButton: function(isTooLong) {
			if(this.newNameWidget.domNode.value !== '' && !this._selectedItemNoFeature && !isTooLong){
				dojo.removeClass(this._newPageWidget.buttons[0].domNode,'Disabled');
				dojo.addClass(this._newPageWidget.buttons[0].domNode,'Active');
			} else {
				dojo.removeClass(this._newPageWidget.buttons[0].domNode,'Active');
				dojo.addClass(this._newPageWidget.buttons[0].domNode,'Disabled');
			}

			if(this._selectedItemNoFeature) {
				dojo.addClass(this.selectNode, "DialogErrorNormalFontWeight Force");
			} else {
				dojo.removeClass(this.selectNode, "DialogErrorNormalFontWeight Force");
			}
		},

		_onChangeName: function(evt){
			var isTooLong = this.newNameWidget.domNode.value.length>100;

			dojo[isTooLong? 'addClass' : 'removeClass'](this.newNameWidget.domNode, 'DialogError');
			this._setSaveButton(isTooLong);
		},

		_onChangeType: function(evt) {
			var cTypeId = this.selectNode.value;
			var item = this._classStore.fetchItemByIdentity(cTypeId);
			if(item) {
				var icName=epages.cartridges.de_epages.presentation.icon.getIconFileName(item.alias, true, false, 'l');
				if(item.title){
					this.typeNameNode.innerHTML=item.title;
					this.newNameWidget.domNode.value = item.title;
					this.newNameWidget.domNode.select();
				}else{
					this.typeNameNode.innerHTML="";
				}
				if(item.description){
					this.typeDescNode.innerHTML=item.description;
				}else{
					this.typeDescNode.innerHTML="";
				}
				var feature = item.feature;
				if(feature.currentValue != undefined && feature.maxValue != undefined && (
					parseInt(feature.currentValue) >= parseInt(feature.maxValue))){
					this.disabledFeatureNode.style.display='';
					this._selectedItemNoFeature=true;
				} else {
					this.disabledFeatureNode.style.display='none';
					this._selectedItemNoFeature=false;
				}
				this.typeDescNode.style.backgroundImage="url("+epages.vars.IconsRoot+"/"+icName+")";
				this._setSaveButton();

			}
		}
	}
);