try{
	window.addEvent('domready', show_fck);
	window.addEvent('unload', function(){try{GUnload()}catch(e){}});
}catch(e){}

function show_fck() {
    //alert('hello');
    var replaced = Array();
    var ii       = 0;
    var in_it    = 0;
    var obj      = document.getElementsByTagName('textarea');

    try {
        //alert( obj.length  );
        if( obj.length < 1 ) {
            return false;
        }

        for( i=0 ;i < obj.length; i++) {
            if( obj[i].type == "textarea" && obj[i].getAttribute("rel") == "fck" ) {
                in_it = 0;
                for( key in replaced ) {
                    if( replaced[key] == obj[i].id ) {
                        in_it = 1;
                    }
                }

                if( in_it == 0 ) {
                    //alert(obj[i].id);
                    replaced[ii] = obj[i].id;
                    ii++;

                    var oFCKeditor = new FCKeditor(obj[i].id) ;
                    oFCKeditor.BasePath = "/fckeditor/" ;
                    if(obj[i].getAttribute("toolbar")) {
                        oFCKeditor.ToolbarSet = obj[i].getAttribute("toolbar");
                    }
                    else {
                        oFCKeditor.ToolbarSet = "Basic";
                    }

                    // get the width and height of textarea
                    //alert( parseInt( obj[i].getAttribute("height") ) );
                    if(parseInt( obj[i].getAttribute("height") ) > 0) {
                        oFCKeditor.Height = parseInt( obj[i].getAttribute("height") ) ;
                        //alert( oFCKeditor.Height );
                    }

                    if(parseInt( obj[i].getAttribute("width") ) > 0) {
                        oFCKeditor.Width = parseInt( obj[i].getAttribute("width") ) ;
                    }
                    oFCKeditor.ReplaceTextarea() ;
                }
            }
        }
    }
    catch (e)
    {
    }
}

function do_fck( tid )
{
    var oFCKeditor = new FCKeditor( tid ) ;
    oFCKeditor.BasePath = "/fckeditor/" ;
    //alert( 'tool' + $(tid).getAttribute("toolbar") );
    if( $(tid).getAttribute("toolbar")  ) {
        oFCKeditor.ToolbarSet = $(tid).getAttribute("toolbar");
    }
    else {
        oFCKeditor.ToolbarSet = "Basic";
    }

    // get the width and height of textarea
    //alert( parseInt( obj[i].getAttribute("height") ) );
    if( parseInt( $(tid).getAttribute("height") ) > 0 ) {
        oFCKeditor.Height = parseInt( $(tid).getAttribute("height") ) ;
        //alert( oFCKeditor.Height );
    }

    if( parseInt( $(tid).getAttribute("width") ) > 0 ) {
        oFCKeditor.Width = parseInt( $(tid).getAttribute("width") ) ;
    }
    oFCKeditor.ReplaceTextarea() ;
}


function changecolor(){
	$("border1").toggleClass('mouseover');
	$("border2").toggleClass('mouseover');
	$("border3").toggleClass('mouseover');
	$("border4").toggleClass('mouseover');
	$("border5").toggleClass('mouseover');
}


function ajax_get_contents( to , from ,fun) {
	fun=eval(fun);
    var myAjax = new Ajax(from, {
        update: to,
        evalScripts: false,
        onComplete: function(res){
			try{
				fun(res);
			}catch(e){}
		}
     }).request();
}

function ajax_get_scripts( to , from  ,fun) {
	fun=eval(fun);
    var myAjax = new Ajax(from, {
        update: to,
		evalScripts:true,
        onComplete: fun
     }).request();
}
//ajax request with no update to dom
function ajax_request(from  ,fun) {
	fun=eval(fun);
    var myAjax = new Ajax(from, {
        onComplete: function(responseText){
			fun(responseText);
		}
     }).request();
}

function getPositions(obj){
    var el = obj, left = 0, top = 0;
    var overflown = [];
    do{
        left += el.offsetLeft || 0;
        top += el.offsetTop || 0;
        el = el.offsetParent;
    } while (el);

    overflown.each(function(element){
        left -= element.scrollLeft || 0;
        top -= element.scrollTop || 0;
    });

    return {'x': left, 'y': top};
}


