/*
1:
[
    {
        renderer: new DefaultMenuRenderer(),
        items: [
        
        ]
    }
]

2:
[
    { text: 'menu item 1', icon: 'http://www......' }
]
*/


var _defaultValues = [];

function Menu(config) {

    this._container = null;
	this._items = null;
    this._parent = null;
    this._renderer = null;
    this._parentDataItem = null;
	
	// css properties
	this._cls = null;
	this._itemcls = null;
	this._itemovercls = null;
	this._itemdisabledcls = null;
	this._itemdisabledovercls = null;
	this._iconcls = null;
	this._childmenuarrowcls = null;
	
	this._arrow_right = null;
	
	this._initailized = false;
	this._isDisplayed = false;
	
	// initialize
	if(config.renderer || config.items) {
		if(config.renderer)
			this.setRenderer(config.renderer);
		if(config.items)
			this._items = config.items;
			
		// other properties
		if(config.cls)
			this._cls = config.cls;
		if(config.itemcls)
			this._itemcls = config.itemcls;
		if(config.itemovercls)
			this._itemovercls = config.itemovercls;
		if(config.itemdisabledcls)
			this._itemdisabledcls = config.itemdisabledcls;
		if(config.itemdisabledovercls)
			this._itemdisabledovercls = config.itemdisabledovercls;
			
		if(config.rightarrow)
			this._arrow_right = config.rightarrow;
			
	} else {
		this._items = config;
	}
}

Menu._iTimerID = 0;
Menu._menuZIndexOrder = 1306;

// 获取菜单显示的容器
Menu.prototype.getContainer = function () {
	return this._container;
}

// 获取菜单的父菜单
Menu.prototype.getParent = function () {
    return this._parent;
}

// 设置菜单的父菜单
Menu.prototype.setParent = function (parent) {
    this._parent = parent;
}

// 获取菜单所属父级的数据项
Menu.prototype.getParentDataItem = function () {
    return this._parentDataItem;
}

// 设置菜单所属父级的数据项
Menu.prototype.setParentDataItem = function (item) {
    this._parentDataItem = item;
}

Menu.prototype.isDisplay = function() {
	return this._isDisplayed;
}

// 获取菜单的渲染器
Menu.prototype.getRenderer = function () {
    if (this._renderer)
        return this._renderer;

    var parent = this.getParent();
    if (parent != null)
        return parent.getRenderer();

    var renderer = new DefaultMenuRenderer();
    this.setRenderer(renderer);

    return renderer;
}

Menu.prototype.setRenderer = function (renderer) {
    this._renderer = renderer;
	this._renderer.setMenu(this);
}

Menu.prototype.getItems = function() {
	if(this._items != null)	
		return this._items;
		
	return [];
}

Menu.prototype.getRightArrow = function(){
	if(this._arrow_right != null)
		return this._arrow_right;
		
	if(this.getParent() != null)
		return this.getParent().getRightArrow();
		
	return null;
}
Menu.prototype.setRightArrow = function(arrow){
	this._arrow_right = arrow;	
}

// --------------------- css properties

// 菜单容器的 CSS
Menu.prototype.getCls = function(){
	if(this._cls != null)
		return this._cls;
		
	if(this.getParent() != null)
		return this.getParent().getCls();
		
	// else
	return null;
}
Menu.prototype.setCls = function(cls){
	this._cls = cls;
}

Menu.prototype.getItemCls = function(){
	if(this._itemcls != null)
		return this._itemcls;
		
	if(this.getParent() != null)
		return this.getParent().getItemCls();
		
	// else
	return null;
}
Menu.prototype.setItemCls = function(cls) {
	this._itemcls = cls;
}

Menu.prototype.getItemOverCls = function() {
	if(this._itemovercls != null)
		return this._itemovercls;
		
	if(this.getParent() != null)
		return this.getParent().getItemOverCls();
		
	// else
	return null;
}
Menu.prototype.setItemOverCls = function(cls) {
	this._itemovercls = cls;
}

