﻿//判断字符串的长度（按字符获取）
function GetStrLength(str) {
    var intLength = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255) {
            intLength += 2;
        }
        else {
            intLength += 1;
        }
    }
    return intLength;
}
//按字符截取子串
function SubString(str, length) {
    var childstr = "";
    for (var i = 0; i < str.length; i++) {
        if (GetStrLength(childstr) > length) {
            childstr = childstr.substring(0, childstr.length - 1);
            break;
        }
        childstr += str[i];
    }
    return childstr;
}
function textCounter(maxlimit) {
    var cText = document.getElementById("askCon");
    var InNum = document.getElementById("countNum"); //alert(cText.value.length);
    if (cText) {
        if (GetStrLength(cText.value) > maxlimit) {
            cText.value = SubString(cText.value, maxlimit);
        }
        if (InNum) {
            InNum.value = maxlimit - GetStrLength(cText.value);
            InNum.innerHTML = maxlimit - GetStrLength(cText.value);
        }
    }


}

function hide(id) { var Div = document.getElementById(id); if (Div) { Div.style.display = "none" } } //隐藏某容易函数
function show(id) { var Div = document.getElementById(id); if (Div) { Div.style.display = "block" } } //显示某容易函数

function currentFun(index, head, divs) {	//标签切换函数====索引值，最外大层id，标签组的id，轮换层的id头			
    var tab_heads = document.getElementById(head);
    if (tab_heads) {  //判断对象是否存在
        var lis = tab_heads.getElementsByTagName("li");
        var alis = tab_heads.getElementsByTagName("a");  //经过时移除所有a样式 隐藏所有层
        for (var i = 0; i < alis.length; i++) {
            alis[i].className = ""; lis[i].className = ""; hide(divs + "_" + i);
            if (i == index) { lis[i].className = "current"; } 
        }
        show(divs + "_" + index);
    }
}

function tabs(head, divs) {
    var tab_heads = document.getElementById(head);
    if (tab_heads) {
        currentFun(0, head, divs);
        var alis = tab_heads.getElementsByTagName("a");
        for (var i = 0; i < alis.length; i++) {
            alis[i].num = i;
            alis[i].onclick = function() { currentFun(this.num, head, divs); return false; this.blur(); }
            alis[i].onfocus = function() { currentFun(this.num, head, divs); return false; } 
        } 
    }
}

function ZebraStrips(id, tag) {	//斑马线
    var ListId = document.getElementById(id);
    if (ListId) {
        var picli = ListId.getElementsByTagName(tag);
        for (var i = 0; i < picli.length; i++) {
            picli[i].className += " barry" + i % 2;
            picli[i].onmouseover = function() { this.className += " hover" }
            picli[i].onmouseout = function() { this.className = this.className.replace(" hover", "") } 
        } 
    }
}
var messageIsShow = false;

function popload(showId) {//蒙版生成div+iframe
    var h = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + 'px';
    var w = document.documentElement.scrollWidth + 'px';
    var popCss = "background:#000;opacity:0.3;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(opacity=30)\"; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30); position:absolute;left:0;top:0;overflow:hidden;"

    var exsit = document.getElementById("popBox1");
    if (!exsit) {
        pop_Box = document.createElement("div"); 
        pop_Box.id = "popBox1";
        document.getElementsByTagName("body")[0].appendChild(pop_Box);
        pop_Box.style.cssText = popCss; 
        pop_Box.style.zIndex = "1";
        pop_Box.style.height = h;
        pop_Box.style.width = w;

        pop_Iframe = document.createElement("iframe"); 
        pop_Iframe.id = "popIframe1";
        document.getElementsByTagName("body")[0].appendChild(pop_Iframe);
        pop_Iframe.style.cssText = popCss;
         pop_Iframe.style.zIndex = "6";
        pop_Iframe.style.height = h; pop_Iframe.style.width = (parseInt(w) - 5) + "px";
    } 
    show("popIframe1"); show("popBox1");show(showId);
    pop_Win = document.getElementById(showId);
    pop_Win.style.position = "absolute";
    pop_Win.style.zIndex = "99999";
    pop_Win.style.top = document.documentElement.scrollTop + window.screen.availHeight / 2 - pop_Win.offsetHeight / 2 + 'px';
    pop_Win.style.left = (document.documentElement.clientWidth / 2  - pop_Win.offsetWidth / 2) + 'px';
    
    return false;
}

