﻿/**
 * Bind Method
 */
Function.prototype.Bind = function() { 
	var __m = this, object = arguments[0], args = new Array(); 
	for(var i = 1; i < arguments.length; i++){
		args.push(arguments[i]);
	}
	
	return function() {
		return __m.apply(object, args);
	}
};

var isIE = false;
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.indexOf('msie') != -1) && (userAgent.indexOf('opera') == -1)) {
	isIE = true;
}

if(typeof IO == 'undefined' )IO = {};
IO.Script = function(){
	this.Init.apply(this, arguments);
};

IO.Script.prototype = {
	_scriptCharset: 'gb2312',
	_oScript: null,
	
	/**
	 * Constructor
	 * 
	 * @param {Object} opts
	 */
	Init : function(opts){
		this._setOptions(opts);
	},
	
	_setOptions: function(opts) {
		if (typeof opts != 'undefined') {
			if (opts['script_charset']) {
				this._scriptCharset = opts['script_charset'];
			}
		}
	},
	
	_clearScriptObj: function() {
		if (this._oScript) {
			try {
				this._oScript.onload = null;
				if (this._oScript.onreadystatechange) {
					this._oScript.onreadystatechange = null;
				}
				
				this._oScript.parentNode.removeChild(this._oScript);
				//this._oScript = null;
			} catch (e) {
				// Do nothing here
			}
		}
	},
	
	_callbackWrapper: function(callback) {
		if (this._oScript.onreadystatechange) {
			if (this._oScript.readyState != 'loaded' && this._oScript.readyState != 'complete') {
				return;
			}
		}
		//throw(typeof callback);
		if (typeof callback != 'undefined') {
			callback();
		}
		
		this._clearScriptObj();
	},
	
	load: function(url, callback){
		this._oScript = document.createElement('SCRIPT');
		this._oScript.type = "text/javascript";
		
		if (isIE) {
			this._oScript.onreadystatechange = this._callbackWrapper.Bind(this, callback);
		} else {
			this._oScript.onload = this._callbackWrapper.Bind(this, callback);
		}
		
		this._oScript.charset = this._scriptCharset;
		this._oScript.src = url;
		
		//document.body.appendChild(this._oScript);
		var _ihead = document.getElementsByTagName("head").item(0);
		_ihead.appendChild(this._oScript);
	}
} 


if (!floater) var floater = {};
var floater_loop=null;
var floater_scroll_pixel=null;
var floater_gtpos=null;
var floater_gbpos=null;
var floater_moving_spd=null;
if(!outSelect) var outSelect = false;