document.onmousemove = function(e) {
    var event = e ? e : window.event;
    if (event.pageX) {  // Mozilla Firefox
        mouse_x = event.pageX;
        mouse_y = event.pageY;
    }
    else if (event.clientX) {
    	if(document.documentElement)   
		 mouse_x   =   document.documentElement.scrollLeft + event.clientX;
		 mouse_y   =   document.documentElement.scrollTop + event.clientY;
    }
}

//返回x坐标
function getX(){
    return mouse_x;
}

//返回y坐标
function getY(){
    return mouse_y;
}


function get_win_size() {
		var winWidth = 0;
		var winHeight = 0;
		
		//获取窗口宽度
		if (window.innerWidth)
		   winWidth = window.innerWidth;
		else if ((document.body) && (document.body.clientWidth))
		   winWidth = document.body.clientWidth;
		//获取窗口高度
		if (window.innerHeight)
		   winHeight = window.innerHeight;
		else if ((document.body) && (document.body.clientHeight))
		   winHeight = document.body.clientHeight;
		//通过深入Document内部对body进行检测，获取窗口大小
		if (document.documentElement && document.documentElement.clientHeight && 
		    document.documentElement.clientWidth)
		{
		   winHeight = document.documentElement.clientHeight;
		   winWidth = document.documentElement.clientWidth;
		}
		
		return {width: winWidth, height: winHeight};
		}

function func(res){
}

function clear_textarea(id){
	if($(id)){
		$(id).value = '';
	}
}

function get_form_value(name) {
    var queryString = [];
    $(name).getFormElements().each(function(ele) {
        var name  = ele.name;
        var value = ele.value;
		var type  = ele.type;
        var rel   = ele.getProperty('rel');

        if (rel != null && rel == 'fck' && typeof(FCKeditorAPI)!='undefined') {
            var editor = FCKeditorAPI.GetInstance(name);
            queryString.push(encodeURIComponent(name)+'='+encodeURIComponent(editor.EditorDocument.body.innerHTML));
        }else if (type == 'checkbox' && ele.checked == false) {
    }else if(type == 'radio' && ele.checked == false){
    	name = null;
    	value = null;
    }else {
			queryString.push(encodeURIComponent(name)+'='+encodeURIComponent(value));
		}
    });

	//解决ajax获取的form表单内的字段问题
	var hiddenString = [];
	$ES('input','name').each(function(ele){
		if(ele.type !== 'radio'){
			hiddenString.push(encodeURIComponent(ele.name)+'='+encodeURIComponent(ele.value));
		}
	});

	queryString = queryString.merge(hiddenString);

    return queryString;
}

function send_form(name,fun) {
    queryString = get_form_value(name);
    fun=eval(fun);
    return new Ajax($(name).getProperty('action'), {
        postBody: queryString.join('&'),
        method: 'post',
        onComplete: fun
    }).request();
}

function set_form(res) {
    var values = Json.evaluate(res);
    if( values['info'] == 'ok' ) {
    	values['msg'] = values['msg'] == false ? '操作成功！' : values['msg'];
    	info(values['msg'] ,values['location'] ,true)
    }
    else {
        info(values['info'], values['location'], false,function(){
        	(function(){
        		var box = $(values['msg']);
        		try{box.focus();}catch(e){};
        		if(box && (( box.tagName.toLowerCase() == 'input' && (box.type.toLowerCase() == 'text' || box.type.toLowerCase() == 'password')) || box.tagName.toLowerCase() == 'textarea')){
	        		var fx = box.effects({wait: true, duration: 300, transition: Fx.Transitions.Quart.easeOut});
					fx.start({'background-color':'#CC3333'}).chain(function(){fx.start({'background-color':'#FFFFFF'})});
				}
        	}).delay(50)
        });
    }
}


