
////////////////////////////////// ajax controller \\\\\\\\\\\\\\\\\\\\\\\\\

function createXMLHttpRequest(){	// start Ajax
	var xmlHttp;
	if( window.ActiveXObject ){
		xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
	} else if( window.XMLHttpRequest ){
		xmlHttp = new XMLHttpRequest();
	}
	return xmlHttp;
}

function ControllerBase( iUrl ) {
	var date = new Date();
	var timestamp = date.getTime();
	this.url = iUrl;
	this.addUrlParameter( "time", timestamp );
}

ControllerBase.prototype.initView = function() {
	window.alert( "init coller view must be done by subclasses. " );
};

ControllerBase.prototype.doGet = function( asyn ) {
	this.initView();
	var controller = this;
	var xmlHttp = createXMLHttpRequest();	
	xmlHttp.onreadystatechange = function() {
		var xmlContent;
		if(xmlHttp.readyState==4){
			if(xmlHttp.status==200){
				controller.handle( xmlHttp );
			}
			controller.afterDoGet();
		}
	};
	var f = true;
	if( asyn===false ){
		f = false;
	}
	xmlHttp.open("GET", this.url, f );
//	alert( "url is " + this.url );
	xmlHttp.send(null);
};

ControllerBase.prototype.handle = function( xmlHttp ){
	xmlContent = xmlHttp.responseXML;
	this.dispatchXMLDocument( xmlContent );
	//alert( xmlHttp.responseText );
};

ControllerBase.prototype.dispatchXMLDocument = function( xml ){
};

ControllerBase.prototype.afterDoGet = function() {
};

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

ControllerBase.prototype.addUrlParameter = function( name, value, encodeToken ) {
	var index;
	var encodeName;
	var encodeValue;
	//alert( "encodeName=" + name + " encodeValue=" + value + " url=" +this.url );
	if( name ){
		if( value==null||value==undefined ){
			value = "";
		}
		if( encodeToken ){
			encodeName = name;
			encodeValue = value;
		}else{
			encodeName = encodeURIComponent( name );
			encodeValue = encodeURIComponent( value );
		}
		if( this.url ) {
			index = this.url.indexOf( "?" );
			if( index<0 ){
				this.url = this.url + "?";
			}else if( index != this.url.length-1 ){
				this.url = this.url + "&";
			}
			this.url = this.url + encodeName + "=" + encodeValue;
//			alert( "encodeName=" + encodeName + " encodeValue=" + encodeValue + " url=" +this.url );
		}
	}
};

AjaxController.prototype = new ControllerBase();

// override
AjaxController.prototype.dispatchXMLDocument = function( xml ){
	var response = xml.getElementsByTagName( "response" );
	//alert( " response = " + response );
	if( response ) {
		if( response.length>0 ) {
			for( i=0; i<response.length; i=i+1 ) {
				if( response[i] ) {
					this.dispatchResponse( response[i] );
				}
			}
		} else {
			alert( " with out response tag. " );
		}
	} else {
		alert( " unknown ajax response :" + response  );
	}
};

// the hook before dispatch records. 
AjaxController.prototype.beforeDispatchRecords = function( records ) {
	//window.alert( " beforeDispatchRecords, the records is: " + records );
};

AjaxController.prototype.beforeDispatchRecord = function( record ) {
};

AjaxController.prototype.emptyRecords = function() {
	//window.alert( " emptyRecords!" );
};

AjaxController.prototype.dispatchResponse = function( response ) {
	var records = response.getElementsByTagName( "record" );
	var record;
	if( records&&records.length>0 ) {
		this.beforeDispatchRecords( records );
		for( i=0; i<records.length; i=i+1 ) {
			record = records[i];
			if( record ) {
				this.beforeDispatchRecord( record );
				this.dispatchRecord( i, record );
			}
		}	
	} else {
		this.emptyRecords();
	}
};

