/*
	Copyright (c) 2006-2007, ePages GmbH
	All Rights Reserved.
*/
dojo.provide("epages.cartridges.de_epages.design.widget.Designtool");
dojo.require("epages.widget.LocalizedWidget");
dojo.require('epages.widget.Tooltip');
dojo.require('epages.cartridges.de_epages.design.widget.Designtoolitem');

dojo.declare(
	"epages.cartridges.de_epages.design.widget.Designtool", [epages.widget.LocalizedWidget], {
	/**
	 * public properties
	 */
	title: 'Select',
	data: "",
	imagedir: "",
	active: "",
	controllerId: "",
	folder: "",
	folderID: "",
	objectId: "",
	visible: false,
	position: 99, // to sort folder

	/**
	 * private properties
	 */
	_lookup: undefined,
	_lastSelected: null,
	_width: "",
	_height: "",
	_overflowY: "scroll",
	_tooltipCoor: null, //coordinates to position tooltip

	/**
	 * constants
	 */

	ITEM_WIDTH: 62, //Width of the div with padding and margin where the ico is in
	ITEM_HEIGHT: 62, //Height of the div with padding and margin where the ico is in
	WIDTH_SCROLLBAR: 20, //width of scrollbar
	NUMBER_ITEMS_FIRST_ROW: 5, // number of items in the first row
	NUMBER_ITEMS_SECOND_ROW: 10, //number of items in the first an second row together
	NUMBER_ITEMS_THIRD_ROW: 15, //number of items in the first, second and third row together

	/**
	 * widget properties
	 */
	declaredClass: 'epages.design.Designtool',
	imagePath: epages.themeUrl('images'),
	templatePath: dojo.moduleUrl('epages.cartridges.de_epages.design.widget', 'templates/Designtool.html'),
	translationName: dojo.moduleUrl('epages.cartridges.de_epages.design.widget', 'templates/translation'),
	widgetsInTemplate: true,

	postMixInProperties: function () {
		if (this.data != "") {
			if (typeof (this.data) == 'string') {
				this.data = dojo.fromJson(this.data);
			}
			this._lookup = {};
			for (var i = 0, l = this.data.length; i < l; i++) {
				var t = {};
				var s = this.data[i];
				t.objectId = s.ID;
				t.title = s.Name != undefined ? s.Name : '';
				t.image = this.imagedir + '/' + (s.PreviewImage || "general_img_transparentpixel.gif");
				t.text = s.InfoText;
				t.alias = s.Alias;
				if (s.PageSize) {
					t.pagesize = s.PageSize;
				}
				this._lookup[t.objectId] = this.data[i] = t;
			}
		}
		this.inherited("postMixInProperties", arguments);
	},

	postCreate: function () {
		this.inherited("postCreate", arguments);
		this._setWidthHeight();

		if (this._lookup[this.folderID] && this._lookup[this.folderID].pagesize) {
			var pagesize = this._lookup[this.folderID].pagesize;
		}

		var templateString = '<div class="Tooltip DesigntoolMenu"><div class="Menu" style="margin:-12px;"><div class="Layer"><div class="PropertyContainer">' +
			'<div class="dijit dijitMenu dijitReset dijitMenuTable" waiRole="menu">' +
			'<div class="dijitReset" dojoAttachPoint="containerNode"><div dojoAttachPoint="layoutsNode"></div><div class="ClearBoth"></div></div>' +
			'</div>';

		if (this.folder === "Content-Products" && pagesize) {
			templateString += '<span class="ep-designtool-content-productsperpage">' + this.translation.get("ProductsPerPage") + ': <span class="ep-designtool-content-pagesize">' + pagesize.selected + '</span> <a name="ProductSettingsLink" class="Action" href="?ViewAction=MBO-ViewProductSettings&amp;ObjectID=' + epages.vars.SiteID + '">' + this.translation.get("ToChange") + '</a>';
		}

		templateString += '</div></div>' +
			'<div class="LayerFooter"><div class="PropertyContainer"></div></div></div></div>';

		this._toolTipWidget = new epages.widget.Tooltip({
			templateString: templateString,
			tooltipArea: this.toolTipTarget,
			interactive: true
		});
		this.DesigntoolNode.appendChild(this._toolTipWidget.domNode);
		// _toolTipWidget style props
		this._toolTipWidget.containerNode.style.height = this._height;
		this._toolTipWidget.containerNode.style.overflowX = "hidden";
		this._toolTipWidget.containerNode.style.overflowY = this._overflowY;
		this._toolTipWidget.containerNode.parentNode.style.width = this._width;
		this._toolTipWidget.containerNode.parentNode.style.paddingTop = "4px";
		setTimeout(dojo.hitch(this, function () {
			this._toolTipWidget.show(-9999, -9999);
			this._toolTipWidget.hide();
		}), 1);
		for (var i = 0, l = this.data.length; i < l; i++) {
			this._addLayout(this.data[i]);
		}
		if (this.active) {
			this.setOption(this.active);
		}
		this.connect(this.clickNode, 'onclick', '_OnClickSelector');
	},

	_addLayout: function (layout) {
		var parentWidget = this;
		var entry = new epages.cartridges.de_epages.design.widget.Designtoolitem({
			id: this.title + ':' + layout.objectId + ':MenuItem',
			label: layout.title,
			infoText: layout.text,
			iconSrc: layout.image,
			objectId: layout.objectId,
			onClick: function () {
				parentWidget.setOption(this.objectId);
				parentWidget._toolTipWidget.hide();
			}
		});
		this._toolTipWidget.layoutsNode.appendChild(entry.domNode);


		if (this.active == layout.objectId) {
			dojo.addClass(entry.domNode, "dojoMenuItem2Selected");
		}
	},

	setOption: function (active, publish, objectId) {
		if (objectId) {
			this.objectId = objectId;
		}
		var menuItem = $$(this.title + ':' + active + ':MenuItem');
		if (menuItem != this._lastSelected) {
			if (this._lastSelected) {
				dojo.removeClass(this._lastSelected.domNode, "Selected");
			}
			dojo.addClass(menuItem.domNode, "Selected");
			if (this.folder === 'Content-Products' && this.active) {
				var productSettingsLink = dojo.query('a[name="ProductSettingsLink"]', this._toolTipWidget.domNode),
					newPageSize = this._lookup[active].pagesize,
					activePageSize = this._lookup[this.active].pagesize,
					pagesizeNode = dojo.query('.ep-designtool-content-pagesize'),
					productsPerPageNode = dojo.query('.ep-designtool-content-productsperpage');

				if (newPageSize && activePageSize && newPageSize.selected !== activePageSize.selected && productSettingsLink) {
					productSettingsLink[0].innerHTML = this.translation.get("ToChange");
					pagesizeNode[0].innerHTML = newPageSize.selected;
				} else if (newPageSize && !activePageSize) {
					dojo.create(
						"span", {
						'class': 'ep-designtool-content-productsperpage',
						'innerHTML': this.translation.get("ProductsPerPage") + ': <span class=ep-designtool-content-pagesize>' + newPageSize.selected + '</span> <a name="ProductSettingsLink" class="Action" href="?ViewAction=MBO-ViewProductSettings&amp;ObjectID=' + epages.vars.SiteID + '">' + this.translation.get("ToChange") + '</a>'
					},
						dojo.query('div.dijitMenuTable', this._toolTipWidget.domNode)[0]);
				} else if (!newPageSize && productSettingsLink) {
					dojo.destroy(productsPerPageNode[0]);
				}
			}

			this._lastSelected = menuItem;
			var data = this._lookup[active];
			if (data === undefined || data == null) {
				return;
			}
			this.SelectedOptionNode.src = data.image;
			this.SelectedOptionNode.alt = data.title;
			this.SelectedOptionNode.title = data.title;
			this.active = active;
			if (publish !== false) {
				dojo.publish('Designtool/select', [{
						id: this.id
					}]);
			}
		}
	},

	getActive: function () {
		if (this.active === "") {
			return undefined;
		} else {
			var data = this._lookup[this.active];
			if (data === undefined || data == null) {
				return;
			}
			return {
				folder: this.folder,
				alias: data.alias,
				objectId: this.objectId,
				templateTypeId: data.objectId,
				lastSelected: this._lastSelected
			};
		}
	},


	_OnClickSelector: function (opt) {
		var curTarget = $E(opt.currentTarget);
		var coords = curTarget.getAbsolutePosition();
		coords['y'] += curTarget.object.clientHeight;

		this._tooltipCoor = {
			x: coords['x'],
			y: coords['y']
		};
		if (this.controllerId == "") {
			this.openMenuWidget();
		} else {
			//if Controller is defined ask if SelectLayout is allowed
			$$(this.controllerId).allowSelectLayout(this.id);
		}
	},

	openMenuWidget: function () {
		this._toolTipWidget.show(parseInt(this._tooltipCoor.x), parseInt(this._tooltipCoor.y));
	},

	_setWidthHeight: function () {
		var layouts = this.data.length;
		var multiWidth = this.NUMBER_ITEMS_FIRST_ROW;
		var multiHeight = 3;
		var scrollbar = 0;
		var overflowY = "hidden";
		if (layouts <= this.NUMBER_ITEMS_FIRST_ROW) {
			multiWidth = layouts;
			multiHeight = 1;
			scrollbar = 0;
		} else if (layouts > this.NUMBER_ITEMS_FIRST_ROW && layouts <= this.NUMBER_ITEMS_SECOND_ROW) {
			multiHeight = 2;
		} else if (layouts > this.NUMBER_ITEMS_THIRD_ROW) {
			overflowY = "scroll";
			scrollbar = this.WIDTH_SCROLLBAR;
		}
		//this._width = ((multiWidth*this.ITEM_WIDTH)+scrollbar)+"px";
		//this._height = (multiHeight*this.ITEM_HEIGHT)+"px";
		this._overflowY = overflowY;
	},

	show: function () {
		this.visible = true;
		this.domNode.style.display = "";
	},

	hide: function () {
		this.visible = false;
		this.domNode.style.display = "none";
	},
	setSeperator: function (active) {
		if (active == true) {
			this.seperatorNode.style.display = "";
		} else {
			this.seperatorNode.style.display = "none";
		}
	}
});