Event.observe(window,"load",function(){
	init();
});

var template_editor_configuration = {};

function setConfig(config){
	template_editor_configuration = config;
}

var editor_mode = "editor";
function init(){

	PanelManager.init("template_wrapper");
	//ブロックリスト
	if($("block_list")){
		PanelManager.getPanel("west").addTab(soycms.lang.template_editor.block_list_tab_name,$("block_list"),{deletable : false});
	}

	//ヘルプ
	if($("block_help_area")){
		PanelManager.getPanel("west").addTab(soycms.lang.template_editor.block_help_erea_tab_name,$("block_help_area"),{deletable : false});
	}

	//HTMLテンプレート
	PanelManager.getPanel("west").addTab(soycms.lang.template_editor.html_editor_tab_name,$("template_editor_wrapper"),{onresize : resizeTextArea, deletable : false, onactive : activeTemplateEditor});

	//携帯ページ用仮想ツリー
	if($("virtual_tree")){
		$("virtual_tree").show();
		PanelManager.getPanel("west").addTab(soycms.lang.template_editor.virtual_tree_tab_name,$("virtual_tree"),{ deletable : false});
	}

	PanelManager.getPanel("west").show();

	//クッキーからエディターの状態の取得
	var regexp = new RegExp('; editor_mode=(.*?);');
	var match  = ('; ' + document.cookie + ';').match(regexp);
	editor_mode = (match) ? match[1] : 'editor';

	//テキストエリアの初期化
	var textarea = $("template_content");
	textarea.style.position = "relative";
	textarea.style.width = "100%";
	textarea.style.height = "100%";
	textarea.hide();

	//フレームの初期化
	var textarea = $("template_editor_frame");
	textarea.show();

	textarea.contentWindow.location.href = textarea.getAttribute("_src") + "?tn" + (new Date()).getTime();

	textarea.style.position = "relative";
	textarea.style.width = "100%";
	textarea.style.height = "100%";

	if(getStyleSheet().length == 0 && $("cssButton")){
		$("cssButton").hide();
	}

	Event.observe($("main_form"), 'submit', function() {
		sync_code();
	});

	//絵文字
	try{
		if(typeof mceSOYCMSEmojiURL == "undefined"){
			throw "error";
		}
	}catch(e){
		if($("emojiButton"))$("emojiButton").hide();
	}
}

function debug(str,flag){
	if(flag){
		$("debug").innerHTML += str + "<br>";
	}else{
		$("debug").innerHTML = str;
	}
}

/**
 *	エディタの切り替え
 */
function toggle_editor(){

	if(editor_mode == "editor"){
		sync_code();
		editor_mode = "textarea";
	}else{
		var code = $("template_content").value;
		if(code.length < 1)code = "\n";
		$("template_editor_frame").contentWindow.TemplateEditor.setCode(code);
		editor_mode = "editor";
	}

	document.cookie = 'editor_mode=' + editor_mode + '; expires=' + new Date(2030, 1).toUTCString();

	$("template_content").toggle();
	$("template_editor_frame").toggle();
}

/**
 *	HTMLコードの同期を取る
 */
function sync_code(){

	if(editor_mode == "editor"){
		$("template_content").value = template_editor_get_code();
	}else{
		var code = $("template_content").value;
		if(code.length < 1)code = "\n";
		if($("template_editor_frame").contentWindow.TemplateEditor){
			$("template_editor_frame").contentWindow.TemplateEditor.setCode(code);
		}
	}

	return $("template_content").value;

}

