/*
 * @author:Siemon Huang
 * @version:beta1.0
 * @date:2011-3-10
 */
(function(){
	//var overlay;
    $.widget('ui.modtools', {
        _init:function(){
			var o = this.options;
			/*$('.mod-toolbox').remove();*/
			this.element
				.attr('id','module_'+(moduleSer++))
				.hover(
					function(){
						toolbox.fadeIn("slow");
					},
					function(){
						toolbox.fadeOut("slow");
					}
				);
			var self = this,
				firstChild = $('>div:first-child',this.element),
				toolbox = $('<div class="mod-toolbox editable-mode"/>').hide().insertBefore(firstChild);
				if(o.editable){
					
					var moduleInner = $('.modulelist_inner',this.element);
					if(moduleInner.length){
						var	appendbtn = $('<a href="javascript:;" title="列表项添加" class="ui-animate-rotate-360deg" style="float:left;"><span class="ui-icon ui-icon-plusthick" style="float:left;"/></a>')
										.appendTo(toolbox)
										.hover(
											function(){
												$(this).addClass('ui-state-hover').css({'border':'0','background':'none'});
											},
											function(){
												$(this).removeClass('ui-state-hover');
											}
										)
										.click(function(){
											var mod = $(this.parentNode.parentNode),
												template = $('.hidden_info',mod),
												template_content = template.attr('listcode');//模块内容
												template_content = encodeURI(encodeURI(template_content));																	
											var	controller = createDialogBox('列表项添加',function(){
														var appendFrame = $('#newsappend')[0].contentWindow,
															reqForm = appendFrame.document.getElementById('bokaadd');
															
															//submitBtn = appendFrame.document.getElementById('newsubmit');
														$('#newsappend').load(function(){
															var returnContent = appendFrame.document.getElementById('boka_itemadd');
															if(Number(returnContent.innerHTML)){
																controller.dialog('close');
																var info = $('.hidden_info',mod).eq(0).attr('listcode');
																self.refreshModule(info);
															}else{
																controller.dialog('close');
															}
														});
														//alert(appendFrame.document.getElementById('author').value);
														//alert(appendFrame.document.getElementById('content').value);
														//reqForm.submit();
														//alert(appendFrame.submitNew)
														appendFrame.submitNew();
													},
													null,
													'moduleedit.php?action=add&variable='+template_content,
													true
												);						
										});
					}
					var	editbtn = $('<a href="javascript:;" title="编辑" class="ui-animate-rotate-45deg" style="float:left;"><span class="ui-icon ui-icon-wrench" style="float:left;"/></a>')
									.appendTo(toolbox)
									.hover(
										function(){
											$(this).addClass('ui-state-hover').css({'border':'0','background':'none'});
										},
										function(){
											$(this).removeClass('ui-state-hover');
										}
									)
									.click(function(){
										var mod = $(this.parentNode.parentNode),
											template = $('.hidden_info',mod),
											template_content = template.attr('listcode');//模块内容
											
										template_content = encodeURI(encodeURI(template_content));
										
										if($('.bokacontent',mod)[0]){
											var //content_layout = $(this.parentNode).next(),
												content = $('.bokacontent',mod).clone();
											content.find('.hidden_content').remove();
											content = content.html().replace(/\s/g,' ');
											var	urls = location.href.split('/'),
												url = urls[urls.length-1],
												controller = createDialogBox('内容编辑',function(){
														var editcontent = $('#elm1').val()
																			.replace(/&quot;/g,'"')
																			.replace(/\&/g, '%26')
																			.replace(/\+/g, '%2B')
																			.replace(/(\w+)=([^"\s<>]+)([> ])/g,'$1="$2"$3')
																			//.replace(/<div[^<>]+tagcode="(\{\w+\})"><\/div>/ig,'$1')
																			.replace(/<img[^<>]+title="([^"\s<>]+)"[^<>]+\/>/ig,'$1');
														$.ajax({
															url:'moduleedit.php?action=editcontent',
															type:'POST',
															data:'url='+url+'&editcontent='+encodeURI(encodeURI(editcontent)),
															success:function(data){
																/*if(Number(data)){
																	$('.hidden_content',mod).html(editcontent);
																}*/
																//$('#hidden_content > .modulelist').insertAfter($('>.mod-toolbox',mod))
																$('.bokacontent',mod).html(data);
																mod.heightResize('reset');
																controller.dialog('close');
															}
														});
														_setBoxMode(mod,$('.bokacontent', mod));
													},
													null,
													'moduleedit.php?action=bokacontent&url='+url,
													false,
													function(){
														content = content.replace(/<br>/i,'')
																		.replace(/(\w+)=([^"\s<>]+)([> ])/g,'$1="$2"$3')
																		.replace(/<div[^<>]+tagcode="(\{\{[^"\s<>]+\}\})"[^<>]+><\/div>/ig,'$1')
																		.replace(/<div[^<>]+listcode="([^"\s<>]+)"><\/div>/ig,'<img title="$1" src="/images/replace/code.gif"/>');
														editor = $('#elm1').val(content).xheditor({
																upLinkUrl:"/xhupload.php",
																upLinkExt:"zip,rar,txt",
																upImgUrl:"/xhupload.php",
																upImgExt:"jpg,jpeg,gif,png",
																upFlashUrl:"/xhupload.php",
																upFlashExt:"swf",
																upMediaUrl:"/xhupload.php",
																upMediaExt:"wmv,avi,wma,mp3,mid,flv",
																html5Upload:false,
																plugins:allplugin,
																tools:tool,
																inlineScript:true,
																internalScript:true
														});
														_loadBoxMode(mod,$('.bokacontent', mod));
														/*
														editor.settings.blur=function(){											
															preview_newcontent();
															//$('#hidden_content .modulelist_newcontent').html(editor.getSource());										
														}
														*/											
													}
													//'<table width="100%"><tr><td><textarea id="elm1" name="elm1" rows="26" cols="80" style="width: 100%;overflow-x:hidden;">'+content+'</textarea></td></tr></table>'
												);
										}
										else if($('.modulelist_newcontent',mod)[0]){
											var content_layout = $(this.parentNode).next(),
												modheader = $('.modulelist_header',content_layout),
												header = modheader[0]?modheader.html().replace(/\s/g,''):'',
												content = $('.modulelist_newcontent',content_layout).clone();
											content.find('.hidden_content').remove();
											content = content.html().replace(/\s/g,' ');

											var controller = createDialogBox('自定义模块编辑',function(){
													header = $('#module_name').val();
													content = $('#elm1').val();
													//alert(content.match(/\<address|blockquote|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul/gi).length);
													//alert(content.match(/\<\/address|blockquote|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul\>/gi).length);
													//content_layout.html('<div class="modulelist_header">'+header+'</div><div class="modulelist_newcontent"><div class="hidden_content">'+content+'</div></div>');
													//$('#modulelist').val('sohu');
													$('#hidden_content .modulelist_header').html(header);
													var newcontent = $('#hidden_content .modulelist_newcontent').html(content),
														replacedtxt = content.replace(/&quot;/g,'"')
																			.replace(/\&/g, '%26')
																			.replace(/\+/g, '%2B')
																			.replace(/(\w+)=([^"\s<>]+)([> ])/g,'$1="$2"$3')
																			.replace(/<img[^<>]+title="([^"\s<>]+)"[^<>]+\/>/ig,'$1');
													$('.modulelist',mod).remove();
													$('#hidden_content .modulelist').insertAfter($('>.mod-toolbox',mod));

													$.ajax({
														type: 'POST',
														url : '/tabs.php?action=newcontentpreview&addhiddeninfo=1',
														data: 'textareavalue='+encodeURI(encodeURI(replacedtxt)),
														dataType : 'html',
														success : function(data){
															//data = data.replace(/\\"/g,'"');
															$('.modulelist_newcontent', mod).html(data);
														}
													});
													_setBoxMode(mod,$('.modulelist_newcontent', mod));
													mod.heightResize('reset');
													controller.dialog('close');
												},
												null,
												'modules.php?module=newcontent',//'<table width="100%"><tr><td nowrap="" style="width:70px;">模块名称:</td><td><input type="text" class="inpTxt" style="width: 100%;" id="module_name"></td></tr><tr><td colspan="2">模块内容</td></tr><tr><td colspan="2"><textarea id="elm1" name="elm1" class="xheditor" rows="26" cols="80" style="width: 100%;overflow-x:hidden;">'+content+'</textarea></td></tr></tbody></table>'
												false,
												function(){
													content = content.replace(/<br>/i,'')
																	.replace(/(\w+)=([^"\s<>]+)([> ])/g,'$1="$2"$3')
																	.replace(/<div[^<>]+tagcode="(\{\{[^"\s<>]+\}\})"[^<>]+><\/div>/ig,'$1')
																	.replace(/<div[^<>]+listcode="([^"\s<>]+)"><\/div>/ig,'<img title="$1" src="/images/replace/code.gif"/>');
													//alert(content.replace(/<div[^<>]+class="hidden_info">(\[info\][^<>]+\[\/info\])<\/div>/ig,'<img info="$1" src="/images/replace/code.gif"/>'));
													if ($('#elm1')[0]) {
														editor = $('#elm1').val(content).xheditor({
															upLinkUrl:"/xhupload.php",
															upLinkExt:"zip,rar,txt",
															upImgUrl:"/xhupload.php",
															upImgExt:"jpg,jpeg,gif,png",
															upFlashUrl:"/xhupload.php",
															upFlashExt:"swf",
															upMediaUrl:"/xhupload.php",
															upMediaExt:"wmv,avi,wma,mp3,mid,flv",
															html5Upload:false,
															plugins:allplugin,
															tools:tool,
															inlineScript:true,
															internalScript:true
														});
														editor.settings.blur=function(){
															preview_newcontent();
															//$('#hidden_content .modulelist_newcontent').html(editor.getSource());										
														}
													}
													var listcss = $('.modulelist',mod).attr('class').match(/modulelist_\w+/)[0].substr(11),
														modheader = $('.modulelist_header',mod),
														headercss = modheader[0]&&modheader.attr('class').match(/modulelist_header_\w+/)[0].substr(18),
														modulelist = $('#modulelist')[0],
														moduleHeader = $('#modulelist_header')[0];

													$.each(modulelist.options,function(i,n){
														if(n.value==listcss) modulelist.selectedIndex = i;
													});
													
													$.each(moduleHeader.options,function(i,n){
														if(n.value==headercss) moduleHeader.selectedIndex = i;
													});
																									
													$('#module_name').val(header);
													//preview();
													_loadBoxMode(mod,$('.modulelist_newcontent', mod));
													$('#hidden_content .modulelist_header').html(header);
													$('#hidden_content .modulelist_newcontent').html(content);
													$('button').attr('disabled', false);											
												}
											);
										}else if($('.tags_inner',mod)[0]){
											var controller = createDialogBox('编辑间距',function(){
													_setBoxMode(mod,$('.tags_inner', mod));
													controller.dialog('close');											
												},
												null,
												'tabs.php?action=marginpadding',
												false,
												function(){
													_loadBoxMode(mod,$('.tags_inner', mod));
												}
											);
										}else{
												var controller = createDialogBox('列表编辑',function(){
													preview(function(){
														var htm = $('#hidden_content').html();
														$('.modulelist',mod).remove();
														//mod.append(htm);
														/*if(tip[0]){
															tip.remove();
														}*/
														//mod.mod({handle:'.mod,.tag',accept:'.mod,.tag,.customize-frame-tip',draggable:'.mod,.tag'}).modtools();
														$('#hidden_content > .modulelist').insertAfter($('>.mod-toolbox',mod))
														_setBoxMode(mod,$('.modulelist_inner', mod));	
														mod.heightResize('reset');
														controller.dialog('close');
													});												
												},
												null,
												'modules.php?variable='+template_content,
												false,
												function(){
													_loadBoxMode(mod,$('.modulelist_inner', mod));
												}
											);					
										}
										return false;
									});					
				}
			var	deletebtn = $('<a href="javascript:;" title="删除" class="ui-animate-rotate-360deg" style="float:left;margin-right:1px;"><span class="ui-icon ui-icon-closethick" style="float:left;"/></a>')
							.appendTo(toolbox)
							.hover(
								function(){
									$(this).addClass('ui-state-hover').css({'border':'0','background':'none'});
								},
								function(){
									$(this).removeClass('ui-state-hover');
								}
							)
							.click(function(){
								var mod = $(this.parentNode.parentNode);
								//if(mod.siblings().length < 1){
								//	mod.parent().html('<div class="customize-frame-tip"/>').css('paddingBottom',20);
								//}
								//mod.hide().attr('state','removed');
								saveInvoke(mod,1);
								return false;
							});				
		},
		refreshModule:function(info){
//			if(rubbish[0]){
				var //info = rubbish.html(),
					result =  info.match(/module=\w*/);
				if(result.length){
					var matchstr = result[0].toString();
					$('.modulelist .hidden_info').each(function(){
						//alert(this)
						//if(this == rubbish[0]) return true;
						var currentInfo = this.getAttribute('listcode');
						//alert(currentInfo.indexOf(matchstr))
						if(currentInfo.indexOf(matchstr)>0){
							//alert(matchstr);
							var self = this,
								value = encodeURI(encodeURI(this.getAttribute('listcode')));
							$.ajax({
								url:'moduleedit.php?action=refreshlist',
								type:'POST',
								data:'bokavariable='+value,
								dataTpye:'html',
								success:function(html){
									//alert(html)
									if (html && html.trim() != '' && self.parentNode) {
										$(self).before(html);
										$(self).next().remove();
										$(self).remove();
									}//.innerHTML = html;
								}
							});
						}
					});
					msgInfoBox('正在更新...');
				}
//			}
		}
/*		createDialog:function(title,handler,html,url,frame,callback){
			if(controller) controller.dialog('close');
			var width = Math.floor($(window).width() / 1.5),
				height = Math.floor($(window).height() / 1.5),
				left = ($(document.documentElement).width()- width)/2,
				top = ($(window).height() - height)/2;
			controller = $('<div title="'+title+'"><div style="width:100%;height:100%;position:relative;"><img src="images/loading.gif" style="position:absolute;top:45%;left:45%;"/></div></div>').dialog({
					width:width,
					height:height,
					//modal:true,
					resizable:false,
					draggable:false,
					open:function(){
						var box = $('.ui-dialog').css({'position':'fixed',
								'left':	left,
								'top': top
						});						
						if (!$.browser.msie) {
							box.css({opacity:0,
								top: -height
							}).animate({
									opacity:1,
									top:top + 30			
							},330).animate({
									top:top		
							},270);						
						}
					},											
					beforeclose:function(){
						if ($.browser.msie) {
							$('#xhePanel').hide();
							controller.dialog('destroy').remove();
							overlay.remove();					
						}else{
							controller.css('opacity',0);
							var box = $('.ui-dialog');
							box.animate({
								opacity:0,
								top: -height			
							},450,function(){
									$('#xhePanel').hide();
									controller.dialog('destroy').remove();
									overlay.animate({opacity:0},50,function(){
										overlay.remove();
									});													
							});							
						}
						return false;
					},
					buttons:{
						'取消':function(){
							controller.dialog('close');
						},
						'应用':function(){
							handler.call();
						}
					},
					zIndex:10002
				});
				
				overlay = dialogOverlay(10001);
				
				if(html){
					controller.html(html);
				}
				if(url){
					if(frame){
						controller.html('<iframe id="newsappend" width="100%" height="'+(Math.floor($(window).height() / 1.5)-100)+'" frameborder="no" marginheight="1" marginwidth="0" border="0" src="'+url+'"/>');
					}else{
						controller.load(url,callback);
					}
				}
			return controller;			
		}
*/		
    });

    $.extend($.ui.modtools, {
        version: '1.0',
        defaults: {
			editable:true
        }
    });

})($);



//address|blockquote|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul

var createDialogBox = function(title,handler,html,url,frame,callback){
	//if(controller) controller.dialog('close');
	var width = Math.floor($(window).width() / 1.2),
		height = Math.floor($(window).height() / 1.2),
		left = ($(document.documentElement).width()- width)/2,
		top = ($(window).height() - height)/2,
		loading = $('<div style="width:100%;height:100%;position:absolute;top:0;left:0"><img src="images/loading.gif" style="position:absolute;top:45%;left:45%;"/></div>')
		controller = $('<div title="'+title+'" style="position:relative;"></div>')
		.append(loading)
		.dialog({
			width:width,
			height:height,
			//modal:true,
			resizable:false,
			draggable:false,
			open:function(){
				var box = $('.ui-dialog').css({'position':'fixed',
						'left':	left,
						'top': top
				});						
				if (!$.browser.msie) {
					box.css({opacity:0,
						top: -height
					}).animate({
							opacity:1,
							top:top + 30			
					},330).animate({
							top:top		
					},270);						
				}
			},											
			beforeclose:function(){
				if ($.browser.msie) {
					$('#xhePanel').hide();
					controller.dialog('destroy').remove();
					overlay.remove();					
				}else{
					controller.css('opacity',0);
					var box = $('.ui-dialog');
					box.animate({
						opacity:0,
						top: -height			
					},450,function(){
							$('#xhePanel').hide();
							controller.dialog('destroy').remove();
							overlay.animate({opacity:0},50,function(){
								overlay.remove();
							});													
					});							
				}
				return false;
			},
			buttons:{
				'取消':function(){
					controller.dialog('close');
				},
				'应用':function(){
					handler&&handler.call();
				}
			},
			zIndex:10002
		});
		
		var overlay = dialogOverlay(10001).click(function(){
			controller.dialog('close');
		});
		
		if(html){
			controller.html(html);
		}
		if(url){
			if(frame){
				var uiframe = $('<iframe id="newsappend" width="100%" height="'+(Math.floor($(window).height() / 1.2)-100)+'" frameborder="no" marginheight="1" marginwidth="0" border="0" src="'+url+'" style="position:absolute;top:0;left:0;"/>')
					.load(function(){
						loading.remove();
					});
				controller.append(uiframe);
			}else{
				controller.load(url,callback);
			}
		}
	return controller;			
}
var	_loadBoxMode=function(marginEl,paddingEL){
	var margintop = marginEl.css('marginTop'),
		mtu = margintop.substr(margintop.length-2),
		marginbottom = marginEl.css('marginBottom'),
		mbu = marginbottom.substr(marginbottom.length-2),
		marginLeft = marginEl.css('marginLeft'),
		mlu = marginLeft.substr(marginLeft.length-2),
		marginRight = marginEl.css('marginRight'),
		mru = marginRight.substr(marginRight.length-2),
		paddingtop = paddingEL.css('paddingTop'),
		ptu = paddingtop.substr(paddingtop.length-2),
		paddingbottom = paddingEL.css('paddingBottom'),
		pbu = paddingbottom.substr(paddingbottom.length-2),
		paddingleft = paddingEL.css('paddingLeft'),
		plu = paddingleft.substr(paddingleft.length-2),
		paddingright = paddingEL.css('paddingRight'),
		pru = paddingright.substr(paddingright.length-2),
		inputMT = $('input[name=margin-top]'),
		selectMt = inputMT.next();
		inputMB = $('input[name=margin-bottom]'),
		selectMB = inputMB.next();
		inputML = $('input[name=margin-left]'),
		selectML = inputML.next();
		inputMR = $('input[name=margin-right]'),
		selectMR = inputMR.next();
		inputPT = $('input[name=padding-top]'),
		selectPT = inputPT.next();
		inputPB = $('input[name=padding-bottom]'),
		selectPB = inputPB.next();
		inputPL = $('input[name=padding-left]'),
		selectPL = inputPL.next();
		inputPR = $('input[name=padding-right]'),
		selectPR = inputPR.next();
		
	inputMT.val(parseFloat(margintop));
	selectMt.val(mtu);
	inputMB.val(parseFloat(marginbottom));
	selectMB.val(mbu);
	inputML.val(parseFloat(marginLeft));
	selectML.val(mlu);
	inputMR.val(parseFloat(marginRight));
	selectMR.val(mru);
	inputPT.val(parseFloat(paddingtop));
	selectPT.val(ptu);
	inputPB.val(parseFloat(paddingbottom));
	selectPB.val(pbu);
	inputPL.val(parseFloat(paddingleft));
	selectPL.val(plu);
	inputPR.val(parseFloat(paddingright));
	selectPR.val(pru);
	$('.ui-numeric-margin').numeric();
	$('.ui-numeric-padding').numeric();
},
_setBoxMode=function(marginEl,paddingEL){
	$('.ui-numeric-margin').each(function(){
		var attr = $('>input',this).attr('name'),
			val = $('>input',this).val(),
			unit = $('>select',this).val();

		marginEl.css(attr,val+unit);
	});
	$('.ui-numeric-padding').each(function(){
		var attr = $('>input',this).attr('name'),
			val = $('>input',this).val(),
			unit = $('>select',this).val();
		paddingEL.css(attr,val+unit);
	});			
};
