/**
 * Widgets for "jQuery" framework
 * Author 2007-2008 Oleg V. Lubarsky aka Dr.LOV
 * Copyright (c) 2008 CREATIVE ZONE Studio (http://www.cz-site.com/)
*/



/**
 * Tooltip v2.5
 * 
 * @usage:
 *   $(".tooltip").Tooltip({tipboxid:"#tooltipbox"});
 *   $("a.btn").Tooltip({tipboxid:"#tooltipboxa", attr:"href", killattr:false});
 */
(function(){
	var $$ = $.Tooltip = function (options) {
		this.options = $.extend({}, $$.options, options);
	};
	$$.options = {
		tipboxid  : "#tooltip",
		messageid : ".message",
		shiftx    : 5,
		shifty    : 20,
		zindex    : 3000,
		cursor    : "help",
		speed     : false,
		delay     : 300,
		follow    : true,
		attr      : "title",
		killattr  : true,
		onshow    : null,
		onhide    : null,
		onmove    : null
	};
	$$.prototype = {
		options   : {},
		message   : "",
		pos       : null,
		timeid    : null,
		mouseover : function (e) {
			var _t = e.data._t;
			_t.pos = {x:e.pageX, y:e.pageY};
			if (!_t.options.onshow || (_t.options.onshow && _t.options.onshow(_t))) {
				if (_t.options.delay) _t.timeid = setTimeout(function(){_t.show()}, _t.options.delay);
				else _t.show();
				$().bind("mousemove",{_t:_t},_t.mousemove);
			}
		},
		mousemove : function (e) {
			var _t = e.data._t;
			if (_t.options.follow) {
				_t.pos = {x:e.pageX, y:e.pageY};
				_t.place();
			}
		},
		mouseout : function (e) {
			var _t = e.data._t;
			_t.hide();
		},
		place : function () {
			var _t = this;
			_t.tx = _t.ty = 0;
			//if (!$(_t.options.tipboxid).is(":visible")) return;
			$(_t.options.tipboxid+" "+_t.options.messageid).html(_t.message);
			var ts = {w:$(_t.options.tipboxid).outerWidth(), h:$(_t.options.tipboxid).outerHeight()};
			var ws = {w:$(window).width(), h:$(window).height()};
			var wss = {x:$(window).scrollLeft(), y:$(window).scrollTop()};
			var x = _t.pos.x + _t.options.shiftx;
			var y = _t.pos.y + _t.options.shifty;
			if (x+ts.w > ws.w+wss.x-5) {
				x = _t.pos.x-ts.w-_t.options.shiftx;
				_t.tx = 1;
			}
			if (y+ts.h > ws.h+wss.y-5) {
				y = _t.pos.y-ts.h-(_t.options.shifty>>1);
				_t.ty = 1;
			}
			if (_t.options.onmove) _t.options.onmove(_t,_t.tx,_t.ty);
			$(_t.options.tipboxid).css({left:x,top:y});
		},
		show : function () {
			var _t = this;
			_t.timeid = null;
			$(_t.options.tipboxid).show(_t.options.speed);
			_t.place();
			//$(_t.options.tipboxid+" "+_t.options.messageid).html(_t.message);
			_t.isshow = true;
		},
		hide : function () {
			var _t = this;
			if (_t.timeid) {
				clearTimeout(_t.timeid);
				_t.timeid = null;
			}
			if (_t.options.onhide) _t.options.onhide(_t);
			$(_t.options.tipboxid).hide(_t.options.speed);
			$().unbind("mousemove",_t.mousemove);
			_t.isshow = false;
		}
	};	
	$.fn.extend({
		Tooltip: function(options) {
			return this.each(function() {
				if (this.Tooltip) return;
				var _t = new $$(options);
				$(_t.options.tipboxid).hide().css({"position":"absolute", "zIndex":_t.options.zindex});
				if ($(this).attr(_t.options.attr)) {
					_t.message = $(this).attr(_t.options.attr);
					_t.tx = _t.ty = 0;
					_t.isshow = false;
					if (_t.options.killattr) $(this).removeAttr(_t.options.attr);
					if (_t.options.cursor) $(this).css("cursor",_t.options.cursor);
					$(this).bind("mouseover",{_t:_t}, _t.mouseover).bind("mouseout",{_t:_t},_t.mouseout);
					this.Tooltip = _t;
				}
			});
		}
	});
})();