var old_template_value = "";
function showPreview(){

	sync_code();

	//同期
	$("template_content").value = template_editor_get_code();

	var content = $("template_content").value;
	var is_appended = false;
	//iframeの追加
	if(!$("template_content_preview_wrapper")){
		var iframeWrapper = document.createElement("div");
		iframeWrapper.setAttribute("id","template_content_preview_wrapper");
		iframeWrapper.innerHTML = '<iframe id="template_content_preview" frameborder="0" style="width:100%;height:100%;background-color:white;border:none;" src="about:blank"></iframe>';
		document.body.appendChild(iframeWrapper);

		if($("block_list")){
			if($("block_list").panel_pos == "south"){
				PanelManager.inactiveSouthPanel();
			}
		}

		PanelManager.getPanel("east").addTab("Preview",iframeWrapper,{onactive : showPreview});

		if($("block_list")){
			if($("block_list").panel_pos == "south"){
				PanelManager.activeSouthPanel();
			}
		}

		is_appended = true;
	}else{
		if($("template_content").value == old_template_value){
			return;
		}
	}

	//前の値を保存
	old_template_value = $("template_content").value;

	//contentを書き換える
	content = '<base href="'+siteURL+'"/>'+content;

	var lines = content.replace("\r\n","\n").split("\n");
	var newContent = new Array();
	for(var i=0; i < lines.length; i++){
		var line = lines[i];

		var r = line.match(/<(div)[\s>]|<(p)[\s>]|<(h[1-5])[\s>]|<(li)[\s>]/i);
		if(r){

			var tag =	(r[1]) ? r[1] :
						(r[2]) ? r[2] :
						(r[3]) ? r[3] :
						(r[4]) ? r[4] : null;

			if(!tag)continue;

			var pos = content.indexOf(line) + line.indexOf("<" + tag);

			//onclick無効化
			line = line.replace("onclick=","_onclick=");

			//行数属性追加
			line = line.replace('<'+tag,'<'+tag+' text:line="'+i+'" text:pos="'+pos+'" ');

			//onclick属性追加
			var ondblclick = new Array();
			ondblclick.push('if(!event)event=arguments.callee.caller.arguments[0];');
			ondblclick.push('event.returnValue=false;event.cancelBubble=true;');
			ondblclick.push('event.returnValue=false;event.cancelBubble=true;');
			ondblclick.push('var pos = this.getAttribute(\'text:pos\');');
			ondblclick.push('window.parent.scrollTextArea(this.getAttribute(\'text:line\'),pos);');
			ondblclick.push('return false;');
			line = line.replace('<'+tag,'<'+tag+' ondblclick="'+ondblclick.join("")+'" ');
		}

		if(line.match(/<a/i)){
			//onclick無効化
			line = line.replace("onclick=","_onclick=");
			line = line.replace(/<a/i,'<a onclick="return false;" ');
		}

		newContent.push(line);
	}
	content = newContent.join("\n");

	//絵文字用の書き換え
	try{
		if(typeof(mceSOYCMSEmojiURL) != "undefined"){
			var imageUrl = mceSOYCMSEmojiURL.replace("index.html","");
			content = content.replace(/\[e:([0-9]+)\]/g,'<img src="'+imageUrl + '$1.gif' + '" />');
		}
	}catch(e){
	}


	if($("css_list") && $("css_list").value != "none"){

	}
	content += "<style type=\"text/css\">"+$("css_editor").value+"</style>";



	var frame = $("template_content_preview");
	frame.hide();
	var d = frame.contentWindow.document;

	d.clear();
	d.write(content);
	d.close();

	frame.show();

	frame.contentWindow.document.onclick = function(){
		showPreview();
	}
}
function scrollTextArea(line,pos){

	var tab_id = $("template_content").tab_id;
	if(!$(tab_id))return;
	var panel_pos = $(tab_id).panel_pos;

	PanelManager.getPanel(panel_pos).activeTab(tab_id);

	$("template_content").scrollTop = line * 12;

	var textarea = $("template_content");
	textarea.focus();

	if(document.all){//ie
		if(textarea.value.substring(0,pos).indexOf("\n") != -1){
			var step = textarea.value.substring(0,pos).match(/\n/g).length;
		}else{
			var step = 0;
		}

		var range = textarea.createTextRange();
		range.move('character', pos-step);
		range.select();
	}else{//other
		textarea.setSelectionRange(pos,pos);
	}

	textarea.focus();
}

function resizeTextArea(wrapper,container){

	var textarea = $("template_content");

	if(!wrapper)return;

	var diff = (is_ie) ? 0 : 2;

	textarea.style.width = wrapper.offsetWidth - diff + "px";
	textarea.style.height = wrapper.offsetHeight - diff + "px";
}

function resizeCSSEditArea(wrapper,container){

	var textarea = $("css_editor");

	if(!wrapper)return;
	if(!textarea)return;

	var adjustSize = function(element,node,size){
		var p_node = (node != null) ? node : element.parentNode;
		var height = p_node.offsetHeight;
		height = height - element.offsetTop - size;
		element.style.height = height + "px";	//borderとかの計算はとりあえず無視

		textarea.style.width = wrapper.offsetWidth - 173 + "px";
	};

	var container_id = $("css_editarea").container_id;
	if($(container_id)){
		if(is_ie){
			if($("css_editor"))adjustSize($("css_editor"),$(container_id).parentNode,40);
			if($("cssMenu"))adjustSize($("cssMenu").parentNode,$(container_id).parentNode,1);
		}else{
			if($("css_editor"))adjustSize($("css_editor"),$(container_id).parentNode,2);
			if($("cssMenu"))adjustSize($("cssMenu").parentNode,$(container_id).parentNode,2);
		}
	}

}