AjaxController.prototype.dispatchRecord = function( i, record ) {
	var name = record.getElementsByTagName( "name" )[0];
	var value = record.getElementsByTagName( "value" )[0];
//	alert( "record " + i 
//		+ " name = " + name.firstChild.nodeValue 
//		+ " value = " + value.firstChild.nodeValue );
	var tagid;
	var tagvalue;
	if( name ) {
		if( value ) {
			tagid = name.firstChild.nodeValue;
			tagvalue = value.firstChild.nodeValue;
			if( typeof(tagid)=='string'&&typeof(tagvalue)=='string' ) {
				this.dispatchTagValue( trim( tagid ), trim( tagvalue ) );
			} else {
				alert( " the type of child of record " + i + " name or value is not string. "  );
			}
		} else {
			alert( " record " + i + " doesn't have value element. " );
		}
	} else {
		alert( " record " + i + " doesn't have name element. " );
	}
}; 

AjaxController.prototype.dispatchTagValue = function( tagid, tagvalue ) {
//	alert( " to insert value " + tagvalue 
//		+ " to tag which id is '" + tagid + "'." );
	var tag = document.getElementById( tagid );
	if( tag ) {
		tag.innerHTML = tagvalue; 
	} else {
		alert( " document doesn't have the tag which id is '" + tagid + "'." );
	}
};


////////////////////////// utils \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

function trim( s ) {
	if( s ) {
		if( typeof(s)=='string' ) {
			s = s.replace( /^[\s|\u3000]+/, "" );
			s = s.replace( /[\s|\u3000]+$/, "" );
		}
	}
	return s;
}

// added the javascript escape not processed seven characters: *@-_+./
function gipsescape( s ) {
//	alert( "called " );
	if( s ) {
		if( typeof(s)=='string' ) {
			s = escape( s );						// seven characters remain unchanged. 
			s = s.replace( /\*/g, 	'%2A' );		// *
			s = s.replace( /@/g, 	'%40' );		// @
			s = s.replace( /\-/g, 	'%2D' );		// -
			s = s.replace( /_/g, 	'%5F' );		// _
			s = s.replace( /\+/g, 	'%2B' );		// +
			s = s.replace( /\./g, 	'%2E' );		// .
			s = s.replace( /[\/]/g, '%2F' );		// /
			return s;
		} else {
			alert( " cannot gipsescape none string objects. " );
		}
	}
	return '';
}

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

function getImageContent( imgname, width, height ) {
	var content = "<table width=" + width 
		+ " height=" + height + ">"
		+ "   <tr><td width='100%' height='100%' align='center' valign='middle' >"
		+ "       <img src='" + imgname + "' border='0'/>"
		+ "       <br/>"
		+ "       载入中..."
		+ "   </td></tr></table>"
	;
	return content;
}

function doSearch() {
	var query = document.getElementById( "query" );
	if( query ) {
		var queryValue = query.value;
		queryValue = trim( queryValue );
		searchWord( queryValue );
	}
	return true;
}

function searchWord( queryValue ,targetBar , column ) {
	var reqUrl = "search.htm?q=" 
		+ encodeURIComponent( queryValue );
	if(targetBar != null){
		reqUrl = reqUrl + "&target=" + targetBar ;
	}
	if(column != null){
		reqUrl = reqUrl + "&tid=" + column ;
	}
	document.location= reqUrl ;
	return true;
}



function indexColumnWord( queryValue ) {
	var input = document.getElementById( "query" );
	input.value = queryValue;
	document.location="../search.htm?query=" 
		+ gipsescape( queryValue );
	return true;
}

function appendSearchWord( word ) {
	var query = getQueryFormUrl();
	if( query ) {
		searchWord( unescape( query ) + " " + word );
	}
}

function setGIPSHomePage() {
	var home = document.getElementById( "home" );
	home.style.behavior='url(#default#homepage)';
	home.setHomePage('http://www.shengso.com');
}

function doKeyDown( event ){					//enter event
	//alert( " do key down called! key code = " + event.keyCode );
	if( event.keyCode == 13 ){
		doSearch();
		event.returnValue=true;
	}
}

function setFocus() {
	var q = document.getElementById( "query" );
	if( q ) {
		q.focus();
	}
}

function fillQuery() {
	var queryStr = getQueryFormUrl();
	if( queryStr ) {
	var q = document.getElementById( "query" );
		q.value= unescape( queryStr );
	}
}

function getQueryFormUrl() {
	var forWardUrl=window.location.href;
	if( forWardUrl ) {
		var flag = "q";
		return getParamFromUrlString( flag, forWardUrl );
	}
	return "";
}

