
(function (undefined) {
//TOP 
var KI = {};
KI.version = '1.0.0 (2010-10-13)';
KI.scriptPath = (function() {
	var elements = document.getElementsByTagName('script');
	for (var i = 0, len = elements.length; i < len; i++) {
		if (elements[i].src && elements[i].src.match(/kindimage[\w\-\.]*\.js/)) {
			return elements[i].src.substring(0, elements[i].src.lastIndexOf('/') + 1);
		}
	}
	return '';
})();

KI.browser = (function() {
	var ua = navigator.userAgent.toLowerCase();
	return {
		VERSION: ua.match(/(msie|firefox|webkit|opera)[\/:\s](\d+)/) ? RegExp.$2 : '0',
		IE: (ua.indexOf('msie') > -1 && ua.indexOf('opera') == -1),
		GECKO: (ua.indexOf('gecko') > -1 && ua.indexOf('khtml') == -1),
		WEBKIT: (ua.indexOf('applewebkit') > -1),
		OPERA: (ua.indexOf('opera') > -1)
	};
})();

KI.setting = {
	ImageGetFilePath : "/kindeditor/asp.net/file_manager_json.ashx",//?path=Image/",
	ImageUploadFilePath : "/kindeditor/asp.net/upload_json.ashx",//?path=Image/",
	ImageUpdatePath: "/Public/Products/Image/",//  "/kindeditor/attached/",//默认图片目录

	domain:"http://"+document.domain+"/",
	APP:"",	
	FileFilter:".jpg;.jpeg;.gif;.png;.bmp",//图片类型	
	IsLoadImageList:false,
	//ImageGetFilePath    : "/Plus/asp.net/file_manager_json.ashx",//?path=Image/",
	//ImageUploadFilePath : "/Plus/asp.net/upload_json.ashx",//?path=Image/",
//	ImageUpdatePath: "/Plus/Upload/",//默认图片目录
	SetTimeOutSecond:5000,//5秒 	
	InputPathId : "",//
	InputObj:null,
	CurrentSelectImagePath:"", //当前选中的图片路径
	ImageData:null

	//,
	//IntervalId:"MyInterval"
};

KI.$ = function(id, doc){
	var doc = doc || document;
	return doc.getElementById(id);
};
KI.$$ = function(name, doc){
	var doc = doc || document;
	return doc.createElement(name);
};

KI.util= {
	parseJson : function (text) {
		var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
		cx.lastIndex = 0;
		if (cx.test(text)) {
			text = text.replace(cx, function (a) {
				return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
			});
		}
		if (/^[\],:{}\s]*$/.
		test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
		replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
		replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
			return eval('(' + text + ')');
		}
		throw 'JSON parse error';
	}
	,
	addEvent : function () {  
	     if (window.addEventListener) {  
	         return function(el, eventName, fn, capture) {  
	             el.addEventListener(eventName, fn, (capture));  
	         };  
	     } else if (window.attachEvent) {  
	         return function(el, eventName, fn, capture) {  
	             el.attachEvent("on" + eventName, fn);  
	         };  
	     } else {  
	         return function() {  
	         };  
	     }  
	 }	
	 ,
	 getFileExt	:function(filePath){ //获取文件扩展名
	 	var extIndex = filePath.lastIndexOf(".");
		filePath = filePath.substr(extIndex);//.jpg
	//	alert(filePath);
		return filePath.toLowerCase();
	 } 
	 ,
	 checkFileType:function(fileExt){//检查是否是图片.
	 	return (KI.setting.FileFilter.indexOf(fileExt)>=0);//查询不到的话,返回 false
	 }	 	 
};


if (window.KI === undefined) window.KI = KI;
window.KindImage = KI;

})();



function OpenDlg(imagePath)
{
	KI.setting.InputPathId = imagePath;//定义当前图片框的ID,方便选取图片后的赋值(没有该值,则不能赋值,弹出框就没有什么用处了).
	KI.setting.InputObj = KI.$(imagePath);
	
	var CurrentBigClassName = " 测试 ";
	addDialogbox("#DialogUpLoadImageDiv","选择/上传图片",20001,560);
	//quitScreenMask();
	
	$.ajax({
		type: "GET",
		url: KI.setting.APP+"/Plus/Image.htm?t="+ new Date().getTime(),
		//data:{"id":""},
		cache: false,
		success: function(msg){
			//msg = '<div style="width:300px;height:200px"></div>';
			$("#DialogUpLoadImageDiv .dialogboxContent").html(msg);
			$("#DialogUpLoadImageDiv .dialogboxContent").addClass("regWrap");
		},
		error:function(msg)
		{
			alert(msg.responseText +"error");
		}
	});
}


