/**
 *************************************************************************************
 * [标题：ExmayUI JQuery Rich Eidtor 插件]<br>
 *************************************************************************************
 * [描述：ExmayUI JQuery Rich Eidtor 插件]<br>
 *************************************************************************************
 * @author Exmay Team / 亿美团队
 *************************************************************************************
 * @version Version 1.0.1 Beta / v1.0.1 测试版
 *************************************************************************************
 */

/*
 * ***********************************************************************************
 * 版权：Copyright © 2012 Exmay Inc. All Rights Reserved. 长沙亿美软件有限公司　版权所有
 * ***********************************************************************************
 * 企业文化：专注　创新　分享　共赢
 * ***********************************************************************************
 * 官方网站：http://www.exmay.com
 * ***********************************************************************************
 * 官方邮箱：service@exmay.com
 * ***********************************************************************************
 */

(function($) {

	$.exmayLoader.load(Exmay.path.framework + "/editor/ckeditor.js");
	
	// 初始化Tip
	function initExmayEditor(target) {
		var $target = $(target);
		var opts = $target.data("exmayEditor").options;

		var editor = CKEDITOR.replace($target.attr("id"), {
			width : opts.width,
			height : opts.height,
			uiColor : "#EAF3FC",
			toolbar : opts.toolbar
		});

		$target.data("exmayEditor", {
			options :opts,
			exmayEditor : editor
		});
		
		$(editor).hide();

		// @import url(exmayui-editor/skin/default/exmayui-editor.css);

	}
	;

	function bindExmayEditorEvents(target) {
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		// onchange 多种情况需要考虑
		editor.on("instanceReady", function() {
			//set keyup event   
				this.document.on("keyup", function() {
					exmayChange(target);
				});
				/*//and paste event   
				this.document.on("paste", function() {
					alert("#FG");
					CKEDITOR.tools.setTimeout(function() {
						alert("ABC");
						exmayChange(target);
					}, 0);
				});*/
			var $button = $("a", $("#cke_top_" + $target.attr("id")));
			$button.click(function() {
				exmayChange(target);
			});
			/*var $dialog = $("cke_editor_" + $target.attr("id") +"_dialog");
			$dialog.live(function() {
				CKEDITOR.tools.setTimeout(function() {
					exmayChange(target);
				}, 0);
			});*/
		});
		editor.on("key", function(evt) {
			exmayChange(target);
		});
		editor.on("paste", function(evt) {
//			CKEDITOR.tools.setTimeout(function() {
				/*var html = exmayGetHtml(target);
				html = '<div class="exmay-ui-content-proxy">' + html + '</div>';
				var $html = $(html);*/
//			}, 0);
			/*$("#exmay-editor-pager").click(function() {
				$.exmayMessagebox.prompt("内容分页", "请输入分页子标题：", function(title) {
					exmayPager(target, title)
				});
			});
			$("#exmay-editor-pager").click(function(){
				$.exmayMessagebox.prompt("内容分页", "请输入分页子标题：", function(title){
					$("#exmay-content").exmayEditor("pager",title);
				});
			});*/
		});
		editor.on('saveSnapshot', function( evt ){
			if ( !evt.data || !evt.data.contentOnly ) {
				var $html = exmayGet$Html(target);
				var $imgs = $html.find("img");
				if($imgs.length > 0) {
					var flag = false;
					$imgs.each(function(){
						if(exmayHasRelativepath($(this))) {
							flag = true;
							return false;
						};
					});
					if(flag) {
						$.exmayMessagebox.prompt("输入框信息提示", "请输入内容来源完整网址：", function(url){
							if (url){
								exmayAutoComplement($html,$imgs, url);
							} else {
								exmayChange(target);
							}
						});
					} else {
						exmayChange(target);
					}
					
				}				
			}
		});		
		editor.on('mode', function( e ){
			if ( editor.mode != 'source' )
				return;

			editor.textarea.on('keydown', function( event ){
					if ( !event.data.$.ctrlKey && !event.data.$.metaKey )
						exmayChange(target);
			});

			editor.textarea.on('drop', exmayChange(target));
			editor.textarea.on('input', exmayChange(target));
		});
		
		function exmayHasRelativepath($img) {
			var flag = false;
			var src = $img.attr("data-cke-saved-src");
			var href = window.location.href;
			href = href.substr(0,href.indexOf('?'));
			var flag = false;
			if(src.indexOf(href) != -1){ // 代表有编辑页前缀
				flag = true;
			}
			if(src.indexOf("http://") == -1){ // 等于-1代表无http://前缀
				flag = true;
			} 
			if(src.indexOf("file:///") == -1 && src.indexOf("http://") == -1) { // 等于-1代表无file://前缀
				flag = true;
			}
			return flag;
		}
		
		function exmayAutoComplement($html,$imgs,url){
			//var url = "http://news.xinhuanet.com/world/2011-04/29/c_121360882.htm";
			$imgs.each(function(){
				var $this = $(this);
				var flag = exmayHasRelativepath($this);
				if(flag) {
					var href = window.location.href;
					href = href.substr(0,href.indexOf('?'));
					var src = $this.attr("data-cke-saved-src");
					src = src.replace(href, "");
					var imgPath = "";
					//var url = "http://news.xinhuanet.com/world/2011-04/29/c_121360882.htm";
					imgPath = url.substring(0,url.lastIndexOf("/"));
					var path = "";
					var img = "";
					if(img.indexOf("/")>0) {
						path = src.substring(0,src.lastIndexOf("/"));
						img = src.substring(src.lastIndexOf("/"),src.length);
					} else {
						img = src;
					}
					imgPath = imgPath.replace(path,"");
					if(src.indexOf("/") != -1) {
						// http://www.chinaz.com/Webmaster/report/04111G3342011.html
						var http = "http://";
						imgPath = imgPath.replace(http,"");
						imgPath = imgPath.substr(0,imgPath.indexOf("/"));
						imgPath = http + imgPath;
					} else {
						imgPath += "/"; 
					}
					src = imgPath + img;
					$this.attr("src",src);
					$this.attr("data-cke-saved-src",src);
				}
			});
			exmaySetHtml(target, $html.html());
		};
		
//		editor.on("key", function(evt) {
//			alert("keydown");
//		});

	}
	;

	// 获取编辑器
	function exmayGetEditor(target) {
		var $target = $(target);
		return $target.data("exmayEditor").exmayEditor;
	}
	;

	// 获取文本值
	function exmayGetText(target) {
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		var text = editor.document.getBody().getText();
		return text;
	}
	;
	
	// 获取JQuery对象
	function exmayGet$Html(target){
		return $('<div class="exmay-ui-content-proxy">' + exmayGetHtml(target) + '</div>');
	}

	// 设文本值
	function exmaySetText(target, data) {
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		data = data.replace(/<\/?[^>]+>/g, ''); //去除HTML tag
		data = data.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
		data = data.replace(/\n[\s| | ]*\r/g, '\n'); //去除多余空行
		editor.setData(data);
		exmayChange(target);
	}
	;

	// 获取HTML值
	function exmayGetHtml(target) {
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		var html = editor.document.getBody().getHtml();
		// html = editor.getData();
		return html;
	}
	;

	// 设HTML值
	function exmaySetHtml(target, data) {
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		editor.setData(data);
		exmayChange(target);
	}
	;
	
	// 插入HTML
	function exmayInsertHtml(target, data){
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		editor.insertHtml(data);
		exmayChange(target);
	};
	
	// 分页
	function exmayPager(target, data) {
		var $target = $(target);
		var editor = $target.data("exmayEditor").exmayEditor;
		
		if(data == undefined) {
			data = "&nbsp;";
		}
		exmayInsertHtml(target,'<p class="exmayui-editor-pager">'+ data +'</p>');
		var $html = exmayGet$Html(target);
		if($(".exmayui-editor-pager", $html).length < 2) {
			$html.prepend('<p class="exmayui-editor-pager">'+ data +'</p>');
			exmaySetHtml(target, $html.html());
		}
		/*$(".exmayui-editor-pager", $html).bind("click",function(){
			alert("ABC");
		})*/
	};
	
	function exmayLengthPager(target, data) {
		var $content = exmayGet$Html(target);
		var $pager = $content.find(".exmayui-editor-pager");
		if($pager.length > 0) {
			$pager.remove();
		}
		var html = $content.html();
		html = html.replace(/<br><br>/ig, "</p><p>");
		$content.html(html);
		var content = $content.text();
		var contentLength = content.length;
		var pageLength = 500;
		if(data != undefined && data.pageLength != undefined) {
			pageLength = data.pageLength;
		} else if(data != undefined) {
			pageLength = data;
		}
		pageLength = parseInt(pageLength);
		if (contentLength <= pageLength) {
			return false;
		}
		var $bug = $("#exmay-action");
		var $roots = exmayGetRoots($content);
		var begin = 0;
		var end = pageLength;
		var pages = [];
		$roots.each(function() {
			var page = {
				length : 0,
				beginIndex : 0,
				endIndex : 0
			};
			var $proxy = $("<div></div>");
			$proxy.append($(this));
			var length = $(this).text().length;
			var beginIndex = content.indexOf($proxy.html());
			var endIndex = beginIndex + $proxy.html().length;
			page.length = length;
			page.beginIndex = beginIndex;
			page.endIndex = endIndex;
			pages.push(page);
		});
		pages.sort(by("endIndex"));
		var contents = [];

		for (begin; begin < contentLength;) {
			var isEnd = false;
			exmayGetEndIndex();
			if (end > contentLength) {
				end = contentLength;
				isEnd = true;
			}
			var text = content.substring(begin, end);
			if (begin < (contentLength - pageLength) && (end + pageLength) <= contentLength) {
				text += '<p class="exmayui-editor-pager"></p>';
			}
			contents.push(text);
			if(isEnd) {
				break;
			}
			begin = end;
			end = end + pageLength;
			if (end > contentLength) {
				end = contentLength;
			}

		}
		function exmayGetRoots($root) {
			var $children = $root.children();
			if ($children.length == 1) {
				return exmayGetRoots($children);
			}
			content = $root.html();
			contentLength = content.length;
			return $children;
		}
		
		function exmayGetEndIndex() {
			var length = 0;
			for ( var i = 0; i < pages.length; i++) {
				var flag = false;
				length = length + pages[i].length;
				
				if(length >= pageLength) {
					flag = true;
				} else { // 微误差版 
					var nextIndex = i+1;
					if(nextIndex < pages.length) {
						var nextLength = length + pages[nextIndex].length;
						if(nextLength > pageLength) {
							if((pageLength - length) < (nextLength - pageLength)) {
								flag = true;
							}
						}
					}
				}
				if(flag) {	
					end = pages[i].endIndex;
					var index = i+1;
					if (index !== pages.length) {
						pages = pages.slice(index, pages.length);
					}
					break;
				}
			}
		}		
		
		exmaySetHtml(target, '<p class="exmayui-editor-pager"></p>' + contents.join(""));
	};	
	
	function exmaySizePager(target, data) {

		var $content = exmayGet$Html(target);
		var content = exmayGetHtml(target);
		content = content.replace(/<br><br>/ig, "</p><p>");
		$content.html(content);		
		var contentLength = content.length;
		var contentSize = getByteSize(content);
		var pageSize = 1000;
		if(data != undefined && data.pageSize != undefined) {
			pageSize = data.pageSize;
		} else if(data != undefined) {
			pageSize = data;
		}
		if (contentSize <= pageSize) {
			return false;
		}
		
		var $pager = $content.find(".exmayui-editor-pager");
		
		if($pager.length > 0) {
			$pager.remove();
		}
		var $roots = exmayGetRoots($content);

		var begin = 0;
		var end = pageSize;
		var pages = [];
		$roots.each(function() {
			var page = {
				beginIndex : 0,
				endIndex : 0,
				size : 0
			};
			var $proxy = $("<div></div>");
			$proxy.append($(this));
			var beginIndex = content.indexOf($proxy.html());
			var endIndex = beginIndex + $proxy.html().length;
			var size = getByteSize($proxy.text());
			page.size = size;
			page.beginIndex = beginIndex;
			page.endIndex = endIndex;
			pages.push(page);
		});	
		pages.sort(by("endIndex"));
		var contents = [];
		var isEnd = false;
		for (begin; begin < contentLength;) {
			exmayGetEndIndex();
			if (end > contentLength) {
				end = contentLength;
				isEnd = true;
			}	
			if(begin == end) {
				end = contentLength;
				isEnd = true;
			}
			var text = content.substring(begin, end);
			if (!isEnd) {
				text += '<p class="exmayui-editor-pager"></p>';
			}
			contents.push(text);
			begin = end;
			if(isEnd) {
				break;
			}
		}
		exmayGetEndIndex();
		function exmayGetRoots($root) {
			var $children = $root.children();
			if ($children.length == 1) {
				return exmayGetRoots($children);
			}
			content = $root.html();
			contentSize = getByteSize(content);
			return $children;
		}
		function exmayGetEndIndex() {
			var size = 0;
			for ( var i = 0; i < pages.length; i++) {
				size = size + pages[i].size;
				if(size >= pageSize) {
					end = pages[i].endIndex;
					var index = i+1;
					if (index !== pages.length) {
						pages = pages.slice(index, pages.length);
					}
					break;
				}
			}
		}
		exmaySetHtml(target, '<p class="exmayui-editor-pager"></p>' + contents.join(""));		
		
		//计算字符串的字节数  
		function getByteSize(str){
			var l = str.length;
			var n = l;
			for (var i=0;i<l;i++){  
				if(str.charCodeAt(i)<0 || str.charCodeAt(i)>255){  
					n++;   
				}
			}
			return n;   
		};
		
	};
	
	function by(name){
	    return function(o, p){
	        var a, b;
	        if (typeof o === "object" && typeof p === "object" && o && p) {
	            a = o[name];
	            b = p[name];
	            if (a === b) {
	                return 0;
	            }
	            if (typeof a === typeof b) {
	                return a < b ? -1 : 1;
	            }
	            return typeof a < typeof b ? -1 : 1;
	        }
	        else {
	            throw ("error");
	        }
	    };
	};	
	
	function exmayChange(target) {
		CKEDITOR.tools.setTimeout(function() {
			var $target = $(target);
			var opts = $target.data("exmayEditor").options;
			var editor = $target.data("exmayEditor").exmayEditor;
			var text = exmayGetText(target);
			var $currentLength = $("#" + $target.attr("id") + "-length");
			if ($currentLength.html() != null) {
				$currentLength.html(text.length);
			}
			if (opts.onChange) {
				opts.onChange.call(target);
			}
		}, 0);
	};

	// 提示
	$.fn.exmayEditor = function(options, data) {
		// 方法调用
		if (typeof options == "string") {
			return $.fn.exmayEditor.methods[options](this, data);
		}
		this.each(function() {
			var $this = $(this);
			var opts = null;
			var cache = $this.data("exmayEditor");
			if (cache) {
				opts = $.extend(cache.options, options);
				cache.options = opts;
			} else {
				opts = $.extend( {}, $.fn.exmayEditor.defaults, $.fn.exmayEditor.parseOptions(this), options);
				$this.data("exmayEditor", {
					options : opts
				});
				initExmayEditor(this);
				bindExmayEditorEvents(this);
			}
		});

	};

	// 插件方法
	$.fn.exmayEditor.methods = {
		editor : function(target, data) {
			return exmayGetEditor(target);
		},
		getText : function(target, data) {
			return exmayGetText(target);
		},
		setText : function(target, data) {
			return exmaySetText(target, data);
		},
		getHtml : function(target, data) {
			return exmayGetHtml(target);
		},
		get$Html : function(target, data) {
			return exmayGet$Html(target);
		},
		setHtml : function(target, data) {
			return exmaySetHtml(target, data);
		},
		insertHtml : function(target,data) {
			return exmayInsertHtml(target, data);
		},
		pager : function(target,data) {
			return exmayPager(target, data);
		},
		lengthPager : function(target, data){
			return exmayLengthPager(target, data);
		},
		sizePager : function(target, data) {
			return exmaySizePager(target, data);
		},
		change : function(target, data) {
			return exmayChange(target);
		}
	};

	// 解析插件属性
	$.fn.exmayEditor.parseOptions = function(target) {
		var $target = $(target);
		return {
			width : (parseInt(target.style.width) || undefined),
			height : (parseInt(target.style.height) || undefined),
			toolbar : $target.attr("toolbar")
		};
	};

	$.fn.exmayEditor.defaults = {
		width : "auto",
		height : "auto",
		toolbar : "Full",
		onChange : function() {

		}
	};

})(jQuery);