﻿/**
* 网站全局JS函数库
*
* @FileName: global.js
* @Auther: Pandao
* @QQ: 272383090
* @CreateTime: 2011-09-06 16:59:42
* @UpdateTime: 2011-09-08 16:49:28
* @Updated By: pandao
 * Copyright 2011 泉州市科伟信息咨询有限公司版权所有，禁止非法用于商业用途，否则后果自负!
*/

//_$函数
function _$(id)
{
   return document.getElementById(id);
}

//$id函数
function $id(id)
{
   return document.getElementById(id);
}

function $cE(tag)
{
    return document.createElement(tag);
}

function $name(name, obj)
{
    return document.getElementsByName(name);
}

function $tag(obj, tag)
{
    if(typeof obj =='undefined') obj = document;//默认值

    return obj.getElementsByTagName(tag);
}

//JS取class相同的节点（终极方案）
//var obj = _$("spec_value_list"+spec_id);
//var optBtn = GetByClass('opt_related_btn',obj,'div');
function GetByClass(searchClass,node,tag)  //类名，要查找的（父）对象，标签
{
    var classElements = new Array();
    if ( node == null )  node = document;
    if ( tag == null )   tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++)
    {
        if ( pattern.test(els[i].className) )
        {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

//添加到收藏夹
function addBookmark(title,url)
{
	if (window.sidebar)
	{
		window.sidebar.addPanel(title, url,"");
	}
	else if( document.all )
	{
		window.external.AddFavorite( url, title);
	}
	else if( window.opera && window.print )
	{
		return true;
	}
}

//Ajax Loading 等待效果
function AjaxLoading(type, id, msg)
{
   parent._$(id).innerHTML = msg;
   if(type == 'show') parent._$(id).style.display = '';
   if(type =='hide')  parent._$(id).style.display = 'none';
}

//Loading初始化
function StartLoading()
{
    document.write('<div id="loading" class="loading" style="color:#04AEFC;position:absolute;top:0;left:0;border:3px solid #04AEFC;background:#fff;padding:3px 10px;"><img src="images/loading.gif"/>&nbsp;页面加载中...</div>');
}

//页面载入完成后移除Loading
function EndLoading()
{
    _$("loading").parentNode.removeChild(_$("loading"));
}

//TAB选项卡函数
function Tab(name, cursel, n)
{
     for(i = 1; i <= n; i ++)
     {
          _$(name+i).className = (i == cursel) ? "hover" : "";
          _$(name+"Box"+i).style.display = (i == cursel) ? "block" : "none";
     }
}

//点击展开/关闭函数
function  show(id)
{
    var div = _$(id);
    div.style.display = (div.style.display == "") ? "none" : "";
}

//按钮删除确认
function getconfirm(str)
{
    var str;
    if (confirm(str) == true) return true;
    else return false;
}

//iframe自适应高度函数
function SetWinHeight(obj)
{
    var win = obj;
    if (document.getElementById)
    {
        if (win && !window.opera)
        {
            if (win.contentDocument && win.contentDocument.body.offsetHeight)
                win.height = win.contentDocument.body.offsetHeight;
            else if(win.Document && win.Document.body.scrollHeight)
                win.height = win.Document.body.scrollHeight;
        }
    }
}

//检测邮箱地址
function isEmail(str)
{
     var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
     return reg.test(str);
}

//按钮删除确认
function is_Del(msg)
{
    if(confirm(msg)) return true;
    else return false;
}

//JS全选 、反选、取消复选框函数
//全选
function selectAll(obj)
{

    for(var i = 0; i < obj.elements.length; i++)
    {
        if(obj.elements[i].type == "checkbox") obj.elements[i].checked = true;
    }
}

//反选
function selectOther(obj)
{
    for(var i = 0; i < obj.elements.length; i++)
    {
        if(obj.elements[i].type == "checkbox" )
        {
            if(!obj.elements[i].checked) obj.elements[i].checked = true;
            else obj.elements[i].checked = false;
        }
    }
}

//取消选择
function selectCancel(obj)
{
    for(var i = 0; i < obj.elements.length; i++)
    {
        if(obj.elements[i].type == "checkbox" )  obj.elements[i].checked = false;
    }
}

//判断是否选择一个
function is_checked(name)
{
    var x = document.getElementsByName(name);
    var count = 0;
    for(var i = 0; i < x.length; i++)
    {
        if(x[i].checked) count += 1;
        else count = 0;
    }
    parseInt(count);
    return count;
}

//表格隔行换色，经过和点击变色函数
function table_color(obj, js, os, onover, ondown)
{
     var t = _$(obj).getElementsByTagName("tr");
     for(var i=0; i<t.length; i++)
     {
        t[i].style.backgroundColor = (t[i].sectionRowIndex%2 == 0) ? js : os;

        t[i].onclick = function(){
            if(this.x != "1"){
                  this.x = "1";//本来打算直接用背景色判断，FF获取到的背景是RGB值，不好判断
                  this.style.backgroundColor = ondown;
            }else{
                  this.x = "0";
                  this.style.backgroundColor = (this.sectionRowIndex%2 == 0) ? js : os;
            }
        }

        t[i].onmouseover = function(){
              if(this.x != "1") this.style.backgroundColor = onover;
        }

        t[i].onmouseout = function(){
              if(this.x != "1") this.style.backgroundColor = (this.sectionRowIndex%2 == 0) ? js : os;
        }
     }
}

//表格经过变色函数,只能放在页尾或者对象结束后面
function table_color2(id, OnColor, OutColor)
{
     var t = _$(id).getElementsByTagName("tr");
     for(var i=0; i<t.length; i++)
     {
        t[i].onmouseover = function(){
              if(this.x != "1") this.style.backgroundColor=OnColor;
        }
        t[i].onmouseout = function(){
              if(this.x != "1") this.style.backgroundColor=OutColor;
        }
     }
}

//跳出框架
function breakOut()
{
    if(window.top != window.self) window.top.location = "login.php";
}

//下拉列表赋值到文本框
function dochange(select_Id, text_Id)
{
    var select_Value = _$(select_Id).value;
    var text_Value = _$(text_Id);
    text_Value.innerText = select_Value;
}

//动态增加textarea高度
var addH=1;
function addHeight(id)
{
    if (!_$(id)) return flase;
    var comment =_$(id);
    var nowH = parseInt(comment.style.height);
    if (nowH < 400)
    {
        nowH += 50;
        comment.style.height = nowH + "px";
        addH ++;
        if (addH > 1) addH = 1;
        else  window.setTimeout("addHeight(id)", "10");
    }
}

//动态减去textarea高度
function redHeight(id)
{
    if (!_$(id)) return flase;
    var comment = _$(id);
    var nowH = parseInt(comment.style.height);
    if (nowH > 100)
    {
        nowH -= 50;
        comment.style.height = nowH + "px";
        addH ++;
        if (addH > 1)  addH = 1;
        else  window.setTimeout("redHeight(id)", "10");
    }
}

//取浏览器类型
function is_browser()
{
    var browser = '';
    //JS判断浏览器
    if(window.XMLHttpRequest) //Mozilla, Safari, IE7
    {
        if(!window.ActiveXObject) browser = 'FF'; // Mozilla, Safari,
        else browser = 'IE7'; // IE7,
    }
    else
    {
        browser =  'IE6';
    }

    return browser;
}

//取得页面的高宽
function getBodySize()
{
   var bodySize = [];
   with(document.documentElement)
   {
       //如果滚动条的宽度大于页面的宽度，取得滚动条的宽度，否则取页面宽度
       bodySize[0] = (scrollWidth > clientWidth) ? scrollWidth : clientWidth;

       //如果滚动条的高度大于页面的高度，取得滚动条的高度，否则取高度
       bodySize[1] = (scrollHeight > clientHeight) ? scrollHeight : clientHeight;
   }

   return bodySize;
}

//图片按比例缩放
var flag = false;
function DrawImage(ImgD, iwidth, iheight)
{
    //参数(图片,允许的宽度,允许的高度)
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
        flag=true;
        if(image.width/image.height>= iwidth/iheight){
            if(image.width>iwidth){
                ImgD.width=iwidth;
                ImgD.height=(image.height*iwidth)/image.width;
            }else{
                ImgD.width=image.width;
                ImgD.height=image.height;
            }
            ImgD.alt=image.width+"×"+image.height;
        }else{
            if(image.height>iheight){
                ImgD.height=iheight;
                ImgD.width=(image.width*iheight)/image.height;
            }else{
                ImgD.width=image.width;
                ImgD.height=image.height;
            }
            ImgD.alt=image.width+"×"+image.height;
        }
    }
    //alert(image.height);
    var nowheight=image.height;
    /*if(nowheight!==iheight){
        ImgD.style.marginTop=((iheight-ImgD.height)/2)+"px";
    }*/
}

//文本框只能输入整数
function setint(num)
{
    num.value = num.value.replace(/\D/g, '');

    return true;
}

//取上传图片的完整路径
function getImgPath(obj) {
    if( !obj.value.match( /.jpg|.gif|.png/i ) ){
        alert('错误：图片文件格式不正确！\n只能上传gif/jpg/png格式的图片！');
        return false;
    }
    if(obj){
        if (window.navigator.userAgent.indexOf("MSIE")>=1){ //ie
            obj.select();
            return document.selection.createRange().text;
        }else if(window.navigator.userAgent.indexOf("Firefox")>=1) { //firefox
            if(obj.files){
                return obj.files.item(0).getAsDataURL();
            }
            return obj.value;
        }
        return obj.value;
    }
}

//去掉数组中相同的值
Array.prototype.delSame = function(){
    for(var i = 0; i < this.length; i ++)
    {
        for(var j = i + 1; j < this.length; j ++)
        {
            if(this[j] == this[i]) this.splice(j,1);
        }
    }

    return this;
}


//in_array - js模拟php中的in_array
function in_array(stringToSearch, arrayToSearch)
{
    for (s = 0; s <arrayToSearch.length; s++)
    {
        thisEntry = arrayToSearch[s].toString();
        if (thisEntry == stringToSearch) return true;
    }

    return false;
}

//JS实现类似PHP的implode函数功能
function implode( glue, pieces ) {
    // Joins array elements placing glue string between items and return one string
    //
    // version: 812.316
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    //      example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    //      returns 1: 'Kevin van Zonneveld'
    return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}

// 说明：获取鼠标位置

function mousePosition(ev)
{
    if(ev.pageX || ev.pageY)
    {
        return {
            x : ev.pageX,
            y : ev.pageY
        };
    }

    return {
        x : ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y : ev.clientY + document.body.scrollTop  - document.body.clientTop
    };
}

//去除数组中相同的元素
function unique(data)
{
    data = data || [];
    var a = {}; //声明一个对象，JavaScript中的对象可以当哈希表用
    for (var i=0; i <data.length; i++) {
        //document.write(data[i]);
        a[data[i]] = true;  //设置标记，把数组的值当下标，这样就可以去掉重复的值
    };
    //alert(a);
    data.length=0;
    for (var t in a){ //遍历对象，把已标记的还原成数组
        data[data.length] = t;
    }

    return data;
}
//var arrs = [9,1,1,1,3,3];
//alert(unique(arrs));

//判断文件格式
var right_type=new Array(".gif",".jpg",".jpeg",".png");
//var oFileChecker = document.getElementById("fileChecker");
/* function changeSrc(filePicker)
 {
    if(!checkImgType(filePicker.value))
    {
        alert("文件格式不正确！\n\n 只能上传gif/jpg/png/bmp格式的图片");
        return;
    }
 }*/
function checkImgType(fileURL)
{
    var right_typeLen = right_type.length;
    var imgUrl = fileURL.toLowerCase();
    var postfixLen = imgUrl.length;
    var len4 = imgUrl.substring(postfixLen-4, postfixLen);
    var len5 = imgUrl.substring(postfixLen-5, postfixLen);
    for (i=0; i < right_typeLen; i++)
    {
        if( (len4 == right_type[i]) || (len5 == right_type[i]) ) return true;
    }
}

//检测上传的文件格式
var right_type = new Array(".gif",".jpg",".jpeg",".png",".swf");
function changeSrc(filePicker)
{
    if(!checkImgType(filePicker.value))
    {
        _$("up_tishi").style.display = "";
        _$("up_tishi").className = "red_tishi";
        return false;
    }
}

//全兼容js实时限制textarea字数效果，能监控粘贴
function textCounter(textareaObj, count, maxlimit, callback)
{
    if (textareaObj.value.length > maxlimit)
    {
        textareaObj.value = textareaObj.value.substring(0, maxlimit);
        callback();
        return false;
    }
    else
    {
        count.value = maxlimit - textareaObj.value.length;
    }
}
/*
//示例
<form  method="POST" name="form">
    <textarea cols="45" name="memo" rows="8" wrap="on" class="editbox2" onKeyDown="textCounter(this.form.memo, this.form.remLen, 100);" onKeyUp="textCounter(this.form.memo, this.form.remLen,100);"></textarea>
    <br>共可输入100字，还剩<input type="text" name="remLen" size="3" maxlength="3" value="100" class="editbox1" readonly>字。<br>
</form>
*/

//文本框特效——获取焦点时自动清除默认文本 失去焦点重新显示默认文字
//使用方法：<input type="text" value="输入关键字" style="color:#ccc;" onfocus="defaultText(this, '输入关键字')" onblur="defaultText(this, '输入关键字')" />
function defaultText(obj, str) {
    if(obj.value == str) {
        obj.value = '';
        obj.style.color = '#444';
    }
    else if(obj.value =='') {
        obj.value = str;
        obj.style.color = '#ccc';
    }
}
/*
//检测密码强度
function chkpwd(obj)
{
    var t = obj.value;
    var id = getResult(t);

    //定义对应的消息提示
    var msg = new Array("密码太短","密码强度差","密码强度良好","密码强度高");
    var sty = new Array('-45', '-30', '-15', '0');
    var _color = new Array("gray","red","#ff6600","Green");

    //设置显示效果
    var bImg="images/bar.gif";//一张显示用的图片
    var sWidth = 300;
    var sHeight = 15;
    var Bobj = _$('chkpw_Result');
    _$('chkpw').style.display = '';

    Bobj.style.fontSize = "12px";
    Bobj.style.display = "";
    Bobj.style.color = _color[id];
    Bobj.style.width = sWidth + "px";
    Bobj.style.height = sHeight + "px";
    Bobj.style.lineHeight = sHeight + "px";
    Bobj.style.background = "url(" + bImg + ") no-repeat left " + sty[id] + "px";
    Bobj.style.paddingLeft = "20px";
    Bobj.innerHTML = "检测提示：" + msg[id];
}

//定义检测函数,返回0/1/2/3分别代表无效/差/一般/强
function getResult(s)
{
    if(s.length < 4) return 0;
    var ls = 0;
    if (s.match(/[a-z]/ig)) ls++;
    if (s.match(/[0-9]/ig)) ls++;
    if (s.match(/(.[^a-z0-9])/ig)) ls++;
    if (s.length < 6 && ls > 0) ls--;
    return ls;
}*/

//登陆检测
function chk_login()
{
    if(_$('user_name').value == '用户名/邮箱')
    {
        alert('错误：请输入您的用户名或注册时填写的邮箱！');
        return false;
    }

    if(_$('user_password').value == '用户密码')
    {
        alert('错误：请输入您的用户密码！');
        return false;
    }
}

//自动向上滚动
function textScroll(obj)
{
    $(obj).find("ul:first").animate({
        marginTop: "-23px"
    }, 500, function() {
        $(this).css({ marginTop: "0px"}).find("li:first").appendTo(this);
    });
}

//=================== jQuery扩展插件 Start ===================

$.fn.extend({
    listHover : function(newOverStyle, newOutStyle) {
        var overStyle = {backgroundColor:'#FCFCDB', cursor: 'pointer'};
        var outStyle = {background:'none'};

        $.extend(overStyle, newOverStyle);
        $.extend(outStyle, newOutStyle);

        $(this).hover(function() {
            $(this).css(overStyle);
        },function() {
            $(this).css(outStyle);
        });
    },

    //选项卡切换插件
    tab : function(eventType, callback) {
        eventType = eventType || 'mouseover';

        if(eventType == 'mouseover' || eventType == 'click')
        {
            callback = callback || function() {};
            var tabCutover = function() {
                $(this).addClass("hover").siblings().removeClass("hover");
                var id = $(this).attr('id');
                $('#'+id+'_con').show().siblings('.tab_con').hide();
                callback();
            };

            $(this).bind(eventType, tabCutover);
        }
        else
        {
            alert('错误：选项卡切换事件只能是mouseover和click事件，请修改！');
            return false;
        }
    }
});

//=================== jQuery扩展插件 End ===================

$(function() {
    //标示当前一级菜单
    $('#menu li').eq(thisMenuIndex).addClass('this').siblings().removeClass('this');

    //标示当前子菜单
    //$('#menu li').eq(thisMenuIndex).children('dl').children('dd').children('a').eq(thisSubMenuIndex).addClass('this').siblings().removeClass('this');


    $('#loading').fadeOut(1000);

    //=================== 锚点的缓动移动 Start ===================
    $('a[href*=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({
                    scrollTop: targetOffset
                },
                800);
                return false;
            }
        }
    });

    $('a').click(function() {
        $(this).blur();
    });

    //=================== 锚点的缓动移动 End ===================

    //=================== 导航菜单 Start ===================

    $('#menu li').hover(function() {
        var index = $(this).index();
        $(this).addClass('hover').css({backgroundPosition: -(index * 120 )+'px 0'});
        //$(this).children('dl').show();//slideDown(500);
    }, function() {
        $(this).removeClass('hover');
        //$(this).children('dl').hide();//slideUp(500);
    });

    //=================== 导航菜单 End ===================

    $("#content img").lazyload({
        placeholder: "images/grey.gif",
        effect : "fadeIn"
        //threshold : 200 //敏感度
        //event : "click" //事件
    });

    //网站地图当前列提示