function resize_image(obj, MaxW, MaxH){
	var imageObject = obj;
	var state = imageObject.readyState;
	if(state!='complete'){
		//setTimeout("resizeImage("+imageObject+","+MaxW+","+MaxH+")",50);
		//return;
	}
	var oldImage = new Image();
	oldImage.src = imageObject.src;
	var dW = oldImage.width;
	var dH = oldImage.height;
	if(dW>MaxW || dH>MaxH){
		a = dW/MaxW; b = dH/MaxH;
		if( b>a ) a = b;
		dW = dW/a; dH = dH/a;
	}
	if(dW > 0 && dH > 0){
		imageObject.width = dW;
		imageObject.height = dH;
	}
}

function back(){
	this.location.href="javascript: history.back()";
}

function ajax_get_user_list(url){
	ajax_get_contents('user_list' ,url ,'func');
}

function ajax_get_notice_reply(url){
	ajax_get_contents('notice_reply' ,url ,'func');
}

function after_notice_reply(res){
	result = Json.evaluate(res);
	if(result['info']=='ok'){
		clear_textarea('content');
		ajax_get_notice_reply(result['location'])
	}else{
		set_form(res);
	}
}

function link(url,name){
	return '<a href="'+url+'">'+name+'</a>';
}

function last_points(){
	if($('last_points')){
		var temp = Cookie.get('point_cookie');
		temp = Json.evaluate(temp);
		var lastpoints = '';
		for(var a in temp){
			lastpoints = link('/point/display/id/'+a ,temp[a].replace(/\+/g, ' '))+'<br>'+lastpoints;
		}
		if(lastpoints!=''){lastpoints = '<div class=title >您最近浏览的地点....<br></div>' + lastpoints}
		$('last_points').innerHTML = lastpoints;
	}
}


function listen_form(){
	function fire_event(form){
		$(form).getChildren().each(function(ele) {
			if(ele.getProperty('onclick')){
//				ele.fireEvent('onclick');
				eval(ele.getProperty('onclick'));
			}
		});
	}
	var args;
	if(arguments.length == 1){
		args = 'event.key == \'enter\'';
	}else if(arguments.length == 2){
		args = 'event.key == \''+ arguments[1] +'\'';
	}else if(arguments.length > 2){
		args = 'event.key == \''+ arguments[1] +'\' && event.' + arguments[2];
	}else{
		return false;
	}
	var form = arguments[0];//防止丢失
	$(form).addEvents({
			'keyup': function(event) {
		        var event = new Event(event);
		        if (eval(args)) {
		        	fire_event(form);
		        }
		   }
	});
}


function tips(){
   this.width= 0;//提示窗口的宽度
   this.height=200;//提示窗口的高度,0为自适应
   this.titleheight=18 //提示窗口标题高度
   this.bordercolor="#999999";//提示窗口的边框颜色
   this.titlebackgroundcolor="#f0fae7";//提示窗口的标题颜色
   this.titlecolor="#f0fae7";//提示窗口的标题颜色
   this.titlebordercolor="#f0fae7";//提示窗口的标题颜色
   this.title = '大地提示';
   this.content='未定义';
   this.top = 0;
   this.left = 0;
   this.draggable = false;//是否可以拖动，有输入框时应该设置为true，否则火狐下有文字无法输入的bug
  // this.winsize = get_win_size();
  this.winWidth = getWidth();
  this.winHeight = getHeight();
  this.ajax=false;
  this.load = '';
   this.render = function(){
		
	   var msgObj=new Element('div',{
			'id':'msgDiv',
			'class':'fwinmask'
	   }); 

	   msgObj.style.position = "absolute";
       if(this.width) msgObj.style.width = this.width+'px';
	   if(this.height) msgObj.style.height = this.height+'px';

	   var boxhtml= '<table cellspacing="0" cellpadding="0" class="fwin"><tbody><tr><td class="t_l"/><td class="t_c"/><td class="t_r"/></tr><tr><td class="m_l"/><td id="fwin_content_login" class="m_c" style="" fwin="login"><div class="fcontent"><div id="layer_login" fwin="login"><h3 class="float_ctrl" id="fctrl_login" style="cursor: move;"><em id="returnmessage" fwin="login">' + this.title + '</em><span><a title="关闭" onclick="my_tip.remove();" class="float_close" href="javascript:;">关闭</a></span></h3><div class="postbox" id="bmsg"></div></div></div></td><td class="m_r"/></tr><tr><td class="b_l"/><td class="b_c"/><td class="b_r"/></tr></tbody></table>';
	   
	   this.remove =function(){
			 document.body.removeChild(msgObj);
		}

		msgObj.innerHTML = boxhtml;
		document.body.appendChild(msgObj);
		$('bmsg').innerHTML = '<img src="/images/autocomplete_spinner.gif" />加载中...';

		if(this.ajax){
			var myAjax = new Ajax(this.load,{
				method:'get',
				onComplete:function(responseText){
					$('bmsg').innerHTML = responseText;
				}
			}).request();	
		}else{
			$('bmsg').innerHTML = this.content;
		}
		
		this.top = this.top || document.documentElement.scrollTop +(this.winHeight-$('msgDiv').getStyle('height').toInt())/2;
		this.left = this.left || (this.winWidth-parseInt($('msgDiv').getStyle('width')))/2;
		msgObj.style.top = this.top+'px';
		msgObj.style.left = this.left+'px';


		if(this.draggable)
			new Drag.Move(msgObj, {});//有输入框时有bug

   }

   this.set = function(){
   		try{
   			this.remove();
   			eval('this.'+arguments[0] + '=' + arguments[1]);
   			this.render();
   			}catch(e){}
   		
   }
}



