//添加cookie
function addcookie(name,value,expireHours){
	var cookieString=name+"="+escape(value);
	//判断是否设置过期时间
	if(expireHours>0){
		var date=new Date();
		date.setTime(date.getTime+expireHours*3600*1000);
		cookieString=cookieString+"; expire="+date.toGMTString();
	}
	document.cookie=cookieString;
}

//获取cookie
function getcookie(name){
	var strcookie=document.cookie;
	var arrcookie=strcookie.split("; ");
	for(var i=0;i<arrcookie.length;i++){
		var arr=arrcookie[i].split("=");
			if(arr[0]==name){
				return arr[1];
			}
	}
	return "";
}
//删除cookie
function delcookie(name){
	var strcookie=document.cookie;
	var arrcookie=strcookie.split("; ");
	for(var i=0;i<arrcookie.length;i++){
		var arr=arrcookie[i].split("=");
			if(arr[0]==name){
				addcookie(name,"",-24);
				return arr[1];
			}
	}
	return "";
}
//天时分秒
function get_time_str(time_distance){
	var int_day=0, int_hour=0, int_minute=0, int_second=0;
	var time_str;
    if(time_distance > 0){
        // 天时分秒换算
        int_day = Math.floor(time_distance/86400)
        time_distance -= int_day * 86400;        
        int_hour = Math.floor(time_distance/3600)
        time_distance -= int_hour * 3600;
        int_minute = Math.floor(time_distance/60)
        time_distance -= int_minute * 60;
        int_second = time_distance;
        
        // 显示时间
        time_str = "";
        if(int_day>0)
        	time_str = time_str+int_day+"天";
        if(int_hour>0 || int_second>0 || int_minute>0)
        	time_str = time_str+int_hour+"时";
        if(int_second>0 || int_minute>0)
        	time_str = time_str+int_minute+"分";        
        if(int_second>0)
        	time_str = time_str+int_second+"秒";
    }else{
    	time_str = "0秒";
    }
    return time_str;
}

function get_num_str(num){
	if(num<=0) return "";
	var num_array = ["零","一","二","三","四","五","六","七","八","九"];
	return num_array[num];
}
//获取url文件名
function get_file_name(url) {
    url=url.replace(/(.*\/)*([^.]+).*/ig,"$2");
    return url;
}
//访问代理
function requestPorxy(interface_url_tmp,jsoncallback){
	var interface_url_tmp = BASE64.encode(interface_url_tmp);
    var dateObj=new Date();
	$.ajax({ //这里使用到Jquery的ajax方法
		  type: "GET", 
		  dataType: "json", //json
		  url: "/proxy?url="+interface_url_tmp+"&t="+dateObj.getTime(), //请求的处理数据 
		  success: function(data) {		
			  eval(jsoncallback);
		  },
		  error: function(data){
			  eval(jsoncallback);
		  }
		});
}
/**
* 我在网上看到过很多BASE64的JavaScript算法，都觉得不满意，于是自己写了一个，在这里分享一下。
* 我的代码在质量的效率都较高，没有一些冗余的操作。总体来讲我觉得非常不错。
* 如果大家有什么不懂的地方可以问我。
*/
var BASE64={
    /**
     * 此变量为编码的key，每个字符的下标相对应于它所代表的编码。
     */
    enKey: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
    /**
     * 此变量为解码的key，是一个数组，BASE64的字符的ASCII值做下标，所对应的就是该字符所代表的编码值。
     */
    deKey: new Array(
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,	//15
	-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,	//31
	-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,62,-1,63,	//47
	52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,	//63
	-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,	//79
	15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,63,	//95
	-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,	//111
	41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1
    ),
    /**
     * 编码
     */
    encode: function(src){
        //用一个数组来存放编码后的字符，效率比用字符串相加高很多。
        var str=new Array();
        var ch1, ch2, ch3;
        var pos=0;
       //每三个字符进行编码。
        while(pos+3<=src.length){
            ch1=src.charCodeAt(pos++);
            ch2=src.charCodeAt(pos++);
            ch3=src.charCodeAt(pos++);
            str.push(this.enKey.charAt(ch1>>2), this.enKey.charAt(((ch1<<4)+(ch2>>4))&0x3f));
            str.push(this.enKey.charAt(((ch2<<2)+(ch3>>6))&0x3f), this.enKey.charAt(ch3&0x3f));
        }
        //给剩下的字符进行编码。
        if(pos<src.length){
            ch1=src.charCodeAt(pos++);
            str.push(this.enKey.charAt(ch1>>2));
            if(pos<src.length){
                ch2=src.charCodeAt(pos);
                str.push(this.enKey.charAt(((ch1<<4)+(ch2>>4))&0x3f));
                str.push(this.enKey.charAt(ch2<<2&0x3f), '');
            }else{
                str.push(this.enKey.charAt(ch1<<4&0x3f), '');
            }
        }
       //组合各编码后的字符，连成一个字符串。
        return str.join('');
    },
    /**
     * 解码。
     */
    decode: function(src){
        //用一个数组来存放解码后的字符。
        var str=new Array();
        var ch1, ch2, ch3, ch4;
        var pos=0;
       //过滤非法字符，并去掉'='。
        src=src.replace(/[^A-Za-z0-9\+\/]/g, '');
        //decode the source string in partition of per four characters.
        while(pos+4<=src.length){
            ch1=this.deKey[src.charCodeAt(pos++)];
            ch2=this.deKey[src.charCodeAt(pos++)];
            ch3=this.deKey[src.charCodeAt(pos++)];
            ch4=this.deKey[src.charCodeAt(pos++)];
            str.push(String.fromCharCode(
                (ch1<<2&0xff)+(ch2>>4), (ch2<<4&0xff)+(ch3>>2), (ch3<<6&0xff)+ch4));
        }
        //给剩下的字符进行解码。
        if(pos+1<src.length){
            ch1=this.deKey[src.charCodeAt(pos++)];
            ch2=this.deKey[src.charCodeAt(pos++)];
            if(pos<src.length){
                ch3=this.deKey[src.charCodeAt(pos)];
                str.push(String.fromCharCode((ch1<<2&0xff)+(ch2>>4), (ch2<<4&0xff)+(ch3>>2)));
            }else{
                str.push(String.fromCharCode((ch1<<2&0xff)+(ch2>>4)));
            }
        }
       //组合各解码后的字符，连成一个字符串。
        return str.join('');
    }
};