//------------------------------------------------------
function GetUploadPicPath(oIframe)
{
	var oIframe = document.getElementById("IFrame1");
	oIframe.contentWindow.document.body.style.display="none";
	var s ="";
//	alert( oIframe.contentWindow.document.body.innerHTML);
	s = oIframe.contentWindow.document.body.innerHTML;  //getElementById("inputHideId").value();
	
	try
	{
		var data = KI.util.parseJson(s);
		KI.setting.CurrentSelectImagePath =  data["url"];
		//alert(KI.setting.CurrentSelectImagePath + "\r\n" + data["url"]);
		CloseImageDlg();
	}
	catch(e)
	{
		KI.setting.SetTimeOutSecond -=100;
		if(KI.setting.SetTimeOutSecond>1) setTimeout(function(){GetUploadPicPath();},100);
	}
}

//弹出框时的初始化
function InitInput()
{
	LoadImageList();
	KI.setting.CurrentSelectImagePath = $("#"+ KI.setting.InputPathId ).val();
	$("#input_0_Path").val(KI.setting.CurrentSelectImagePath);
	//$("#div_1_ul").css("height","400px").css("overflow","scroll");
}

//关闭本弹出框
function CloseImageDlg()
{
	$("#"+ KI.setting.InputPathId ).val(KI.setting.CurrentSelectImagePath);//赋值
	KI.setting.IsLoadImageList=false;
	removeDialogbox("#DialogUpLoadImageDiv");
}

//加载和加载后的处理
function ToggleToImageList(IsShowImageList)
{
	if(IsShowImageList==false)
	{
		$("#div_1_waiting").css("display","");$(".ImgList").css("display","none");
	}
	else
	{
		$("#div_1_waiting").css("display","none");$(".ImgList").css("display","");			
	}
}

function LoadImageList()
{
	//alert("0")
	if(KI.setting.IsLoadImageList==false)
	{
		if(	KI.setting.ImageData!=null)
		{
			
			Ul_Fill(KI.setting.ImageData);
		}
		else
		{
		// KI.setting.domain + KI.setting.ImageGetFilePath
			$.ajax({
				"url": KI.setting.APP  +  KI.setting.ImageGetFilePath,
				cache: false,
				type: "GET",
				"data": '',
				dataType:"json",
				beforeSend:function(XMLHttpRequest){
					ToggleToImageList(false)
				},
				success: function(content){
					var json = content;
					//alert(json)
					KI.setting.ImageData = json;
					Ul_Fill(json);
				},
				error:function(msg)
				{
					alert(msg.responseText);
				}
			
			});
		}
	}
}

function Ul_Fill(json)
{
	ToggleToImageList(true);
	if(json==null)
		return ;
	//缓存数据		
	var s = "";
	var i =0;
	$.each(json["file_list"],function(i,DataRow)
	{	
		/*<li id="li_1"><img src="00022"  /></li>	*/	
		if(DataRow["filename"]!="Thumbs.db")
		{
			s += '<li id="li_'+ i +'" ><img src="' + KI.setting.ImageUpdatePath + DataRow["filename"] +'"  /></li>\r\n'
			i++;
		}
	});
	$("#div_1_ul").html(s);
	if(json["file_list"].length / 5 > 4)//4行
	{
		$("#div_1_ul").css("height","300px").css("overflow-y","scroll");
	}
	

	$(".DivContent .ImgList li").click(function(){
			var o = $(this);
			var index= $(".DivContent .ImgList li").index(o);
			$(".DivContent .ImgList li").each(function(i)
			{
				$(this).removeClass("ImageDlgSelectedImage");
			}); 
		o.addClass("ImageDlgSelectedImage");
		KI.setting.CurrentSelectImagePath = $(".DivContent .ImgList li img").eq(index).attr("src").replace(KI.setting.domain,"");
	});	
	
	//列表选中项初始化
	$("#input_0_Path").val(KI.setting.CurrentSelectImagePath);
	var index = 0;
	$(".DivContent .ImgList li").each(function(i){
		if($(".DivContent .ImgList li img").eq(i).attr("src").replace(KI.setting.domain,"")==KI.setting.CurrentSelectImagePath)
		 index = i;
		$(this).removeClass("ImageDlgSelectedImage");
	}); 
	$(".DivContent .ImgList li").eq(index).addClass("ImageDlgSelectedImage");	
	
	KI.setting.IsLoadImageList = true;	
}
/*
{"file_list":
[
{"datetime":"2010-10-11 16:28:00","filename":"20101011162800_5781.jpg","is_dir":false,"filesize":104005,"has_file":false,"filetype":"jpg","is_photo":true},
{"datetime":"2010-10-11 16:28:22","filename":"20101011162822_7343.jpg","is_dir":false,"filesize":47783,"has_file":false,"filetype":"jpg","is_photo":true},
{"datetime":"2010-10-12 07:44:40","filename":"20101012074440_7343.jpg","is_dir":false,"filesize":76377,"has_file":false,"filetype":"jpg","is_photo":true}
]
,
"current_dir_path":"",
"moveup_dir_path":"",
"total_count":3,
"current_url":"/kindeditor/asp.net/../attached/"
}
*/

//var mmmmm= '{"url":"../attached/20101014034334_8906.jpg","error":0}';
//var mydata = KI.util.parseJson(mmmmm);
//alert(mydata["url"]);