Menu.prototype.getItemDisabledCls = function() {
	if(this._itemdisabledcls != null)
		return this._itemdisabledcls;
		
	if(this.getParent() != null)
		return this.getParent().getItemDisabledCls();
		
	// else
	return null;
}
Menu.prototype.setItemDisabledCls = function(cls) {
	this._itemdisabledcls = cls;
}

Menu.prototype.getItemDisabledOverCls = function() {
	if(this._itemdisabledovercls != null)
		return this._itemdisabledovercls;
		
	if(this.getParent() != null)
		return this.getParent().getItemDisabledOverCls();
		
	// else
	return null;
}
Menu.prototype.setItemDisabledOverCls = function(cls) {
	this._itemdisabledovercls = cls;
}

Menu.prototype.getIconCls = function() {
	if(this._iconcls != null)
		return this._iconcls;
		
	if(this.getParent() != null)
		return this.getParent().getIconCls();
		
	// else
	return null;
}
Menu.prototype.setIconCls = function(cls) {
	this._iconcls = cls;
}

Menu.prototype.getChildMenuArrowCls = function() {
	if(this._childmenuarrowcls != null)
		return this._childmenuarrowcls;
		
	if(this.getParent() != null)
		return this.getParent().getChildMenuArrowCls();
		
	// else
	return null;
}
Menu.prototype.setChildMenuArrowCls = function(cls) {
	this._childmenuarrowcls = cls;
}
// --------------------- end

Menu.prototype.show = function (xy) {
	if(!this._intialized){
		this._initialize();
		this._intialized = true;
		
		if(this.getParent() == null){
			Menu._topMenus.push(this);	
		}

		for(var i = 0; i < this.getItems().length; i++) {
			Menu.setDefaultValue(this.getItems()[i]);
		}
	}
	
	for(var i = 0; i < this.getItems().length; i++){	
		/*if(this.getItems()[i].checked) {
			this.getItems()[i].dom.className = this.getItemDisabledCls();
		} else {
			this.getItems()[i].dom.className = this.getItemCls();
		}*/
		Menu.setItemDefaultCls(this.getItems()[i], false);
	}
	
    var mx = 0;
    var my = 0;

    if (this.getParent()) {
		var pp = this.getParent();
        var pContainer = this.getParent().getContainer();
		var pWidth = pContainer.offsetWidth;
		if(pp.getItems().length > 10 && this.getParentDataItem().odd == 1) {
			pWidth = pWidth / 2;
		}
        mx = pContainer.style.pixelLeft + pWidth - 5;
        my = pContainer.style.pixelTop + 2;
		
        my += this.getRenderer().getItemOffsetTop(this.getParentDataItem().dom);

    } else {
		if(xy) {
			mx = xy.x;
			my = xy.y;
		} else {
			mx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			my = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
		}
    }

    this.getContainer().style.display = 'block';

    var mbx = document.body.offsetWidth + document.body.scrollLeft + document.documentElement.scrollLeft;
    var mby = document.body.offsetHeight + document.body.scrollTop + document.documentElement.scrollTop;
    var mmw = this._container.offsetWidth;
    var mmh = this._container.offsetHeight;

    if (mx + mmw > mbx) {
        if (this.getParent()) {
            mx = this.getParent().getContainer().style.pixelLeft - this.getContainer().offsetWidth + 5;
        } else {
            mx = mx - mmw;
        }
    }

    if (my + mmh > mby) {
		my = my + mmh - mby - 10
        //my = my - mmh;
       // if (this.getParentDataItem()) {
        //    my += this.getParentDataItem().dom.offsetHeight + 3;
       // }
    }


    this.getContainer().style.left = mx;
    this.getContainer().style.top = my;
	
	this.hideChildMenus();
	this._isDisplayed = true;
}

Menu.prototype.hide = function() {
	this.getContainer().style.display = 'none';	
	this.hideChildMenus();
	this._isDisplayed = false;
}

Menu.prototype.hideChildMenus = function() {
	for (var i = 0; i < this.getItems().length; i++) {
        var childMenu = this.getItems()[i].childMenu;
        if (childMenu) {
            childMenu.hide();
        }
    }
}