Date.prototype.format = function(format) //author: meizz
{
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond
  }
  if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length==1 ? o[k] :
        ("00"+ o[k]).substr((""+ o[k]).length));
  return format;
} 

//扩展jQuery方法：上下移动元素
    jQuery.extend({
        scrollup:function(obj,pdepth,ptag,callback){
           var thistr=$(obj).parent();
           var i=0;
           pdepth-=1;
           while(i<pdepth){
               thistr=$(thistr).parent();
               i++;
           }
           var upme=thistr.prev();
           if(!upme.is(ptag))return;
           var wrapupwme=upme.clone();
           thistr.after(wrapupwme);
           upme.remove();
           //$('a[action-type="popbox"]').unbind('click').bind('click',showdiv);
           if(callback!=''){
                eval(callback);
           }
        },
        scrolldown:function(obj,pdepth,ptag,callback){
           var thistr=$(obj).parent();
           var i=0;
           pdepth-=1;    
           while(i<pdepth){
               thistr=$(thistr).parent();
               i++;
           }
           var donwme=thistr.next();
           if(!donwme.is(ptag))return;
           var wrapdonwme=donwme.clone();
           thistr.before(wrapdonwme);
           donwme.remove();
           //$('a[action-type="popbox"]').unbind('click').bind('click',showdiv);
           if(callback!=''){
                eval(callback);
           }
        },
        delitem:function(obj,pdepth){
            if(!confirm('你确认要删除吗？'))return;
            var thistr=$(obj).parent();
            var i=0;
            pdepth-=1;
            while(i<pdepth){
               thistr=$(thistr).parent();
               i++;
            }
            thistr.remove();
        }
    });