/**
 * Treeview v1.04
 * 
 * @usage:
 *   $("#mytree").Treeview{{onclickitem: function(a,t) {}, isclicknode: true}); // where: a - link element, t - li element
 *   $("#mytree").TreeviewSetActive(idofelement, "metadata", md_type, md_name, "id"); 
 * 
 * Based on:
 *   Treeview v1.5 - Jörn Zaefferer, Myles Angell
 */
(function(){
	var $$ = $.treeview = {
		options : {
			collapsed   : true,
			speed       : false,
			ontoggle    : null,
			isclicknode : false,
			onclickitem : null
		},
		classes : {
			treeview        : "treeview",
			open            : "open",
			closed          : "closed",
			expandable      : "expandable",
			collapsable     : "collapsable",
			lastCollapsable : "lastCollapsable",
			lastExpandable  : "lastExpandable",
			last            : "last",
			hitarea         : "hitarea"
		},
		hitareacss : {
			height      : 15,
			width       : 15,
			marginLeft  : "-15px",
			marginRight : "-2px",
			"float"     : "left",
			cursor      : "pointer",
			display     : "inline"
		}
	};

	$.fn.extend({
		Treeview: function(options, classes) {
			options = $.extend({}, $$.options, options || {});
			classes = $.extend({}, $$.classes, classes || {});
			return this.each(function() {
				var list = this;
				$(list).addClass(classes.treeview);
				$("li:last-child", list).addClass(classes.last);
				if ($.browser.msie) $.extend($$.hitareacss, {background:"#fff", filter:"alpha(opacity=0)"});
				function _toggler() {
					$(this).parent()
						.swapClass(classes.collapsable, classes.expandable )
						.swapClass(classes.lastCollapsable, classes.lastExpandable )
						.find("ul")
						.toggle(options.speed, options.ontoggle?options.ontoggle($(this).parent()[0]):null);
				}
				var li = $("li", list).filter(function(){return $(this).children("ul").length;});
				li.filter(":has(ul:hidden)")
					 .addClass(classes.expandable)
					 .replaceClass(classes.last, classes.lastExpandable)
					 .end()
				   .filter(":has(ul:visible)")
					 .addClass(classes.collapsable)
					 .replaceClass(classes.last, classes.lastCollapsable)
					 .end()
				   .prepend("<div class=\"" + classes.hitarea + "\"></div>")
				   .find("div."+classes.hitarea)
					  .css($$.hitareacss)
					  .toggle(_toggler, _toggler);

				if (options.onclickitem) {
					var li = $("li", list).filter(function(){return !($(this).children("ul").length);});
					li.each( function(){
						var s = $(this).text();
						$(this).html("<a class='item' href='#"+s+"'>"+s+"</a>").find("a.item").click(function(){
							this.blur();
							var list = $(this).metaData().list;
							if (list.active) $(list.active).removeClass("active");
							$(this).addClass("active");
							list.active = this;
							options.onclickitem($(this).text(),$(this).parent());
							return false;
						}).metaData().list = list;
					});
					if (options.isclicknode) {
						li.each( function(){
							var s = this.childNodes[1].nodeValue;
							$(this.childNodes[1]).remove();
							$("<a class='item' href='#"+s+"'>"+s+"</a>").insertBefore(this.childNodes[1]).click(function(){
								this.blur();
								var list = $(this).metaData().list;
								if (list.active) $(list.active).removeClass("active");
								$(this).addClass("active");
								list.active = this;
								options.onclickitem($(this).text(),$(this).parent());
								return false;
							}).metaData().list = list;
						});
					}
				}
			});
		},
		// type: 'cont', 'metadata'
		TreeviewSetActive: function(id, type, md_type, md_name, md_attr) {
			return this.each(function() {
				var list = this;
				if (list.active) {
					$(list.active).removeClass("active");
					if ($.browser.msie) list.active.focus();
				}
				if (type=="metadata") {
					$("li", list).filter( function(){
						return ($(this).metaData(0, md_type, md_name))[md_attr]==id;
					}).each( function(){
						var _this = $(">a.item",this);
						_this.addClass("active");
						list.active = _this[0];
						if ($.browser.msie) _this[0].focus();
					});
				} else {
					$("li>a.item", list).filter( function(){
						return $(this).text()==id;
					}).each( function(){
						$(this).addClass("active");
						list.active = this;
						if ($.browser.msie) this.focus();
					});
				}
			});
		}

	});
})();