Menu.prototype._initialize = function () {

    this._container = this.getRenderer().renderContainer();
	this._container.style.zIndex = Menu._menuZIndexOrder++;
	this._container.onselectstart = function() { return false; }

    for (var i = 0; i < this.getItems().length; i++) {
        var di = this.getItems()[i];
        var dom = this.getRenderer().renderItem(di);

        // 
		di.odd = (i + 1) % 2;
        dom.dataitem = di;
        di.dom = dom;
        di.menu = this;

        // attach events
        dom.onmouseover = Menu._menuItemMouseOver;
        dom.onmouseout = Menu._menuItemMouseOut;
        dom.onmouseup = Menu._menuItemClick;

		if(this.getItems().length > 10) {
			dom.style.float = 'left';
			dom.style.width = Menu._width+ 'px';
		}
    }

	if(document.body.childNodes.length == 0)
		document.body.appendChild(this._container);
	else
	    document.body.insertBefore(this._container, document.body.childNodes[0]);
		
	if(this.getItems().length > 10) {
		this._container.style.width = (Menu._width * 2 + 4) + 'px';
	} else {
		this._container.style.width = Menu._width + 'px';
	}
}

Menu._menuItemMouseOver = function () {
	clearTimeout(Menu._iTimerID);
	var menu = this.dataitem.menu.hideChildMenus();

	if(this.dataitem.title == '-')
		return ;

	Menu.showChildMenu(this.dataitem);
	if(this.dataitem.dom.iocls)
		this.dataitem.dom.className = this.dataitem.dom.iocls;
	else
		this.dataitem.dom.className = this.dataitem.menu.getItemOverCls();
}

Menu.showChildMenu = function (dataitem, xy) {

    if (dataitem.children) {
        if (dataitem.childMenu) {
            dataitem.childMenu.show(xy);
        } else {
            dataitem.childMenu = new Menu(dataitem.children);
            dataitem.childMenu.setParent(dataitem.menu);
            dataitem.childMenu.setParentDataItem(dataitem);

            dataitem.childMenu.show(xy);
        }
    }
}

Menu._topMenus = [];

Menu._menuItemMouseOut = function () {
	if(this.dataitem.title == '-')
		return ;
	
	// if(this.dataitem.checked)
	Menu.setItemDefaultCls(this.dataitem, false);
	//if(Menu.setItemDefaultCls(this.dataitem, false))
	//	this.className = this.dataitem.menu.getItemDisabledCls();
	//else
	//	this.className = this.dataitem.menu.getItemCls();
	Menu._iTimerID = setTimeout('Menu.hideAllTopMenus()', 2000);
}

Menu._menuItemClick = function () {
	event.returnValue = false;
	event.cancelBubble = true;

	if(event.srcElement.tagName == 'INPUT');
		return ;
	
	if(this.dataitem.title == '-')
		return ;
		
	if(!this.dataitem.disabled){
		if(this.dataitem.click){
			Menu.hideAllTopMenus();
			this.dataitem.click.call(this.dataitem);
		} else if(!this.dataitem.children) {
			Menu.hideAllTopMenus();
		}
	}
}

Menu.hideAllTopMenus = function(){
	for(var i = 0; i < Menu._topMenus.length; i++){
		Menu._topMenus[i].hide();	
	}
}
Menu.init = function(){
	window.attachEvent('onload', function(){
		document.body.attachEvent('onmouseup', Menu.hideAllTopMenus)									  
	});
}

Menu.hasParentSelected = function(item) {
	if(!item.menu)
		return false;

	var pItem = item.menu.getParentDataItem();
	while(pItem != null){
		if(pItem.checked)
			return true;

		if(pItem.menu == null)
			return false;

		pItem = pItem.menu.getParentDataItem();
	}

	return false;
}

