/*
	Copyright (c) 2006-2007, ePages GmbH
	All Rights Reserved.
*/
dojo.provide("epages.cartridges.de_epages.content.widget.ToolChangeVisibility");
dojo.require("epages.widget.LocalizedWidget");
dojo.require('epages.widget.FormElement');

dojo.declare(
	"epages.cartridges.de_epages.content.widget.ToolChangeVisibility",
	[epages.widget.LocalizedWidget],
	{
		/**
		 * public properties
		 */
		objectTreeId  : 'contentExplorerObjectTree',
		classStoreId  : 'contentClassStore',
		imageUrl      : epages.vars.StoreRoot + '/BO/icons',
		userGroups    : '',
		url           : '?',

		/**
		 * private properties
		 */
		_classStore      :   undefined,
		_objectTree      :   undefined,
		_currentItem     :   undefined,
		_currentNodeItem :   undefined,
		_dialogWidget    :   undefined,
		_advanced        :   false,
		_userGroups      :   [],
		_currentLanguageID : null,

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

		postCreate: function() {
			this.inherited("postCreate", arguments);
			this._classStore = dojo.getObject(this.classStoreId);
			this._objectTree = $$(this.objectTreeId);
			dojo.subscribe(this.objectTreeId+'/select', this, '_onSelectObject');
			dojo.subscribe(this.objectTreeId+'/changeCurrentVisibility',this,'_onSelectObject');

			this.IsVisibleContentViewOnNode = new epages.widget.FormElement({}, this.IsVisibleContentViewOnNode).elementNode;
			this.IsVisibleContentViewOffNode = new epages.widget.FormElement({}, this.IsVisibleContentViewOffNode).elementNode;
			this.visibleInNavigationOnNode = new epages.widget.FormElement({}, this.visibleInNavigationOnNode).elementNode;
			this.visibleInNavigationOffNode = new epages.widget.FormElement({}, this.visibleInNavigationOffNode).elementNode;
			this.readPermissionSelectNode = new epages.widget.FormElement({}, this.readPermissionSelectNode).elementNode;

			dojo.connect(this.IsVisibleContentViewOnNode, 'onclick', this, '_onClickIsVisibleContentView');
			dojo.connect(this.IsVisibleContentViewOffNode, 'onclick', this, '_onClickIsVisibleContentView');

			var groups = this.userGroups.split(",");
			for( var i=0,iLength=groups.length ; i<iLength ; i++ ){
				var group = groups[i].split("|");
				if(group && group[0] && group[1]){
					var groupId = parseInt(group[0]);
					var groupName = group[1];
					var optionNode = document.createElement('option');
					optionNode.value = groupId;
					optionNode.innerHTML = groupName;
					this.readPermissionSelectNode.appendChild(optionNode);
				}
			}

		},

		_onSelectObject:function(node){
			this._currentClassId = node.item.classId;
			this._currentItem = this._classStore.fetchItemByIdentity(this._currentClassId);
			this._currentNodeItem = node.item;

			this._changeVisibilityIcon(node.item.IsVisibleContentView);
			if(this._currentItem.EffectedVisibilityAttributes){
				var attr = this._currentItem.EffectedVisibilityAttributes;
				if(attr.IsVisibleContentView){
					this._advanced = false;
					this.VisiblityLabelNode.innerHTML = this.translate('Visible');
					this.VisiblityOnLabelNode.innerHTML = this.translate('Yes');
					this.VisiblityOffLabelNode.innerHTML = this.translate('No');
					if(parseInt(this._currentNodeItem.IsVisibleContentView) == 1) {
						$$(this.IsVisibleContentViewOnNode.id).setChecked(true);
						$$(this.IsVisibleContentViewOnNode.id).domNode.checked=true;
					}else {
						$$(this.IsVisibleContentViewOffNode.id).setChecked(true);
					}
				}
				//EPG-19425 on these pages it should not be able to change read permission
				var excludePages = /TermsAndConditions|CustomerInformation|PrivacyPolicy|Imprint/;
				if(attr.ReadPermissionFor && !(this._currentItem.alias.match(excludePages))){
					this._advanced = true;
					this.readPermissionNode.style.display = '';
					var selectedIndex = null;
					for( var i=0,iLength=this.readPermissionSelectNode.options.length ; i<iLength ; i++ ){
						var el = this.readPermissionSelectNode.options[i];
						if(el.value == node.item.ReadPermissionFor){
							selectedIndex = el.index;
						}
					}
					if(selectedIndex != null){
						this.readPermissionSelectNode.selectedIndex = selectedIndex;
					}
				}
				else {
					this.readPermissionNode.style.display = 'none';
				}
				if(attr.VisibleInNavigation){
					this._advanced = true;
					this.visibleInNavigationNode.style.display = '';
				}
				else{
					this.visibleInNavigationNode.style.display = 'none';
				}
				if(attr.Text){
					this._advanced = true;
					if(attr.Text.Alias && attr.Text.Alias == 'ShopClosedMessage'){
						this.VisiblityLabelNode.innerHTML = this.translate('ShopStatusIs');
						this.VisiblityOnLabelNode.innerHTML = this.translate('IsOpen');
						this.VisiblityOffLabelNode.innerHTML = this.translate('IsClosed');
					}
				}
			}
			else{
				this._advanced = false;
			}
		},

		_onClick: function (evt) {
			if(this._objectTree == undefined){
				this._objectTree = $$(this.objectTreeId);
			}
			if(this._advanced){
				if (this._dialogWidget === undefined){
					this.createModalDialog();
				}
				this._dialogWidget.setTitle(this.translate('ChangeVisibility')+": "+this._currentNodeItem.title);
				this._dialogWidget.show();
				//set radio buttons
				$$( parseInt(this._currentNodeItem.IsVisibleContentView) ?
					this.IsVisibleContentViewOnNode.id :
					this.IsVisibleContentViewOffNode.id ).attr('checked',true);
				$$( parseInt(this._currentNodeItem.VisibleInNavigation) ?
					this.visibleInNavigationOnNode.id :
					this.visibleInNavigationOffNode.id ).attr('checked',true);

				// check radio buttons for visibility: no is checked
				if(this.IsVisibleContentViewOffNode.checked){
					this._manageVisibility(true, [this.visibleInNavigationOnNode, this.visibleInNavigationOffNode, this.readPermissionSelectNode]);
				// yes is checked
				}else if(this.IsVisibleContentViewOnNode.checked){
					this._manageVisibility(false, [this.visibleInNavigationOnNode, this.visibleInNavigationOffNode, this.readPermissionSelectNode]);
				}

				var visibilityText = this._currentItem.EffectedVisibilityAttributes.Text;
				if(visibilityText){
					this.textNode.style.display = '';
					this.VisibleNavigationTooltip.style.display = 'none';
					this.VisibleTooltip.style.display = 'none';
					var languageNative = null;
					for( var i=0,iLength=epages.vars.CurrentLanguages.length ; i<iLength ; i++ ){
						var elm = epages.vars.CurrentLanguages[i];
						if(elm.LocaleID == contentEventHandler._locale){
							this._currentLanguageID = elm.LanguageID;
							languageNative = elm.Native;
						}
					}
					if(!this._currentItem.EffectedVisibilityAttributes.Text.originalValue || !this._currentItem.EffectedVisibilityAttributes.Text.originalValue[this._currentLanguageID]){
						var json = new epages.io.Json();
						var result = json.loadSync(this.url, {
							'ViewAction': 'JSONGet',
							'Attributes': visibilityText.Alias,
							'ObjectID'  : epages.vars.SiteID,
							'LanguageID': this._currentLanguageID
						});
						if(!result.error){
							if(!this._currentItem.EffectedVisibilityAttributes.Text.originalValue){
								this._currentItem.EffectedVisibilityAttributes.Text.originalValue = {};
							}
							this._currentItem.EffectedVisibilityAttributes.Text.originalValue[this._currentLanguageID] = result.data[visibilityText.Alias];
						}
					}
					var textAreaValue = '';
					if(this._currentItem.EffectedVisibilityAttributes.Text.originalValue[this._currentLanguageID]){
						textAreaValue = this._currentItem.EffectedVisibilityAttributes.Text.originalValue[this._currentLanguageID];
					}
					var objectId = this._currentItem.EffectedVisibilityAttributes.Text.objectId ? this._currentItem.EffectedVisibilityAttributes.Text.objectId : epages.vars.SiteID;
					var inputId = visibilityText.Alias+'Input_'+objectId+'_'+this._currentLanguageID;
					if($(inputId)){
						textAreaValue = $(inputId).value;
					}
					this.textAreaNode.value= textAreaValue;
					this.textAreaLabelNode.innerHTML = this.translate(visibilityText.Alias);
				}
				else {
					this.textNode.style.display = 'none';
					this.VisibleNavigationTooltip.style.display = '';
					this.VisibleTooltip.style.display = '';
				}
			}
			else{
				this._objectTree.changeVisibilityCurrent();
			}
		},

		_onClickIsVisibleContentView: function(evt){
			// check radio buttons for visibility: no is checked
			if(this.IsVisibleContentViewOffNode.checked){
				this._manageVisibility(true, [this.visibleInNavigationOnNode, this.visibleInNavigationOffNode, this.readPermissionSelectNode]);
			// yes is checked
			}else if(this.IsVisibleContentViewOnNode.checked){
				this._manageVisibility(false, [this.visibleInNavigationOnNode, this.visibleInNavigationOffNode, this.readPermissionSelectNode]);
			}
		},

		_manageVisibility: function(visible, nodeList){
			var strOp = visible? "addClass" : "removeClass";

			for(var key in nodeList){
				var objTmp = nodeList[key];
				if(objTmp){
					objTmp.disabled = visible;
					dojo[strOp](objTmp.parentNode, "Disabled");
				}
			}
		},

		createModalDialog: function () {
			dojo.require("epages.widget.Modaldialog");
			var me = this;
			this._dialogWidget = new epages.widget.Modaldialog({
				options:{
					title : this.translate('ChangeVisibility'),
					width : 450,
					scroll: "auto",
					content: this.dialogNode
				},
				buttons: [{
					label: this.translate('Apply'),
					//cssClass: 'Disabled',
					onclick: function() {
						me.changeAttributes();
						this._modalDialogWidget.hide();
					}
				},{
					label: epages.io.dictionary.get('Cancel'),
					onclick: function() {
						this._modalDialogWidget.hide();
					}
				}]
			});
			document.body.appendChild(this._dialogWidget.domNode);
			this.dialogNode.style.display = "";
		},

		_changeVisibilityIcon: function(status){
			this.imageNode.src = this.imageUrl + ((status == 1 ) ? '/ico_m_visible.png' : '/ico_m_notvisible.png');
		},

		changeAttributes: function(){
			var attr = this._currentItem.EffectedVisibilityAttributes;
			var objectId = this._objectTree.currentItem().objectId;
			if(attr.ReadPermissionFor){
				if(this.readPermissionSelectNode.options[this.readPermissionSelectNode.selectedIndex].value != this._currentNodeItem.ReadPermissionFor){
					this._objectTree.model.store.changeAttribute(
						{
							objectId: objectId,
							name:'ReadPermissionFor',
							value:this.readPermissionSelectNode.options[this.readPermissionSelectNode.selectedIndex].value
						}
					);
				}
			}
			if(attr.VisibleInNavigation){
				var VisibleInNavigationNew = this.visibleInNavigationOnNode.checked  == true ? 1 : 0;
				var objectId = this._objectTree.currentItem().objectId;
				if(parseInt(this._currentNodeItem.VisibleInNavigation) != VisibleInNavigationNew){
					this._objectTree.model.store.changeAttribute(
						{
							objectId: objectId,
							name:'VisibleInNavigation',
							value:VisibleInNavigationNew
						}
					);
				}
			}
			if(attr.IsVisibleContentView){
				var IsVisibleContentViewNew = this.IsVisibleContentViewOnNode.checked == true ? 1 : 0;
				if(parseInt(this._currentNodeItem.IsVisibleContentView) != IsVisibleContentViewNew){
					this._objectTree.changeVisibilityCurrent();
				}
			}
			if(attr.Text && this._currentLanguageID){
				var name = attr.Text.Alias;
				var textNew = this.textAreaNode.value;
				if(textNew != attr.Text.originalValue[this._currentLanguageID]){
					this._objectTree.model.store.changeAttribute(
						{
							objectId: epages.vars.SiteID,
							name:name,
							value:textNew,
							languageId: this._currentLanguageID,
							oldValue: attr.Text.originalValue[this._currentLanguageID]
						}
					);
					attr.Text.originalValue[this._currentLanguageID] = textNew;
				}
			}
		}
	}
);