function getParamFromUrlString( param, url ) {
	var i; var index; var p; var v;
	var value = null;
	if( url ) {
		index = url.indexOf( "?" );
		if( index>=0 ) {
			var paramStr = url.substring( index+1 );
			index = paramStr.indexOf( "#" );
			if( index>=0 ) {
				paramStr = paramStr.substring( 0, index );
			}
			if( paramStr.length>0 ) {
				var pairs = paramStr.split("&");
				if( pairs ) {
					for( i=0; i<pairs.length; i=i+1 ) {
						index = pairs[i].indexOf( "=" );
						if( index!=-1 ) {
							v = pairs[i].substring( index+1 );
							p = pairs[i].substring( 0, index );
							if( p==param ) {
								if( v ) {
									value = v;
									break;
								}
							}
						}
					}
				}
			}
		}
	}
	return value;
}

// search logic for tabs.:

var callback = function( tabs, tab ){
	if( tab ) {
		if( tab.id=='web' ) {
			doFirstWebSearch();
		} else if( tab.id=="rssnews" ) {
			doRssNews();
		} else if( tab.id=="blog" ) {	
			setContent( "blogSearch.htm", tab );
		} else if( tab.id=="mp3" ) {	
			setContent( "mp3Search.htm", tab );
		} else {
			setContentFromUrl( tab.id );			// default callback, local search logic;
		}
	}
};

function setContent( urlPrefix, tab ) {
	if( urlPrefix ) {
		var queryString = getQueryFormUrl();
		if( !queryString ) {
			queryString = "";
		}
		var url = urlPrefix + "?queryString=" + queryString;
		if( tab ) {
			doAjaxGet( tab.id, url );
		}
	}
}

function setContentFromUrl( tabId, subtype ) {
	var url = "localSearch.htm";
	var divId = tabId;
	//var innerDiv = "<div ><table height='300'></table></div>";
	//tab.setContent( innerDiv );
	//var tagContainer = document.getElementById( tabId );
	//tagContainer.innerHTML = innerDiv;
	var queryString = getQueryFormUrl();
	if( !queryString ) {
		queryString = "";
	}
	url = url + "?type=" + getType( tabId, subtype ) 
		+ "&queryString=" + queryString;
	if( divId!='picture' ) {
		url = url + "&pageSize=5";
	} else {
		url = url + "&pageSize=9";
	}
	doAjaxGet( divId, url );
}

function showMp3( ev, obj ) {
	var ev=window.event||ev;
	ev.returnValue=false;
	return windowsOpen( obj.href,588,228,1,1 );
}

function windowsOpen( url, w, h, m, s ) {
	var left=(screen.width-w)/2;
	var top=m?(screen.height-h)/2:0;
	window.open(url,'','width='+w+',height='+h+',top='+top+',left='+left+',scrollbars=0,resizable=0,status='+s);
	return false;
}

function indexWord( queryValue ) {
	var input = document.getElementById( "headQuery" );
	input.value = queryValue;
	return true;
}


function setValueToInputTag( tagId, value ){
	var input = document.getElementById( tagId );
	if( input ){
		input.value = value;
	}
}

//////////////////////// show human image ///////////////////////////////////
function showImg(obj){
	var limit = 600;
	var w,h,k;
	w = obj.width;
	h = obj.height;
	k = w/h;
	if(k>1){
		if(obj.width> limit) {
			obj.width= limit ;
			obj.height = limit/k;
		}
	}else{
		if(obj.height> limit){
			obj.height = limit ;
			obj.width = k*limit ; 
		}
	}	
}

function bbimg(imgobj){
	var zoom = parseInt(imgobj.style.zoom)||100;
	zoom += event.wheelDelta/12 ;
	if(zoom>50)imgobj.style.zoom = zoom+'%';
	
	return false;
}


//function localDetail( div, param ) {
//	alert( param.url );
//}

function appendUrlParameter( url, name, value, encodeToken ){
	var index;
	var encodeName;
	var encodeValue;
	if( name ){
		if( !value ){
			value = "";
		}
		if( encodeToken ){
			encodeName = name;
			encodeValue = value;
		}else{
			encodeName = encodeURIComponent( name );
			encodeValue = encodeURIComponent( value );
		}
		if( url ) {
			index = url.indexOf( "?" );
			if( index<0 ){
				url = url + "?";
			}else if( index != url.length-1 ){
				url = url + "&";
			}
			url = url + encodeName + "=" + encodeValue;
			//alert( "encodeName=" + encodeName + " encodeValue=" + encodeValue + " url=" + url );
			return url;
		}
	}
	return url;
}

