// 本地测试需修改 sSboxServerUrl为本地路径并把有sSboxDomain的地方去除.  
// 在线压缩网址：http://www.51240.com/jsmin/ (采用普通 压缩 )


SBOX = {
	//是否开启
	flag:true,
    // cookie有效期60天
    nExpireDate:60,
    // cookie名称  yesky_sharpshooter（MD5加密后的串）
    sSboxCookie:"B4165F4AE8D3053A6DFF1BD13162550D",
    // 转化点：conveyid MD5 加密之后
    sSboxConveyID:"AF745EA1344DCEDD3EAE72C00BEA2310", 
    // cookie path
    sSboxCookiePath:"/",
    // domain
    sSboxDomain:".yesky.com",
    // mbox 的名称
    sSboxName:"",
    // 服务器端url
    sSboxServerUrl:"http://sharpshooter.yesky.com/track/shooter.action",
//    sSboxServerUrl:"http://localhost:93/track/shooter.action",

    // refer url
    sReferUrl:"",
    // 广告推送ID
    conveyID:"0",
    // uv cookie名称
    uv_cookie:"tmg_ssu",
    // visit cookie名称
    visit_cookie:"tmg_visitu",
    // 创建sbox实例   sSboxName:sbox的名称
    sboxCreate:function(sSboxName){
	    if (SBOX.flag){
	    	SBOX.initSbox(sSboxName);
    		initCookie_Sbox();
	    }
	},
	// sbox的初始化
	initSbox:function (sName){
	    SBOX.sSboxName += sName + "|";
	    SBOX.sReferUrl = document.referrer;
	    SBOX.getConveyID();
	},
	// 获取服窗口中的隐藏域的值（广告推送ID） 转化sbox使用
	getConveyID:function(){
		SBOX.conveyID = getCookieParameters_Sbox(SBOX.sSboxConveyID);
		deleteCookieParameters_Sbox(SBOX.sSboxConveyID);
	}
}
	// 获取所有的cookie
	getCookieAll_Sbox = function(){
	     var sCookies = document.cookie;
	     return sCookies;
	}
    // 获取cookie中的数据
	getCookieParameters_Sbox = function(key){
	    var sCookie = document.cookie;
	    if (sCookie == null || sCookie.length < 0){
	        return "";
	    }
	    var arrayCookies = sCookie.split(";");
	    for (var n = 0; n < arrayCookies.length; n++){
	       var sCookieItem = arrayCookies[n];
	       if (sCookieItem == null || sCookieItem.length < 0){
	           continue;
	       }
	       var i = sCookieItem.indexOf("=");
	       if (i >= 1){
	    	   var sCookieKey = sCookieItem.substring(0,i);
		       var sCookieValue = sCookieItem.substring(i+1);
		       if (sCookieKey.replace(" ","") == key){
		           return sCookieValue;
		       }
	       }
	    }
	    return "";
	}
	// 打开广告页面 并将conveyid写入cookie
	send = function(url, conveyID){
		if (url == undefined || url.length <= 0){
			 return;
	    }
		addCookie_Sbox(SBOX.sSboxConveyID, conveyID, 0.15);
		window.open(url, 'new_window');
	}
	// 设置cookie (根据字符串)
	setCookieParameters_Sbox = function (cookies){
	    var expireDate = new Date();
	    expireDate.setTime(expireDate.getTime() + SBOX.nExpireDate * 24 * 60 * 60 * 1000);
		document.cookie = cookies + ";domain="+SBOX.sSboxDomain+";expires="+expireDate.toUTCString()+";path="+SBOX.sSboxCookiePath;
	}
	// 删除cookie
	deleteCookieParameters_Sbox = function (key){
	    var expireDate = new Date();
	    expireDate.setTime(expireDate.getTime() - 1);
	    document.cookie = key + "=;domain="+SBOX.sSboxDomain+"expire="+expireDate.toUTCString()+";path="+SBOX.sSboxCookiePath;
	}
	// 初始化cookie
	initCookie_Sbox = function(){
	    try {
	        if (getSharpShooterCookie(SBOX.uv_cookie) == null) {
	            addCookie_Sbox(SBOX.uv_cookie, getUID_Sbox(), 2 * 12 * 30 * 24 * 60);
	        }
	        if (getSharpShooterCookie(SBOX.visit_cookie) != null && getSharpShooterCookie(SBOX.visit_cookie).length > 0) {
	            setCookieTime_Sbox(SBOX.visit_cookie, 30);
	        } else {
	            addCookie_Sbox(SBOX.visit_cookie, getUID_Sbox(), 30);
	        }
	    } catch(a) {}
	}
	// 设定cookie
	addCookie_Sbox = function(a, b, c) {
	    var d = new Date();
	    d.setTime(d.getTime() + c * 60 * 1000);
	    document.cookie = a + "=" + escape(b) + ";domain="+SBOX.sSboxDomain+";expires=" + d.toUTCString() + ";path="+SBOX.sSboxCookiePath;
    }
	// 设定cookie的有效期
	setCookieTime_Sbox = function(a, b) {
	    var c = new Date();
	    c.setTime(c.getTime() + b * 60 * 1000);
	    document.cookie = a + "=" + escape(getSharpShooterCookie(a)) + ";domain="+SBOX.sSboxDomain+";expires=" + c.toUTCString() + ";path="+SBOX.sSboxCookiePath;
    }
	// 生成uid
	getUID_Sbox = function() {
	    var d = Math.random().toString().split(".")[1].split("");
	    var a = "";
	    while (d.length != 19) {
	        if (d.length < 19) {
	            d[d.length] = Math.round(Math.random());
	        } else {
	            if (d.length > 19) {
	                d[d.length] = null;
	            }
	        }
	    }
	    for (var c = 0; c < 19; c++) {
	        a += d[c];
	    }
	    var b = (new Date()).valueOf();
	    return b + a;
	}
	getSharpShooterCookie = function(b){
		var a = document.cookie.match(new RegExp("(^| )" + b + "=([^;]*)(;|$)"));
	    if (a != null) {
	        return unescape(a[2]);
	    }
	    return null;
	}
	var element = document.createElement("script");
    var keyword_js = null;

	// 跨域访问
	// boxname:sbox名称
	// cookies:sbox相关的cookie
	// root:搜索来源(即将去除)
	// conveyid：推送广告的id
	// visit: visitor
	// uv: uv sharpshooter自己的uv
	// passportuid: passport用户的id
	// yeskyuv: counter标示的uv
	createScript_Sbox = function(){
        var s = SBOX.sSboxServerUrl+"?boxname=" +
        ""+SBOX.sSboxName+"&cookies="+getCookieParameters_Sbox(SBOX.sSboxCookie)+"&root=" +
        ""+encodeURIComponent(SBOX.sReferUrl)+"&conveyid="+encodeURIComponent(SBOX.conveyID)+
        "&uv="+getSharpShooterCookie(SBOX.uv_cookie)+"&visit="+getSharpShooterCookie(SBOX.visit_cookie)+
        "&passportuid="+uidCookie()+"&yeskyuv="+getCounterCookie("tmg_utma");		
        if(keyword_js){			
			keyword_js = keyword_js.replace(" ","");
			keyword_js = keyword_js.replace(" ","");
			keyword_js = keyword_js.replace(" ","");			
            element.src = s+ "&keyword_js="+keyword_js;
        }else{
            element.src = s;
        }
		        element.type = "text/javascript";
		        element.language = "javascript";
	}
	// 根据响应信息 记录cookie或是显示广告
	writeContent_Sbox = function(){
		 if (msg != undefined && msg != null && msg.length > 0 && msg.indexOf("@#$%^&*") > -1){
			 var msgArray = msg.split("@#$%^&*");
			 for (var i = 0; i < msgArray.length; i++){
				 var msgStr = msgArray[i];
				 if (msgStr == null || msgStr.length <= 0){
					 continue;
				 }
				 // 监测性sbox 返回的数据写入cookie
				 if (msgStr.indexOf(SBOX.sSboxCookie) >= 0){
	                 setCookieParameters_Sbox(msgStr);
			     } else{ // 展示型sbox 返回的数据进行页面展示
				     document.getElementById("sboxDefault").innerHTML = "";
				     set_innerHTML_Sbox("sboxDefault", msgStr);
			     }
			 }
		 }
	}
	// 程序加载时 向服务器请求
	window.onload = function(){
		    createScript_Sbox(); // 这个就是请求后台 action
	        document.getElementsByTagName("head")[0].appendChild(element);
	}
	// 请求完毕 及js文件加载完成后，进行写cookie或是显示广告
	if(document.all){
	   element.onreadystatechange = function(){//IE用
	        var state = element.readyState;
	        if (state == "loaded" || state == "interactive" || state == "complete") {
	             writeContent_Sbox();  //这儿写cookie
	        }
	   };
	} else {
	   element.onload = function(){//FF用
	      writeContent_Sbox();
	   };
	}
	
    // 处理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 = "";
	set_innerHTML_Sbox = function(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 += 100;
	            } 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);
	}
	
	
    // sharpshooter version2.0 中添加, 获取passport用户的uid
	var Base64 = function() {
	}
	Base64.decode = function(str)
	{
	    var c1, c2, c3, c4;
	    var i, len, out;
	
	    len = str.length;
	    i = 0;
	    out = "";
	    while (i < len)
	    {
	        /* c1 */
	        do
	        {
	            c1 = Base64.decodeChars[str.charCodeAt(i++) & 0xff];
	        }
	        while (i < len && c1 == - 1);
	        if (c1 == - 1)
	            break;
	
	        /* c2 */
	        do
	        {
	            c2 = Base64.decodeChars[str.charCodeAt(i++) & 0xff];
	        }
	        while (i < len && c2 == - 1);
	        if (c2 == - 1)
	            break;
	
	        out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
	
	        /* c3 */
	        do
	        {
	            c3 = str.charCodeAt(i++) & 0xff;
	            if (c3 == 61)
	                return out;
	            c3 = Base64.decodeChars[c3];
	        }
	        while (i < len && c3 == - 1);
	        if (c3 == - 1)
	            break;
	
	        out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
	
	        /* c4 */
	        do
	        {
	            c4 = str.charCodeAt(i++) & 0xff;
	            if (c4 == 61)
	                return out;
	            c4 = Base64.decodeChars[c4];
	        }
	        while (i < len && c4 == - 1);
	        if (c4 == - 1)
	            break;
	        out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
	    }
	    return out;
	}

	getCookie = function(name) //取cookies函数
	{
	    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
	    if (arr != null) return unescape(Base64.decode(arr[2].toString()));
	    return null;
	}
	
	
	var findInfoCookie = "my_tmggroup_info_ck";
	// 获取passport的用户uid
	uidCookie = function(){
	    var uid = null;
	    var start = "uid=";
	    var info = getCookie(findInfoCookie);
	    //alert(info);
	    if (info != null) {
	        if (info.indexOf(start) != -1) {
	            uid = info.substring(info.indexOf(start)+start.length, info.length);
	        }
	    }
	    return uid;
	}

	// 获取天极网登陆的cookie标示 及uv  ： getCounterCookie("tmg_utma")
    getCounterCookie = function(b) {
	    var a = document.cookie.match(new RegExp("(^| )" + b + "=([^;]*)(;|$)"));
	    if (a != null) {
	        return unescape(a[2]);
	    }
	    return null;
   }






