(function($) {
	/**
	* MissyiEditor - WYSIWYG HTML Editor for Internet
	*
	* @author Michael  robert2041@163.com
	* @site http://www.missyi.com
	* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
	* @version 1.1.0
    *
	*/
	 	var parentObj;
	$.fn.missyiEditor = function(settings) {
		var obj = this;
		parentObj = obj;
		obj.items = {};
		obj.settings = jQuery.extend({
									 
		editorPath: "/include/missyiEditor/",			   //编辑器位置			 
		skinPath  : "skins/default/",
		cssPath   : "css/skin.css",
		imagePath : "images/",
		picserver : "",
		servecePath: "services/upload.php",
		usePath   : "",
		icons     :["image","emoticons","fontcolor","fontsizeup","bold","italic","underline","quote","link","about"]
								 },settings);
		obj.status = {
			running : false
		},			  
		obj.lang = {
			image : "插入图片",
			music  : "插入音乐",
			fontsizeup :"改变字体大小",
			fontcolor: "字体颜色",
			bold : '粗体',
			italic : '斜体',
			quote : '引用',
			underline : '下划线',
			emoticons : '插入表情',
			link     :"插入超链接",
			yes : '确定',
			no : '取消',
			close : '关闭',
			about : '关于编辑器'
		},
		obj.emoticons = "",
	obj.init = function(){    //初始化编辑器
			obj.initAttr();
			obj.util.loadCss(obj.settings.usePath+obj.settings.cssPath);
			obj.setupIcons();

		},
	obj.createItem = function(itemname,itemobj){    //创造按钮
		obj.items[itemname] = itemobj;
		return obj.items[itemname];
	}
	
	obj.initAttr  = function(){      //初始化常数
		
		obj.settings.usePath = obj.settings.editorPath+obj.settings.skinPath;
		
		obj.windows.emoticons.html = obj.util.getEmoticons();      //加载表情图标
	},
	obj.setupIcons = function(){                    //装载按钮
		var tmp_item;
		var item_name;
		for(var i = 0;i < obj.settings.icons.length; i++){
			item_name = obj.settings.icons[i];
			tmp_item = obj.createItem(item_name,$("<img src='"+obj.settings.usePath+obj.settings.imagePath+"icons/"+item_name+".gif' class='icon_img item_"+item_name+"' title='"+obj.lang[item_name]+"'/>"));
			obj.before(tmp_item);	
			obj.setupEvent(item_name);
		}
			obj.before("<BR />");
			
	},
	 
	obj.setupEvent = function(itemname){				   //装载按钮事件
		if(obj.items[itemname] != null){
			 if(obj.windows[itemname].hasWindow != true) {  //按钮不生成窗口,直接注册点击事件
				 obj.windows[itemname].init();
				 return;
			 }
			obj.items[itemname].click(function(eve){
				if(!obj.status.running){
					if(obj.actionWindow.object != null && obj.actionWindow.windowItem.Name == itemname  && obj.actionWindow.object.css("display") == "block") {
						obj.actionWindow.remove();    //切换按钮的时候自动隐藏窗体
						return;
					}		
				 
				  
				  var pos = obj.util.getItemPos(obj.items[itemname],"window");  //窗口位置					//窗口大小
				  obj.actionWindow.create();
				  obj.actionWindow.object.hasButton = obj.windows[itemname].hasButton;
				  obj.actionWindow.show(obj.windows[itemname],pos);

				}
			});
		}
	},

	obj.actionWindow = {            //操作窗口
		windowItem:{},
		Buttons  : {},
		hasButton: false,           //是否带有标准按钮 【确定，取消】
		create : function(){         //创建窗口
			if(obj.actionWindow.object == null){
			obj.actionWindow.object = $('<div id="missyiEditorContainer"><div class="arrow_top"><img src="'+obj.settings.usePath+obj.settings.imagePath+'arrow_top.gif" /></div><div style="position:absolute;right:5px;" class="hand close_button" title="关闭"><img src="'+obj.settings.usePath+obj.settings.imagePath+'close.gif?a=1"  /></div><div id="missyiEditorContent"></div></div>');
			obj.before(obj.actionWindow.object);
			$(".close_button").click(function(){obj.actionWindow.remove()});
			}
			return obj.actionWindow.object;
		},
		show   : function(windowItem,pos){        //显示窗口	
			obj.actionWindow.windowItem = windowItem;
			if(obj.actionWindow.object != null){
				if(windowItem.html != ""){
					obj.actionWindow.object.children("#missyiEditorContent").html(windowItem.html);					
				}
				obj.actionWindow.object.css({top:pos.y,left:pos.x,width:windowItem.bound.width,height:windowItem.bound.height});
				obj.util.setupButtonEvent();	     //注册标准按钮事件
				obj.actionWindow.object.show();
			}else{
				obj.actionWindow.object	 = obj.actionWindow.create();
				obj.actionWindow.object.show();
			}			
			windowItem.init();
			$(document.body).css("opacity",0.4);
		},
		hide   : function(){			
			$(document.body).css("opacity",1);
			obj.actionWindow.object.hide();
		},
		remove : function(){

				obj.actionWindow.object.empty();
				obj.actionWindow.object.remove();
				jQuery.event.remove(obj.actionWindow.object); 
				jQuery.removeData(obj.actionWindow.object); 
				obj.actionWindow.object = null;		
				$(document.body).css("opacity",1);
		}
	}
	
	obj.windows = {   //定义各种窗口参数
		image: {                         //图片
			init:   function(){
						 obj.actionWindow.Buttons.children("input.submit_button").click(function(){ 	  //确定按钮事件	
							$(this).attr("disabled","disabled");	   //按钮无效
							
							if($("input.uploadfile").val() != ""){     //从本地上传
								obj.status.running = true;
								$(".uploadform").submit();
								obj.actionWindow.hide();	
								obj.actionWindow.object.animate({height:28,width:20});
							obj.actionWindow.object.append($("<div class='center'><img src='"+obj.settings.usePath+obj.settings.imagePath+"uploading.gif' width='16' height='16' /></div>"));
							obj.actionWindow.object.children("#missyiEditorContent").hide();
							obj.actionWindow.object.children(".close_button").hide();
								return false;
							}else{									   //输入网络连接			
								var img = $("input.imgurl").val();
								var text = $("input.imgtext").val();
								var head = img.substr(0,7).toLowerCase();
								if(img!="" && head!="http://"){
									  alert("请输入以http://开头的图片地址");
									  $(this).removeAttr("disabled");
									  return false;
								}
								else if(img!=""){ 
									obj.util.appendImg(img,text);
								}
							}
							obj.actionWindow.remove();	
					})	
				
				},
			Name:   "image",
			hasButton: true,  //是否有按钮
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "250px",
					height  :  "200px"
					},
			html  : "<form action='"+obj.settings.editorPath+obj.settings.servecePath+"' enctype='multipart/form-data' method='post' target='hiddenframe' class='uploadform'><div class='green bold mb'>网络地址:<span>(图片自动同步到米易)</span><input type='text' class='missyi_input imgurl' /></div><div class='green bold mb'>本地上传:<input type='file' class='missyi_input uploadfile' style='width:220px;background:#FFF;' name='uploadfile'/></div><div class='green bold mb'>图片介绍:<span>(显示于图片下方)</span><input type='text' class='missyi_input imgtext' id='imgtext'/></div><iframe class='hide' name='hiddenframe'></iframe></form>"
				},
		emoticons: {					 //表情
			init:   function(){
				$(".emoticon_item").click(function(){ //为表情图标添加事件
						obj.util.appendString("[em]"+$(this).attr("num")+"[/em]");  
						obj.actionWindow.remove();
								   })
				},
			Name:   "emoticons",
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "540px",
					height  :  "200px"
					},
			html  : obj.emoticons
				},
		fontsizeup    :{
			Name     : "fontsizeup",
			init:   function(){
				var selectText;
				$(".item_fontsizeup").click(function(){		
					selectText = obj.util.getSelectionText();
											   })
				
				$(".fontbar").children("span").click(function(){
					var size = $(this).attr("size");
					if(selectText.text != ""){
					selectText.text = "[size="+size+"]"+selectText.text+"[/size]";	
					}
					if(selectText.text=="") obj.actionWindow.remove();
			   })
			},
			hasButton: false,
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "240px",
					height  :  "35px"
					},
			html  : "<div class='green bold mb hand fontbar'><span style='font-size:11px' size='11'>微号</span> <span style='font-size:12px' size='12'>小号</span> <span style='font-size:13px' size='13'>中号</span> <span style='font-size:14px' size='14'>大号</span> <span style='font-size:15px' size='15'>超大号</span></div>"	
		},fontcolor    :{
			Name     : "fontcolor",
			init:   function(){
				var selectText;
				$(".item_fontcolor").click(function(){		
					selectText = obj.util.getSelectionText();
											   })
				
				$(".colorbar").children("span").click(function(){
					var color = $(this).attr("color");
					if(selectText.text != ""){
					selectText.text = "[ftc=#"+color+"]"+selectText.text+"[/ftc]";	
					}
					if(selectText.text=="") obj.actionWindow.remove();
			   })
			},
			hasButton: false,
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "240px",
					height  :  "100px"
					},
			html  : "<div class='bold mb hand colorbar'><span style='color:#669900' color='669900'>青绿色</span> <span style='color:#FF6600' color='FF6600'>橘橙色</span> <span style='color:#FF6EC7' color='FF6EC7'>可爱粉</span> <span style='color:#0099FF' color='0099FF'>霓虹蓝</span><BR /><BR /> <span style='color:#5C4033' color='5C4033'>浓深棕</span> <span style='color:#9932CD' color='9932CD'>深兰花</span> <span style='color:#5C3317' color='5C3317'>巧克力</span> <span style='color:#FF0000' color='FF0000'>中国红</span><BR /><BR /> <span style='color:#D98719' color='D98719'>冷铜色</span> <span style='color:#238E23' color='238E23'>森林绿</span> <span style='color:#8E236B' color='8E236B'>褐红色</span> <span style='color:#D9D919' color='D9D919'>亮金色</span> </div>"	
		},
		bold     :{
			init:   function(){
				
				$(".item_bold").click(function(){
					obj.util.setSelectionText("[b]","[/b]");	   
											   })
			},
			hasWindow: false		
		},
		underline     :{
			init:   function(){
				
				$(".item_underline").click(function(){
					obj.util.setSelectionText("[u]","[/u]");	   
											   })
			},
			hasWindow: false		
		},
		italic     :{
			init:   function(){
				
				$(".item_italic").click(function(){
					obj.util.setSelectionText("[i]","[/i]");	   
											   })
			},
			hasWindow: false		
		},
		quote     :{
			init:   function(){	
			var selectText;
				$(".item_quote").click(function(){
					 selectText = obj.util.getSelectionText();	
					 $(".missyi_textarea").val(selectText.text);
											   })			
				
					obj.actionWindow.Buttons.children("input.submit_button").click(function(){ 	  //确定按钮事件
						if($(".missyi_textarea").val() != ""){
							selectText.text = "[quote]"+$(".missyi_textarea").val()+"[/quote]";
						}
					obj.actionWindow.remove();					
					});	

			},
			Name     : "quote",
			hasButton: true,  //是否有按钮
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "250px",
					height  :  "150px"
					},
			html  : "<div class='green bold mb'>插入引用:<BR /><textarea class='missyi_textarea'></textarea></div>"
		},
		link :{
			init:   function(){
				var selectText;
				$(".item_link").click(function(eve){
					$(".link_text").val(obj.util.getSelectionText().text);
					 selectText = obj.util.getSelectionText();				
											   })
				obj.actionWindow.Buttons.children("input.submit_button").click(function(){ 	  //确定按钮事件	
					if($(".link_text").val() != ""){
						selectText.text = "[url="+$(".link_url").val()+"]"+	$(".link_text").val()+"[/url]";	
					}
					obj.actionWindow.remove();
																						 });	
				 
			},
			Name:   "link",
			hasButton: true,  //是否有按钮
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "250px",
					height  :  "150px"
					},
			html  : "<div class='green bold mb'>链接地址:<input type='text' class='missyi_input link_url' /></div><div class='green bold mb'>链接内容:<input type='text' class='missyi_input link_text' /></div>"
			},about    :{
			Name     : "about",
			init:   function(){
				obj.actionWindow.Buttons.children("input.submit_button").click(function(){
									obj.actionWindow.remove();												
																						})
			},
			hasButton: true,  //是否有按钮
			hasWindow: true, //是否有窗体
			bound :
					{
					width   :  "240px",
					height  :  "135px"
					},
			html  : "<div class='bold mb green'>MissyiEditor V1.1<BR /><BR />作者 麦克乔恩 2009年7月22日<BR /><BR /><a href='http://www.missyi.com' target='_blank' class='green' style='text-decoration:none;'>米易网</a> 版权所有 © 2009 </div>"	
		}
	}
	obj.util = {                          //常用功能
		 inArray : function(str, arr) {
        for (var i = 0; i < arr.length; i++) {if (str == arr[i]) return true;}
        return false;
   		 },
		 exec	 : function(id,itemName,attr){
				alert(itemName); 
		 },
		 loadCss : function (css){          //加载CSS样式表
			var csslink = $("<link type='text/css' rel='stylesheet' href='"+obj.settings.usePath+obj.settings.cssPath+"' />");
			$("head").append(csslink);
		 },
		 getEventPos : function(eve,type){       //获得事件坐标
				var pos = {};
				if(type == "window"){
					pos.x   = eve.pageX - 10;
					pos.y   = eve.pageY + 20;
				}else{
					pos.x   = eve.pageX;
					pos.y   = eve.pageY;
				}
				return pos;
		 },
		  getItemPos : function(itemobj,type){       //获得可视元素底坐标
				var pos = {};
				if(type == "window"){
					pos.x   = itemobj.offset().left;
					pos.y   = itemobj.offset().top + itemobj.height() + 10;
				}else{
					pos.x   = itemobj.offset().top;
					pos.y   = itemobj.offset().left;
				}
				return pos;
		 },
		 setupButtonEvent: function(){				 //注册按钮事件	
		 	if(!obj.actionWindow.object.hasButton) return false;
			 obj.actionWindow.Buttons = $("<div class='center'><input type='button' value='确定' class='missyi_input_button submit_button' ></div>");  //生成按钮 [确定,取消]
			 obj.actionWindow.object.children("#missyiEditorContent").append(obj.actionWindow.Buttons);   //插入按钮						
 
		 },
		 appendString   : function(str){
			 if(window.getSelection)   
           	 window.getSelection().removeAllRanges();   
				else if(document.selection) {  
					document.selection.empty();   
			}   
			 	obj.val(obj.val() + str);	
				obj.focus();
		 },
		 appendImg		: function(url,text){
			
			if(text == ""){
				obj.val(obj.val() + "[img]"+url+"[/img]");	
			}else{
				obj.val(obj.val() + "[img="+text+"]"+url+"[/img]");		
			}
		 },
		 getEmoticons   : function(){
			 var str = "<table>";
			 	for(var i=0;i<24;i++){
					if(i % 8 == 0) str+= "<tr>";
					str += '<td><img src="'+obj.settings.editorPath+obj.settings.skinPath+obj.settings.imagePath+'emoticons/'+i+'.gif" class="icon_img emoticon_item" num="'+i+'" /></td>';
					if(i % 8 == 7) str+= "</tr>";
				}
			 return str;
		 },
		setSelectionText :	function(startTag,endTag){
			if(document.selection.createRange().text == "") return;
			obj.focus();
			document.selection.createRange().text = startTag+document.selection.createRange().text+endTag;	
		},
		getSelectionText :	function(){
			obj.focus();
			return document.selection.createRange();
		},
		addTagText: function(startTag,endTag,content){
			obj.focus();
			obj.util.appendString(startTag+content+endTag);	
		}
	 }
	 
	this.init();	
	return parentObj;
	}
//return this.unbind('click').click(_init);
		  })(jQuery);