window.util={
    //模仿PHP的sprintf方法，方便于模板拼接
    sprintf:function() {
        var i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = '';
        while (f) {
            if (m = /^[^\x25]+/.exec(f)) {
                o.push(m[0]);
            }
            else if (m = /^\x25{2}/.exec(f)) {
                o.push('%');
            }
            else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
                if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) {
                    //throw('Too few arguments.');
                    m[1]=0;
                }
                if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) {
                    throw('Expecting number but found ' + typeof(a));
                }
                switch (m[7]) {
                    case 'b':a = a.toString(2);break;
                    case 'c':a = String.fromCharCode(a);break;
                    case 'd':a = parseInt(a);break;
                    case 'e':a = m[6] ? a.toExponential(m[6]) : a.toExponential();break;
                    case 'f':a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a);break;
                    case 'o':a = a.toString(8);break;
                    case 's':a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a);break;
                    case 'u':a = Math.abs(a);break;
                    case 'x':a = a.toString(16);break;
                    case 'X':a = a.toString(16).toUpperCase();break;
                }
                a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a);
                c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
                x = m[5] - String(a).length - s.length;
                p = m[5] ? str_repeat(c, x) : '';
                o.push(s + (m[4] ? a + p : p + a));
            }
            else {
                throw('Huh ?!');
            }
            f = f.substring(m[0].length);
        }
        return o.join('');
    },
    checkPhone:function(phone){
        //验证电话号码手机号码，包含至今所有号段   
        var ab=/^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$/;
        if(ab.test(phone) == false){
            //alert("请正确填写手机号码!");
            return false;
        }
        //alert("手机号码正确");
        return true;
    },
    //判断操作系统类型
    ispc:function () {   
        var sUserAgent= navigator.userAgent.toLowerCase();    
        var bIsIpad= sUserAgent.match(/ipad/i) == "ipad";  
        var bIsIphoneOs= sUserAgent.match(/iphone/i) == "iphone";    
        var bIsMidp= sUserAgent.match(/midp/i) == "midp";    
        var bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";    
        var bIsUc= sUserAgent.match(/ucweb/i) == "ucweb";    
        var bIsAndroid= sUserAgent.match(/android/i) == "android";
        var bIsWindowsPhone= sUserAgent.match(/windows phone/i) == "windows phone";
        var bIsCE= sUserAgent.match(/windows nt/i) == "windows nt"; 
        var bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile";  
        var bIsMac= sUserAgent.match(/mac/)=="mac";
        if((bIsMac && bIsIpad) || (bIsMac && bIsIphoneOs) ){
            bIsMac=false;
        }
        if(bIsAndroid) {
            return 2;//Android
        }else if (bIsCE || bIsWM || bIsMac) {   
            return 3;//PC
        } else {   
            return 1;//IOS
        }
    },
    iswp:function(){
        var sUserAgent= navigator.userAgent.toLowerCase();
        var bIsWP= sUserAgent.match(/windows phone/i) == "windows phone";
        return bIsWP;
    },
    //可以访问外网的URL
    getapi:function(url){
        var param = BASE64.encode(url);
        var dateObj=new Date();
        return "/proxy?url="+param+"&t="+dateObj.getTime();
    },
    //URL参数
    getUrlParam:function(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r!=null) return unescape(r[2]); return null; //返回参数值
    },
    //node-type里的&格式数据
    getParam:function(params,name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = params.match(reg);  //匹配目标参数
        if (r!=null) return unescape(r[2]); return null; //返回参数值
    },
    //从路径里获取文件名称(包含扩展名)
    getFileName:function(obj){
        var pos = $(obj).val().lastIndexOf("\\")*1;
        return $(obj).val().substring(pos+1);
    },
    getFileExt:function(obj){
        var filename=this.getFileName(obj);
        var dot = filename.lastIndexOf(".");
        return filename.substr(dot+1);
    },
    //生成随机数
    rand:function(){
        return Math.floor(Math.random()*10000);
    },
    //对象数组生成json格式
    arrayToJson:function(o){ 
        var r = []; 
        if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\""; 
        if (typeof o == "object") { 
            if (!o.sort) { 
                for (var i in o) 
                    r.push('"'+i + "\":" + util.arrayToJson(o[i])); 
                if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) { 
                    r.push("toString:" + o.toString.toString()); 
                } 
                r = "{" + r.join() + "}"; 
            } else { 
                for (var i = 0; i < o.length; i++) { 
                    r.push(util.arrayToJson(o[i])); 
                } 
                r = "[" + r.join() + "]"; 
            } 
            return r; 
        } 
        return o.toString(); 
    },
    //首页Portal数据
    getPortal:function(){
        if(portalobj!=''){
            if(portalobj.ext!='')
                return eval('('+portalobj.ext+')');
        }
        return false;
    },
    //JJ提供BAC通用方法:写入
    setCustomData:function(alias,data){
        data=this.arrayToJson(data);
        $.ajax({ 
            type: "GET", 
            dataType: "json", 
            url: '/customdata?t='+util.rand(), 
            data:{act:'replace',file:alias,contenttype:'text/javascript', content:data},
            async:false,
            success: function(data) { 
                
            } 
        });
    },
    //JJ提供BAC通用方法:读取
    getCustomData:function(alias){
        $.ajax({ 
            type: "GET", 
            dataType: "json", 
            url: '/vfs-custom/'+alias+'?t='+util.rand(), 
            async:false,
            success: function(data) {
                CONFIG.customdata=data;
            },
            //为处理JJ那不能在取自定义数据时不能返回默认值，只能是404的问题
            error : function() {  
                //CONFIG.customdata={};  
                util.setCustomData(alias,{});
            }
        });
        return CONFIG.customdata;
    },
    lazyload:function(){
        $('img[node-type="lazy"]').each(function(){
            var imglazy=new Image();
            var curimg=$(this);
            var url=$(this).attr('node-data');
            if(url==''||url=="%s"){
                return;
            }
            if(url!='undefined'){
                imglazy.src=url;
                $(imglazy).load(function(){
                    curimg.attr('src',imglazy.src);
                    curimg.attr('node-type','');
                });
            }
        });
    },
    click:function(){
        var url='http://portal.lianwo168.com/portal/hit';
        $('a').each(function(){
            var suda=$(this).attr('click-data');
            //if(suda=='')continue;
            $(this).unbind('click').bind('click',function(){
                $.ajax({ 
                    type: "GET", 
                    dataType: "json", 
                    url:this.getapi(url), 
                    success: function(data) {
                        //console.log(data);
                    } 
                });
            });
            
        });
    }
};