function setMode( mode ) {
	var i;
	var queryMode=document.getElementsByName('queryMode');
	queryMode[0].checked = true;				//default
	for(i=0;i<queryMode.length;i++){
		if( queryMode[i].value==mode ){  
		  queryMode[i].checked=true;
		  break;
		}
	}
}

// old school cookie functions grabbed off the web
var Cookies = {};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};



function simplifiedEdition() {
	Cookies.set( "charset", "simplified" );
	window.location.reload();
}

function traditionalEdition() {
	Cookies.set( "charset", "traditional" );
	window.location.reload();
}

function addFavourate() {
 	if (document.all) {
       window.external.addFavorite('http://www.shengso.com','盛搜语义网');
    } else if ( window.sidebar) {
       window.sidebar.addPanel('盛搜语义网', 'http://www.shengso.com', "");
 	}
}

function setHomepage() {
 	if (document.all) {
        document.body.style.behavior='url(#default#homepage)';
		document.body.setHomePage('http://www.shengso.com');
    } else if ( window.sidebar ) {
    	if(window.netscape) {
         	try {  
            	netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
         	}  catch ( e ) {  
    			alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,"
    			+ "然后将项 signed.applets.codebase_principal_support 值该为true" );  
         	}
    	} 
    	var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
    	prefs.setCharPref('browser.startup.homepage',
    		'http://www.shengso.com');
 	}
}

function viewCategory( tabUrl ) {
	return jumpUrlWithValue( tabUrl, "q" );
}

function toGlobalSearch() {
	return jumpUrlWithValue( "globalSearch.htm", "headQuery" );
}

function toCategorySearch( url ) {
	return jumpUrlWithValue( url, "headQuery" );
}

function jumpUrlWithValue( url, tagId ) {
	var query = document.getElementById( tagId ).value;
	if( query!="" ) {
		url = appendUrlParameter( url, "q", query );
	}
	document.location = url;
	return false;
}

function indexTryWord( atag ) { 
	var word = atag.innerHTML;
	//alert( word );
	var form = document.getElementById( 'qForm' );
	form.q.value = word;
	form.submit();
	return;
}

// web search 
function SearchController( iUrl, iDivId ) {
	AjaxController.call( this, iUrl );
	this.divId = iDivId;
}

SearchController.prototype = new AjaxController();

SearchController.prototype.initView = function() {
	loading( this.divId, 'images/loading/loading4.gif', '100%', '300', '0', false );
};

function initWebSearch(){
	var url = 'webSearch.htm';
	var controller = new SearchController( url );
	controller.addUrlParameter( "q", getQueryFormUrl(), true );
	controller.doGet();
}

function getById( id ) {
	return document.getElementById( id );
}

function doSearch( url, divId ) {
	var controller = new SearchController( url, divId );
	controller.addUrlParameter( "q", getById('q').value, false );
	controller.addUrlParameter( "toDiv", divId, true );
	controller.doGet();
	return false;
}

var cache = new Object();
function doTabSearch( divId, tabId, url, cssClass ,activeIcoCss,name) {
	changeTabCss( divId, tabId, cssClass );
	if(activeIcoCss != null){
		changeIconCss( divId, tabId, activeIcoCss );		
	}
	//黄志礼加，改变右侧信息列表上方位置
	if(name!=null){
			if( getById('result') != null){
				getById('result').innerHTML=name;
			}
			
	}
	var controller = new SearchController( url, divId );
	controller.doGet();
	return false;
}

function changeTabCss( block, tabId, cssClass ) {
	var oldTabId = cache[block];
	cache[ block ] = tabId;
	changeElementClass( oldTabId, "" );
	changeElementClass( tabId, cssClass );
	//父节点样式变化
	changeParentElementClass( oldTabId, "" );
	changeParentElementClass( tabId, "nav_sub_cur" );
}
function changeIconCss( block, tabId, activeCss) {
	block = block + "_ico" ;
	tabId = tabId + "ico" ;	// 与页面ID 有关 lawico
	var blockCss = block + "css" ;
	
	var oldTabId = cache[block];
	var notActiveCss = cache[ blockCss ] ;
	var element = getById( tabId );	
	if( element != null){
		cache[ block ] = tabId;		
		cache[ blockCss ] = element.className ;			
		changeElementClass( tabId, activeCss );		
	}
	if( oldTabId != null && tabId != oldTabId){		
		changeElementClass( oldTabId, notActiveCss );	
	}
	
	// alert( "Param:>"+ cache[ block ]);
	//alert( "Param:>"+ oldTabId + "@·@" + cssblock+"——" +oldCss　);
}