function popShow(Bid, Did) {//点击bid，弹出did，同时自动生成蒙版
    var UploadBtn = document.getElementById(Bid);
    if (UploadBtn) { UploadBtn.onclick = function() { popload(Did); return false; } }
}
function popHide(Bid, Did) {//点击bid，隐藏did，同时隐藏自动生成蒙版
    var UploadBtn = document.getElementById(Bid);
    if (UploadBtn) {
        UploadBtn.onclick = function() {

            hide(Did); 
            hide("popBox1"); 
            hide("popIframe1");
            IsInit();
            return false;
        } 
    }
}
var oldInitNews, oldinitMessage, oldInitBuy, user_cityid, user_dealerId;
function IsInit() {
    if (oldInitNews) {
//        gid("chioseDiv").innerHTML = oldInitNews;
//        show("chioseDiv");
//        hide("Logindiv");
        hide("orderLayer");
        gid("orderLayer").innerHTML = "";
    }
    if (oldinitMessage) {
        gid("initDiv").innerHTML = oldinitMessage;
        BindDate();
        if (gid("countNum")) {
            gid("countNum").value = 500;
            gid("countNum").innerHTML = 500;
        }
        var cText = document.getElementById("askCon");
        if (cText) {
            cText.onkeydown = function() { textCounter(500); };
            cText.onkeyup = function() { textCounter(500); };
        }
        popHide("OSCancel", "ordersubmit");
    }
    if (user_dealerId && oldInitBuycarid) {
        gid("orderLayer").innerHTML = "";
        O.GetPriceInfo(user_dealerId, oldInitBuycarid);
//        show("Logindiv");
    }
}
function clickHide(Bid, Did) {//点击bid，隐藏did，同时隐藏自动生成蒙版
    var UploadBtn = document.getElementById(Bid);
    if (UploadBtn) { UploadBtn.onclick = function() { hide(Did) } }
}
function clickShow(Bid, Did) {//点击bid，隐藏did，同时隐藏自动生成蒙版
    var UploadBtn = document.getElementById(Bid);
    if (UploadBtn) { UploadBtn.onclick = function() { show(Did); hide(Bid) } }
}
function newsBarry(id, Tag) {
    var Div = document.getElementById(id);
    if (Div) {
        var sfEls = Div.getElementsByTagName(Tag);
        for (var i = 0; i < (sfEls.length - 1); i++) { if ((i + 1) % 5 == 0) { sfEls[i].className += " barry"; } } 
    }
}

var foucsArea = document.getElementById("pictures");
if (foucsArea) {
    //首页自动播放
    var tablink_idname = new Array("sli")
    var tabcontent_idname = new Array("bigdiv")
    var loadtabs = new Array("1")
    var autochangemenu = 1;
    var changespeed = 2;
    var stoponhover = 0;

    var lis = document.getElementById("picturesLi").getElementsByTagName("a");
    var znum = lis.length + "";
    var tabcount = new Array(znum)

    function easytabs(menunr, active) {
        if (menunr == autochangemenu) { currenttab = active; }
        if ((menunr == autochangemenu) && (stoponhover == 1)) { stop_autochange() }
        else if ((menunr == autochangemenu) && (stoponhover == 0)) { counter = 0; }
        menunr = menunr - 1;
        for (i = 1; i <= tabcount[menunr]; i++) {
            document.getElementById(tablink_idname[menunr] + i).className = ' ';
            document.getElementById(tabcontent_idname[menunr] + i).style.display = 'none';
        }
        if (document.getElementById(tablink_idname[menunr] + active)) {
            document.getElementById(tablink_idname[menunr] + active).className = 'current';
            document.getElementById(tabcontent_idname[menunr] + active).style.display = 'block';
        }
    }
    var timer; counter = 0;
    var totaltabs = tabcount[autochangemenu - 1];
    var currenttab = loadtabs[autochangemenu - 1];
    function start_autochange() {
        counter = counter + 1;
        timer = setTimeout("start_autochange()", 1000);
        if (counter == changespeed + 1) {
            currenttab++;
            if (currenttab > totaltabs) {
                currenttab = 1
            } easytabs(autochangemenu, currenttab);
            restart_autochange();
        }
    }
    function restart_autochange() { clearTimeout(timer); counter = 0; start_autochange(); }
    function stop_autochange() { clearTimeout(timer); counter = 0; }
    foucsArea.onmouseover = function() { stop_autochange() }
    foucsArea.onmouseout = function() { restart_autochange() }
}