floater = {
    title : "车型对比工具栏",
    sprites : "images/sprites.gif",
    btn_sprites : "images/btn-sprite.gif",
    padding : 10,
    speed : 10,
    top_margin : 116,
    height : 280,//168,
    width : 330,//210,
    text : "",
    expires : 3,
    cookieName : "collection",
    compedtext : "",
    compedNum : 6, //已对比工具栏COOKIE最大记录数
    compedCookie : "old_collection",
    moving_stat : 1,
    proNum : 4,
    Car_Brand : ["car_b"],
    Car_Series : ["car_s"],
    Car_Product : ["car_p"],
    outSelect : false,
    compObjId : "",
    init : function(){
        this.setStyle();
        this.getMain();
        this.check_scrollmove();
        this.setBtnDom("a0_CompAddBtn");
        this.setBtnDom("a0_CompBtn");
        this.setBtnDom("a0_CleanBtn");
        
        CookieCheck(this.cookieName, this.expires);
        CookieCheck(this.compedCookie, this.expires*999999);
        var iosc = new IO.Script();
		iosc.load("http://qiche.eastmoney.com/carbsp.ashx",floater.JsonSelectAdd);
    },
    setStyle : function(){
        var styleStr = "";
        styleStr += ".a0_icoShow,.a0_icoHidden,.a0_icoDelete,a0_icoDeleteOn,.a0_icoDown,.a0_icoSetting,.floater_Main .floater_Main_left .title { width:15px; height:15px; line-height:15px; background:url("+this.sprites+"); float:left;background-repeat:no-repeat; display:inline; margin:5px 0px 5px 3px; cursor:pointer; padding:0; overflow:hidden;}";
        styleStr += ".a0_BtnleftKok,.a0_BtnrightKok,.a0_BtnCenter { height:21px; line-height:21px; background:url("+this.btn_sprites+"); float:left;background-repeat:no-repeat; cursor:pointer;}";
        styleStr += ".floater_CompBtn { margin-top:0px;}";
        styleStr += ".a0_btn { height:21px; float:left; margin:0 7px 0 7px;}";
        styleStr += ".a0_BtnleftKok,.a0_BtnrightKok { width:3px; font-size:1px;}";
        styleStr += ".a0_BtnleftKok { background-position:0 0;}";
        styleStr += ".a0_BtnrightKok { background-position:0 -21px;}";
        styleStr += ".a0_BtnCenter { background-position:0 -42px;background-repeat:repeat-x; padding:0 12px 0 12px;}";
        styleStr += ".a0_btnOn .a0_BtnleftKok { background-position:0 -63px;}";
        styleStr += ".a0_btnOn .a0_BtnrightKok { background-position:0 -84px;}";
        styleStr += ".a0_btnOn .a0_BtnCenter { background-position:0 -105px;}";
        styleStr += ".a0_btnDown .a0_BtnCenter { background-position:0 -126px;}";
        styleStr += ".a0_icoHidden { background-position:0 -15px;}";
        styleStr += ".a0_icoDown,.a0_icoSetting { height:16px; margin:3px 7px 3px 7px;}";
        styleStr += ".a0_icoDown { background-position:0 -45px; width:11px;}";
        styleStr += ".a0_icoSetting { background-position:-14px -45px; width:16px; }";
        styleStr += ".a0_reco { clear:both; display:block; height:24px; line-height:24px; overflow:hidden; font-size:14px;}";
        styleStr += ".a0_reco .a0_icoDeleteOn { background-position:0 -30px; float:right;}";
        styleStr += ".a0_reco .a0_icoDelete { background-position:-15px -30px; float:right; height:14px; line-height:14px;}";
        styleStr += ".a0_reco .a0_baise { float:left;}";
        styleStr += "#floater_Hidden div,.floater_Main .hiddenBtn { cursor:pointer;width:22px;background:url(images/comprightbg.gif);background-repeat:repeat-y; color:#FFF; text-align:center; font-size:14px; font-weight:bold;}"
        styleStr += "#floater_Hidden { display:inline;float:left; border:1px solid #E54602;width:24px; }";
        styleStr += "#floater_Hidden div{height:"+ (this.height - 118) +"px; border:1px solid #FFB785; }";
        styleStr += "#floater_Show { float:left; width:"+ (this.width + 24) +"px; font-size:12px; border:1px solid #FF7102; background:#FFF;}";
        styleStr += "#floater_SelObject select{ width:110px; height:20px; font-size:12px;}";       
        styleStr += ".onBtn { background:#FB6711;}";
        styleStr += ".floater_Main .floater_Main_left { float:left; width:"+ this.width +"px; height:"+this.height+"px;}";
        styleStr += ".floater_Main .floater_Main_left .title{ height:24px; line-height:24px; font-size:14px; font-weight:bold; width:auto; background-position:0 -61px;background-repeat:repeat-x; width:"+this.width+"px; margin:0; border-top:1px solid #FFB785; border-bottom:1px solid #FF7102; color:#FFF;}";
        styleStr += ".floater_Main .floater_Main_left #floater_CompObject{ padding:4px; line-height:24px; clear:both; height:"+(this.height - 180)+"px; }";
        styleStr += ".floater_Main .floater_Main_left .floater_CompBtn{ }";
        styleStr += ".floater_Main .hiddenBtn { float:right; border:1px solid #FFB785; height:"+this.height+"px;}";
        styleStr += ".floater_spacer { font-size:1px; clear:both; line-height:1px; height:8px;}"
        styleStr += ".floater_Main .floater_Main_left .floater_OldComped{ clear:both; height:98px; background:#FFF0C5; }";
        styleStr += ".floater_OldComped #floater_CompedObject{ }";
        styleStr += ".floater_OldComped #floater_CompedObject ul{ height:24px; line-height:24px; list-style:none; margin:0; padding:0; clear:both; overflow:hidden; }";
        styleStr += ".floater_OldComped #floater_CompedObject ul li{ float:left; width:50%; font-size:13px; cursor:pointer;}";
        styleStr += ".floater_OldComped #floater_CompedObject ul li span{ text-decoration:underline;}";
        
        var styleId = "floaterSheet";
        var _head = document.getElementsByTagName("head").item(0);
				var _old = document.getElementById(styleId);
				if (_old) _head.removeChild(_old);
				var mystyle = document.createElement("style");
				mystyle.type = "text/css";
				mystyle.id = styleId;
				if(mystyle.styleSheet){// IE
					mystyle.styleSheet.cssText = styleStr;
				} else {// w3c
					var cssText = document.createTextNode(styleStr);
					mystyle.appendChild(cssText);
				}
				//mystyle.innerHTML = styleStr;
				_head.appendChild(mystyle);

    },
    JsonSelectAdd : function (){
        var s = selects;
        var a = $('f_car_b');
        var b = $('f_car_s');
        var c = $('f_car_p');
        s.bind(a,cb);s.bind(b,cs);s.bind(c,cp);
        s.parent(a,b);s.parent(b,c);
        if(floater.outSelect) floater.OutJsonSelectAdd();
    },
    OutJsonSelectAdd : function (){
        var s = selects;
        var objCount = this.Car_Brand.length
        if(this.Car_Series.length == objCount && this.Car_Product.length == objCount){
            for(var i = 0; i < objCount; i++){
                var a = $(this.Car_Brand[i]);
                var b = $(this.Car_Series[i]);
                var c = $(this.Car_Product[i]);
                s.bind(a,cb);s.bind(b,cs);s.bind(c,cp);
                s.parent(a,b);s.parent(b,c);
            }
        }
    },
    getMain : function (){
        var divStr = "";
        divStr += "\t<div id=\"floater_Hidden\" style=\"display: block;\" onclick=\"floater.setVisible()\"><div><b class=\"a0_icoShow\"></b>"+this.title+"</div></div>\n";
        divStr += "\t<div id=\"floater_Show\" style=\"display: none;\">\n";
        divStr += "\t\t<div class=\"floater_Main\">\n";
        divStr += "\t\t\t<div class=\"floater_Main_left\">\n";
        divStr += "\t\t\t\t<div class=\"title\"><b class=\"a0_icoDown\"></b>"+this.title+"</div>\n";
        divStr += "\t\t\t\t<div id=\"floater_SelObject\"><select id=\"f_car_b\"></select><select id=\"f_car_s\"></select><select id=\"f_car_p\"></select></div>\n";
        divStr += "\t\t\t\t<div id=\"floater_CompObject\">等待添加...</div>\n";
        divStr += "\t\t\t\t<div class=\"floater_CompBtn\">\n";
        divStr += "\t\t\t\t\t<div id=\"a0_CompAddBtn\" class=\"a0_btn\" onclick=\"floater.compadd('f_car_p')\">\n";
        divStr += "\t\t\t\t\t\t<b class=\"a0_BtnleftKok\"></b>\n";
        divStr += "\t\t\t\t\t\t<div class=\"a0_BtnCenter\">添加对比</div>\n";
        divStr += "\t\t\t\t\t\t<b class=\"a0_BtnrightKok\"></b>\n";
        divStr += "\t\t\t\t\t</div>\n";
        divStr += "\t\t\t\t\t<div id=\"a0_CompBtn\" class=\"a0_btn\" onclick=\"floater.compare()\">\n";
        divStr += "\t\t\t\t\t\t<b class=\"a0_BtnleftKok\"></b>\n";
        divStr += "\t\t\t\t\t\t<div class=\"a0_BtnCenter\">查看对比结果</div>\n";
        divStr += "\t\t\t\t\t\t<b class=\"a0_BtnrightKok\"></b>\n";
        divStr += "\t\t\t\t\t</div>\n";
        divStr += "\t\t\t\t\t<div id=\"a0_CleanBtn\" class=\"a0_btn\" onclick=\"floater.clear()\">\n";
        divStr += "\t\t\t\t\t\t<b class=\"a0_BtnleftKok\"></b>\n";
        divStr += "\t\t\t\t\t\t<div class=\"a0_BtnCenter\">清除数据</div>\n";
        divStr += "\t\t\t\t\t\t<b class=\"a0_BtnrightKok\"></b>\n";
        divStr += "\t\t\t\t\t</div>\n";
        divStr += "\t\t\t\t</div>\n";
        divStr += "\t\t\t\t<div class=\"floater_spacer\"></div>\n";
        divStr += "\t\t\t\t<div class=\"floater_OldComped\">\n";
        divStr += "\t\t\t\t\t<div class=\"title\"><b class=\"a0_icoDown\"></b>对比过的车型</div>\n";
        divStr += "\t\t\t\t\t<div id=\"floater_CompedObject\"></div>\n";
        divStr += "\t\t\t\t</div>\n";
        divStr += "\t\t\t</div>\n";
        divStr += "\t\t\t<div class=\"hiddenBtn\" onclick=\"floater.setVisible()\"><b class=\"a0_icoHidden\"></b></div>\n";
        divStr += "\t\t</div>\n";
        divStr += "\t</div>\n";
        //divStr += "<div id=\"floater_div_id\" style=\"left:0px; position: absolute; top:"+this.top_margin+"px; z-index:1000\">\n"
        //divStr += "</div>\n";
        //document.write(divStr);
        
        var divId = "floater_div_id";
        var _mainbody = document.getElementsByTagName("body").item(0);
				var _oldDiv = document.getElementById(divId);
				if (_oldDiv) _mainbody.removeChild(_oldDiv);
				var myDiv = document.createElement("div");
				myDiv.id = divId;
				myDiv.style.left = "0px";
				myDiv.style.top = this.top_margin + "px";
				myDiv.style.position = "absolute";
				myDiv.style.zIndex = "1000";
				
				myDiv.innerHTML = divStr;
				
				document.getElementById("floatComp").appendChild(myDiv);

				/**/
    },
    setBtnDom : function (el){
        var obj = $(el);
        var onClass = " a0_btnOn";
        var downClass = " a0_btnDown";
        var overF = function(e){
            if (obj.className.indexOf(onClass) < 0)
                obj.className += onClass;
        };
        var outF = function(e){
            obj.className = obj.className.replace(onClass,"");
        }
        var downF = function(e){
            if (obj.className.indexOf(downClass) < 0)
                obj.className += downClass;
        }
        var upF = function(e){
            obj.className = obj.className.replace(downClass,"");
        }
        dom.addEvent(obj, "mouseover", overF, false);
        dom.addEvent(obj, "mouseout", outF, false);
        dom.addEvent(obj, "mousedown", downF, false);
        dom.addEvent(obj, "mouseup", upF, false);
    },
    setVisible : function (){
        if($("floater_Hidden").style.display == "block"){
            $("floater_Show").style.display = "block";
            $("floater_Hidden").style.display = "none";
        }else if($("floater_Show").style.display == "block"){
            $("floater_Hidden").style.display = "block";
            $("floater_Show").style.display = "none";
        }
    },
    add : function (id, name){
        //alert(this.cookieName);
        $("floater_Show").style.display = "block";
        $("floater_Hidden").style.display = "none";
        var str = getCookie(this.cookieName);
        
        var str1 = id + "%%%" + name;
        //需要检查是否已存在相同项 以及是否超出了个数
        var show = str.split("@");
        if(show.length > 1)
        for(i = 1; i < show.length; i++){
            if(show[i] == str1){
                alert("此车型已经添加到了对比窗口中！");
                return;
            }
        }
        if(show.length <= this.proNum){
            str = str + "@" + str1;
            setCookie(this.cookieName, str, this.expires);
            this.compedAdd(id, name);
        }else{
            alert("最多只能选择 " + this.proNum + " 种车型进行对比！");
        }
    },
    compedAdd: function(id, name){
        var str = getCookie(this.compedCookie);
        
        var str1 = id + "%%%" + name;
        //需要检查是否已存在相同项 以及是否超出了个数
        var show = str.split("@");
        var tempStr = "";
        if(show.length > 1){
            for(i = 1; i < show.length; i++){
                if(show[i] != str1){
                    tempStr += "@"+show[i];
                }
                if(i>this.compedNum) break;
            }
            tempStr = "@" + str1 + tempStr;
        }else{
            tempStr = "@" + str1;
        }
        setCookie(this.compedCookie, tempStr, this.expires*999999);
    },
    del: function (id, name){
        var str = getCookie(this.cookieName);
        if(str != ""){
            var strtemp = "@" + id + "%%%" + name;
            setCookie(this.cookieName, str.replace(strtemp,""), this.expires);
            //deleteCookie(this.cookieName);
        }
    },
    clear : function (){
        setCookie(this.cookieName, "", -1);
    },
    compadd : function (el){
        obj = $(el);
        var index = obj.selectedIndex;
        var idVal = obj.value;
        if(idVal!="") {
            this.add(obj.value, obj.options[index].text);
        }else{
            alert("请选择具体车型");
        }
    },
    compare : function (){
        var s = "/carcomp.html";
        var cookie = getCookie(this.cookieName);
        var show = cookie.split("@");
        var url = "";
        if(show.length > 1){
            for(i = 1; i < show.length; i++){
                var str1 = show[i].split("%%%");
                url += "," + str1[0];
            }
        }
        var i = url.indexOf(",");
        var idStr = url.substring(i + 1);
        //url = s + "?CarId=" + idStr;
        if(idStr.indexOf(",") < 0) alert("至少选择两辆车才能进行比较!");
        else //alert(url);
            window.open(s);
            //window.open(url);
    },

    display : function (){
        var str = "";
        var cookie = getCookie(this.cookieName);
        var show = cookie.split("@");
        if(show.length > 0){
            for(i = 1; i < show.length; i++){ 
                str += "<div class=\"a0_reco\">";
                var str1 = show[i].split("%%%"); 
		        str += "<div class=\"a0_baise\">";
		        //var tempstr = str1[1];
		        var tempstr = this.getInterceptedStr(str1[1],26);
		        //if(str1[1].length > 20) tempstr = this.subs();
		        str += tempstr;
		        str += "</div>";
		        str += "<div class=\"a0_icoDelete\" id=\""+str1[0]+"\" onclick=\"return floater.del('"+str1[0]+"','"+str1[1]+"')\" title=\"点击删除\"></div>";
                str += "</div>";
            }
        }
        //alert(this.text);
        if(this.text != str){
            this.text = str;
            //$("floater_CompObject").innerHTML = "";
            if(this.text != "") $("floater_CompObject").innerHTML = this.text;
            else $("floater_CompObject").innerHTML = "等待添加...";
        }
    },
    compedisplay : function(){
        var str = "";
        var cookie = getCookie(this.compedCookie);
        //alert(cookie);
        var show = cookie.split("@");
        var rowNum = 3;
        var colNum = 2;
        var iNum = 0;
        if(show.length > 0){
            for(i = 0; i < rowNum; i++){ 
                str += "<ul>";
                for(var j = 0; j < colNum; j++){
                    var iNum = colNum * i + j + 1;
                    if(iNum >= show.length) {break;}
                    //alert(show.length);
                    var str1 = show[iNum].split("%%%"); 
                    var tempstr = this.getInterceptedStr(str1[1],26);
                    str += "<li onclick=\"floater.add('"+str1[0]+"','"+str1[1]+"')\" title=\""+str1[1]+"\">·<span>"+tempstr+"</span></li>";
                }
		        
                str += "</ul>";
            }
        }
        if(this.compedtext != str){
            this.compedtext = str;
            //$("floater_CompObject").innerHTML = "";
            if(this.compedtext != "") $("floater_CompedObject").innerHTML = this.compedtext;
            else $("floater_CompedObject").innerHTML = "等待添加...";
        }
    },
    check_scrollmove : function (){ 
        var div_id = $("floater_div_id");
        floater_scroll_pixel = document.documentElement.scrollTop || document.body.scrollTop;;
        floater_gtpos = floater_scroll_pixel + this.top_margin;
        floater_gbpos = floater_scroll_pixel + this.top_margin;
        if(parseInt(div_id.style.top) < floater_gtpos){ 
            floater_moving_spd = (floater_gbpos - parseInt(div_id.style.top)) / this.padding;
            div_id.style.top = parseInt(div_id.style.top) + floater_moving_spd + "px";    
        }
        if(parseInt(div_id.style.top) > floater_gtpos){
            floater_moving_spd = (parseInt(div_id.style.top) - floater_gtpos) / this.padding;
            div_id.style.top = parseInt(div_id.style.top) - floater_moving_spd + "px";
        }
        
        this.display();
        this.compedisplay();
        this.loop = setTimeout("floater.check_scrollmove()", this.speed);
    },
    subs : function (str, n){
        var s=n;
        for(i=0;i<n;i++){
            if(this.checkchinese(str.charAt(i))==true){ s--;n--}
        }
        if(s>str.length) return str;
        else return str.substring(0,s);
        return str;
    },

    checkchinese : function (str){  
        var re1 = new RegExp("^[\u4E00-\uFA29]*$")  
        var re2 = new RegExp("^[\uE7C7-\uE7F3]*$")
        var str = str.replace(/(^\s*)|(\s*$)/g,'');
        if (str == ''){return false;}
        if (!(re1.test(str) && (! re2.test(str)))){
            return false;
        }
        return true;
    },
    
    getStrActualLen : function (sChars)
    {
        return sChars.replace(/[^\x00-\xff]/g,"xx").length;
    },

    // 截取固定长度子字符串 sSource为字符串iLen为长度
    getInterceptedStr : function (sSource, iLen){
        if(sSource.replace(/[^\x00-\xff]/g,"xx").length <= iLen) return sSource;

        var str = "";
        var l = 0;
        var schar;
        for(var i=0; schar = sSource.charAt(i); i++) {
            str += schar;
            l += (schar.match(/[^\x00-\xff]/) != null ? 2 : 1);
            if(l >= iLen) break;
        }

        return str;
    }
}

