/**
 * menu_Tmv1 v3.77 - Tree Menu Variant 1
 * Author 2007-2008 Oleg V. Lubarsky aka Dr.LOV
 * Copyright (c) 2008 CREATIVE ZONE Studio (http://www.cz-site.com/)
 * 
 * @usage:
 *
 */

(function(){
	var $$ = $.menu_Tmv1 = function (options) {
		this.options = $.extend({}, $$.options, options||{});
	};
	$$.arrMenus = [];
	$$._onClickFromFlash = function(arrIdx,divId) {
		var _t = $$.arrMenus[arrIdx];
		if (_t) _t.onClickItem(divId);
	};
	$$.options = {
		type          : "xml", // | sql
		db_table      : "",
		xml_url       : null,
		xml_tagname   : "",
		xml_id        : "",
		data_url      : null,
		langid        : "",
		prefix        : "",
		minopenlevel  : 1,
		cutlinelevel  : 1,
		cutlineid     : "cutline",
		showdir       : "height",
		speed         : 300, // | false
		name          : "menuitem",
		subsearch     : 2,
		activeId      : "",
		flashparam    : [],
		isFlash       : false,
		isIndent      : true,
		isAutoHide    : true,
		isCutline     : true,
		isCache       : false,
		isGlobal      : true,
		onClickItem   : null,
		onClickNode   : null,
		onMake        : null
	};
	$$.prototype = {
		arrIdx      : 0,
		options     : {},
		place       : null,
		xml_dom     : null,
		xml_node    : null,
		divs        : null,
		isLoading   : false,
		_lastActive : null,
		load : function(options) {
			var _t = this;
			_t.isLoading = true;
			_t.options = $.extend({}, _t.options, options||{});
			_t.options.activeId = $.file.delBoundSlash(_t.options.activeId);
			$(_t.place).hide();
			var data = {action      : "printMenuXml",
						type        : _t.options.type,
						db_table    : _t.options.db_table,
						xml_url     : _t.options.xml_url,
						xml_tagname : _t.options.xml_tagname,
						xml_id      : _t.options.xml_id,
						langid      : _t.options.langid,
						prefix      : _t.options.prefix};
			$.ajax({async:true, type:"GET", dataType:"xml", cache:_t.options.isCache, global:_t.options.isGlobal, data:data, url:_t.options.data_url, complete:function(xml,status){
					_t.isLoading = false;
					if (status=="success") {
						_t.xml_dom = xml.responseXML;
						if (_t.options.xml_id) {
							_t.xml_node = $.XML.xpath(_t.xml_dom,'//*[@id="'+_t.options.xml_id+'"]')[0];
						} else {
							_t.xml_node = $(_t.options.xml_tagname,_t.xml_dom)[0];
						}
						_t.make();
					} else {
					
						$.errors.trigger($.errors.ERROR, "Cannot load menu xml [func: $.menu_Tmv1.make]");
					}
				}
			});
		},
		make : function(options) {
			var _t = this, md;
			_t.options = $.extend({}, _t.options, options||{});
			_t.options.activeId = $.file.delBoundSlash(_t.options.activeId);
			var parseNode = function(node,level,flag) {
				var type, cnode, text, id, parentid, href;
				for (var i=0; i<node.childNodes.length; i++) {
					cnode = node.childNodes[i];
					type = cnode.nodeType;
					if (type == $.XML.ELEMENT_NODE) {
						parseNode(cnode, level+1, cnode.childNodes.length>1);
					} else if (type >= $.XML.TEXT_NODE && level>0) {
						text = $.trim(cnode.nodeValue);
						if (text.length>0) {
							id = $(node).attr("id");
                                                        if($("#citylist").attr('id') !=undefined)                                               
                                                          if( new RegExp("goods\/type\/cities").exec(id) != null)
                                                              continue;
                                                      
							img =  $(node).attr("img");
                                                        good_type=  $(node).attr("good_type");
							parentid = $(node.parentNode).attr("id");
							href = _t._formatHref(id);
							$(_t.place).append(_t.getItem(id,parentid,level,text,!flag,false,img,good_type));



						}
					}
				}
			};
			$(_t.place).empty().hide();
			if (_t.xml_node) {
				parseNode(_t.xml_node,0,false);
				var level = 1;
				var parentid = _t.xml_tagname;
				$("div",_t.place).each(function(){
					md = $(this).metaData("attr","data");
					if (md.level>_t.options.minopenlevel) $(this).hide();
					if (!md.iscont && md.level<_t.options.minopenlevel) $("*",this).replaceClass(_t.options.name+"_open",_t.options.name+"_close");
					if (_t.options.isCutline && md.level < level && md.level<=_t.options.cutlinelevel) {
						var cut = $(this).before(_t.getItem(_t.options.cutlineid,parentid,level," ",true)).prev();
						if (level>_t.options.minopenlevel) cut.hide();
					}
					level = md.level;
					parentid = md.parentid;
				});
			}
			_t.setChanges();
			if (_t.options.speed) {
				$(_t.place).slideDown(_t.options.speed);
			} else {
				$(_t.place).show();
			}
			if (_t.options.onMake) _t.options.onMake();
		},
		setChanges : function() {
			var _t = this;
			_t.divs = $("div",_t.place);
			$("div a",_t.place).bind("click", {_t:_t}, _t._onClickA);
		},
		onClickItem : function(id) {
			var _t = this, res, tmp, md, isShow, isHide, arrShow=[], arrHide=[];
			if (_t.isLoading) return;
			res = _t.findDivById(id);
			if (res == null) return;
			if (res.md.iscont && _t.options.onClickItem) {
				return _t.options.onClickItem(res.md.id, res.md);
			} else {
				_t.divs.each(function(){
					isShow = false;
					isHide = false;
					md = $(this).metaData("attr","data");
					if (md.level == 1) return;
					if (md.parentid==res.md.id) {
						if ($(this).is(":visible")) isHide = true;
						else isShow = true;
					} else {
						if (_t.options.isAutoHide) {
							isHide = (md.level>=(res.md.level+1));
						} else {
							tmp = md;
							do {
								tmp = _t.findDivById(tmp.parentid);
								if (!tmp) break;
								tmp = tmp.md;
								 if (res.md.id==tmp.id) {
								 	isHide = true;
									break;
								}
							} while (true);
						}
					}
					if (isHide && md.level>_t.options.minopenlevel) {
						arrHide.push(this);
					} else if (isShow) {
						arrShow.push(this);
					}
				});
				_t.animate(arrShow,arrHide);
				if (_t.options.onClickNode) return _t.options.onClickNode(res.md.id, res.md);
			}
		},
		setCurrItem : function(id) {
			var _t = this, res, md, is, arr=[], arrHide=[], arrShow=[];
			if (_t.isLoading) return false;
			res = _t.findDivById(id);
			if (!res) {
				id = $.file.getPath(id);
				for (var i=0; i<_t.options.subsearch; i++) {
					res = _t.findDivById(id);
					if (res) break;
					id = $.file.parentFolder(id);
				}
				if (!res) {
					_t.closeAllItems();
					return false;
				}
			}
			var ares = res;
			do {
				arr.push(res);
				res = _t.findDivById(res.md.parentid);
			} while (res!=null);
			_t.divs.each(function(){
				md = $(this).metaData("attr","data");
				if (md.level == 1) return;
				is = false;
				for (var i=0; i<arr.length; i++) {
					if (arr[i].md.parentid == md.parentid) {
						is = true;
						break;
					}
				}
				if (is) {
					arrShow.push(this);
				} else {
					if (_t.options.isAutoHide && md.level>_t.options.minopenlevel) arrHide.push(this);
				}
			});
			_t.animate(arrShow,arrHide);
			_t.delActive();
			_t.setActive(ares);
			return true;
		},
		clickFirstItem : function() {
			var _t = this, md;
			md = $(_t.divs[0]).metaData("attr","data");
			setTimeout(function(){_t.onClickItem(md.id,md);},50);
		},
		closeAllItems : function (level) {
			var _t = this, md, arrShow=[], arrHide=[];
			if (_t.isLoading) return;
			level = level || _t.options.minopenlevel;
			_t.divs.each(function(){
				md = $(this).metaData("attr","data");
				if (md.level > level) arrHide.push(this);
			});
			_t.delActive();
			_t.animate(arrShow,arrHide);
		},
		animate : function (arrShow,arrHide) {
			var _t = this, md, res;
			if (_t.options.speed) {
				var hide={}, show={};
				hide[_t.options.showdir]="hide";
				show[_t.options.showdir]="show";
				$(arrHide).animate(hide,_t.options.speed);
				$(arrShow).animate(show,_t.options.speed);
			} else {
				$(arrHide).hide();
				$(arrShow).show();
			}
			$(arrShow).each(function(){
				md = $(this).metaData("attr","data");
				res = _t.findDivById(md.parentid);
				if (res) $("*",res.div).replaceClass(_t.options.name+"_open",_t.options.name+"_close");
			});
			$(arrHide).each(function(){
				md = $(this).metaData("attr","data");
				res = _t.findDivById(md.parentid);
				if (res) $("*",res.div).replaceClass(_t.options.name+"_close",_t.options.name+"_open");
			});
		},
		setActive : function(res) {
			var _t = this;
			if (_t.options.isFlash) {
				setTimeout(function(){
					$.Flash.setVariable(_t._formatFlashId(res.md.id),"active","true");
				}, 300);
			} else {
				$("a",res.div).addClass(_t.options.name+"_active").addClass(_t.options.name+"_active"+res.md.level);
			}
			_t._lastActive = res;
		},
		delActive : function(res) {
			var _t = this;
			if (!res) {
				res = _t._lastActive;
				_t._lastActive = null;
			}
			if (res) {
				if (_t.options.isFlash) {
					setTimeout(function(){
						$.Flash.setVariable(_t._formatFlashId(res.md.id),"active","false");
					}, 300);
				} else {
					$("a",res.div).removeClass(_t.options.name+"_active").removeClass(_t.options.name+"_active"+res.md.level);
				}
			}
		},
		isActive : function(id) {
			var _t = this;
			return _t._lastActive ? _t._lastActive.md.id==id : false;
		},
		findDivById : function (id) {
			var _t = this, seek="";
			if (id) {
				id = $.file.delBoundSlash(id);
				seek = $.file.isFile(id) ? "fullid" : "pathid";
				for (var i=0; i<_t.divs.length; i++) {
					if (_t.divs[i][seek] == id) {
						return {div:_t.divs[i], md:$(_t.divs[i]).metaData("attr","data")};
					}
				}
			}
			return null;
		},
		findDivByIndex : function (i) {
			var _t = this;
			return i>=_t.divs.length ? null : {div:_t.divs[i], md:$(_t.divs[i]).metaData("attr","data")};
		},
		findNodeById : function (id) {
			var _t = this;
			return $("[id="+id+"]",_t.xml_node)[0];
		},
		getItem : function (id,parentid,level,text,iscont,isclose,img,good_type) {
			var _t = this, div, md, s, ss="", iscut = (id==_t.options.cutlineid), isactive;
			if (!iscut) {
				id = _t._formatId(id);
				parentid = _t._formatId(parentid);
			}
			div = $.create("div",{"class":_t.options.name+(iscut?"_cutline":"_div")})[0];
			md = $(div).metaData("attr","data");
			md.id = id;
			div.fullid = id;
			div.pathid = $.file.delEndSlash($.file.getPath(id));
			md.level = level;
			md.parentid = parentid;
			md.text = text;
			if ( img )
			{
			md.img = img;
			}
			else md.img = "";

                        if ( good_type )
                            md.good_type = good_type;
                        else md.good_type = "";
			
			md.iscont = iscont;
			isactive = _t.options.activeId == ($.file.isFile(_t.options.activeId) ? div.fullid : div.pathid);
			if (!iscut) {
				if (_t.options.isFlash) {
					var url = "media/"+_t.options.name;
					var fp = _t.options.flashparam[level];
					if (fp) {
						url += level;
					} else {
						fp = _t.options.flashparam[0];
						url += 0;
					}
					fp.url = url+".swf";
					fp.id = _t._formatFlashId(id);
					s = $.Flash.getHTML(fp, {text:$.langs.str(text), level:level, arrIdx:_t.arrIdx, divId:id, callback:"$.menu_Tmv1._onClickFromFlash", active:isactive?"true":"false"});
					
				} else {
					if (_t.options.isIndent) {
						for (var i=0; i<level; i++) ss+="&nbsp;&nbsp;&nbsp;&nbsp;"
					}
					if (!iscont && level < _t.options.minopenlevel) {
						s = '<span class="'+_t.options.name+' '+_t.options.name+level+' '+(iscont?"":_t.options.name+(isclose?'_close':'_open'))+'">'+ss+$.langs.str(text)+'</span>';
					} else {
						s = '<a href="'+_t._formatHref(id)+'" class="'+_t.options.name+' '+_t.options.name+level+' '+(iscont?"":_t.options.name+(isclose?'_close':'_open'))+'">'+ss+$.langs.str(text)+'</a>';
					}
				}
			} else {
				s = "&nbsp;"
			}
			$(div).append(s);
			if (isactive) _t.setActive({div:div,md:md});
			return div;
		},
		_onClickA : function(e) {
			var _t = e.data._t;
			this.blur();
			if (_t.isLoading) return false;
			var md = $(this).parent("div").metaData("attr","data");
			return _t.onClickItem(md.id)==true ? true : false;
		},
		_formatId : function (id) {
			var _t = this;
			if (_t.options.prefix) id = $.file.addEndSlash(_t.options.prefix) + $.file.delBoundSlash(id);
			return id;
		},
		_formatHref : function (id) {
			var _t = this, id = $.file.addStartSlash(id);
			if (!$.file.isFile(id)) id = $.file.addEndSlash(id);
			return id;
		},
		_formatFlashId : function (id) {
			var _t = this;
			id = $.file.delEndSlash($.file.getPath(id));
			id = id.replace(/\//gi, "_");
			return _t.options.name+"_swf_"+id;
		}
	};	
	$.fn.extend({
		menu_Tmv1: function(options, isNotLoad) {
			return this.each(function() {
				if (this.menu_Tmv1) return;
				var _t = new $$(options);
				$$.arrMenus.push(_t);
				_t.arrIdx = $$.arrMenus.length-1;
				_t.place = this;
				if (!isNotLoad) _t.load();
				this.menu_Tmv1 = _t;
			});
		}
	});
})();