/**
 * modal v1.14
 * 
 * @usage:
 *   $().modal(".testwin");
 *   $().unmodal();
 *
 * Inspired by:
 *   BlockUI (http://malsup.com/jquery/block)
 */
(function(){
	var $$ = $.Modal = {
		startZ    : 1000,
		currlevel : 0,
		options   : {
			classover  : "extModalOver",
			classdata  : "extModalData",
			csssize    : {position: "fixed", left: "0px", top: "0px", width: "100%", height: "100%"},
			css        : {"background-color": "#fff", cursor: "wait", opacity: "0.5"},
			speed      : false
		},
	    handler: function(e) {
			var classover = $$.options.classover+''+$$.currlevel;
			var classdata = $$.options.classdata+''+$$.currlevel;
    	    if ($(e.target).parents('div.'+classdata).length > 0) return true;
	        return false;
	    },
	    bind: function(b) {
	        $.each(['mousedown','mouseup','keydown','keypress','click'], function(i,o) {
	            $()[b?'bind':'unbind'](o, $$.handler);
	        });
	    },
		arrModal : []
	};
	$.fn.extend({
		addModal: function(ref, options) {
			options = $.extend({}, $$.options, options || {});
			$$.currlevel++;
			//return this.each(function() {
				var currz = $$.startZ+$$.currlevel*3;
				var classover = options.classover+''+$$.currlevel;
				var classdata = options.classdata+''+$$.currlevel;
		        var f = ($.browser.msie6) ? $('<iframe class="'+classover+'" src="javascript:false;document.write(\'\');"></iframe>').css(options.csssize).css({"z-index":currz, "opacity": "0.0"})
                                          : $('<div class="'+classover+'" style="display:none"></div>');
		        var w = $('<div class="'+classover+'"></div>').css(options.csssize).css(options.css).css({"z-index": currz+1});
		        var m = $('<div class="'+classover+' '+classdata+'"></div>').css(options.csssize).css({"z-index": currz+2, cursor:options.css.cursor});
				$([f[0],w[0],m[0]]).appendTo('body');
				$("."+classover).msiefixFixed();
				var data = $(ref).css({cursor: "default"})[0];
				data.parent = $(data).parent()[0];
				$$.arrModal[$$.currlevel] = data;
				$('.'+classdata).append(data);
				options.speed ? $(ref,'.'+classdata).msiefixPNG().css({opacity: 0}).show().animate({opacity: 1.0},options.speed) 
							  : $(ref,'.'+classdata).msiefixPNG().show();
			//});
			if ($$.currlevel==1) setTimeout(function(){$$.bind(true);},20);
			return this;
		},
		removeModal: function() {
			if ($$.currlevel==0) return this;
			var data = $$.arrModal[$$.currlevel];
			$(data).hide().appendTo(data.parent);
			$$.currlevel--;
			if ($$.currlevel==0) $$.bind(false);
			return this.each(function() {
				var classover = $$.options.classover+''+($$.currlevel+1);
				$("."+classover).remove();
			});
		}
	});
})();






/**
 * Wysiwyg v1.51
 * 
 * @usage:
 *
 */
