var modules = new Array();
var linkWin = new Array();
var inccount = 1;
var serverpath = "";

// -------------------------------------------------------------- //
//get Incriment num
function getInccount() {
	inccount++;
	return inccount;
}

function formatDate(value){
	d = new Date(value * 1000);
	return value ? d.toLocaleString() : '-';
};

// -------------------------------------------------------------- //
//first Function of Document load
$(function() {
	new Ext.Viewport({
		layout: 'border',
		items: [{
			region: 'north',
			xtype: 'box',
			applyTo: 'header'
		}, new Ext.Panel({
			title: 'Tools',
			region: 'west',
			collapsible: true,
			layout:'accordion',
			width: 200,
			split: true,
	    layoutConfig: {
        animate: true
  	  },
			items: [{
				title: 'Main Menu',
				xtype: 'treepanel',
				autoScroll :true,
				loader: new Ext.tree.TreeLoader({
					dataUrl:serverpath+'/Ext_menu.json'
				}),
				root: treeroot = new Ext.tree.AsyncTreeNode({
					text: 'Root',
					id:'root'
				})
			}, modules["serchForm"] = new Ext.Panel({
        title: 'Site Serch',
				autoScroll :true,
				bodyStyle  :'background-color: white;',
				listeners  :{'enable':function(){
					genAjaxLink($('#serchForm_win'), this, "-1");
				}}
    	})]
		}), {
			region: 'center',
			xtype: 'panel',
			bodyStyle:"background-color: #eef;"
		}, {
			region: 'south',
			xtype: 'box',
			applyTo: 'footer'
		}]
	});
	treeroot.expand();
	modules["serchForm"].body.load({url:serverpath+'/Ext_serch.html',params:{noTemplate:1},callback:function(){modules["serchForm"].enable();},scripts:true});

//	getMenu();
//	getSerch();
	getNews();
});

// -------------------------------------------------------------- //
function getMenu(){
	var winid = "treeMenu";
	if(!modules[winid]){
		modules[winid] = new Array();
		modules[winid]['window'] = new Ext.Window({
			id         :winid,
			title      :winid,
			layout     :'fit',
			width      :240,
			height     :360,
			minWidth   :64,
			closable   :false,
			collapsible:true,
			bodyStyle:'background-color: white;',
			items:[modules[winid]['contents'] = new Ext.tree.TreePanel({
				autoScroll :true,
				loader: new Ext.tree.TreeLoader({
					dataUrl:serverpath+'/Ext_menu.json'
				}),
				root: treeroot = new Ext.tree.AsyncTreeNode({
					text: 'Root',
					id:'root'
				})
			})]
		});
		treeroot.expand();
		modules[winid]['window'].show();
		modules[winid]['window'].setPosition(24,96);
	} else {
		modules[winid]['window'].show();
	}
}

// -------------------------------------------------------------- //
function getSerch(){
	var winid = "serchForm";
	if(!modules[winid]){
		modules[winid] = new Array();
		modules[winid]['window'] = new Ext.Window({
			title      :winid,
			layout     :'fit',
			width      :320,
			height     :82,
			minHeight  :82,
			closable   :false,
			maximizable:true,
			collapsible:true,
			autoScroll :true,
			bodyStyle  :'background-color: white;',
			listeners  :{'enable':function(){
				$('form',$('#serchForm_win')).submit(function(){
					$.ajax({
						async     :false,
						url       :'/Ext_serch.html',
						type      :'POST',
						ifModified:true,
						dataType  :'html', //xml,html, script, json
						data      :{search:$('#ajaxSearch_input').val(),noTemplate:1},
						timeout   :300,
						success: function(html){
							modules['serchForm']['window'].body.update(html);
							genAjaxLink($('#serchForm_win'), this, "-1");
							if(html.length > 300 && modules['serchForm']['window'].getSize().height <= 300) modules['serchForm']['window'].setHeight(480);
						}
					});
					return false;
				});
			}}
		});
		modules[winid]['window'].show();
		modules[winid]['window'].body.load({url:'/Ext_serch.html',params:{noTemplate:1},callback:function(){modules[winid]['window'].enable();},scripts:true});

		modules[winid]['window'].setPosition(640,28);
	}
}