//输入提示
function jSuggest(obj){
	if(obj.values){
		var url = obj.url;
		var values = obj.values;
	}else{
		var url = obj.url;
	}
	var box = $(obj.id);
	var timer = (function(){}).delay(1);
	var current_a = null;
	box.position = box.getPosition();
	box.addEvent('blur' ,empty_div);
	
	box.addEvent('keyup', function (event){
		var event = new Event(event); 
   	    if(event.key == 'up'){
   	    	if(!current_a){
   	    		current_a = suggest_div.getLast();
   	    		box.value = current_a.innerHTML;
   	    	}else{
   	    		current_a.className = 'suggest-el';
   	    		current_a = current_a.getPrevious() || suggest_div.getLast();
   	    		box.value = current_a.innerHTML;
   	    	}
   	    	return current_a.className = 'suggest-el2';
   	    }
   	    else if(event.key == 'down'){
   	    	if(!current_a){
   	    		current_a = suggest_div.getFirst();
   	    		box.value = current_a.innerHTML;
   	    	}else{
   	    		current_a.className = 'suggest-el';
   	    		current_a = current_a.getNext() || suggest_div.getFirst();
   	    		box.value = current_a.innerHTML;
   	    	}
   	    	return current_a.className = 'suggest-el2';
   	    }
   	    else if(event.key == 'enter'){
 	    	if(current_a && box.value == current_a.innerHTML)
 	    		box_effects(box);
 	    	empty_div();
   	    }
   	    else{
			$clear(timer);
			timer = suggest_get_contents.delay(1000);
		}
	});
	
	function suggest_get_contents(){
		var value = obj.id+'/'+encodeURI(box.value.trim())+'/';
		if(obj.values){
			obj.values.each(function(el){
				if($(el)){
					value += el + '/' + encodeURI($(el).value) + '/';
				}
			});
		}
		if(value == '')return empty_div();
		var myAjax = new Ajax(url+value, {
	        evalScripts: false,
	        onComplete: format_content
	     }).request();
	}
	
	function format_content(res){
		var value = Json.evaluate(res); 
		empty_div();
		if(value.length===0)return;
		value.each(function(el){
			var a = new Element('a', {
			    'events': {
			        'mousedown': function(){
			           box.value = el;
					   (function(){box.focus()}).delay(1);
			           //box_effects(box);
			        },
			        'mouseover': function(){
			        	try{current_a.className = 'suggest-el';}catch(e){}
			        	current_a = this;
			        	this.className = 'suggest-el2';
			        }
			    },
			    'class': 'suggest-el'
			});
			a.innerHTML = el;
			a.inject(suggest_div);
		});
		open_div();
	}
	function empty_div(){
		current_a = null;
		suggest_div.empty();
		suggest_div.setStyle('display', 'none');
	}
	function open_div(){
		suggest_div.setStyle('display', 'block');
	}
	var suggest_div = new Element('div', {
		'id':'jSuggest',
	    'styles': {
	        'display': 'none',
	        'position':'absolute',
	        'z-index': 5000,
	        'top':box.position.y+box.getStyle('height').toInt()+box.getStyle('padding-top').toInt()+box.getStyle('padding-bottom').toInt()+box.getStyle('border-width').toInt()+'px',
	        'left':box.position.x+'px'
	    }
	});
	suggest_div.inject(document.body);
}