(function(){
	var $$ = $.Wysiwyg = {
		name      : null,
		basePath  : "",
		editor    : null,
		isloaded  : false,
		isloading : false,
		width     : null, // todo: set in 
		height    : null, // 
		language  : null,
		imagepath : "/",
		editors   : {
			"fckeditor" : {
				options :{
					skinpath : "skins/cms/",
					toolbarset : "CMS01"
				},
				load : function () {
					if ($$.isloading || $$.isloaded) return;
					$$.isloading = true;
					$.ajax({
						cache : true,
						url : $$.basePath+"fckeditor/fckeditor.js",
						dataType : "script",
						complete : function (xml,status){
							$$.isloaded = true;
							$$.isloading = false;
						}
					 });
				},
				isActive : function (id) {
					return (FCKeditorAPI.GetInstance(id)!=null);
				},
				isCanged : function (id) {
					var inst = FCKeditorAPI.GetInstance(id);
					return false;
				},
				setCanged : function (id,flag) {
				},
				activate : function (id) {
					var inst = new FCKeditor(id, $$.width, $$.height);
					inst.BasePath = $$.basePath+"fckeditor/" ;
					inst.Config['SkinPath'] = $$.editor.options.skinpath;
					inst.ToolbarSet = $$.editor.options.toolbarset;
					inst.ReplaceTextarea() ;
				},
				deactivate : function (id) {
					var inst = FCKeditorAPI.GetInstance(id);
					alert("not implement");
				},
				Focus : function (id) {
					var inst = FCKeditorAPI.GetInstance(id);
					inst.Focus();
				},
				getContent : function (id) {
					var inst = FCKeditorAPI.GetInstance(id);
					return inst.GetXHTML(true);
				},
				setContent : function (id,cont) {
					var inst = FCKeditorAPI.GetInstance(id);
					inst.SetHTML(cont);
				},
				openFilemanager : function () {
					alert("not implement");
				}
			},
			"tiny_mce" : {
				options :{
					mode : "exact",
					theme : "advanced",
					language : "en",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_path_location : "bottom",
					plugins : "contextmenu,paste,preview,table,layer,style,safari",
					theme_advanced_buttons1 : "newdocument,|,cut,copy,paste,pasteword,|,undo,redo,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect, fontselect,fontsizeselect,forecolor,backcolor,|,removeformat",
					theme_advanced_buttons2 : "bullist,numlist,numlist,|,outdent, indent, |,link,unlink,|,image,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,charmap",
					theme_advanced_buttons3 : "table,tablecontrols",
					plugin_preview_width : "700",
					plugin_preview_height : "500",
					theme_advanced_resize_horizontal : false,
					theme_advanced_resizing : true,
					theme_advanced_path : false,
					convert_urls : false,
					relative_urls : true,
					//force_br_newlines : true,
			        //forced_root_block : '',
					document_base_url : $.file.parentFolder(PATH_BASE),
					file_browser_callback :  "$.Wysiwyg.openFilemanager"
				},
				load : function () {
					if ($$.isloading || $$.isloaded) return;
					// TODO ajax load
					// currently static load
					$$.isloaded = true;
					var options = $$.editor.options;
					options.mode = "none";
					options.width = $$.width;
					options.height = $$.height;
					options.language = $$.language;
					tinyMCE.init(options);
				},
				isActive : function (id) {
					return tinyMCE.get(id) != null;
				},
				isCanged : function (id) {
					var inst = tinyMCE.get(id);
					return inst ? inst.isDirty() : false;
				},
				setCanged : function (id,flag) {
					var inst = tinyMCE.get(id);
					inst.isNotDirty = !flag;
				},
				activate : function (id) {
					var options = $$.editor.options;
					options.elements = id;
					options.width = $$.width;
					options.height = $$.height;
					options.language = $$.language;
					var inst = tinyMCE.get(id);
					if (inst) {
						tinyMCE.remove(inst);
						//tinymce.execCommand('mceFocus', false, id); 
						//tinymce.execCommand('mceRemoveControl',false,id);
					}
					tinyMCE.init(options);
					tinyMCE.execCommand("mceAddControl",false, id);
				},
				deactivate : function (id) {
					tinyMCE.execCommand("mceRemoveControl",false,id);
				},
				toggle : function (id) {
					var inst = tinyMCE.get(id);
					if (inst) {
						$$.editor.deactivate(id);
					} else {
						$$.editor.activate(id);
					}
				},
				Focus : function (id) {
					tinyMCE.execCommand("mceFocus",false,id); 
				},
				getContent : function (id) {
					var inst = tinyMCE.get(id);
					return inst.getContent();
				},
				setContent : function (id,cont) {
					var inst = tinyMCE.get(id);
					inst.setContent(cont);
				},
				openFilemanager : function (field_name, url, type, win) {
					top.filemanager = { win   : win,
										url   : url,
										type  : type,
										field : field_name,
										path  : $$.imagepath };
					window.open("/framework/modules/filemanager/wysiwyg_tiny_mce.php","Filemanager","width=890,height=480,status=no,toolbar=no,menubar=no,titlebar=yes");
				}
			}
		},
		Setup : function (data) {
			$$.name      = data.name;
			$$.basePath  = data.basePath;
			$$.width     = data.width;
			$$.height    = data.height;
			$$.language  = data.language;
			$$.imagepath = data.imagepath;
			$$.editor    = $$.editors[$$.name];
			$.extend($$.editor.options, data.options);
		},
		Load : function (onLoad) {
			$$.editor.load();
			var wait = function() {
				if ($$.isloaded) {
					if (onLoad) onLoad();
				} else setTimeout(wait, 10);
			};
			wait();
		},
		Activate : function (id) {
			var _activate = function(id) {
				if ($("#"+id)[0].wysiwyg) return;
				$$.editor.activate(id);
				$("#"+id)[0].wysiwyg = true;
			};
			if (!$$.isloaded) {
				$$.Load(function(){_activate(id);});
			} else {
				_activate(id);
			}
		},
		Deactivate : function (id) {// id - one, null - all 
			if (!$$.isloaded) return;
			$("textarea"+(id?("#"+id):"")+"[@wysiwyg]").each(function(){
				$$.editor.deactivate(this.id);
				this.wysiwyg = null;
			});
		},
		Toggle : function (id) {
			if (!$$.isloaded || id==null) return;
			$$.editor.toggle(id);
		},
		isActive : function (id) {
			return (!$$.isloaded || id==null) ? false : $$.editor.isActive(id);
		},
		isCanged : function (id) {
			return (!$$.isloaded || id==null) ? false : $$.editor.isCanged(id);
		},
		setCanged : function (id, flag) {
			if (!$$.isloaded || id==null) return;
			$$.editor.setCanged(id,flag);
		},
		Focus : function (id) {
			if (!$$.isloaded || id==null) return;
			$$.editor.Focus(id);
		},
		getContent : function (id) {
			return $$.isloaded && $$.isActive(id) ? $$.editor.getContent(id) : null;
		},
		setContent : function (id,cont) {
			if (!$$.isloaded) return;
			if (!cont) { cont = id; id = null; }
			if ($$.isActive(id)) $$.editor.setContent(id,cont);
		},
		openFilemanager : function () {
			if (!$$.isloaded) return;
			$$.editor.openFilemanager.apply(this, arguments);
			return false;
		}
	}
})();