/*
    $('#sitemap_nav dl').hover(function() {
        $(this).css({borderColor:'#E21F2B'});
        $(this).children('dt').children('a').css({color : '#E21F2B'});
    }, function() {
        $(this).css({borderColor:'#fff'});
        $(this).children('dt').children('a').css({color : '#555'});
    });
*/

    //服务优势图标翻滚
    $('#service_advantage a').hover(function() {
        $(this).css({backgroundPositionY:'0px'}).animate({backgroundPositionY:'-79px'}, 300);
    }, function() {
        $('#service_advantage a').stop();
    });
/*
    //服务优势的介绍提示Tips
    $('#service_advantage a').poshytip({
        className: 'tip-twitter',
        showTimeout: 5,
        alignTo: 'target',
        alignX: 'center',
        offsetY: 5,
        fade : true
    });*/

    //=================== 在线客服边栏 Start ===================

    //定义一个名字为scrollAD的函数
    function scrollAd(name)
    {
        //定义位移为floatdiv的高度加上滚动条的顶部距离
        var offset = $(name).height() + $(document).scrollTop() - 30;

        //为floatdiv添加动画为TOP位移offset的高度，持续0.8秒。
        $(name).stop().animate({top : offset}, 1000);
    }//

    scrollAd('#online_service_bar');
    //scrollAd('#mini_online_service_bar', 0);

    $(window).scroll(function() {
        scrollAd('#online_service_bar');
    });
    //$(window).scroll(scrollAd('#mini_online_service_bar', 0));

    //为ID为close的DIV添加点击事件
    $('#service_bar_close').click(function(){
        $('#online_service_fullbar').hide(1000, function() {
            $('#online_service_minibar').show(500);
            $('#online_service_minibar').bind('mouseover', function() {
                $('#online_service_minibar').hide(500, function() {
                    $('#online_service_fullbar').show(500);
                });
            });
        });
    });

    function showServiceMenu(obj, speed)
    {
        speed = speed || 500;
        obj.addClass('hover').children('dl').children('dd').slideDown(speed);
        obj.siblings().children('dl').children('dd').slideUp(speed);
    }

    showServiceMenu($('.service_menu li.hover'));

    $('.service_menu li dl dt').hover(function() {
        var obj = $(this).parent().parent();
        $('.service_menu li').stop();
        $('.service_menu li.hover').removeClass('hover');
        showServiceMenu(obj);
    }, function() {
        $('.service_menu li').stop();
    });

    //=================== 在线客服边栏 End ===================
});