// -------------------------------------------------------------- //
function getNews(){
	var winid = "UpdateInfo";
	if(!modules[winid]){
		modules[winid] = new Array();
		modules[winid]['window'] = new Ext.Window({
			id         :winid,
			title      :winid,
			layout     :'fit',
			width      :480,
			height     :180,
			minHeight  :120,
			closable   :false,
			maximizable:true,
			collapsible:true,
			autoScroll :true,
			bodyStyle  :'background-color: white;',
			items: modules[winid]['grid'] = new Ext.grid.GridPanel({
				id         :winid + "Grid",
				store: store = new Ext.data.JsonStore({
					url: serverpath + '/Ext_news.json',
					root: 'entries',
					fields: Ext.data.Record.create([
						{name:"title", type:'string'},
						{name:"link", type:'string'},
						{name:"date", type:'string'},
						{name:"guid", type:'string'},
						{name:"author", type:'string'}
					])
				}),
				columns: [
					{header:"更新日", width:140, sortable:true, dataIndex:'date', renderer:formatDate},
					{header:"タイトル", width:240, sortable:true, dataIndex:'title'},
					{header:"リンク", width:240, sortable:true, dataIndex:'link'}
				],
				sm: new Ext.grid.RowSelectionModel({
					singleSelect:true,
					listeners  :{'rowselect':function(obj, rowIndex, record){
						link = record.get('link');
//						link = link.replace(serverpath+"/", "");
						link = link.replace("http://"+location.hostname+"/", "");
						if(link.indexOf('?') > -1) {
							link = link + "&noTemplate=1";
						} else {
							link = link + "?noTemplate=1";
						}
						getDoc(link, record.get('title'));
					}}
				})
			})
		});
		modules[winid]['window'].show();
		store.load();

		modules[winid]['window'].setPosition(360,360);
	}
}

// -------------------------------------------------------------- //
// Get the Document into Window
function getDoc(url,title){
	if(url.indexOf('http://') > -1 || url.indexOf('https://') > -1) {
		getLink(url);
		return false;
	}
	did = url.replace(/[^0-9a-z]/ig, "\-"); //make id
	//make longer Title is Short
	if(title.length > 60) {
		titlestr = title.substr(0,60) + "...";
	} else {
		titlestr = title;
	}
	if(!modules[url]){
		modules[url] = new Array();
		modules[url]['window'] = new Ext.Window({
			id         :'doc_'+did,
			title      :titlestr,
			layout     :'fit',
			width      :580,
			height     :480,
			closeAction:'hide',
			maximizable:true,
			collapsible:true,
			autoScroll :true,
			bodyStyle  :'background-color: white;',
			//Document Scripting after hook load callback(enable Event)
			listeners  :{'enable':function(){
				genAjaxLink($('#doc_'+did), this, null);
			}},
			tools:[{ //make Titlebar Tool
				id:'left', //Back navigation
				hidden:true,
				handler: function(event, toolEl, panel){
					if(panel['linkInc'] > 0) {
						panel['linkInc']--;
						link = panel['link'][panel['linkInc']];
						panel.body.load({url:link,params:{noTemplate:1},callback:function(){panel.enable()},scripts:true});
						if(panel['linkInc'] == 0) panel.tools.left.hide();
						panel.tools.right.show();
					}
				}
			},{
				id:'right', //Next navigation
				hidden:true,
				handler: function(event, toolEl, panel){
					if(panel['linkInc'] < panel['link'].length - 1) {
						panel['linkInc']++;
						link = panel['link'][panel['linkInc']];
						panel.body.load({url:link,params:{noTemplate:1},callback:function(){panel.enable()},scripts:true});
						if(panel['linkInc'] == panel['link'].length - 1) panel.tools.right.hide();
						panel.tools.left.show();
					}
				}
			}]
		});
		modules[url]['window'].show();

		//preparations link Navigation
		modules[url]['window']['linkInc'] = 0;
		modules[url]['window']['link'] = new Array();
		modules[url]['window']['link'].push(url);
		link = modules[url]['window']['link'][modules[url]['window']['linkInc']];
		//Document Ajax load
		modules[url]['window'].body.load({url:link,params:{noTemplate:1},callback:function(){modules[url]['window'].enable()},scripts:true});

		//Randam window position
		box = modules[url]['window'].getBox(true);
		pos_x = Math.floor(5*Math.random()) * 8 + box.x;
		pos_y = Math.floor(5*Math.random()) * 8 + box.y;
		modules[url]['window'].setPosition(pos_x,pos_y);
	} else {
		modules[url]['window'].show();
		modules[url]['window'].body.load({url:url,params:{noTemplate:1},callback:function(){modules[url]['window'].enable()},scripts:true});
	}
//Contents Change Expample:
//modules[url]['window'].body.update("HELLO!");
//Ext.getCmp('doc_'+url).body.update("HELLO!");
}