function changeElementClass( elementId, cssClass ) {
	var element = getById( elementId );
	if( element ) {
		element.className = cssClass;
	}
}
//父节点样式变化 黄志礼加
function changeParentElementClass( elementId, cssClass ) {
	var _element = getById( elementId );
	if(_element){
		var element=_element.parentNode;
		if( element ) {
			element.className = cssClass;
		}
	}
}

function changePage( url, divId ) {
	var controller = new SearchController( url, divId );
	controller.doGet();
	return false;
}


////////////////////////// text controller \\\\\\\\\\\\\\\\\\\

function TextController( iUrl, iDivId ) {
	ControllerBase.call( this, iUrl );
	if( iDivId ) {
		this.divId = iDivId;
	} else {
		alert( "text controller without divid" );
	}
}

TextController.prototype = new ControllerBase();

TextController.prototype.handle = function( xmlHttp ) {
	var text = xmlHttp.responseText;
	//alert( "text " + text );
	getById( this.divId ).innerHTML = text;
}

TextController.prototype.initView = function() {
	loading( this.divId, 'images/loading/loading4.gif', '100%', '300', '0', false );
};

function showDetailDialogue( tag, title, urlparams ) {
	getById( 'dialogue' ).innerHTML="";
	getById( 'dialogueTabTitle' ).innerHTML="";
	
	
	var i = 0; var urlparam;
	var tab;
	var lis = '';
	var first = "";
	for( i=0;i<urlparams.length;i=i+1 ) {
		urlparam = urlparams[ i ];
		var id = 'diag' + i;
		var script = ' doDialogueTabSearch( \'dialogue\', \'' + id + '\', \'' + urlparam.url + '?' + urlparam.params + '\', \'current\' ) ';
		var li = getLiElement( id, urlparam.title, script );
		//alert( li );
		lis += li;
		if( i==0 ) {
			first = script;
		}
	}
	var tab = getTab( lis );
	
	getById( 'dialogueTabTitle' ).innerHTML = tab;
	eval( first );
	
	showDiv( tag, title );// need yang's jquery api.
	return false;
}



function showDetailDialogue_new( tag, title, urlparams,type ) {
	var i = 0; var urlparam;
	var tab;
	var lis = '';
	var first = "";
	var url = '';
	for( i=0;i<urlparams.length;i=i+1 ) {
		urlparam = urlparams[ i ];
		url = type+'result.htm?method=viewDetail&keyword='+keyword+"&imageurl="+imageurl+'&' + urlparam.params ;
		break;
	}
	window.open (url);
	return false;
}

function showDetailDialogue_new2(type,dataTypeID,docId) {
	var url = type + 'result.htm?method=viewDetail&keyword='
	+ keyword 
	+"&imageurl="+imageurl
	+ "&queryString=" + encodeURIComponent(queryStr) 
	+ "&dataTypeID=" + dataTypeID
	+ "&docId=" + docId;
	window.open (url);
	return false;
}


function getLiElement( id, name, script ) {
	var li = '<li id=' + id + '><a href=\"#\" onclick=\" return ' + script + '\"><samp>' + name + '</samp></a></li>   \n';
	return li;
}

function getTab( allElement ) {
	var tab = '' ;
	  tab+=  '<ul>  \n';
	  tab+=	    allElement;
	  tab+=  '</ul>    \n';
	return tab;
}

function doDialogueTabSearch( divId, tabId, url, cssClass ) {
	changeTabCss( divId, tabId, cssClass );
	var controller = new TextController( url, divId );
	controller.addUrlParameter( "toDiv", "dialogue", true );		//fixed div.
	controller.doGet();
	return false;
}

function showDialogue( divId, title, urlparams ) {
	showDetailDialogue( getById( divId ), title, urlparams );
}

function changeKnWords( url ) {
	changePage( url, 'knwords' );
}