/**
 * Tabs v1.4
 * 
 * @usage:
 *   $(".container").Tabs({start:"section1"});
 */
(function(){
	var $$ = $.Tabs = function (options) {
		this.options = $.extend({}, $$.options, options);
	};
	$$.options = {
		start    : 1,
		speed    : false,
		onClick  : null,
		callback : null
	};
	$$.prototype = {
		options   : {},
		wrapall   : null,
		active    : null,
		getTabname : function (el) {
			return el.href.replace(/^.*#/, '');;
		},
		mouseclick : function (e) {
			var _t = e.data._t;
			var tabname = _t.getTabname(this);
			this.blur();
			_t.set(tabname);
			return false;
		},
		set : function (tabname) {
			var _t = this;
			if (_t.options.onClick && !_t.options.onClick(tabname)) return;
			$("ul.anchors a",_t.wrapall).removeClass("active").filter("a[@href$="+tabname+"]").addClass("active");
			$("#"+_t.active,_t.wrapall).hide(_t.options.speed);
			$("#"+tabname,_t.wrapall).show(_t.options.speed);
			_t.active = tabname;
			if (_t.options.callback) _t.options.callback(_t.active);
			return;
		}		
	};	
	$.fn.extend({
		Tabs: function(options) {
			return this.each(function() {
				var _t = new $$(options);
				_t.wrapall = this;
				_t.active = _t.options.start;
				$("div.fragment:not(#"+_t.active+")",_t.wrapall).hide();
				$("div#"+_t.active,_t.wrapall).show();
				$("ul.anchors a[@href$="+_t.active+"]",_t.wrapall).addClass("active");
				$("ul.anchors a",_t.wrapall).bind("click",{_t:_t}, _t.mouseclick);
				this.Tabs = _t;
			});
		}
	});
})();



/**
 * Sifr v1.0
 * 
 * @usage:
 *
 *
 */
(function(){
	var $$ = $.Sifr = function (options) {
		this.options = $.extend({}, $$.options, options);
	};
	$$.options = {
		path             : "media/sifr/",
		font             : null,
		color            : null,
		backgroundColor  : null,
		textAlign        : null,
		width            : null,
		height           : null,
		offsetLeft       : null,
		offsetTop        : null,
		link             : null,
		hover            : null,
		underline        : null
	};
	$$.prototype = {
		options     : {},
		flashparams : {},
		flashvars   : {}
	};	
	$.fn.extend({
		Sifr: function(options) {
			return this.each(function() {
				if (this.Sifr) return;
				var _t = new $$(options);
				var $this = $(this);
				var text = $this.text();
				if ($this.css('textTransform')=='uppercase') text = text.toUpperCase();
				if ($this.css('textTransform')=='lowercase') text = text.toUpperCase();
				var font = _t.options.font || (/([^\'\",]+)[,]?/.exec($this.css('fontFamily')) || [,] )[1];
				var bgColor = $.color2hex(_t.options.backgroundColor || $this.css('backgroundColor'));
				_t.flashparams.url = _t.options.path + font + '.swf';
				_t.flashparams.width = _t.options.width || $this.width();
				_t.flashparams.height = _t.options.height || $this.height();
				_t.flashparams.transparent = true;
				_t.flashvars.w = _t.flashparams.width;
				_t.flashvars.h = _t.flashparams.height;
				_t.flashvars.textalign = _t.options.textAlign || $this.css('textAlign') || 'left';;
				_t.flashvars.txt = text;
				_t.flashvars.textcolor = $.color2hex(_t.options.color || $this.css('color'));
				if (_t.options.underline || ($this.css('textDecoration')=='underline')) _t.flashvars.underline = true;
				if (bgColor) _t.flashvars.bgColor = bgColor;
				if (_t.options.link) _t.flashvars.linkColor = s.link;
				if (_t.options.hover) _t.flashvars.hoverColor = s.hover;
				if ($this.css('textDecoration')=='underline') _t.flashvars.underline = true;
				if (_t.options.offsetLeft) _t.flashvars.offsetLeft = _t.options.offsetLeft;
				if (_t.options.offsetTop) _t.flashvars.offsetTop = _t.options.offsetTop;
				$this.wrapInner('<span style="display:none;"></span>');
				$this.append($.Flash.getHTML(_t.flashparams, _t.flashvars));
				this.Sifr = _t;
			});
		}
	});
})();



//---------------------------------------------------------
// template 
// --------------------------------------------------------

(function($){
	var $$ = $._NAME_ = function(options) {
		this.options = $.extend({}, $$.options, options||{});
	};
	$$.options = {
		param1   : 1,
		param2   : 2,
		param3   : 3
	};
	$$.prototype = {
		options : {},
		var1: "v1",
		var2: "v2",
		func1 : function() {
			var _t = this;
			return (_t.options.param1);
		}
	};	
	$.fn.extend({
		_NAME_: function(options) {
			return this.each(function() {
				if (this._NAME_) return;
				var _t = new $$(options);
				this._NAME_ = _t;
			});
		}
	});
})(jQuery);



