﻿/*js实现“设为首页”“ 加入收藏”功能 
*<a onclick="AddFavorite(window.location,document.title)" style="cursor:hand">加入收藏</a> 
*<a onclick="SetHome(this,window.location)" style="cursor:hand">设为首页</a>
*/


function AddFavorite(sURL, sTitle) {
    try {
        window.external.addFavorite(sURL, sTitle);
    }
    catch (e) {
        try {
            window.sidebar.addPanel(sTitle, sURL, "");
        }
        catch (e) {
            alert("加入收藏失败,请使用Ctrl+D进行添加!");
        }
    }
}
function SetHome(obj, vrl) {
    try {
        obj.style.behavior = 'url(#default#homepage)'; obj.setHomePage(vrl);
    }
    catch (e) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', vrl);
        }
    }
}
//js判断文件后缀名
function checkisflash(v, ext) {
    if (v.indexOf(".") > 0) {
        var o = v.split(".");
        var e = o[o.length - 1].toLowerCase();
        if (e == ext)
            return true;
        else
            return false;
    }
    else { return false; }
}

//js通过参数名称获取超链接值方法
function GetQueryString(name) {
   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
   var r = window.location.search.substr(1).match(reg);
   if (r!=null) return unescape(r[2]); return null;
}

//js获取url参数的function  实例代码：js获取url参数改变网站访问地址
//原文：http://www.liehuo.net/a/201005/2617235.html
//<example>var theurl= requestParam("url");if (theurl != ''){location = theurl; } </example>
function requestParam(paras) {
    var url = location.href;
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf
("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {
        return "";
    } else {
        return returnValue;
    }
}

//原文：http://www.liehuo.net/a/201005/2617233.html
//<example>alert(getQueryStringRegExp(locationurl,'test')); </example>
function getQueryStringRegExp(name) {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(location.href))
        return unescape(RegExp.$2.replace(/\+/g, " "));
    return "";
}

function doPrint() {
    bdhtml = window.document.body.innerHTML;
    sprnstr = "<!--startprint-->";
    eprnstr = "<!--endprint-->";
    prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
    prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
    window.document.body.innerHTML = prnhtml;
    window.print();
}

function StringBuffer() {
    this._strs = new Array;
}

StringBuffer.prototype.append = function (str) {
    this._strs.push(str);
};

StringBuffer.prototype.toString = function () {
    this._strs.join("");
};

//js字符串处理函数
String.prototype.htmlDecode = function () {
    var result = this.toString();
    result = result.replace(/&quot;/g, '"');
    result = result.replace(/&acute;/g, "'");
    result = result.replace(/&wrap/g, "<br/>");
    return result;
}
String.prototype.textDecode = function () {
    var result = this.toString();
    result = result.replace(/&acute;/g, "'");
    result = result.replace(/&quot;/g, '"');
    result = result.replace(/&wrap/g, "\n");
    result = result.replace(/&nbsp;/g, ' ');
    return result;
}

function format(formatstr) {
    var args = arguments;
    var pattern = new RegExp("{([0-" + arguments.length + "])}", "g");
    return String(formatstr).replace(pattern, function (match, index) {
        var currentIndex = parseInt(index);
        if (currentIndex + 1 > args.length || currentIndex < 0) {
            throw new Error("参数索引出错");
        }
        return args[currentIndex + 1];
    });
}