//页面执行方法
window.onload = function() {
    popShow("investCheck", "investRuselt");
    popHide("investRuseltClose", "investRuselt");
    popHide("close_btnvote", "investRuselt");
    ZebraStrips("message", "dl");
    newsBarry("news", "li");
    show("click_btn");
    hide("tel");
    if (messageIsShow) {
        popload("ordersubmit");
    }
    else {
        hide("ordersubmit");
    }
    hide("investRuselt");
    clickShow("click_btn", "tel");
    ZebraStrips("hot_car", "tr");
    ZebraStrips("salenews", "li");
    tabs("setup", "data")

    //新闻最终页买车
//    popShow("buycarbtn","ordersubmit");
    popHide("close_btn", "ordersubmit");

    //在线答疑窗口
    popShow("LeaveMsg", "ordersubmit");
    popShow("LeaveMsg1", "ordersubmit");
    popShow("LeaveMsg2", "ordersubmit");
    popHide("OSSubmit", "ordersubmit");
    popHide("OSCancel", "ordersubmit");
    popHide("OSAClose", "ordersubmitA");
    popHide("OSAClose2", "ordersubmitA");
    popHide("alert_close", "ordersubmitA");
    var SubmitAct = document.getElementById("OSSubmit");
    if (SubmitAct) { SubmitAct.onclick = function() { popHide("OSSubmit", "ordersubmit"); popShow("OSSubmit", "ordersubmitA"); } }

    var cText = document.getElementById("askCon");
    var InNum = document.getElementById("countNum");
    if ((cText) && (InNum)) { InNum.value = 500; InNum.innerHTML = 500; cText.onkeydown = function() { textCounter(500); }; cText.onkeyup = function() { textCounter(500); } }

    var aLog = document.getElementById("Login");
    if (aLog) { var mLog = document.getElementById("memberLogin"); mLog.style.display = "none"; aLog.onclick = function() { mLog.style.display = "block" } }

    //伸缩
    var DivId = document.getElementById("salers");
    if (DivId) {
        var tags = DivId.getElementsByTagName("div");
        if (tags.length > 3) { show("change") }
        for (var i = 3; i < tags.length; i++) { tags[i].style.display = "none" }
        var ChangeBtn = document.getElementById("change");
        if (ChangeBtn) {
            ChangeBtn.onclick = function() {
                if (ChangeBtn.className == "change") {
                    for (var j = 3; j < tags.length; j++) { tags[j].style.display = "block" }
                    ChangeBtn.innerHTML = "点击收缩";
                    ChangeBtn.className += " changeup"
                }
                else {
                    for (var k = 3; k < tags.length; k++) { tags[k].style.display = "none" }
                    ChangeBtn.innerHTML = "查看更多";
                    ChangeBtn.className = "change"
                }
            }
        }
    }
    //伸缩

    //鼠标经过变色
    var areas = document.getElementById("phototypes");
    if (areas) {
        var divs = areas.getElementsByTagName("div");
        for (var i = 0; i < divs.length; i++) {
            if (divs[i].className == "phototype") {
                divs[i].onmouseover = function() { this.className += " hover"; }
                divs[i].onmouseout = function() { this.className = this.className.replace(" hover", "") }
            }
        }
    }


    //幻灯片播放
    var foucsArea = document.getElementById("pictures");
    if (foucsArea) {
        var menucount = loadtabs.length; var a = 0; var b = 1; do { easytabs(b, loadtabs[a]); a++; b++; } while (b <= menucount);
        if (autochangemenu != 0) { start_autochange(); }

        var car_tab = document.getElementById("picturesLi");
        if (car_tab) {
            var lis = car_tab.getElementsByTagName("a");
            for (var i = 0; i < lis.length; i++) {
                lis[i].num = i;
                lis[i].onmouseover = function() { easytabs(1, this.num + 1); }
                lis[i].onfocus = function() { easytabs(1, this.num + 1); }
                lis[i].onclick = function() { return false; }
            }
        }
    }
    //幻灯片结束	
}