function get_url(url, title){
	loading();
	var myAjax = new Ajax(url,{
		method:'get',
		onComplete:function(responseText){
			try{my_tip.remove()}catch(e){};
			my_tip = new tips();
			my_tip.title = title;
			my_tip.content = responseText;
			loading('close');
			setTimeout(function (){my_tip.render();}, 10);
		}
	}).request(); 
}

function info(msg ,back ,flag ,fun){
	try{my_tip.remove()}catch(e){};
	my_tip = new tips();
	my_tip.width = 300;
	my_tip.draggable = true;
	my_tip.title = '大地百科-提示';
	var call = fun == undefined ? '' : fun;
	var gif = (flag == undefined || flag == false) ? '/images/!.gif' : '/images/yes.gif';
	var url = (back == false || back == true || back == undefined) ? 'javascript:my_tip.remove()' : back;
	my_tip.content = '<div align=center style="width:200px;"><img src='+gif+'>&nbsp;&nbsp;' + msg + '<br><br><a id=confirm href='+url+'>确定</a></div>';
	my_tip.render();
	$('confirm').focus();
	$('confirm').onclick = function(){try{fun()}catch(e){}};
}

function loading(flag, mes){
	if(flag=='close'){
		try{$('loading').remove();}catch(e){};
		return ;
	}
	var win_size = get_win_size();
	var loading = new Element('div', {
		'id':'loading',
	    'styles': {
	        'display': 'block',
	        'border': '1px solid #999999',
	        'padding':'5px 10px',
	        'position':'absolute',
	        'background':'#ffffff',
	        'top':(document.documentElement.scrollTop+win_size.height/2)+'px',
	        'left':(win_size.width/2-60)+'px'
	    }
	});
	if(mes!==undefined){
		loading.innerHTML = '<img src=/images/ajax-loading.gif> '+mes;
	}else{
		loading.innerHTML = '<img src=/images/ajax-loading.gif> 信息加载中...';
	}
	loading.inject(document.body);
}

// 去掉空格 ======================================================================
function trim(s){   
	return s.replace(/(^\s*)|(\s*$)/g,"");       
}   

function after_ajax_login(res){
	var values = Json.evaluate(res);
    if( values['info'] == 'ok' ) {
    	info('登录成功' ,false ,true, function(){eval(values['msg']+'()');})
    }else{
    	alert('用户名或密码不对');
    	try{$('uname').focus();}catch(e){}
    }
}



/**sub panel*****/

function toggle_sub_panel(id){
	if($(id).hasClass('sub_panel')){
		$('pOpenSubPanel_' + id).style.display = 'none';
		$('pCloseSubPanel_' + id).style.display = 'block';	
	}else{
		$('pOpenSubPanel_' + id).style.display = 'block';
		$('pCloseSubPanel_' + id).style.display = 'none';		
	}
	$(id).toggleClass('sub_panel');
}

/**********search bar*************/

function setStype(value){
	$('stype').value = value;
	$('selec_stype').toggleClass('show_unshow');
	$('slect_btn').src = '/images/s_' + value + '.png';
	$('keyword').focus();
}


function swap(id1,id2){
	$('updates-title-' + id1).style.display = "block";
	$('updates-title-' + id2).style.display = "none";
	$('point_' + id1).style.display = "block";
	$('point_' + id2).style.display = "none";
	$('point_li_' + id1).toggleClass("active");
	$('point_li_' + id2).toggleClass("active");
}