function showCSSEditor(){
	var csslist = $("css_editarea");

	var styles = getStyleSheet();
	if(styles.length == 0){
		return;
	}
	while($("css_list").firstChild){
		$("css_list").removeChild($("css_list").firstChild);
	}

	var option = document.createElement("option");
	option.value = "none";
	option.innerHTML = soycms.lang.template_editor.css_list_text;
	$("css_list").appendChild(option);

	for(var i=0; i< styles.length; i++){
		var option = document.createElement("option");
		option.value = styles[i];
		option.innerHTML =styles[i];
		$("css_list").appendChild(option);
	}
	
	if(csslist.active)return;

	csslist.show();
	csslist.active = true;
	PanelManager.getPanel("south").addTab("CSS",csslist,{onresize : resizeCSSEditArea, onclose : function(){
		csslist.active = false;
		document.body.appendChild(csslist);
		csslist.hide();
	}});

	$("css_editor").onblur = function(){
		if($("template_content_preview_wrapper"))showPreview()
	}
}

function onSelectCSS(selectedValue){
	CSSView.clear();

	if(selectedValue == "" || selectedValue == "none"){
		return false;
	}
	
	if($("save_css_button")){
		if(selectedValue.indexOf(siteURL) == 0){
			$("save_css_button").show();
		}else{
			$("save_css_button").hide();
		}
	}
	
	var link = selectedValue;//.replace(siteURL,"");

	new Ajax.Request(cssURL+"/GetCSS", {
		method: "post",
		parameters : "path=" + link,
		onSuccess:function(httpObj){
			$("css_editor").value = httpObj.responseText;
			CSSView.render();
		},
		onFailure:function(httpObj){
			$("css_editor").value = soycms.lang.common.read_error;
		}
	});
}

function getStyleSheet(){

	sync_code();

	var content = $("template_content").value;

	var iframe = $("getstylesheet_iframe");
	if(!iframe){
		var iframe = document.createElement("iframe");
		iframe.setAttribute("id","getstylesheet_iframe");
		iframe.src = "about:blank";
		iframe.style.display = "none";
		document.body.appendChild(iframe);
		iframe.contentWindow.document.write('<html><head><base href="'+siteURL+'"/></head><body></body></html>');
		iframe.contentWindow.document.close();
	}

	var doc = iframe.contentWindow.document;

	iframe.contentWindow.document.getStyleSheet = function(){
		var styles = new Array();

		var regExp = new RegExp('<\(link[^>]*\)>',"gi");
		var relRegExp = new RegExp('rel\s*=\s*["\']([^"\']*)["\']',"i");
		var hrefRegExp = new RegExp('href\s*=\s*["\']([^"\']*)["\']',"i");

		while(rs = regExp.exec(content)){
			var link = rs[1];
			var rel = relRegExp.exec(link);
			if(!rel || !rel[1].match(/stylesheet/i))continue;

			var href = hrefRegExp.exec(link);

			var tmp = doc.createElement("img");
			tmp.src = href[1];

			//if(tmp.src.indexOf(siteURL) == 0)styles.push(tmp.src);
			styles.push(tmp.src);
		}

		return styles;
	};

	var styles = iframe.contentWindow.document.getStyleSheet();

	//document.body.removeChild(iframe);

	return styles;
}

function saveCSS(){
	if($("css_list").value == "none"){
		return;
	}
	new Ajax.Request(cssURL+"/SaveCSS", {
		method: "post",
		parameters : $("css_editor").serialize()+'&'+$("css_list").serialize() + "&soy2_token=" + $("main_form").soy2_token.value,
		onSuccess:function(httpObj){
			var res = eval('(' + httpObj.responseText + ')');
			alert(res.result);
			$("main_form").soy2_token.value = res.soy2_token;
		},
		onFailure:function(httpObj){
			alert(soycms.lang.common.read_error);
		}
	});

}

function insertHTML(html){

	if(editor_mode == "editor"){
		var frame = $("template_editor_frame");
		frame.contentWindow.TemplateEditor.insertCode(html);


	}else{
		var textarea = $("template_content");
		textarea.insertHTML(html);
	}
}

