// +----------------------------------------------------------------------
// | Lianwo168
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://lianwo168.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 无线业务
// +----------------------------------------------------------------------
// | Author: 赵桓
// +----------------------------------------------------------------------

/**
 +------------------------------------------------------------------------------
 * Portal页面BAC版首页
 * 描述:本页面包含的业务逻辑较多，已经将能控制页面业务逻辑的标志位放在了config中，并将每一个进行了
 * 详细说明
 * 结构:由于本页面包含的数据较多，故将业务逻辑与数据进行了分离，将后台配置数据通过mapping方法映射到
 * 当前页面中
 +------------------------------------------------------------------------------
 * @author    赵桓<if1983@126.com>
 * @version   1.0 2013-12
 * @modify
 +------------------------------------------------------------------------------
 */

;(function(){
	window.portal={
		//初始化
		init:function(){
			//this.freetime();
			this.mapping();
			this.initlogin();
			this.initscroll();
			this.loadalbum();
			this.loaddiscount();
			CONFIG.ostype=util.ispc();
			$('#os_'+CONFIG.ostype).show();
			//CONFIG.ostype=2;

			//网吧模式显示提示
			if(CONFIG.sitetype==1){
				$('#cybertips').show();
			}


			
			if(CONFIG.ostype!=3){
				$('#mobileonly').show();
				//$('#operate-btn').show();
			}else{
				$('#pop-login').show();
			}

			//开启免费体验
			if(CONFIG.trial==1){
				$('#limianfei').show();
				$('#freetime').text(Math.ceil(CONFIG.freetime/60));
			}else{
				$('#limianfei').hide();
			}

			if(CONFIG.ostype==2){
				//$('#androidconn').show();
			}
			if(CONFIG.apponly==1&&CONFIG.ostype==2){
				$('#apponly').show();
				$('#operate-btn').hide();
			}
			
			this.bind();
			this.loadingicons();
			$(document).ready(function(){
				util.lazyload();
			});
			$('#title').text(initdata.focus.title);
			document.title=initdata.focus.title;
			$('#freetips').text(CONFIG.setting.trial.desc);
			

			if(CONFIG.ostype==2){
				$('#apkdown').show();
			}
			var login_url = CONFIG.usercenter+"user/checkmacphone?siteid="+CONFIG.siteid+"&appMac="+CONFIG.mac+"&jsoncallback=?";
			$.getJSON(login_url, function(data){
				if(data.code==0 || data.code==1002 || data.code==1005){
					CONFIG.phonebind=1;
				}
				portal.checknet();
				//PC模式
				if(CONFIG.ostype==3){
					$(document.body).addClass('pcstyle');
					if(CONFIG.allowpc==1){
						$('#pop-login').hide();
						$('#denypc').hide();
						if(CONFIG.verify==1){
							if(CONFIG.auth.status==0){
								$('#operate-btn').show();
							}
						}else{
							if(CONFIG.auth.status==0){
								$('#pop-login').show();
							}
							
						}
					}else{
						$('#pop-login').hide();
						$('#denypc').show();
					}
					if(CONFIG.phonebind==0){//如果未bind手机	
						$("#liyanzhengma").hide();
						$("#limianfei").hide();
						$('#pop-login').show();
						$("#liuserphone").show();
						$("#liuserphone").click();
					}else{
						$("#liuserphone").hide();
					}
				}
			});
			

			if(util.getUrlParam('topnav')=='no'){
				$('#operate-btn').hide();
				$('#apponly').hide();
				$('#apkdown').hide();
			}
		},
		conf:{
			icon:'/pic/item_%s.png',
			baidu:'http://www.baidu.com/img/bdlogo.gif?version=',
			navtpl:'<a href="%s" target="_blank" click-data="mod=nav">%s</a>'
		},
		ria:{
			TRIAL_OVER:'体验结束',
			TRIAL_DOING:'体验中',
			TRIAL_OVER_NOTICE:'您的免费体验时间已经结束',
			TRIAL_DOING_NOTICE:'您在体验中',
			FLAG_TRIAL_ON:'authed trial',
			FLAG_TRIAL_OFF:'sta logout'
		},
		//映射数据
		mapping:function(){
			env.init();
			var data=env.setting;
			CONFIG.setting=env.setting;
			CONFIG.sitetype=sitetype;
			CONFIG.verify=data.acmode.mode;
			CONFIG.allowpc=(data.pcwifi.en==-1 || data.pcwifi.en==1)?1:0;
			CONFIG.trial=env.setting.trial.enable;
			env.freetime();
			CONFIG.trialtime=CONFIG.setting.trial.time*60;
			if(CONFIG.freetime==''){
				CONFIG.freetime=0;
			}
			var list=util.getPortal();
			for(key in list){
				if(list[key]!=''){
					initdata[key]=list[key];
				}
			}
			var customenv=util.getCustomData('env');
			if(customenv!=undefined && customenv.apponly!=undefined)
				CONFIG.apponly=customenv.apponly;
			if(CONFIG.freetime==0){
				$('span[node-data="trial"]').text(this.ria.TRIAL_OVER);
			}else if(CONFIG.trialflag==portal.ria.FLAG_TRIAL_ON){
				$('span[node-data="trial"]').text(this.ria.TRIAL_DOING);
			}
		},
		//绑定事件
		bind:function(){
			if(CONFIG.trial){
				$('li[node-type="changetab"]').unbind('click').click(function(){
					var node=$(this).attr('node-data');
					if(node != 2){
						if(CONFIG.phonebind==0){//如果未bind手机	
							$("#liuserphone").click();
							return;
						}
					}
					
					$('li[node-type="changetab"]').removeClass('act');
					$(this).addClass('act');
					

					$('#login-page li').each(function(i){
						if($(this).attr('node-data')==node){
							$(this).show().addClass('act');
						}else{
							$(this).hide().removeClass('act');
						}
					});
				});
			}

			$('span[node-type="login"]').unbind('click').bind('click',function(){
				var node=$(this).attr('node-data');
				if(node=='trial'){
					CONFIG.ontrial=true;
					if(CONFIG.freetime<=0){
						alert(portal.ria.TRIAL_OVER_NOTICE);
						return;
					}
					if(CONFIG.trialflag==portal.ria.FLAG_TRIAL_ON){
						$(this).text(portal.ria.TRIAL_DOING);
						$(this).unbind('click');
						alert(portal.ria.TRIAL_DOING_NOTICE);
						return;
					}
					portal.login(1);
					return;
				}
				CONFIG.ontrial=false;
				if($('#number-text').val()==''){
					if(CONFIG.trial==0){
						alert('验证码不能为空!');
						return;
					}
				}
				if(util.ispc()==3){
					$('#pop-shade').hide();
				}
				portal.login();
			});
			$('#phone_step1').unbind('click').bind('click',function(){
				var phoneno=$("#txtphoneno").val();
				CONFIG.phoneno=phoneno;
				if(phoneno==''){
					alert("请输入正确的手机号码！");
					return;
				}
				if(!util.checkPhone(phoneno)){
					alert("请输入正确的手机号码！");
					return;
				}
				$(this).parent().hide().next().show();
				$('#timing').text(59);
				portal.getphonepwd(phoneno);
				var four=phoneno.substr(3,4);
				$('#phoneno').text(phoneno.replace(four,'****'));
				if(!CONFIG.start){
					CONFIG.timing=setInterval('portal.timing();',1000);
				}
				CONFIG.start=true;
			});
			$('#modifyphone').unbind('click').bind('click',function(){
				$('#timing').text(59);
				$(this).parent().parent().hide().prev().show();
			});

			$('#refetchcode').unbind('click').bind('click',function(){				
				if(CONFIG.start){
					return;
				}	
				$('#timing').text(59);
				$('#timing').parent().addClass('re-get-no');
				CONFIG.timing=setInterval('portal.timing();',1000);
				portal.getphonepwd(CONFIG.phoneno);
				CONFIG.start=true;
			});
			
		},
		checkphonepwd:function(){
			if($("#phone_pwd").val()==''){
				alert('请输入四位验证码');
				return;
			}
			var param='channel=2';
				param+='&siteid='+CONFIG.siteid;
				param+='&mac='+CONFIG.mac;
				param+='&pwd='+$("#phone_pwd").val();
				param+='&phoneno='+CONFIG.phoneno;
				param+='&num=';
				param+='&identity=0';
			var login_url = CONFIG.connecturl+'aj_connectee?'+param+"&jsoncallback=?";
			$.getJSON(login_url, function(data){
				if(data.code=='A00006'){
					CONFIG.phonebind=1;
					$('#pop-login').hide();
					$('#pop-shade').hide();
					$("#operate-btn").click();
				}else{
					alert("验证失败！");
				}
			});
			
		},
		getphonepwd:function(phoneno){
			if(CONFIG.start){
				return;
			}
			var param='phone='+phoneno+'&siteid='+CONFIG.siteid;
			var post_url = CONFIG.connecturl+'aj_getphonepwd?'+param+"&jsoncallback=?";
			$.getJSON(post_url, function(msg){
				if(msg.code=="A00006"){
                	//console.log(msg);
                }else{
                	alert("获取失败");
                }
			});
		},
		timing:function(){
			var time=$('#timing').text();
			time=parseInt(time)-1;
			if(time<=0){
				$('#timing').parent().removeClass('re-get-no');
				window.clearInterval(CONFIG.timing);
				CONFIG.start=false;
			}
			$('#timing').text(time);
		},
		login:function(usetrial){
			var code=$('#number-text').val();
			$.ajax({
                type: "GET",
                data: {acode:code,src:'iosportal',ver:'1.0.0',usetrial:usetrial},
                dataType:'json',
                url:'/AC/login.cgi',
                success: function(msg){
                    portal.afterlogin(msg.code,usetrial);
                }
            });
		},
		//登录后处理
		afterlogin:function(code,usetrial){
			var msg=[
				'成功',
				'错误mac',//1
				'错误的src',//2
				'错误的ver',//3
				'认证码错误',//4
				'在黑名单中',//5
				'暂时禁止登陆',//6
				'验证码已被其他终端使用',//7
				'试用时间已到'//8
			];
			if(code==0){
				portal.online();
				if(usetrial==1){
					setInterval('portal.freetime()',20000);
					$('#operate-btn').show();
				}else{
					$('#operate-btn').hide();
				}
				if(CONFIG.ostype==1){
					window.location=window.location.href+'?code=0';
				}
			}else{
				if(code<=msg.length){
					alert(msg[code]);
				}
			}
			
		},
		//加载顶部四个小图标
		loadingicons:function(){
			var logo=0;
			var id=util.ispc()==1?1:0;
			$('a[node-type="icon_about"]').eq(id).attr('title',initdata.about.title);
			$('a[node-type="icon_discount"]').eq(id).attr('title',initdata.discount.title);

			$('#title_album').text(initdata.album.title);
			$('#title_discount').text(initdata.discount.title);

			if(CONFIG.ostype!=2)return;
			logo=initdata.about.logo.substr(7,2);
			logo=parseInt(logo)+100;
			logo=util.sprintf(this.conf.icon,logo.toString().substr(1,2));
			$('a[node-type="icon_about"]').eq(0).find('img').attr('src',logo);
			
			logo=initdata.discount.logo.substr(7,2);
			logo=parseInt(logo)+100;
			logo=util.sprintf(this.conf.icon,logo.toString().substr(1,2));
			$('a[node-type="icon_discount"]').eq(0).find('img').attr('src',logo);

			
		},
		//加载打折信息
		loaddiscount:function(){
			try{
				if(initdata.discount.data.length>0){
					var row=initdata.discount.data[0];
					$('#discount_img').attr('src',row.img);
					$('#discount_title').text(row.title);
				}
			}catch(e){
			}
		},
		//初始化登录窗口
		initlogin:function(){
			$('#operate-btn').click (function () {
				if(CONFIG.phonebind==0){//如果未bind手机	
					$('#pop-login').show();
					if(util.ispc()!=3){
						$('#pop-shade').show();
					}
					$("#liyanzhengma").hide();
					$("#limianfei").hide();
					$("#liuserphone").show();
					$("#liuserphone").click();
					return;
				}else{
					$("#liyanzhengma").show();
					$("#liuserphone").hide();
					//开启免费体验
					if(CONFIG.trial==1){
						$('#limianfei').show();
						$('#freetime').text(Math.ceil(CONFIG.freetime/60));
					}else{
						$('#limianfei').hide();
					}
				}
				if(CONFIG.verify==1){
					//portal.loginsync();
					//$('#loginform').submit();
					portal.login();
				}else{					
					$('#pop-login').show();
					$("#liyanzhengma").click();
					if(util.ispc()!=3){
						$('#pop-shade').show();
					}
					//$('#number-text').focus();
				}
			});

			$('#pop-shade').click(function () {
				$('#pop-login').hide();
				$('#pop-shade').hide();
			});
		},
		//加载相册
		loadalbum:function(){
			var tpl=$('#album').html();
			var html='';
			for (var i = 0; i < 3; i++) {
				var item=initdata.album.data[i];
				html+=util.sprintf(tpl,item);
			};
			$('#album').html(html);
		},
		//加载网站导航数据
		loadsites:function(){
			if(util.iswp()){
				return;
			}
			$.ajax({
                type: "GET",
                url: util.getapi(CONFIG.api),
                dataType:'json',
                success: function(msg){
                    CONFIG.sites=msg.data;
                    portal.layoutsites();
                }
            });
		},
		//加载网页导航
		layoutsites:function(){
			//if(!CONFIG.islogin)return;
			if($('#navigator dl').length>1){
				return;
			}
			if(CONFIG.sites==''||CONFIG.sites==undefined)return;
			var content='';
			var maintpl=$('#navigator').html();
			var subcontent=new Array();
			if(CONFIG.sites==undefined)return;
			var len=CONFIG.sites.length;
			var subtpl=this.conf.navtpl;
			if(len<=0)return;
			for (var i = 0; i < len; i++) {
				var item=CONFIG.sites[i];
				var subhtml='';
				content+=util.sprintf(maintpl,item.logo);
				for (var k = 0; k < item.data.length; k++) {
					var block=item.data[k];
					subhtml+=util.sprintf(subtpl,block.link,block.name);
				};
				subcontent.push(subhtml);
			};
			$('#navigator').html(content).show();
			$('#navigator').find('.clearfix').each(function(i){
				$(this).html(subcontent[i]);
			});
			util.lazyload();
		},
		//检查网络链接状态
		checknet:function(){
			/*var img=new Image();
			img.src=this.conf.baidu+util.rand();
			$(img).load(function(){
				portal.online();
			}).error(function(){
				portal.offline();
			});*/
			if(CONFIG.auth.status==1){
				portal.online();
			}else{
				portal.offline();
			}
		},
		//连网
		online:function(){
			$('#pop-shade').hide();
			$('#pop-login').hide();
			//体验中登录按钮一直存在
			if(CONFIG.trialflag==this.ria.FLAG_TRIAL_ON){
				$('#operate-btn').show();
			}else{
				$('#operate-btn').hide();
			}
				
			$('#successconn').show();
			CONFIG.islogin=true;
			portal.loadsites();

		},
		//断网
		offline:function(){
			if((CONFIG.apponly==0&&CONFIG.ostype!=3) || (CONFIG.apponly==1&&CONFIG.ostype==1)){
				$('#operate-btn').show();
			}

			$('#successconn').hide();
			delcookie('online');
		},
		freetime:function(){
			env.freetime();
			var free=Math.ceil(CONFIG.freetime/60);
			$('#freetime').text(free);
		},
		//初始化顶部滚动图片
		initscroll:function(){
			//电脑端浏览模式下 第一张焦点图
			$('#focus-pc-pic img').attr('node-data',initdata.focus.imgs[0]);

			//IE8及以下 关闭焦点图滑动功能
			var isIE=!!window.ActiveXObject; 
			var isIE6=isIE&&!window.XMLHttpRequest; 
			var isIE8=isIE&&!!document.documentMode; 
			var isIE7=isIE&&!isIE6&&!isIE8; 
			if (isIE){ 
				if (isIE6){ 
					return false;
				}else if (isIE8){
					return false; 
				}else if (isIE7){
					return false; 
				} 
			}

			//检测是否为 iPhone safari 显示“添加到主屏幕”
			if (!(/iPhone/.test(navigator.userAgent)) || /MQQBrowser|CriOS|Android/.test(navigator.userAgent) || !(/Safari/.test(navigator.userAgent)) || getcookie('iphone-shortcut')) {
			} else {
				$('#pop-ios-shortcut').show();
			}

			$('#pop-ios-shortcut').unbind('click').bind('click', function () {
				$(this).hide();
				addcookie('iphone-shortcut',1,86400*30);
			});

			var carousel,
				el,
				i,
				page,
				dots = document.querySelectorAll('#nav-home li'),
				slides = initdata.focus.imgs;
			

			carousel = new SwipeView('#wrapper', {
				numberOfPages: slides.length,
				hastyPageFlip: true
			});

			// Load initial data
			for (i = 0; i < 3; i++) {
				page = i == 0 ? slides.length - 1 : i - 1;

				el = document.createElement('img');
				//el.src = slides[page];
				//console.log();
				$(el).attr('node-data',slides[page]);
				$(el).attr('node-type','lazy');
				carousel.masterPages[i].appendChild(el);
			}

			carousel.onFlip(function () {
				var el,
					upcoming,
					i;

				for (i = 0; i < 3; i++) {
					upcoming = carousel.masterPages[i].dataset.upcomingPageIndex;

					if (upcoming != carousel.masterPages[i].dataset.pageIndex) {
						el = carousel.masterPages[i].querySelector('img');
						el.innerHTML = slides[upcoming];
					}
				}

				document.querySelector('#nav-home .selected').className = '';
				dots[carousel.pageIndex].className = 'selected';

			});
		}
		
	};
})();