var swfu,swfuBanner;
var cfg_lang="zh-cn";
if(cfg_lang=="zh-cn"){
	var lang = ["上传图片","正在上传","上传成功","Ajax处理失败","删除后不可恢复，是否确认删除？",'远程图片'];
}else{
	var lang = ["Upload","Uploading","Success","Ajax Error","Deleted and unrecoverable, whether to confirm the deletion?"];
}
	var formatDate= function (format, date) {
		if (!date)
			return '';
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							output += formatNumber('o',
								Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case 'h':
							output += formatNumber('h', date.getHours(),2);
							break;
						case 'i':
							output += formatNumber('i', date.getMinutes(),2);
							break;
						case 's':
							output += formatNumber('s', date.getSeconds(),2);
							break;
						case '@':
							output += date.getTime();
							break;
						case '!':
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	}
var swfu_settings = {
	upload_url : "/plugins/swfupload/upload.php",
	flash_url : "/plugins/swfupload/flash/swfupload.swf",
	file_size_limit : "2 MB",
	button_placeholder_id : "spanSWFUploadButton",
	button_image_url : "/plugins/swfupload/uploadBtn.png",
	button_width : 89,
	button_height : 30,
	debug:false,
	button_text:"<span class='redText'>"+lang[0]+"</span>",
	button_text_style:".redText { color: #0055B8; font-weight:bold; font-size:14px; word-spacing : 100px;text-align:center;}",
	button_text_top_padding:3,
	button_window_mode:"opaque",
	file_post_name:"Filedata",
	file_upload_limit:0,
	file_queue_limit:1,
	post_params:{
		"type":"",
		"createThumb":"false"
	},
	file_types:"*.jpg;*.gif;*.png;*.rar;*.zip",
	swfupload_loaded_handler:function(){
		//alert("swfupload loaded");
	},
	file_dialog_start_handler:function(){
		//alert("file dialog start");
	},
	file_queued_handler:function(){
		//alert("file_queued");
		swfu.startUpload();
	},
	file_queue_error_handler:function(){
		alert("file_queue_error");
	},
	upload_start_handler:function(){
		//alert("upload_start");
		swfu.setButtonText("<span class='redText'>"+lang[1]+"</span>");
		swfu.setButtonDisabled(true);
	},
	upload_progress_handler:function(){
		//alert("upload_progress");
	},
	upload_error_handler:function(){
		alert("upload_error");
	},
	upload_success_handler:function(obj,data,resp){
		alert(lang[2]);
	},
	upload_complete_handler:function(){
	}
}

var swfu_settings_banner = {
	upload_url : "/plugins/swfupload/upload.php",
	flash_url : "/plugins/swfupload/flash/swfupload.swf",
	file_size_limit : "2 MB",
	button_placeholder_id : "uploadBtnBanner",
	button_image_url : "/plugins/swfupload/uploadBtn.png",
	button_width : 89,
	button_height : 30,
	debug:false,
	button_text:"<span class='redText'>"+lang[0]+"</span>",
	button_text_style:".redText { color: #0055B8; font-weight:bold; font-size:14px; word-spacing : 100px;text-align:center;}",
	button_text_top_padding:3,
	file_post_name:"Filedata",
	post_params:{
		"type":"",
		"createThumb":"false"
	},
	file_types:"*.jpg;*.gif;*.png",
	swfupload_loaded_handler:function(){
		//alert("swfupload loaded");
	},
	file_dialog_start_handler:function(){
		//alert("file dialog start");
	},
	file_queued_handler:function(){
		//alert("file_queued");
		swfuBanner.startUpload();
	},
	file_queue_error_handler:function(){
		alert("file_queue_error");
	},
	upload_start_handler:function(){
		swfuBanner.setButtonText("<span class='redText'>"+lang[1]+"</span>");
		swfuBanner.setButtonDisabled(true);
	},
	upload_progress_handler:function(){
		//alert("upload_progress");
	},
	upload_error_handler:function(){
		//alert("upload_error");
	},
	upload_success_handler:function(obj,data,resp){
		//alert("上传成功");
	},
	upload_complete_handler:function(){
		//alert("complete")
	}
}

$(function(){
	$("body").ajaxError(function(e,r){
		alert(lang[3]+r.responseText);
	});
	$("a.delLink").click(function(){
		if(!confirm(lang[4])){
			return false;
		}
		return true;
	});
	if($.fn.jqTransform){
		$("select.transSelect").jqTransSelect();
	};
	$(".checkLoginName").blur(function(){
		var val = $(this).val();
		var ipt = $(this);
		$(this).next("label").remove();
		$(this).after('<label class="error"></label>')
		if(val==''){
			$(this).next("label.error").html('登录不能为空');
		}else{
			$.ajax({
				type:"POST",
				url:"/data/user",
				data:"inajax=1&act=check&loginName="+val,
				dataType:"json",
				success:function(json){
					if(!json.success){
						ipt.next("label.error").html('用户不存在');
					}else{
						ipt.next("label.error").html('');
					}
				}
			});
		}
	});
	$(".checkUserId").blur(function(){
		var val = $(this).val();
		var ipt = $(this);
		$("#checkUserIdTip").remove();
		var notnull = $(this).hasClass('notnull');
		$(this).after('<label class="error" id="checkUserIdTip"></label>');$(this).next("label.error").hide();		
		if(val=='' && notnull){
			$(this).next("label.error").html('用户ID不能为空').show();return false;
		}
		if(val!=""){
			if(!/^([0-9]+)$/.test(val)){
				$(this).next("label.error").html('用户ID只能为数字').show();return false;
			}
			$.ajax({
				type:"POST",
				url:"/data/user",
				data:"inajax=1&act=check&id="+val,
				dataType:"json",
				success:function(json){
					if(!json.success){
						ipt.next("label.error").html('用户不存在').show();
					}else{
						ipt.next("label.error").html('<font color="green">校验成功</font>').show();
					}
				}
			});
		}
	});

	$("#checkall").click(function(){
		var chk = $(this).attr("checked");
		if(chk){
			$("input[name='id[]']:checkbox").attr("checked","checked");
		}else{
			$("input[name='id[]']:checkbox").removeAttr("checked");
		}
	});
	if($(".ui-btn").length>0 && $.ui){
		$(".ui-btn").button();
	}
	if(("select[name='provinceId']").length>0){
		$("select[name='provinceId']").change(function(){
			var dom = $(this).parent("div.element");var id = $(this).val();if(id==''){ return false; }
				var sdata = 'inajax=1&act=sub&id='+id; var surl = '/data/district';
				$.ajax({ type:"POST",url:surl,data:sdata,cache:false,dataType:"json",success:function(json){
						if(json.success){
							if(json.data.length>0){
								var option = '';
								for(var i=0;i<json.data.length;i++){ var item = json.data[i];option += '<option value="'+item.id+'">'+item.name+'</option>'; }
								$('select[name="cityId"]').find("option").eq(0).siblings().remove();$('select[name="cityId"]').append(option);
							}
						}
					}
				});
		});
		$('select[name="cityId"]').change(function(){
			var dom = $(this).parent("div.element");
			var id = $(this).val();
			if(id==''){ return false; }
				var sdata = 'inajax=1&act=sub&id='+id;var surl = '/data/district';
				$.ajax({ type:"POST",url:surl,data:sdata,cache:false,dataType:"json",success:function(json){
						if(json.success){
							if(json.data.length>0){
								var option = '';
								for(var i=0;i<json.data.length;i++){ var item = json.data[i];option += '<option value="'+item.id+'">'+item.name+'</option>'; }
								$('select[name="countyId"]').find("option").eq(0).siblings().remove();$('select[name="countyId"]').append(option);
							}
						}
					}
				});
		});
	}

	$(".table-list").find("tr").each(function(index){
		if(index>0){
			var cls = index%2==0?'even':'odd';
			$(this).addClass(cls);
			$(this).hover(function(){
				if(!$(this).hasClass("selected")){$(this).removeClass().addClass("hover");}
			},function(){
				if(!$(this).hasClass("selected")){$(this).removeClass().addClass(cls);}
			});
		}
	});
	$(".J-user-anchor").css({'cursor':'pointer'}).click(function(){
		var sid=$(this).attr('sid');var eid="dialog-user-info-"+sid;if(sid){var dtitle= '用户 '+sid+' 资料';var dialogUserInfo=$('<div id="'+eid+'" class="dialog-loading"></div>').dialog({title:dtitle,resizable:false,width:300,height:200,buttons:[{text:'关闭',click:function(){dialogUserInfo.dialog('destroy');}}]});}
		$.ajax({ type:'POST',url:"/data/user",data:{inajax:1,act:'info',id:sid},dataType:'json',success:function(json){ if(json.success){dialogUserInfo.html('用户ID：'+sid+'<br/>邮箱：'+json.data.email+'<br/>手机：'+json.data.mobile);} },error:function(){qlib.tips('Ajax处理失败');} })
	});

});//ready
var msgtimer = null;
function Msg(str){
	if(str){
		var dom = $("#topMsg",parent.frames["topFrame"].document).find("span");
		dom.show();
		dom.html(str);
		window.clearTimeout(msgtimer);
		msgtimer = null;
		var msgtimer = window.setTimeout(function(){
			dom.html("").hide();
		},2000);
	}
}

function createForm(config){
	var f = $("<form></form>");
	f.attr("action",config.action);
	f.attr("method",config.method);
	f.attr("id",config.id);
	if(config.className){f.addClass(config.className);}
	$.each(config.hidden,function(i,item){
		var ipt = $("<input/>");
		ipt.attr("type","hidden");
		ipt.attr("name",item.name);
		ipt.val(item.value);
		ipt.appendTo(f);
	});
	$.each(config.input,function(i,item){
		var line = $("<div></div>");
		line.addClass("form-line");
		var label = $("<label></label>");
		label.addClass("label");
		label.html(item.label+" ： ");
		label.appendTo(line);
		if(!item.type){item.type="text";}
		if(item.type=="select"){
			var ipt = $("<select></select>");
			$.each(item.option,function(i,option){
				var opt = $("<option value='"+option.value+"'>"+option.name+"</option>");
				opt.appendTo(ipt);
			});	
			
		}else{
			var ipt = $("<input/>");
			ipt.attr("type",item.type);
		}
		ipt.attr("name",item.name);
		if(item.className){ipt.addClass(item.className);}
		ipt.appendTo(line);
		line.appendTo(f);
	});
	return f;
}


var dateconfig = { dateFormat:"yy-mm-dd",monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],dayNamesMin: ['日','一','二','三','四','五','六'],prevText:"前一月",nextText:"下一月" };
var uploadInited = false;
function uploadInit(){
					swfu_settings.button_placeholder_id = "uploadBtn";
					swfu = new SWFUpload(swfu_settings);
					swfu.uploadSuccess = function(obj,data,resp){
						if (data.substr(0,1)=="{" && data.substr(data.length-1,1)=="}")
						{
								var data = eval('('+data+')');
								if(data.success){
									var url = decodeURIComponent(data.url);
									swfu.setButtonText("<span class='redText'>上传成功</span>");
									swfu.setButtonDisabled(false);
									$("#img-src").attr("src","/"+url);
									$("#thumbId").val(data.id);
								}else{
									alert(data.message);
									swfu.setButtonText("<span class='redText'>重试</span>");
									swfu.setButtonDisabled(false);
								}
						}else{
							alert(data);
							swfu.setButtonText("<span class='redText'>重试</span>");
							swfu.setButtonDisabled(false);
						}
					}
					uploadInited=true;
}
window.onload = function(){
	if(document.getElementById("uploadBtn")){
		if(typeof(SWFUpload)=='undefined'){
			var doc = document,
			wa = doc.createElement('script'),
			s = doc.getElementsByTagName('script')[0];
			wa.type = 'text/javascript';
			wa.charset = 'utf-8';
			wa.async = true;
			wa.src = '/plugins/swfupload/swfupload.js';
			s.parentNode.insertBefore(wa, s);
			s.onreadystatechange=function(){alert('abc');
				var uA=navigator.userAgent.toLowerCase();
				if(!(!(uA.indexOf("opera")!=-1)&&uA.indexOf("msie")!=-1)||/loaded|complete/i.test(this.readyState)){
					uploadInit();
				}
			}
			if(!uploadInited){
				setTimeout(function(){
					uploadInit();
				},1000)
				
			}
		}else{
			uploadInit();
		}
	}
};
