
////////////////////////// like words logics \\\\\\\\\\\\\\\\\\\\\\

function LikeWordsController( iUrl ) {
	AjaxController.call( this, iUrl );
}

LikeWordsController.prototype = new AjaxController();

LikeWordsController.prototype.initView = function() {
	loadinglikeWords( 'likeWords', 'images/loading/loading6.gif', '100%', '0' );
};

function loadinglikeWords( tagid, imgname, width, height ) {
	var oldHeight = 0;
	var tag = document.getElementById( tagid );
	// preserve the old div height.
	if( tag ) {
		oldHeight = tag.offsetHeight;
		if( oldHeight ) {
			if( oldHeight > height ) {
				height = oldHeight;
			}
		}
		if( imgname ) {
			var content = getlikeWordsImageContent( imgname, width, height );
			tag.innerHTML = content;
		}
	}
}

/*
function getlikeWordsImageContent( imgname, width, height ) {
	var content = "<table width=" + width 
		+ " height=" + height + ">"
		+ "   <tr><td align='center' valign='middle' >"
		+ "       <img src='" + imgname + "' border='0'/>"
		+ "       <br/>"
		+ "   </td></tr></table>"
	;
	return content;
}*/

function getlikeWordsImageContent( imgname, width, height ) {
	var content = "<img src='" + imgname + "' border='0'/>";
	return content;
}

function changeLikeWords( url, pid ) {
	var controller = new LikeWordsController( url );
	controller.doGet();
}

/////////////////////////web like words logics/////////////////////

function WebLikeWordsController( iUrl ) {
	AjaxController.call( this, iUrl );
}

WebLikeWordsController.prototype = new AjaxController();

WebLikeWordsController.prototype.initView = function() {
	loadinglikeWords( 'webLikeWords', 'images/loading/loading6.gif', '100%', '0' );
};

function changeWebLikeWords( url, pid ) {
	var controller = new WebLikeWordsController( url );
	controller.doGet();
}

function initWebLikeWords(){
	var url = 'webLikeWords.htm';
	var controller = new WebLikeWordsController( url );
	controller.addUrlParameter( "q", getQueryFormUrl(), true );
	controller.doGet();
}
////////////////////////webSearchWithTitle//////////////////////////
function WebSearchWithTitleController( iUrl, iDivId ) {
	AjaxController.call( this, iUrl );
	this.divId = "webSearchWithTitle";
}

WebSearchWithTitleController.prototype = new AjaxController();

WebSearchWithTitleController.prototype.initView = function() {
	loading( "webSearchWithTitle", 'images/loading/loading4.gif', '100%', '300', '0' );
};
	
function webSearchWithTitle( url, pId ) {
	//alert( "url= "+url );
	var controller = new WebSearchWithTitleController( url );
	controller.doGet();
}

//////////////////////////localSearchWithTitle////////////////////////
function LocalSearchWithTitleController( iUrl, iDivId ) {
	AjaxController.call( this, iUrl );
	this.divId = "localSearchWithTitle";
}

LocalSearchWithTitleController.prototype = new AjaxController();

LocalSearchWithTitleController.prototype.initView = function() {
	loading( "localSearchWithTitle", 'images/loading/loading4.gif', '100%', '300', '0' );
};

	
function localSearchWithTitle( url, pId ) {
	//alert( "url= "+url );
	var controller = new LocalSearchWithTitleController( url );
	controller.doGet();
}

//////////////////////////humanImgInDialogue////////////////////////
function HumanImgInDialogueController( iUrl, iDivId ) {
	AjaxController.call( this, iUrl );
	this.divId = "humanImgInDialogue";
}

HumanImgInDialogueController.prototype = new AjaxController();

HumanImgInDialogueController.prototype.initView = function() {
	loading( "humanImgInDialogue", 'images/loading/loading4.gif', '100%', '300', '0' );
};
	
function humanImgInDialogue( url, pId ) {
	//alert( "url= "+url );
	var controller = new HumanImgInDialogueController( url );
	controller.doGet();
}
///////////////////////websiteInDialogue//////////////////////
function WebsiteInDialogueController( iUrl, iDivId ) {
	AjaxController.call( this, iUrl );
	this.divId = "websiteInDialogue";
}

WebsiteInDialogueController.prototype = new AjaxController();

WebsiteInDialogueController.prototype.initView = function() {
	loading( "websiteInDialogue", 'images/loading/loading4.gif', '100%', '300', '0' );
};
	
function websiteInDialogue( url, pId ) {
	//alert( "url= "+url );
	var controller = new WebsiteInDialogueController( url );
	controller.doGet();
}

