/*globals jQuery */
(function ($) {
	"use strict";
	var separatorCss = "wijmo-wijmenu-separator ui-state-default",
		headerCss = "ui-widget-header",
		menuItemCss = "ui-widget wijmo-wijmenu-item ui-state-default",
		cornerCss = "ui-corner-all",
		linkCss = "wijmo-wijmenu-link",
		textCss = "wijmo-wijmenu-text",
		listCss = "wijmo-wijmenu-list ui-widget-content ui-corner-all " +
		"ui-helper-clearfix wijmo-wijmenu-child ui-helper-reset";


	//$.wijmo.wijmenu._itemWidgetName: "wijmenuitem", //c1menuitem
	//$.wijmo.wijmenu._menuWidgetName = "c1menu"; //c1-wijmenu

	$.widget("wijmo.c1menu", $.wijmo.wijmenu, {
		options: {
			///	<summary>
			///	A value indicating the width of the wijsplitter.
			/// Default: 400.
			/// Type: Int.
			///	</summary>
			width: "",
			///	<summary>
			///	A value indicates the height of the wijsplitter.
			/// Default: 250.
			/// Type: Int.
			///	</summary>
			height: "",
			postBackEventReference: null
		},

		_setOption: function (key, value) {
			if (key === "width" || key === "height") {
				this.refresh();
			}

			$.wijmo.wijmenu.prototype._setOption.apply(this, arguments);
		},
		widgetEventPrefix: "c1menu",
		refresh: function () {
			var self = this,
				o = self.options,
				width = o.width,
				height = o.height, container;
			$.wijmo.wijmenu.prototype.refresh.apply(self, arguments);
			container = self.domObject.menucontainer;
			if (width !== "") {
				container.width(width);
			}
			if (height !== "") {
				container.height(height);
			}
		},

		/*
		_remove: function (selector) {
		var eles = $(selector, this.element),
		isChanged = false, path, parent, parentPath, parentItem,
		self = this,
		o = self.options;
		eles.each(function (i, n) {
		var item = $(n);
		if (item.is("li.wijmo-wijmenu-item") ||
		item.is("li.wijmo-wijmenu-separator") ||
		item.is("li.ui-widget-header")) {
		parent = item.parent("ul");
		path = item.data("path");
		item.remove();
		if (parent.get(0) === self.element.get(0)) {
		parentPath = "";
		o.items.splice(self._getItemIndex(path), 1);
		}
		else {
		parentPath = parent.parent("li").data("path");
		parentItem = self._getItemByPath(parentPath);
		parentItem.items.splice(self._getItemIndex(path), 1);
		}
		self._rebuildPath(parent, parentPath);
		isChanged = true;
		}
		});
		if (isChanged) {
		$("ul:empty", self.element).remove();
		if (o.mode === "sliding") {
		self._killDrilldown();
		self._drilldown();
		}
		}
		},
		/// <summary>
		/// Remove an item from the menu.
		/// </summary>
		/// <param name="Selector" type="String/Number">
		/// If the selector is number, It will remove a menuitem 
		/// which's index is the value in first level items.
		/// If it's null, It will remove the last item in first level items.
		/// If it's a string, It will remove the menuitem which is the item 
		/// find by selector. 
		/// </param>
		remove: function (selector, index) {
		var strSelector;
		if (index === undefined || index === null) {
		if (selector === undefined || selector === null) {
		strSelector = ">li:last";
		}
		else if (!isNaN(selector)) {
		strSelector = ">li:eq(" + selector + ")";
		}
		else {
		strSelector = selector;
		}
		}
		else {
		if (selector) {
		strSelector = selector + ">ul>li:eq(" + index + ")";
		}
		}
		if (strSelector) {
		this._remove(strSelector);
		}
		},

		/// <summary>
		/// Add an item to menu.
		/// </summary>
		/// <param name="item" type="String/Object">
		/// A menu item, It can be an object which probably contains text, 
		/// header, separator, navigate property.  and it can be an HTML markup, 
		/// or empty string.
		/// </param>
		/// <param name="selector" type="String/Number">
		/// If the selector is a number, add an item to the root menu.
		/// if the selector is a String, add an item to the item 
		/// which finded by jquery with the selector 
		/// </param>
		/// <param name="index" type="number">
		/// add an item at a position.
		/// </param>
		add: function (item, selector, index) {
		var self = this, ele;
		if (selector === undefined || selector === null) {
		ele = self.element;
		}
		else {
		if (isNaN(selector)) {
		ele = $(selector, self.element);
		}
		else {
		index = selector;
		ele = self.element;
		}
		}
		self._add(item, ele, index);
		},

		_add: function (item, node, index) {
		var self = this, mode = self.options.mode,
		menuitem = self._buildItem(item);
		self._additem(menuitem, node, index);
		if (mode === "flyout") {
		self._killFlyout();
		self._flyout();
		}
		else {
		self._killDrilldown();
		self._drilldown();
		}
		},

		_buildItemObj: function (li) {
		var item = { text: "", header: false, separator: false };
		if (li.hasClass("wijmo-wijmenu-separator")) {
		item.separator = true;
		}
		else if (li.hasClass("ui-widget-header")) {
		item.header = true;
		item.text = li.text();
		} else if (li.hasClass("wijmo-wijmenu-item") && 
		li.children("a").length !== 0) {
		item.text = li.text();
		}
		return item;
		},

		_rebuildPath: function (ul, path) {
		if (path !== "") {
		path += "-";
		}
		$(">li", ul).each(function (i, n) {
		$(this).data("path", path + i.toString());
		});
		},

		_getItemByPath: function (path) {
		var items = { items: this.options.items }, i,
		paths = path.split('-');
		if (path === "") {
		return items.items;
		}
		for (i = 0; i < paths.length; i++) {
		items = items.items[parseInt(paths[i], 10)];
		//                if (jQuery.isArray(items)) {
		//				    items = items[parseInt(paths[i], 10)];
		//                } else {                    
		//				    items = items.items[parseInt(paths[i], 10)];
		//                }
		}
		return items;
		},

		_getItemIndex: function (path) {
		if (path === "") { 
		return 0; 
		}
		var paths = path.split('-');
		return parseInt(paths[paths.length - 1], 10);
		},

		_additem: function (item, node, index) {
		var sublist, menulink, menuitem, itemObj, currentObj,
		items, parentPath, parent, path,
		self = this;
		itemObj = self._buildItemObj(item);
		if (node.is("ul")) {
		parent = node;
		if (node.get(0) === self.element.get(0)) {
		parentPath = "";
		items = self.options.items;
		}
		else {
		parentPath = node.parent("li").data("path");
		items = self._getItemByPath(parentPath).items;
		}
		if (index === undefined || index === null || isNaN(index) || index < 0) {
		node.append(item);
		//rebuild path and node.                    
		items.push(itemObj);
		self._rebuildPath(parent, parentPath);
		}
		else {
		menuitem = node.children("li").eq(index);
		if (menuitem.length > 0) {
		menuitem.after(item);
		items.splice(index, 0, itemObj);
		}
		else {
		node.append(item);
		items.push(itemObj);
		}
		self._rebuildPath(parent, parentPath);
		}
		}
		else if (node.is("li.wijmo-wijmenu-item")) {
		sublist = node.children("ul");
		parentPath = node.data("path");
		currentObj = self._getItemByPath(parentPath);
		if (sublist.length === 0) {
		sublist = $("<ul></ul>")
		.addClass(listCss).appendTo(node);
		menulink = node.children("a." + linkCss);
		$("<span></span>").addClass("ui-icon ui-icon-triangle-1-e")
		.appendTo(menulink);
		sublist.append(item);
		currentObj.items = [];
		currentObj.items.push(itemObj);
		self._rebuildPath(sublist, path);
		}
		else {
		menuitem = sublist.children("li").eq(index);
		if (menuitem.length > 0) {
		items = currentObj.items;
		items.splice(index, 0, itemObj);
		menuitem.after(item);
		}
		else {
		sublist.append(item);
		items = currentObj.items;
		items.push(itemObj);
		}
		self._rebuildPath(sublist, path);
		}
		}
		},

		_buildItem: function (item) {
		var menuItem = $("<li></li>"),
		header, link, tempEle;
		if ($.isPlainObject(item)) {
		item = $.extend({}, item, { text: "item" });
		if (item.header) {
		header = $("<h3></h3>").text(item.text);
		item.addClass(headerCss);
		menuItem.append(header);
		}
		else if (item.separator) {
		item.addClass(separatorCss);
		}
		else {
		link = $("<a></a>").addClass(linkCss).addClass(cornerCss)
		.appendTo(menuItem);
		$("<span></spam>").addClass(textCss).text(item.text).appendTo(link);
		if (item.navigateUrl) {
		link.attr("link", item.navigateUrl);
		}
		item.addClass(menuItemCss);
		}
		}
		else {
		tempEle = $(item);
		if (tempEle.is("a")) {
		tempEle.addClass(linkCss).addClass(cornerCss);
		if (tempEle.children("span").length === 0) {
		tempEle.wrapInner("<span></span>").children().addClass(textCss);
		}
		else {
		tempEle.children("span").addClass(textCss);
		}
		menuItem.addClass(menuItemCss).append(tempEle);
		}
		else if (/<(h[1-7])>.*<\/\1>/.test(item)) {
		menuItem.addClass(headerCss).append(tempEle);
		}
		else {
		if (item === "") {
		menuItem.addClass(separatorCss);
		}
		}
		}

		menuItem.children(".wijmo-wijmenu-link")
		.bind("mouseenter.wijmenuitem", function () {
		$(this).addClass("ui-state-hover");
		}).bind("mouseleave.wijmenuitem", function () {
		$(this).removeClass("ui-state-hover");
		if ($(this).data("subMenuOpened")) {
		$(this).addClass("ui-state-active");
		}
		});
		return menuItem;
		},*/

		_markPath: function (owner) {
			var self = this, path = "";
			if (owner) {
				path = owner.parent("li").data("path");
			}
			else {
				owner = this.element;
			}
			if (path !== "") {
				path += "-";
			}
			$(">li", owner).each(function (i, n) {
				$(n).data("path", path + i.toString());
				var childOwner = $(n).children("ul");
				if (childOwner.length > 0) {
					self._markPath(childOwner);
				}
			});
		},

		_raiseClickEvent: function () {
			var _postBackEventReference = this.options.postBackEventReference;
			if (_postBackEventReference) {
				$(".wijmo-wijmenu-link", this.element).each(function () {
					var link = $(this), href, newRenference;
					if (link.is("a")) {
						href = link.attr("href");
						if (href === undefined) {
							return;
						}
						newRenference = _postBackEventReference
						.replace("_Args", "_ItemClick_" + link.parent("li").data("path"));
						href = href.replace(_postBackEventReference, newRenference);
						link.attr("href", href);
					}
				});
			}
		},

		_create: function () {
			//this.element.wijAssignOptionsFromJsonInput(this);
			this.element.removeClass("ui-helper-hidden-accessible");
			$.wijmo.wijmenu.prototype._create.apply(this, arguments);

			this._markPath();
			this._raiseClickEvent();
		}
	});
} (jQuery));