Menu.setItemChildSelectedCnt = function(item, cnt) {
	if(!item.childSelectedCnt) {
		item.childSelectedCnt = 0;
	}

	item.childSelectedCnt += cnt;
	Menu.setItemDefaultCls(item, false);
	if(!item.menu)
		return ;
	if(item.menu.getParentDataItem() != null) {
		Menu.setItemChildSelectedCnt(item.menu.getParentDataItem(), cnt);
	}
}

Menu.setItemDefaultCls = function(item, tg) {
	var csc = 0;
	if(item.childSelectedCnt) {
		csc = item.childSelectedCnt;
	}

	if(item.checked || csc > 0 || Menu.hasParentSelected(item)){
		if(item.dom.idcls)
			item.dom.className = item.dom.idcls;
		else
			item.dom.className = 'itemdisabledcls';	
	} else {
		if(item.dom.icls)
			item.dom.className = item.dom.icls;
		else
			item.dom.className = 'itemcls';
	}

	if(item.checked || Menu.hasParentSelected(item)) {
		item.checkboxDom.checked = true;
	} else {
		item.checkboxDom.checked = false;
	}
	if(Menu.hasParentSelected(item)) {
		item.checkboxDom.disabled = true;
		item.checked = false;
	} else {
		item.checkboxDom.disabled = false;
	}

	if(tg) {
		if(item.menu && item.menu.getParentDataItem() != null) {
			Menu.setItemDefaultCls(item.menu.getParentDataItem());
		}
	}
}

Menu.unCheckbox = function(item) {
	item.checkboxDom.checked = false;
	item.checkboxDom.onclick();
	// alert(item.checkboxDom.checked);
}

Menu.setDefaultValue = function(item) {
	var code = item.code;
	item.childSelectedCnt = 0;
	for(var i = 0; i < _defaultValues.length; i++) {
		if(_defaultValues[i].code){
			if(code.length <= _defaultValues[i].code.length){
				if(code == _defaultValues[i].code) {
					item.childSelectedCnt = 0;
					item.checked = true;
					Menu._checkboxClick(item);
					return ;
				}

				var tmp = _defaultValues[i].code.substring(0, code.length);
				if(tmp == code) {
					item.childSelectedCnt += 1;
				}
			}
		}
	}
}

function Menu._getPos(obj) {
	var posX = obj.offsetLeft + obj.offsetWidth - 5;
	var posY = obj.offsetTop;
	var aBox = obj;
	do {
		aBox = aBox.offsetParent;
		posX += aBox.offsetLeft;
		posY += aBox.offsetTop;
	} while( aBox.tagName != "BODY" );

	//posX += document.body.scrollLeft + document.documentElement.scrollLeft;
	//posY += document.body.scrollTop + document.documentElement.scrollTop;
	var o = new Object();
	o.x = posX;
	o.y = posY;

	return o;
}

Menu._checkboxClick = function(item) {
	var win = getCurrentLayerWindow();
	if(item.checked) {
		var c = document.createElement('div');
		c.dataitem = item;
		c.style.styleFloat = "left";
		c.innerHTML = '<table border=0 cellspacing=1 cellpadding=2><tr><td>' + item.title + '</td><td onclick=Menu.delSelItem(this) style="cursor:hand"><img src="images/del.gif"></td></tr></table>';
		win.get_slPanel().appendChild(c);
	} else {
		var slPanel = win.get_slPanel();
		for(var i = 0; i < slPanel.children.length; i++) {
			if(slPanel.children[i].dataitem == item) {
				slPanel.removeChild(slPanel.children[i]);
			}
		}
	}

	if(win.get_slPanel().children.length > Menu._maxItems) {
		Menu.unCheckbox(item);
		alert('最多选择 ' + Menu._maxItems + ' 项');
		return ;
	}
}

function Menu.delSelItem(obj) {
	var tmp = obj;
	while(!tmp.dataitem) {
		tmp = tmp.parentElement;
		if(tmp == null)
			return ;
	}

	var win = getCurrentLayerWindow();
	Menu.unCheckbox(tmp.dataitem);
	// Menu.setItemDefaultCls(tmp.dataitem, false);
	// win.get_slPanel().removeChild(tmp);
}