//showbox 弹出框样式
function showbox(title, html, width) {
    var strmask = "_mask";
    var strbox = "_newbox";
    var strtitle = "_boxtitle";
    var strcontent = "_boxcontent";
    //var strclose="_boxclose";
    var newMask = document.getElementById(strmask);
    var newDiv = document.getElementById(strbox);
    var boxtitle = document.getElementById(strtitle);
    var boxcontent = document.getElementById(strcontent);
    //var boxclose=document.getElementById(strclose);
    //if (docEle(_id)) document.body.removeChild(docEle(_id));
    //if (docEle(m)) document.body.removeChild(docEle(m));

    //mask遮罩层
    if (!newMask) {
        newMask = document.createElement("div");
        newMask.id = strmask;
        newMask.style.position = "absolute";
        newMask.style.zIndex = "1";
        _scrollWidth = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
        _scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
        newMask.style.width = _scrollWidth + "px";
        newMask.style.height = _scrollHeight + "px";
        newMask.style.top = "0px";
        newMask.style.left = "0px";
        newMask.style.background = "#33393C";
        newMask.style.filter = "alpha(opacity=40)";
        newMask.style.opacity = "0.40";
        document.body.appendChild(newMask);
    }
    //新弹出层
    if (!newDiv) {
        newDiv = document.createElement("div");
        newDiv.id = strbox;
        newDiv.style.position = "absolute";
        newDiv.style.zIndex = "9999";
        //newDivWidth = 400;
        //newDivHeight = 200;
        //newDiv.style.width = newDivWidth + "px";
        //newDiv.style.height = newDivHeight + "px";
        newDiv.style.width = width + "px";
        newDiv.style.top = 20 + "px"; //(document.body.scrollTop + document.body.clientHeight/2 - newDivHeight/2) + "px";
        //newDiv.style.left = (document.body.scrollLeft + document.body.clientWidth/2 - newDivWidth/2) + "px";
        newDiv.style.background = "#EFEFEF";
        newDiv.style.border = "1px solid #860001";
        //newDiv.style.padding = "5px";
        // newDiv.innerHTML =html; //"<iframe width=\"600px\" height=\"450px\" scrolling=\"no\" border=\"0\" frameborder=\"0\" src=\"http://searchbox.mapbar.com/publish/template/template1010/index.jsp?CID=2shequ&tid=tid1010&nid=MAPBSIFRZOTRJPFAJOCEX&width=600&height=450&control=2&infopoi=1&infoname=1&zoom=10\"></iframe>";
        document.body.appendChild(newDiv);
    }
    if (!boxtitle) {

        boxtitle = document.createElement("div");
        boxtitle.style.width = width - 10 + "px";
        boxtitle.id = strtitle;
        boxtitle.style.color = "red";
        boxtitle.style.fontSize = "12";
        boxtitle.style.height = 24 + "px";
        boxtitle.style.background = "url(/images/showbox_2.gif)";
        boxtitle.style.backgroundRepeat = "repeat-x";
        boxtitle.style.padding = 5 + "px";
        //topdiv.style.height="30px";
        // boxtitle.innerHTML="<a href='javascript:;' onclick=\"document.getElementById('"+strmask+"').style.display='none';document.getElementById('"+strbox+"').style.display='none';\">×</a>";
        newDiv.appendChild(boxtitle);
    }
    if (!boxcontent) {
        boxcontent = document.createElement("div");
        boxcontent.style.width = width - 10 + "px";
        boxcontent.style.overflow = "hidden";
        boxcontent.style.wordbreak = "break-all";
        boxcontent.style.wordwrap = "break-word";
        boxcontent.id = strcontent;
        boxcontent.style.padding = 5 + "px";
        boxcontent.style.textAlign = "left";
        boxcontent.style.lineHeight = 20 + "px";
        //boxcontent.style.fontSize = "17";
        newDiv.appendChild(boxcontent);
    }
    //弹出层滚动居中
    boxcontent.innerHTML = html;
    boxcontent.style.width = width - 10 + "px";
    boxtitle.innerHTML = "<span style='float:left;'>" + title +
    "</span><span style='float:right;'><a href='javascript:;' style='text-decoration:none;' onclick=\"document.getElementById('" +
     strmask + "').style.display='none';document.getElementById('" + strbox +
      "').style.display='none';\"><img src='/images/showbox_1.gif' border='0' /></a></span>";
    newDiv.style.display = "block";
    newMask.style.display = "block";
    newDiv.style.width = width + "px"; //填充10的边距
    boxtitle.style.width = width - 10 + "px";

    function newDivCenter() {
        newDiv.style.top = (document.body.scrollTop + 20) + "px"; //document.body.clientHeight/2 - newDivHeight/2) + "px";
        newDiv.style.left = (document.body.scrollLeft + document.body.clientWidth / 2 - newDiv.offsetWidth / 2) + "px";
        //alert(newDiv.style.top);
    }
    if (document.all) {
        window.attachEvent("onscroll", newDivCenter);
    }
    else {
        window.addEventListener('scroll', newDivCenter, false);
    }

    newDivCenter();

    var nowroll = document.documentElement.scrollTop;

    var rollinterval = setInterval(function () {
        if (nowroll > 0) {
            nowroll -= 10;
            if (nowroll >= 0)
                window.scrollTo(0, nowroll);
            else
                window.scrollTo(0, 0);
        }
        else {
            clearInterval(rollinterval);
        }
    },
                10);
    //newDiv.appendChild(newA);
}

//给样式添加属性
function addcss(id, n, v) {
    $("#" + id).css(n, v);
}

function loadimg(id, errsrc) {
    var img = new Image();
    img.src = $("#" + id).attr("src");
    img.onload = function () {
        alert('load');
    };
    img.onerror = function () {
        alert('error');
        $("#" + id).attr("src", errsrc);
    };
}

//jquery扩展 字符串格式数据转化为json格式string json 
jQuery.extend(
{
    StringtoJSON: function (strJson) {
        return ("(" + strJson + ")");
    }
});