// -------------------------------------------------------------- //
// Out myDomain use ifarme Window
function getLink(url){
	cnt = getInccount();
	$('body').append("<div id='link_"+cnt+"'><iframe id='link_body_"+cnt+"' class='x-panel-body' style='frameBorder:0;width:100%;height:100%;' src="+url+"></iframe></div>");
	if(url.length > 60) {
		titlestr = url.substr(0,60) + "...";
	} else {
		titlestr = url;
	}
	linkWin[cnt] = new Array();
	linkWin[cnt]['window'] = new Ext.Window({
		applyTo: 'link_'+cnt,
		title      :titlestr,
		width      :540,
		height     :480,
		closeAction:'close',
		maximizable:true,
		collapsible:true,
		autoScroll :true,
		bodyStyle  :'background-color: white;',
		baseCls    :"x-panel"
	});
	linkWin[cnt]['window'].show();

	box = linkWin[cnt]['window'].getBox(true);
	pos_x = Math.floor(5*Math.random()) * 8 + box.x;
	pos_y = Math.floor(5*Math.random()) * 8 + box.y;
	linkWin[cnt]['window'].setPosition(pos_x,pos_y);
}

// -------------------------------------------------------------- //
//link of Loaded Document Change Ajaxload
function genAjaxLink(obj, wobj, wflg) {
	$('a', obj).each(function(){
		$(this).attr('href',$(this).attr('href').replace(serverpath,''));
		$(this).click(function(){
			if($(this).attr('href').indexOf('http://') > -1 || $(this).attr('href').indexOf('https://') > -1) {
				getLink($(this).attr('href'));
			} else if(wflg == "-1") {
				getDoc($(this).attr('href'),$(this).attr('href'));
			} else {
				link = $(this).attr('href')
				wobj['linkInc']++;
				wobj['link'].push(link);
				wobj.load({url:link,params:{noTemplate:1},callback:function(){wobj.enable()},scripts:true});
				wobj.tools.left.show();
			}
			return false;
		});
	});
	$('form',$('#serchForm_win')).submit(function(){
		$.ajax({
			async     :false,
			url       :serverpath+'/Ext_serch.html',
			type      :'POST',
			ifModified:true,
			dataType  :'html', //xml,html, script, json
			data      :{search:$('#ajaxSearch_input').val(),noTemplate:1},
			timeout   :300,
			success: function(html){
				modules["serchForm"].body.update(html);
				genAjaxLink($('#serchForm_win'), this, "-1");
			}
		});
		return false;
	});
	table2Grid();
}

// -------------------------------------------------------------- //
//html Table to Ext.grid convert
function table2Grid() {
	var thArray = new Array();

	$("th", "#table2grid").each(function(){
		thArray.push($(this).html());
	});

	if(thArray.length > 0) {
		var tdArray = new Array();
		var fields = new Array();
		var columns = new Array();

		$("tr", "#table2grid").each(function(){
			tmpArray = new Array();
			$("td", this).each(function(){
				tmpArray.push($(this).html());
			});
			if(tmpArray.length > 0) tdArray.push(tmpArray);
		});
		for(i = 0; i < thArray.length; i++) {
			fields.push({name:"td_"+i, type:'string'});
			columns.push({header:thArray[i], width:120, sortable:true, dataIndex:'td_'+i});
		}

		var store = new Ext.data.SimpleStore({
				fields: fields
		});
		store.loadData(tdArray);

		var grid = new Ext.grid.GridPanel({
				width: thArray.length * 120 + 20,
				store: store,
				columns: columns
		});
		$('#table2grid').html('');
		grid.render("table2grid");
	}
};