////////////////////////medicine2illness//////////////////////
function medicine2illnessController( iUrl, iDivId ) {
	AjaxController.call( this, iUrl );
	this.divId = "medicine2illness";
}

medicine2illnessController.prototype = new AjaxController();

medicine2illnessController.prototype.initView = function() {
	loading( "medicine2illness", 'images/loading/loading4.gif', '100%', '300', '0' );
};
	
function medicine2illness( url, pId ) {
	//alert( "url= "+url );
	var controller = new medicine2illnessController( url );
	controller.doGet();
}
/////////////////////Dialogue humanImg detaile (to illness)/////////////////
function imageSearch( area ){
	var query = area.alt;
	if( !query ){
		return false;
	}
	panel.items.each( function(item){
         if ( item.closable ){
         	panel.remove(item);
         }
    } );
    var tabTitle = query + '的相关疾病';
	clickedOpenNewTab( tabTitle, 'dialogueHumanImg2Illness.htm', 'q', query );
}

////////////////////// tabs close menu \\\\\\\\\\\\\\\\\\\\\\\

// Very simple plugin for adding a close context menu to tabs

Ext.ux.TabCloseMenu = function(){
    var tabs, menu, ctxItem;
    this.init = function(tp){
        tabs = tp;
        tabs.on('contextmenu', onContextMenu);
    }

    function onContextMenu(ts, item, e){
        if(!menu){ // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: '关闭此页',
                handler : function(){
                    tabs.remove(ctxItem);
                }
            },{
                id: tabs.id + '-close-others',
                text: '关闭其他页',
                handler : function(){
                    tabs.items.each(function(item){
                        if(item.closable && item != ctxItem){
                            tabs.remove(item);
                        }
                    });
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(tabs.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        tabs.items.each(function(){
            if(this != item && this.closable){
                disableOthers = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-others').setDisabled(disableOthers);
        menu.showAt(e.getPoint());
    }
};

/////////////////// global var \\\\\\\\\\\\\\\

var win;			// the dialogue
var panel;          // the panel

function createWin( outer ) {		
	panel = new Ext.TabPanel({
	    plugins: new Ext.ux.TabCloseMenu(),
	    enableTabScroll:true,
	    deferredRender:false,
	    border:false
	});
	
	win = new Ext.Window( {
	    layout:'fit',
	    width:screen.availWidth*0.7,
	    height:screen.availHeight*0.6,
	    plain: true,
	    closeAction:'hide',
//	    modal:true,		
	    constrain:true,	// important.
	    onEsc:'hide',
	    maximizable:true,
//	    minimizable:true,
	    items: panel,
	    
	    buttons: [ {
	        text: '关闭',
	        handler: function() {
	        	win.hide();
	        }
	    }]
	});
	
	win.addListener( 
		"hide",
		function( ) {
			if( this.extlink ) {
				this.extlink.highlight(
					'#cadaf9'
					, { duration:1 }
				);
			}
//			this.extlink.dom.scrollIntoView();
			panel.items.each(
				function( tab ) {
					panel.remove( tab );
				}
			);
		}, 
		outer
	);
}

/**
 *	the tabs must contain { type, title, url, params } 
 */
function showDialogue( linkId, title, tabparams ) {
	if( linkId ) {
		this.extlink = Ext.get( linkId );
	} else {
		this.extlink = null;
	}
	if( !win ) {
		createWin( this );
	} 
	if ( !win.isVisible() ) {
		var i, tabp, tab;
		for( i = 0; i<tabparams.length; i=i+1 ) {
			tabp = tabparams[i];
			tab = new Ext.Panel( {
				title:tabp.title,
				autoScroll:true,
				id:( 'detail'+i ),
				listeners: { activate: function( tab ) {
						var id = tab.id;
						var index = tab.id.substring( 6, id.length );
						if( !this[id] ) {
							var mgr = tab.getUpdater();
							var updateOptions = tabparams[index];
							updateOptions.callback = function( el, success, response ) {
								var noresult = tab.getEl().query( "*[name=noresult]" );
								var tabi = id.substring( 6, id.length );
								var nextTabi = 1*tabi+1;
								if( noresult && ""!=noresult && (nextTabi<tabparams.length) ){
									panel.activate( nextTabi );
								}
							}
							mgr.update( updateOptions );
						}
						this[id] = true;// only update once.
		        	}
		        }
			} );
			panel.add( tab );
		}
		panel.activate( 0 );
		win.setTitle( title );
		win.restore();
		if( this.extlink ) {
			win.show( extlink.dom );
		} else {
			win.show();
		}
	}
}

function showTp( link, title, did ) {
	var q = link.innerHTML;
	var paramStr = "did=" + did + "&q=" + encodeURIComponent( q ); 
	showDialogue( link, title, [ {url:'dialogueSearchOneResult.htm', params:paramStr, title:title} ] );
	return false;
}

function showTpIntab( link, title, did ) {
	var q = link.innerHTML;
	var paramStr = "did=" + did + "&q=" + encodeURIComponent( q ); 
	addTabToDialogue( title, 'dialogueSearchOneResult.htm', paramStr, true );
	return false;
}
 

function showDialogueWithIframe( linkId, dialogueTitle, tabTitle, queryUrl ){
	if( linkId ) {
		this.extlink = Ext.get( linkId );
	} else {
		this.extlink = null;
	}
	if( !win ) {
		createWin( this );
	}
	var html = '<iframe src="'+ queryUrl + '" width="100%"  height="100%"></iframe>';
	if ( !win.isVisible() ) {
		var tab = new Ext.Panel( {
			title:tabTitle,
			autoScroll:true,
			html:html
		} );
		panel.add( tab );
		panel.activate( 0 );
		win.setTitle( dialogueTitle );
		win.restore();
		if( this.extlink ) {
			win.show( extlink.dom );
		} else {
			win.show();
		}
	}
}

function addTabToDialogue( tabTitle, queryUrl, paramsStr, isActivate ) {
	var uid = queryUrl + paramsStr;
	if( win ) {
		var newtab = panel.getItem( uid );
		if( !newtab ) {
			newtab = new Ext.Panel( {
				title:tabTitle,
				id:uid,
				autoScroll:true,
				closable:true,
				listeners: { activate: function( tab ) {
						var id = tab.id;
						if( !this[id] ) {
							var mgr = tab.getUpdater();
							mgr.update( { url:queryUrl, params:paramsStr } );
						}
						this[id] = true;// only update once.
		        	}
		        }
			} );
			panel.add( newtab );
		}
		if( isActivate!=false ) {
			panel.activate( uid );
		}
	}
}

function addTabToDialogueWithIframe( tabTitle, queryUrl, isActivate ) {
	var uid = queryUrl;
	var html = '<iframe src="'+ queryUrl + '" width="100%"  height="100%"></iframe>';
	if( win ) {
		var newtab = panel.getItem( uid );
		if( !newtab ) {
			newtab = new Ext.Panel( {
				title:tabTitle,
				id:uid,
				autoScroll:true,
				closable:true,
				html:html
			} );
			panel.add( newtab );
		}
		if( isActivate!=false ) {
			panel.activate( uid );
		}
	}
}

function clickedOpenNewTab( tabTitle, queryUrl, paramName, paramValue, isActivate ) {
	var paramsStr = paramName + "=" + encodeURIComponent( paramValue );
	addTabToDialogue( tabTitle, queryUrl, paramsStr, isActivate );
}

function localDetail( linkId, tabparams ) {
	showDialogue( linkId, "记录详细内容", tabparams );
}

// default index is 1 for red detail.
function clickedDetailTitle( linkId, tabparams, paramIndex ) {
	var index;
	if( paramIndex!=undefined ) {
		index = paramIndex;
	} else {
		index=1;
	}
	var tabp = tabparams[ index ];// only get the detail tab.
	var text = linkId.innerHTML;
	var title;
	if( text ) {
		title = text;
	} else {
		title = tabp.title;
	}
	addTabToDialogue( title, tabp.url, tabp.params );
}

function clickedKnowledgeWords( span, content ) {
	var text;
	this.extlink = Ext.get( span );
	if( !win ) {
		createWin( this );
	}
	win.setTitle( "关键词栏目跳转" );
	if( !content ) {
		text = span.innerHTML;
	} else {
		text = content
	}
	clickedOpenNewTab( text, "dialogueJumplist.htm", "q", text );
	if ( !win.isVisible() ) {
		win.show();
	}
}

// favorite delete dialogue
function checkAll( formID ){
	var formObj = document.getElementById(formID) ;
	for(var i=0; i<formObj.elements.length; i++ ){
		var chkone = formObj.elements[i];
		if( chkone.name != 'chkall' && chkone.type == 'checkbox' ){
			chkone.checked = formObj.chkall.checked ;
		}		
	}
}

function chk_chang( formID ){
	var form = document.getElementById(formID) ;
	if(form.chkall.checked == true ) 
		form.chkall.checked = false ;
}

function delCheck( formID , delchk){
	if ( confirm("确实要删除所选的收藏文章?") ){	
			 
		var formObj = document.getElementById(formID) ;
		for(var i=0; i<formObj.elements.length; i++ ){
			var chkone = formObj.elements[i];
			if( chkone.type == 'checkbox' ){
				if(chkone.value == delchk){
					chkone.checked = true ;
				} else {
					chkone.checked = false ;
				}			 					 	
			}
		} 
		var tab = panel.getActiveTab();
		var updater = tab.getUpdater();
		updater.formUpdate( formID );	
	}
}

function delCheckItems( formID ){
	var formObj = document.getElementById(formID) ;
	var i = 0;
	for(i=0; i<formObj.elements.length; i++ ){
		var chkone = formObj.elements[i];
		if( chkone.type == 'checkbox' && chkone.checked == true ) {
			break;
		}
	}
	if( i == formObj.elements.length ){
		alert( "请选择要删除的收藏信息!" );
	}else if ( confirm("确实要删除所选的收藏信息?") ){
		var tab = panel.getActiveTab();
		var updater = tab.getUpdater();
		updater.formUpdate( formID );			
	}
}	
function reNew( formID ){
	var formObj = document.getElementById(formID) ;
	var tab = panel.getActiveTab();
	var updater = tab.getUpdater();
	if(formObj != null){
		formObj.elements["act"].value = "";		
		updater.formUpdate( formID );	
	}else{		
		updater.update( { url:'showDialogueUrls.htm' } );
	}	
}

////////////////////////create TabPanel////////////////////////////////
/**
 *	the tabs must contain { title, divId, url, params } 
 */
function createTabPanel( linkId, tabparams, actTabIndex ) {	
	var father = document.getElementById("father");
	var width = father.clientWidth;
	
	var panel = new Ext.TabPanel({
	    renderTo:linkId,
	    frame:true,
	    width:width,
	    autoHeight:true,
	    plain:true,
	    defaults:{autoHeight: true}
	});
	var i, tabp, tab;
	for( i = 0; i<tabparams.length; i=i+1 ) {
		tabp = tabparams[i];
		if( i==actTabIndex ){
			var tab = new Ext.Panel( {
				title:tabp.title,
				id:( 'tab'+i ),
				contentEl:tabp.divId
			} );
		}else{
			var tab = new Ext.Panel( {
				title:tabp.title,
				id:( 'tab'+i ),
				html:'<div id="'+ tabp.divId + '"></div>',
				listeners: { activate: function( tab ) {
						var id = tab.id;
						var index = tab.id.substring( 3, id.length );
						if( !this[id] ) {
							localInfoTabPanel( tabp.url + '?' + tabp.params, tabp.divId );
						}
						this[id] = true;// only update once.
		        	}
		        }
			} );		
		}
		panel.add( tab );
	}
	panel.activate( actTabIndex );
}

function createTabPanel_bak2( linkId, tabparams, actTabIndex ) {	
	var father = document.getElementById("father");
	var width = father.clientWidth;
	//alert( "width="+width );
	var panel = new Ext.TabPanel({
	    //enableTabScroll:true,
	    //deferredRender:true,
	    //border:true,
	    renderTo:linkId,
	    activeTab:0,
	    frame:true,
	    defaults:{autoHeight: true},
	    width:width,
	    items:[{applyTo:tabparams[0].divId,title:tabparams[0].title}]
	});
}

/////////////////////////////////// ext example javascripts \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Ext.BLANK_IMAGE_URL = 'javascript/ext20/resources/images/default/s.gif';

Ext.example = function(){
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(1).ghost("t", {remove:true});
        },

        init : function(){
            var t = Ext.get('exttheme');
            if(!t){ // run locally?
                return;
            }
            var theme = Cookies.get('exttheme') || 'aero';
            if(theme){
                t.dom.value = theme;
                Ext.getBody().addClass('x-'+theme);
            }
            t.on('change', function(){
                Cookies.set('exttheme', t.getValue());
                setTimeout(function(){
                    window.location.reload();
                }, 250);
            });

            var lb = Ext.get('lib-bar');
            if(lb){
                lb.show();
            }
        }
    };
}();

Ext.onReady(Ext.example.init, Ext.example);

/////////////////ext quickTip//////////////
Ext.onReady(function(){
    Ext.QuickTips.init();
    
    Ext.apply(Ext.QuickTips.getQuickTip(), {
    	maxWidth: 380,
    	//minWidth: 100,
    	showDelay: 500,
    	//width: 300, 
    	trackMouse: false,
    	dismissDelay: 50000
	});
	//alert( "tool tip inited." );
});
//=========================================

//////////////// dialogues \\\\\\\\\\\\\\\\\\\\\

function addDialogueUrl( url, obj ) {
	
	var query = getTabAdditionalParam( "q" );			// get tab q first.
	if( !query ) {
		var urlQuery = getQueryFormUrl();
		if( urlQuery ){
			query = decodeURIComponent( urlQuery );
		}
	}
	if( !query ) {
		query = "";
	}
    var ch = getTabAdditionalParam( "c" );	// only get c from tab.

	var box = Ext.MessageBox.show({
           msg: '正在将此页信息添加到收藏夹，请稍候!',
           progressText: '数据传输中...',
           width:300,
           wait:true,
           waitConfig: {interval:200},
//           icon:'ext-mb-download', //custom class in msg-box.html
           animEl: obj
    });
    
    var timeStart = new Date().getTime();
    
    // delay caller.
    var caller = function( timeEnd, f ) {
    	var elapse = timeEnd - timeStart;
    	if( elapse<1500 ) {
    		setTimeout( f, 2000 - elapse );
    	} else {
    		f();
    	}
    }
    
    // fixed a bug for ext, waiting the box to be displayed.
    var hideBox = function() {
    	if( box.isVisible() ) {
    		box.hide();
    	} else {
    		setTimeout( hideBox, 1000 );
    	}
    }
    
	Ext.Ajax.request( {
   		url: 'addDialogueUrl.htm',
   		success: function() {
   			var f = function() {
   				hideBox();
   				Ext.example.msg( "提示", 
   					"操作成功！" );
   				Ext.get( obj ).setStyle( "display", "none" );
   			}
   			var timeEnd = new Date().getTime();
   			caller( timeEnd, f );
   		},
   		failure: function() {
   			var f = function() {
   				hideBox();
   				Ext.example.msg( "提示", 
   					"操作失败！" );
   			}
   			var timeEnd = new Date().getTime();
   			caller( timeEnd, f );
   		},
   		params: { u: url, q: query, c: ch } 
	} ) 
	
}

function getAdditionalParam( name ) {
	var v = "";
	var t = Ext.get( name );
	if( t ) {
		v = t.dom.value;
	}
	return v;
}

function getTabAdditionalParam( name ) {
	var activeTab = panel.getActiveTab();
	var tel = activeTab.getEl();
	var t = tel.query( "*[name=" + name + "]" );
	var v;
	if( t[0] ) {
		v = t[0].value;
	}
	return v;
}

function showDialogueUrls( tag ) {
	var id = null;
	if( tag ) {
		id = Ext.get( tag ).id;
	}
	showDialogue( 
		id, "收藏夹", 
		[{
			url:'showDialogueUrls.htm', 
			title:'收藏信息条目', 
			params:'a=1' 
		}] 
	);
}

// check the a tag is 

function checkJump( url ) { 
	document.location = url
	return false;
}

function checkTabJump( url, query, tabId ) { 
	if( globalSearch ) {
		document.location = "globalSearch.htm?q=" + encodeURIComponent( query ) 
			+ "&tabId=" + tabId ;
	} else {
		document.location = url
	}
	return false;
}


/* don't add the check to the step of logic.
function checkJump( url ) {
	var activeTab = panel.getActiveTab();
	var tel = activeTab.getEl();
	var t = tel.query( "*[name=addUrl]" );
	var v;
	if( t[0] ) {
		if( !( t[0].style.display=="none" ) ) {
			Ext.MessageBox.show( {
					title:'等待确认',
					msg: '该栏目跳转列表未被添加到收藏夹' +
					'是否真的进行栏目间的跳转？', 
					buttons:{yes:'确认', no:'取消'},
					fn:function( btn ) {
						if( btn=='yes' ) {
							document.location = url;
						}
					}
				}
			);
		} else {
			document.location = url;
		}
	} else {
		document.location = url;
	}
	return false;
}                                */

////////////////////ext form.FieldSet///////////////////////
function initFieldSet( size ){
	for( i=0; i<size; i=i+1 ){
		var input = document.getElementById( "title"+i );
		var title = '';
		if(input==null){
			title = '';
		}
		else{
			title = input.value;
			new Ext.form.FieldSet({
				title: title,
				collapsible:true,
				renderTo: 'render'+i,
				autoHeight:true,
				autoWidth:true,
				//width:200,
				contentEl:'content'+i
			});
		}
	}
}