function checkPhone(id) {
    var mphone = /^[1][358]\d{9}$/; //验证手机号码   
    var tphone = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;  //验证电话号码
    var phone = $("#" + id).val();
    if (phone == "") {
        return false;
    } else {
        if (phone.indexOf('-') != -1) {
            if (!tphone.test(phone)) {
                alert('您输入的格式有误！请核对后重新输入')
                $("#" + id).focus();
                return false;
            } else {
                return true;
            }
        } else {
            if (!mphone.test(phone)) {
               
                alert('您输入的格式有误！请核对后重新输入');
                $("#" + id).focus();
                return false;
            } else {
                return true;
            }
        }
    }
}
///推荐给好友
function CopyToFriend() {
    var clipBoardContent = '';
    clipBoardContent += document.title;
    clipBoardContent += window.location;
    window.clipboardData.setData("Text", clipBoardContent);
    alert("复制成功，请粘贴到你的QQ/MSN上推荐给你的好友");
}

//html的img缩略图
function DrawImage(ImgD, width_s, height_s) {
    var image = new Image();
    image.src = ImgD.src;
    if (image.width > 0 && image.height > 0) {
        flag = true;
        if (image.width / image.height >= width_s / height_s) {
            if (image.width > width_s) {
                ImgD.width = width_s;
                ImgD.height = (image.height * width_s) / image.width;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
        }
        else {
            if (image.height > height_s) {
                ImgD.height = height_s;
                ImgD.width = (image.width * height_s) / image.height;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
        }
    }
    else {
        ImgD.src = "";
        ImgD.alt = ""
    }
}

function GetDateTime() {
    var userAgent = navigator.userAgent.toLowerCase();
    //判断是否为google的浏览器
    var chrome = /chrome/.test(userAgent);

    var now = new Date();
    // 因IE的年为2008和FF为108，判断
    var year = now.getYear();
    if ($.browser.mozilla || chrome) {
        year += 1900;
    }
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();

    var timeValue = year + "-"
    timeValue += month + "-"
    timeValue += day + " "
    timeValue += (hours > 12) ? hours - 12 : hours
    timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
    timeValue += ((seconds < 10) ? ":0" : ":") + seconds;

    return timeValue;
}

/***判断数组中是否存在某个元素方法***/
//Array.prototype.in_array = function (e) {
//    for (i = 0; i < this.length; i++) {
//        if (this[i] == e)
//            return true;
//    }
//    return false;
//}
//或者下面方法
//Array.prototype.in_array = function (e) {
//    for (i = 0; i < this.length && this[i] != e; i++);
//    return !(i == this.length);
//}
//Array.prototype.each = function (callback) {
//    for (var i = 0, j = this.length; i < j; i++) {
//        callback.call(this, this[i], i);
//    }
//} 

/**
 * 判断是否为日期数据
 * 简单的日期检查，成功返回日期对象 
**/ 
String.prototype.isDate = function() { 
    var p; 
    var re1 = /(\d{4})[年./-](\d{1,2})[月./-](\d{1,2})[日]?$/; 
    var re2 = /(\d{1,2})[月./-](\d{1,2})[日./-](\d{2})[年]?$/; 
    var re3 = /(\d{1,2})[月./-](\d{1,2})[日./-](\d{4})[年]?$/; 
    if(re1.test(this)) { 
        p = re1.exec(this); 
        return new Date(p[1],p[2],p[3]); 
    } 
    if(re2.test(this)) { 
        p = re2.exec(this); 
        return new Date(p[3],p[1],p[2]);
    } 
    if(re3.test(this)) { 
        p = re3.exec(this); 
        return new Date(p[3],p[1],p[2]);
    } 
    return false; 
}
  
/**     
* 对Date的扩展，将 Date 转化为指定格式的String     
* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符     
* 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)     
* eg:     
* (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423     
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04     
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04     
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04     
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18     
*/       
Date.prototype.pattern=function(fmt) {        
    var o = {        
    "M+" : this.getMonth()+1, //月份        
    "d+" : this.getDate(), //日        
    "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时        
    "H+" : this.getHours(), //小时        
    "m+" : this.getMinutes(), //分        
    "s+" : this.getSeconds(), //秒        
    "q+" : Math.floor((this.getMonth()+3)/3), //季度        
    "S" : this.getMilliseconds() //毫秒        
    };        
    var week = {        
    "0" : "\u65e5",        
    "1" : "\u4e00",        
    "2" : "\u4e8c",        
    "3" : "\u4e09",        
    "4" : "\u56db",        
    "5" : "\u4e94",        
    "6" : "\u516d"       
    };        
    if(/(y+)/.test(fmt)){        
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));        
    }        
    if(/(E+)/.test(fmt)){        
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);        
    }        
    for(var k in o){        
        if(new RegExp("("+ k +")").test(fmt)){        
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));        
        }        
    }        
    return fmt;        
}      
    
//var date = new Date();     
//window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));  