/**
+---------------------------------------------------------------------
* @author: 赵桓<if1983@126.com>
+---------------------------------------------------------------------
* 说明:由于上网行为数据分布在不同的接口中，未来还有可能增加更多的接口，每个方法都写
* 一个ajax方法十分的不方便、也不好进行扩展提供个多页面使用，所以将所有的接口全部
* 配置到这个地方，可以对所有的接口一次性全部读取及全部写入
+---------------------------------------------------------------------
*/
window.env={
    //初始化后得到上网行为数据
    setting:{},
    //上网行为数据保存API
    setapi:{
        acmode:{//上网行为控制模式
            api:'setacmode',
            data:{}},
        pcwifi:{//允许PC机连接WIFI上网
            api:'setpcwifi',
            data:{}},
        vipips:{//VIP IPs
            api:'setnonviptips',
            data:{}},
        viplimit:{
            api:'setviplimit',
            data:{}},
        ips:{
            api:'addvipips',
            data:{}},
        delvips:{
            api:'delvipips',
            data:{}},
        verifycode:{
            api:'setacodes',
            method:'POST',
            data:{}},
        trial:{//免费体验
            api:'settrial',
            data:{}}
    },
    //上网行为数据读取API
    getapi:{
        codes:{api:'getacodes',type:'html'},//验证码
        acmode:{api:'getacmode'},//上网行为控制模式
        pcwifi:{api:'getpcwifi'},//允许PC机连接WIFI上网
        vipips:{api:'getvipips'},//VIP IPs
        trial:{api:'gettrial'}//免费体验
    },
    init:function(){
        for(key in this.getapi){
            this.getdata(key,this.getapi[key]);
        }
        $.ajax({ 
            type: "GET", 
            dataType: "json", 
            url: '/qbacstat', 
            cache:false,
            async:false,
            success: function(data) { 
            	CONFIG.siteid=data.siteid;
            } 
        });
        $.ajax({ 
            type: "GET", 
            dataType: "json", 
            url: '/AC/deviceinfo.cgi?src=aa&ver=1.0.0', 
            cache:false,
            async:false,
            success: function(data) { 
            	CONFIG.mac=data.stamac;
            } 
        });
        
    },
    //获取上网行为数据
    getdata:function(mod,item){
        var datatype="json";
        if(item.type!=undefined){
            datatype=item.type;
        }
        $.ajax({ 
            type: "GET", 
            dataType: datatype, 
            url: '/'+item.api+'?t='+util.rand(), 
            async:false,
            success: function(data) { 
                env.setting[mod]=data;
            } 
        });
    },
    freetime:function(){
        var api='/AC/authstatus.cgi?src=portal&ver=1.0.0';
        $.ajax({ 
            type: "GET", 
            dataType: "json", 
            url: api, 
            async:false,
            success: function(data) { 
                if(data.trialtime!=undefined){
                    CONFIG.freetime=data.trialtime;
                    CONFIG.trialflag=data.lastdesc;
                    CONFIG.auth=data;
                }
            } 
        });
    }

};