var $ = function(id){
    return document.getElementById(id);
};
/*
* 解决innerHTML 不能执行 js脚本
*/
var global_html_pool = []; 
var global_script_pool = []; 
var global_script_src_pool = []; 
var global_lock_pool = []; 
var innerhtml_lock = null; 
var document_buffer = "";
function set_innerHTML(obj_id, html, time){	
    if (innerhtml_lock == null) { 
        innerhtml_lock = obj_id; 
    }else if (typeof(time) == "undefined") { 
        global_lock_pool[obj_id + "_html"] = html; 
        window.setTimeout("set_innerHTML('" + obj_id + "', global_lock_pool['" + obj_id + "_html']);", 10); 
        return; 
    }else if (innerhtml_lock != obj_id) { 
        global_lock_pool[obj_id + "_html"] = html; 
        window.setTimeout("set_innerHTML('" + obj_id + "', global_lock_pool['" + obj_id + "_html'], " + time + ");", 10); 
        return; 
    } 
    function get_script_id() { 
        return "script_" + (new Date()).getTime().toString(36) 
          + Math.floor(Math.random() * 100000000).toString(36); 
    } 
    document_buffer = ""; 
    document.write = function (str) { 
        document_buffer += str; 
    } 
    document.writeln = function (str) { 
        document_buffer += str + "\n"; 
    } 
    global_html_pool = []; 
    var scripts = []; 
    html = html.split(/<\/script>/i); 
    for (var i = 0; i < html.length; i++) { 
        global_html_pool[i] = html[i].replace(/<script[\s\S]*$/ig, ""); 
        scripts[i] = {text: '', src: '' }; 
        scripts[i].text = html[i].substr(global_html_pool[i].length); 
        scripts[i].src = scripts[i].text.substr(0, scripts[i].text.indexOf('>') + 1); 
        scripts[i].src = scripts[i].src.match(/src\s*=\s*(\"([^\"]*)\"|\'([^\']*)\'|([^\s]*)[\s>])/i); 
        if (scripts[i].src) { 
            if (scripts[i].src[2]) { 
                scripts[i].src = scripts[i].src[2]; 
            }else if (scripts[i].src[3]) { 
                scripts[i].src = scripts[i].src[3]; 
            }else if (scripts[i].src[4]) { 
                scripts[i].src = scripts[i].src[4]; 
            }else { 
                scripts[i].src = ""; 
            } 
            scripts[i].text = ""; 
        }else { 
            scripts[i].src = ""; 
            scripts[i].text = scripts[i].text.substr(scripts[i].text.indexOf('>') + 1); 
            scripts[i].text = scripts[i].text.replace(/^\s*<\!--\s*/g, ""); 
        } 
    } 
    var s; 
    if (typeof(time) == "undefined") { 
        s = 0; 
    }else{ 
        s = time; 
    } 
    var script, add_script, remove_script; 
    for (var i = 0; i < scripts.length; i++) { 
        var add_html = "document_buffer += global_html_pool[" + i + "];\n"; 
        add_html += "document.getElementById('" + obj_id + "').innerHTML = document_buffer;\n"; 
        script = document.createElement("script"); 
        if (scripts[i].src) { 
            script.src = scripts[i].src; 
            if (typeof(global_script_src_pool[script.src]) == "undefined") { 
                global_script_src_pool[script.src] = true; 
                s += 2000; 
            }else{ 
                s += 10; 
            } 
        }else { 
            script.text = scripts[i].text; 
            s += 10; 
        } 
        script.defer = true; 
        script.type =  "text/javascript"; 
        script.id = get_script_id(); 
        global_script_pool[script.id] = script; 
        add_script = add_html; 
        add_script += "document.getElementsByTagName('head').item(0)"; 
        add_script += ".appendChild(global_script_pool['" + script.id + "']);\n"; 
        window.setTimeout(add_script, s); 
        remove_script = "document.getElementsByTagName('head').item(0)"; 
        remove_script += ".removeChild(document.getElementById('" + script.id + "'));\n"; 
        remove_script += "delete global_script_pool['" + script.id + "'];\n"; 
        window.setTimeout(remove_script, s + 10000); 
    } 
    var end_script = "if (document_buffer.match(/<\\/script>/i)) {\n"; 
    end_script += "set_innerHTML('" + obj_id + "', document_buffer, " + s + ");\n"; 
    end_script += "}\n"; 
    end_script += "else {\n"; 
    end_script += "document.getElementById('" + obj_id + "').innerHTML = document_buffer;\n"; 
    end_script += "innerhtml_lock = null;\n"; 
    end_script += "}"; 
    window.setTimeout(end_script, s); 
}
/*!
* 封装的Ajax类
* @param function fnBefore     用户自定义函数 Ajax开始前执行，若无则为null
* @param function fnAfter      用户自定义函数 Ajax完成后执行，若无则为null
* @param function fnTimeout    用户自定义函数 Ajax请求超时后执行，若无则为null
* @param integer  iTime        设置超时时间 单位毫秒
* @param boolean  bSync        是否为同步请求，默认为false
*/
function API_ajax(fnBefore,fnAfter,fnTimeout,iTime,bSync){
	this.before		= fnBefore;
	this.after		= fnAfter;
	this.timeout	= fnTimeout;
	this.time		= iTime ? iTime : 10000;
	this.async		= bSync ? false : true;
	this._request	= null;
	this._response	= null;
}
API_ajax.prototype = {
	/**
	*  将需要发送的数据进行编码
	*  @param object data  JSON格式的数据，如: {username:"fyland",password:"ichenshy"}
	*/
	formatParam : function( data ){
		if ( ! data || typeof data != "object" ) return data;
		var k,r = [];
		for ( k in data ) {
			r.push([k,'=',encodeURIComponent(data[k])].join(''));
		}
		return r.join('&');
	},

	/**
	* 创建 XMLHttpRequest对象
	*/
	create : function(){
		if( window.XMLHttpRequest ) {
			this._request = new XMLHttpRequest();
		} else {
			try {
				this._request = new window.ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
		}
	},
	/**
	* 发送请求
	* @param string				url     请求地址
	* @param object or string   data    可以是字符串或JSON格式的数据，如: {username:"fyland",password:"ichenshy"}
	* @param string             method  请求方式 ： GET or POST
	* @param boolean            ifCache	返回数据是否在浏览器端缓存，默认为false;
	*/
	send : function(url,data,method,ifCache){
		if ( typeof this.before == "function" ) this.before();
		method = method.toUpperCase();
		this.create();
		var self = this;
		var timer = setTimeout(function(){
				if ( typeof self.timeout == "function" ) self.timeout();
				if ( self._request ) {
					self._request.abort();
					self._request = null;
				}
				return true;
			},this.time);
		var sendBody  = this.formatParam(data);
		if ( 'GET' == method ) {
			url = [url, ( url.indexOf('?') == -1 ? '?' : '&') ,sendBody].join('');
			sendBody = null;
		}
		if ( ! ifCache ) {
			url = [url, ( url.indexOf('?') == -1 ? '?' : '&') , "ajaxtimestamp=" , (new Date()).getTime()].join('');
		}
		this._request.open(method,url,this.async);
		if ( "POST" == method ) this._request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this._request.onreadystatechange = function(){
			if( self._request.readyState==4 ){
				if ( self._request.status==200 ){
					if ( timer ) clearTimeout(timer);
					self._response = self._request.responseText;
					if ( typeof self.after == "function") self.after(self._response);
				}
			}
		}
		this._request.send( sendBody );
	},
	/**
	*   简单的GET请求
	*
	*   @param string url  请求地址
	*   @param null or string or object	data
	*   @param object html element or string id	  e
	*   @param string loading                     loading时在e中的显示
	*   @param boolean  ifCache    浏览器是否缓存
	*/
	get : function(url,data,e,loading,ifCache){
		if ( typeof e == "string" ) e = $(e);
		if ( loading ) {
			var rg = /\.(gif|jpg|jpeg|png|bmp)$/i;
			if ( rg.test(loading) ){
				loading = ['<img src="', loading , '"  align="absmiddle" />'].join('');
			}
			this.before = function(){e.innerHTML = loading;}
		}
		this.after		= function(s){e.innerHTML = s;}
		this.timeout	= function(){e.innerHTML = ' 请求超时! ';}
		this.send(url,data,"GET",ifCache ? true : false);
	}
};



// 说明：用 Javascript 操作 Cookie
function API_getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}
function API_setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+'='+escape( value ) +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
        ( ( path ) ? ';path=' + path : '' ) +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}
function API_deleteCookie( name, path, domain ) {
    if ( API_getCookie( name ) ) document.cookie = name + '=' +
            ( ( path ) ? ';path=' + path : '') +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
/*
* 弹窗代码
*/
function API_popWindow(html){
	//step1. 创建div
	var divId = 'yst_tipBox';
	var tipBox = document.createElement('div'); 
	tipBox.id = divId; 
	tipBox.style.position = 'fixed'; 
	tipBox.style.zIndex = '100';
	tipBox.style.right = '0';
	tipBox.style.bottom = '0';
	//tipBox.style.display = 'none';
	document.body.appendChild(tipBox);
	set_innerHTML(divId,html,0);
	//$(divId).innerHTML = html;
}
function API_setTab(name,index,n){
	for(i=1; i<=n; i++){
		var menu = $(name+'_'+i);
		var tab = $('tab_'+name+'_'+i);
		menu.className = (i==index) ? 'select' : '';
		tab.style.display = (i==index) ? 'block' : 'none';
	}
}
/*
* 通过检测cookie yst_pop 的值决定是否弹窗，0或者不存在则继续弹，1为用户手动关闭
*/
function API_init(){
	//API_deleteCookie( 'yst_pop', '/', 'yanshuiting.com' );
	var yst_pop = API_getCookie('yst_pop');
	//console.log(yst_pop);
	if(yst_pop < 1){
		var host = 'http://'+window.location.host;
		var aj = new API_ajax();
		aj.before = function(){
			
		}
		aj.after = function(s){
			var json = eval('('+s+')'); //json字符串转换成json对象
			API_popWindow(json.html);
		}
		aj.timeout = function(){
		
		}
		aj.time = 3000;
		var data = {url:'http://www.yanshuiting.com/ystAPI/pop/pop.htm'};
		aj.send(host+'/apiClient.php',data,"GET");
	}
	
}
/*
* 关闭弹窗 type=remove
*/
function API_close(type){
	var obj = $('yst_tipBox');
	obj.style.display = 'none';
	if(typeof type != 'undefined' && type == 'remove'){
		API_setCookie( 'yst_pop', '1' , '2', '/', 'yanshuiting.com');
	}
}
window.onload = API_init;