//エディタの初期化
function init_template_editor(){

	var textarea = $("template_content");
	var frame = $("template_editor_frame");

	if(!frame.contentWindow || !frame.contentWindow.TemplateEditor){
		return;
	}

	var ua = navigator.userAgent;

	try{
		if(ua.match('MSIE')){
			frame.contentWindow.document.getElementById("main").contentEditable = true;
		}else{
			frame.contentWindow.document.designMode = "On";
		}
		frame.inited = true;
	}catch(e){
		//do nothing
	}

	var code = textarea.value;
	if(code.length < 1)code = "\n";
	frame.contentWindow.TemplateEditor.setCode(code);

	if(editor_mode != "editor"){
		editor_mode = "editor";
		toggle_editor();
	}

	//TextAreaも拡張する
	init_text_area(textarea);
}

//テンプレートエディタがactiveになったときに呼び出される
function activeTemplateEditor(){

	var ua = navigator.userAgent;
	var frame = $("template_editor_frame");

	if(frame.inited)return;

	if(!frame.contentWindow || !frame.contentWindow.TemplateEditor){
		return;
	}

	try{
		if(ua.match('MSIE')){
			frame.contentWindow.document.getElementById("main").contentEditable = true;
		}else{
			frame.contentWindow.document.designMode = "On";
		}
		frame.inited = true;

	}catch(e){
		//do nothing
	}

}

//エディタからHTMLを取得
function template_editor_get_code(){
	var frame = $("template_editor_frame");

	if(!frame.contentWindow || !frame.contentWindow.TemplateEditor){
		return $("template_content").value;
	}

	return $("template_editor_frame").contentWindow.TemplateEditor.getCode();
}

//テンプレートのみ保存
function save_template(url,ele){

	var loading;
	
	//ローディング
	if(ele != null){
		ele.setAttribute("disabled","disabled");

		loading = new Element("span");
		loading.addClassName("loading");
		loading.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";

		if(ele.nextSibling){
			ele.parentNode.insertBefore(loading,ele.nextSibling);
		}else{
			ele.parentNode.appendChild(loading);
		}

	}
	
	//AJAXで保存：soy2_tokenでこけたら5回までやり直す
	save_template_ajax(url,5,loading,ele);

}

function save_template_ajax(url,trials,loading,ele){
	var content = sync_code();

	//soy2_tokenが古い場合に備えて何回かやり直す
	if(trials>0){
		new Ajax.Request(
			url,
			{
				method : "POST",
				parameters : "template=" + encodeURIComponent(content) + "&soy2_token=" + $("main_form").soy2_token.value,
				onComplete : function(req){
	
					var res = eval('(' + req.responseText + ')');
					var done = false;
	
					if($("main_form"))$("main_form").soy2_token.value = res.soy2_token;
					
					if(res.status == '0'){
						trials--;
						save_template_ajax(url,trials,loading,ele);
					}else if(res.status == '-1'){
						done = true;
						alert(soycms.lang.template_editor.wrong_site);
					}else if(res.status == '1'){
						if($("block_list"))$("block_list").innerHTML = res.block;
						
						//CSSが追加されたらCSS編集ボタンを表示する
						if(getStyleSheet().length != 0 && $("cssButton")){
							$("cssButton").show();
						}

						done = true;
					}

					//ローディングを戻す
					if(done){
						if(loading != null)ele.parentNode.removeChild(loading);
						ele.removeAttribute("disabled");
					}

				}
			}
		);
	}else{
		//ローディングを戻す
		if(loading != null)ele.parentNode.removeChild(loading);
		ele.removeAttribute("disabled");

		alert(soycms.lang.template_editor.failed_to_save_template);
	}
}

var CSSView;
Event.observe(window,'load',function(){
	CSSView = new CSSList("cssMenu","css_editor");
	CSSView.lineHeight = 12;
});
function changeImageIcon(id){
	common_element_to_layer($("image_list"),
		{	width:200,
			height:150,
			targetId : "image_list_layer",
			onclose:function(){
				document.body.appendChild($("image_list"));
				$("image_list").hide();
			}});
	$("image_list").label_id = id;
	$("image_list").show();
}

function setChangeLabelIcon(filename,fileAddress){
	$("page_icon").value = filename;
	$("page_icon_show").src = fileAddress;
	
	common_close_layer_by_targetId("image_list_layer");
}