function Menu.createTopCheckboxClick(item) {
	return function() {
		event.cancelBubble = true;

		item.checked = this.checked;
		if (item.children) {
			if (item.childMenu && item.childMenu.isDisplay()) {
				// dataitem.childMenu.show(xy);
				// Menu.showChildMenu(item);
				var pos = Menu._getPos(item.dom);
				Menu.showChildMenu(item, pos);
			}
		}
		//var pos = getPos(item.dom);
		//Menu.showChildMenu(item, pos);
		Menu.setItemDefaultCls(item, false);

		if(Menu._checkboxClick) {
			Menu._checkboxClick(item);
		}
	}
}

function Menu.createDictItems(params) {
	var items = params.items;
	for(var i = 0; i <items.length; i++) {
		var item = items[i];
		Menu.setDefaultValue(item);

		var colw = (100 / params.columns - 0.1) + '%'
		var div = document.createElement('div');
		div.className = 'dictItem';
		div.style.styleFloat = "left";
		div.style.width = colw;
		div.dataitem = item;
		item.dom = div;

		div.idcls = 'ddictItem';
		div.icls = 'dictItem';
		div.iocls = 'odictItem';

		div.onmouseover = function() {
			for(var j = 0; j < items.length; j++) {
				if(items[j].childMenu) {
					items[j].childMenu.hide();
				}

				this.className = 'odictItem';
			}

			if(this.dataitem.children) {
				if(this.mm) {
					this.mm.show(Menu._getPos(this));
				} else {
					this.mm = Menu.createOffice2007Menu(this.dataitem.children);
					this.dataitem.childMenu = this.mm
					this.dataitem.childMenu.setParentDataItem(this.dataitem);
					this.mm.show(Menu._getPos(this));
				}
			}
		}

		div.onmouseout = function() {
			event.returnValue = false;
			event.cancelBubble = true;
			var csc = 0;
			if(this.dataitem.childSelectedCnt) {
				csc = this.dataitem.childSelectedCnt;
			}
			if(this.dataitem.checked || csc > 0) {
				this.className = 'ddictItem';
			} else {
				this.className = 'dictItem';
			}
		}

		// document.getElementById('dictPanel').appendChild(div);
		params.container.appendChild(div);
		var table = document.createElement('<table border=0 cellspacing=1 cellpadding=2 class="di" tableLayout="fixed">');
		div.appendChild(table);

		var tr = table.insertRow();
		
		var icontd = document.createElement('td');
		icontd.className = 'dichk';
		var box = document.createElement('input');
		box.type = 'checkbox';
		box.onclick = Menu.createTopCheckboxClick(item);
		icontd.appendChild(box);
		item.checkboxDom = box;

		tr.appendChild(icontd);
	
		var tltd = document.createElement('td');
		tltd.className = 'title';
		tltd.innerHTML = item.title;
		tr.appendChild(tltd);
		
		var arrtd = document.createElement('td');
		arrtd.className = 'diarr';
		if (item.children) {
			arrtd.className = "diarr diarr2";
		}

		tr.appendChild(arrtd);
		Menu.setItemDefaultCls(item, false);
		if(!Menu._topLevelAvai) box.style.display = 'none';
	}
}

function Menu.createSelWnd(params) {
	var win = createLayerWindow(params);
	Menu._maxItems = params.maxItems || 5; // default for max 5 items.
	Menu._width = params.menuWidth || 150;
	Menu._topLevelAvai = true;
	if(!params.topLevelAvai) Menu._topLevelAvai = false;
	params.container = win.get_contentPanel();
	params.columns = params.columns || 2;
	Menu.createDictItems(params);

	return win;
}

Menu.createOffice2007Menu = function(items){
	return new Menu({

		renderer: new Office2007MenuRenderer(),
		cls: 'menucls',
		itemcls: 'itemcls',
		itemovercls: 'itemovercls',
		itemdisabledcls: 'itemdisabledcls',
		itemdisabledovercls: 'itemovercls',
		
		rightarrow: 'rightarrow',
		items: items
	});
}

Menu.init();