Validator = {
    Require: /.+/,
    Email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
    Phone: /^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/,
    Mobile: /^((\(\d{2}\))|(\d{2}\-))?1\d{10}$/,
    Url: /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
    IdCard: /^\d{15}(\d{2}[A-Za-z0-9])?$/,
    Currency: /^\d+(\.\d+)?$/,
    Number: /^\d+$/,
    Zip: /^[1-9]\d{5}$/,
    QQ: /^[1-9]\d{4,8}$/,
    Integer: /^[-\+]?\d+$/,
    Double: /^[-\+]?\d+(\.\d+)?$/,
    English: /^[A-Za-z]+$/,
    Chinese: /^[\u0391-\uFFE5]+$/,
    UnSafe: /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
    IsSafe: function(str) { return !this.UnSafe.test(str); },
    SafeString: "this.IsSafe(value)",
    Limit: "this.limit(value.length,getAttribute('min'),  getAttribute('max'))",
    LimitB: "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
    Date: "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
    Repeat: "value == document.getElementsByName(getAttribute('to'))[0].value",
    Range: "getAttribute('min') < value && value < getAttribute('max')",
    Compare: "this.compare(value,getAttribute('operator'),getAttribute('to'))",
    Custom: "this.Exec(value, getAttribute('regexp'))",
    Group: "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
    ErrorItem: [document.forms[0]],
    ErrorMessage: ["以下原因导致提交失败：\t\t\t\t"],
    Validate: function(theForm, mode) {
        var obj = theForm || event.srcElement;
        var count = obj.elements.length;
        this.ErrorMessage.length = 1;
        this.ErrorItem.length = 1;
        this.ErrorItem[0] = obj;
        for (var i = 0; i < count; i++) {
            with (obj.elements[i]) {
                var _dataType = getAttribute("dataType");
                if (typeof (_dataType) == "object" || typeof (this[_dataType]) == "undefined") continue;
                this.ClearState(obj.elements[i]);
                if (getAttribute("require") == "false" && value == "") continue;
                switch (_dataType) {
                    case "Date":
                    case "Repeat":
                    case "Range":
                    case "Compare":
                    case "Custom":
                    case "Group":
                    case "Limit":
                    case "LimitB":
                    case "SafeString":
                        if (!eval(this[_dataType])) {
                            this.AddError(i, getAttribute("msg"));
                        }
                        break;
                    default:
                        if (!this[_dataType].test(value)) {
                            this.AddError(i, getAttribute("msg"));
                        }
                        break;
                }
            }
        }
        if (this.ErrorMessage.length > 1) {
            mode = mode || 1;
            var errCount = this.ErrorItem.length;
            switch (mode) {
                case 2:
                    for (var i = 1; i < errCount; i++)
                        this.ErrorItem[i].style.color = "red";
                case 1:
                    alert(this.ErrorMessage.join("\n"));
                    this.ErrorItem[1].focus();
                    break;
                case 3:
                    for (var i = 1; i < errCount; i++) {
                        try {
                            var span = document.createElement("span");
                            span.id = "__ErrorMessagePanel";
                            span.className = "alert";
                            this.ErrorItem[i].parentNode.appendChild(span);
                            span.innerHTML = this.ErrorMessage[i].replace(/\d+:/, ""); //替换获取星号
                        }
                        catch (e) { alert(e.description); }
                    }
                    this.ErrorItem[1].focus();
                    break;
                default:
                    alert(this.ErrorMessage.join("\n"));
                    break;
            }
            return false;
        }
        return true;
    },
    limit: function(len, min, max) {
        min = min || 0;
        max = max || Number.MAX_VALUE;
        return min <= len && len <= max;
    },
    LenB: function(str) {
        return str.replace(/[^\x00-\xff]/g, "**").length;
    },
    ClearState: function(elem) {
        with (elem) {
            if (style.color == "red")
                style.color = "";
            var lastNode = parentNode.childNodes[parentNode.childNodes.length - 1];
            if (lastNode.id == "__ErrorMessagePanel")
                parentNode.removeChild(lastNode);
        }
    },
    AddError: function(index, str) {
        this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
        this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
    },
    Exec: function(op, reg) {
        return new RegExp(reg, "g").test(op);
    },
    compare: function(op1, operator, op2) {
        switch (operator) {
            case "NotEqual":
                return (op1 != op2);
            case "GreaterThan":
                return (op1 > op2);
            case "GreaterThanEqual":
                return (op1 >= op2);
            case "LessThan":
                return (op1 < op2);
            case "LessThanEqual":
                return (op1 <= op2);
            default:
                return (op1 == op2);
        }
    },
    MustChecked: function(name, min, max) {
        var groups = document.getElementsByName(name);
        var hasChecked = 0;
        min = min || 1;
        max = max || groups.length;
        for (var i = groups.length - 1; i >= 0; i--)
            if (groups[i].checked) hasChecked++;
        return min <= hasChecked && hasChecked <= max;
    },
    IsDate: function(op, formatString) {
        formatString = formatString || "ymd";
        var m, year, month, day;
        switch (formatString) {
            case "ymd":
                m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
                if (m == null) return false;
                day = m[6];
                month = m[5]--;
                year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
                break;
            case "dmy":
                m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
                if (m == null) return false;
                day = m[1];
                month = m[3]--;
                year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
                break;
            default:
                break;
        }
        if (!parseInt(month)) return false;
        month = month == 12 ? 0 : month;
        var date = new Date(year, month, day);
        return (typeof (date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate());
        function GetFullYear(y) { return ((y < 30 ? "20" : "19") + y) | 0; }
    }
}
