/**
 * @object 常用网址添加
 * @namespace T.siteEdit
 * @author zzf
 * @update 2013-08-05
 */

T.siteEdit = {
  'defaultWebsiteName' : '如：2345网址导航',
  'defaultwebsiteURL' : '如：www.2345.com',
  'defaultColor' : '#999',
  'clickColor' : '#333',
  'MAX' : 12,
  'tipTimer' : null,
  'tipTimeout' : 3000,
  'preSites' : [],
  'stop' : T.siteClicks.stop, 
  'data' : null,
  'curr' : 0,
  'currTip' : null,
  'errText' : {
     'tips' : {
        'urlExisted': ['该网址已存在', 'ipt_tip'],
        'nameIsEmpty': ['请输入网站名称', 'ipt_tip ipt_tip_2'],
        'urlIsEmpty': ['请输入网址', 'ipt_tip ipt_tip_3']
      },
      'bottom' : {
        'unlogin' : '登录后，常用网址永不丢失，异地也可以便捷使用哦！<a href="#">登录帐号</a><ins>|</ins><a href="http://login.2345.com/qq/?forward=http://www.2345.com/" class="qqdl" target="_self" onclick="clickCount(\'siteEdit_qqyjdl\')">QQ一键登录</a>',
        'logined' : '<a href="http://my.2345.com/fav/?cid=-2" class="fblue">云收藏</a>同步已开启，您添加的网址将自动保存到帐号！',
        'overflow' : '您收藏的网址已经达到12条，点击进入云收藏页面，收藏更多网址！<a href="http://my.2345.com/fav/" class="fblue f_underline">进入云收藏</a>'
      }
  },
  'HTMLEncode' : function(str) {
       return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;').replace(/\'/g, '&#39;').replace(/\"/g, '&quot;');
  },  
  'getPos' : function (el) {
      for (var pos = {x:0, y:0}; el; el = el.offsetParent) { 
          pos.x += el.offsetLeft;
          pos.y += el.offsetTop;
      }
      return pos;
  },
  'getScrollHeight': function() {
          var doc = document,
              html = doc.documentElement,
              bd = doc.body;
          return Math.max(window.pageYOffset || 0, html.scrollTop, bd.scrollTop);
  },
  'render' : function (){
    var  siteClicks = T.siteClicks,
          sites = siteClicks.sites,
          temp=[],
          i=0,
          len= sites.length,item;

    temp.push('<div class="filterbg"></div><div id="J_popBox"><div class="pop" id="J_pop" style="display:none;"><div class="pop_tit">');
    if (siteClicks.isLogin()) {
       temp.push('<h3>管理云收藏</h3>');
       temp.push('<span id="J_p_fav_tip2" class="p_fav_tip2"><em id="J_p_fav_tip_em"><a href="http://my.2345.com/fav/?cid=-2">云收藏</a>同步已开启，您添加的网址将自动保存到帐号！</em></span>');
    }else{
       temp.push('<h3>管理常用网址</h3>');
       temp.push('<span id="J_p_fav_tip2" class="p_fav_tip3"><em id="J_p_fav_tip_em">登录后，常用网址永不丢失，异地也可以便捷使用哦！<a href="#">登录帐号</a><ins>|</ins><a href="http://login.2345.com/qq/?forward=http://www.2345.com/" class="qqdl" target="_self" onclick="clickCount(\'siteEdit_qqyjdl\')">QQ一键登录</a></em></span>');
    }
    temp.push('<span class="t_right"><a title="关闭" target="_self" href="javascript:;" class="btn_close" id="J_siteEdit_btn_close"></a></span></div><div class="myfav clearfix"><dl><dd class="favli"><ul id="J_siteEdit_weblist">');

    if ( len === 0 ) {
       temp.push('<li  id="J_tip_fav5"><em class="tip_fav5">您收藏的网址将显示在这里</em></li>');
    }else{
       for(; i<len; i++){
          item = sites[i].split(siteClicks.DELIMITER);
          temp.push("<li><a href="+item[0]+" onclick=\"allCount('visits"+i+"',this)\">"+unescape(item[1])+"</a><ins title='删除' onmouseover=\"this.className='hov'\" onmouseout=\"this.className=''\"></ins></li>");
      }
    }
    temp.push('</ul></dd></dl></div>');

    temp.push('<div class="pop_bd clearfix"><div class="form_add clearfix"><label for="websiteName">网址名称:</label> <input type="text" value="如：2345网址导航" id="websiteName" name="websiteName" class="p_ipt_01">&nbsp;&nbsp;&nbsp;&nbsp;<label for="websiteURL">网址:</label> <input type="text" style="width:225px;" value="如：www.2345.com" id="websiteURL" name="websiteURL" class="p_ipt_01"><input type="button" id="J_siteEdit_btn_add" class="p_btn_add" value="添加网址"><span class="ipt_tip" id="J_siteEdit_ipt_tip" style="display:none;"></span></div>');
    temp.push('</div><div class="pop_sort  pop_sort_load clearfix"  id="J_pop_sort"></div></div></div>');
    return temp.join('');
  },
  'doSth' : function (){
      var div = document.createElement('DIV') , 
          _div = null;

      if (_div = $('J_popBox_wrap')) {
        document.body.removeChild(_div);
      }
      div.innerHTML = this.render();
      div.setAttribute('id','J_popBox_wrap');
      document.body.appendChild(div);
      if (this.getScrollHeight() < 300) {
           scrollTo(0,300);
      }
      $('J_pop').style.top = this.getPos($('J_myfav_w')).y - 25+'px';
      $('J_pop').style.display = '';
      this.websiteName =  $('websiteName');
      this.websiteURL =  $('websiteURL');
      this.websiteName.focus();
      this.websiteName.value = '';
      this.getRecommend();
      this.delegatePop(); //代理事件
  },
  'getRecommend' : function (){
       T.getScript('/Skins/mb/css/sites_data.js' , { diff: 20 , callback : function (){
            T.siteEdit.renderRecommend();
       }});
  },
  'renderRecommend' :  function (){
      if (!this.data) { return}
      var  i=0,
            len = this.data.length,
            div = document.createElement('DIV'),
            str = [],
            temp,
            temp2,
            tempLen,
            wrapper = $('J_pop_sort');

      wrapper.innerHTML = '';
      str.push('<ul class="nav_left" id="J_nav_left">');
      for(; i<len ; i++) {
         temp = this.data[i];
         str.push('<li'+( i===0 ? ' class ="cur"' : '' )+' data-value="'+i+'">'+temp['title']+'</li>');
      }
      str.push('</ul>');

      str.push('<div class="sort_con" id="J_sort_con">');
      for(i=0 ; i<len ; i++) { //循环二次
         temp = this.data[i]['content'];
         tempLen = temp.length ;

         str.push('<dl'+( i===0 ?  ' style = "display : block"' : '' )+'>');
         for(var j =0; j < tempLen ; j++) {
             str.push('<dt class="firstline">'+temp[j]['subTitle']+'</dt><dd><ul>');
             temp2 = temp[j]['subContent'];
             for(var k=0; k< temp2.length ; k++) {
                 str.push('<li><a href="'+temp2[k]['l']+'" onclick="allCount(\'visit'+temp2[k]['l']+'\',this)">'+temp2[k]['t']+'</a><a href="#" class="'+(this.inSites(temp2[k]['l'])===-1 ? 'fbtn_add' : 'fbtn_cancel' )+'"></a></li>');
             } 
             str.push('</ul><div class="clearfix"></div></dd>');
         }
         str.push('</dl>');
      }
      str.push('</div>');
      div.innerHTML = str.join('');
      wrapper.className = 'pop_sort  clearfix';
      wrapper.appendChild(div);
   },
   'showRecommendTip' : function (target,isAdd){
     clearTimeout(this.tipTimer);
     if (this.currTip && this.currTip.parentNode) {
         this.currTip.parentNode.removeChild(this.currTip);
         this.currTip = null;
     }
     var   span = document.createElement('SPAN');
     if (isAdd) {
        if (T.siteClicks.isLogin()) {
            span.className = 'tip_fav3';
            span.innerHTML = '<ins class="ico_suc"></ins><ins class="arrow"></ins>收藏成功';
        }else{
            span.className = 'tip_fav7';
            span.innerHTML = '<ins class="ico_suc"></ins><ins class="arrow"></ins>收藏成功！<a href="#">保存到帐号</a>';
        }
     }else{
        span.className = 'tip_fav4';
        span.innerHTML = '<ins class="ico_wrong"></ins>网址已满,请删除不常用的网址';
     }
    this.currTip = span;
    target.parentNode.appendChild(span);
     this.tipTimer = setTimeout(function (){
        target.parentNode.removeChild(span);
        span = null;
     },this.tipTimeout);
  },
  'openPop' : function (isAfterLogin){
    var siteClicks = T.siteClicks,
        self = this;

    if ( siteClicks.isLogin() || isAfterLogin) {
          T.getScript('http://my.2345.com/api/get_server_site_str.php',{callback : function (){ //先同步
              siteClicks.strToArr();
              if (!siteClicks.sites.length) { //如果服务器没数据，覆盖？
                  siteClicks.sites = self.preSites;
              }
              self.doSth();
         }});
    }else{
         self.doSth();
    }
  },
  'closePop' : function (){
      var box = $('J_popBox_wrap');
      box.onclick = this.websiteName.onblur = this.websiteURL.onblur = this.websiteName.onfocus = this.websiteURL.onfocus = null;
      T.siteClicks.initRender(true);
      document.body.removeChild(box);
  },
  'p_push' : function (href,name,el){
       var ul = $('J_siteEdit_weblist') ;
       if ($('J_tip_fav5')) {
           ul.innerHTML = '';
       }

      var   len = ul.getElementsByTagName('LI').length, 
            newLI = document.createElement('LI');

     newLI.innerHTML = '<a href="'+this.HTMLEncode(href)+'" onclick="allCount(\'visits'+(len-1)+'\',this)">'+this.HTMLEncode(name)+'</a><ins title="删除" onmouseover="this.className=\'hov\'" onmouseout="this.className=\'\'"></ins>';
     ul.appendChild(newLI);
     T.siteClicks.sites =  this.genArr();
     T.siteClicks.save();
     this.sync(href);
  },
   'delOne' : function (target){
    var li = target.parentNode,
        siteClicks = T.siteClicks,
        J_p_fav_tip_em = $('J_p_fav_tip_em');

    li.parentNode.removeChild(li);
    if (J_p_fav_tip_em.innerHTML.indexOf('您收藏的网址已经达到12条')!==-1) {
      if (siteClicks.isLogin()) {
        J_p_fav_tip_em.innerHTML = this.errText.bottom.logined;
      }else{
        J_p_fav_tip_em.innerHTML = this.errText.bottom.unlogin;
      }
    }
     this.sync(target.previousSibling.getAttribute('href',2).toLowerCase(),true);
     T.siteClicks.sites =  this.genArr();
     T.siteClicks.save();
     clickCount('visitdel'); 
  },
  'sync' : function (url,isDel){
       var hrefs = $('J_sort_con').getElementsByTagName('A'), len = hrefs.length , i=0;
      for(; i<len; i++) {
        if (hrefs[i].getAttribute('href',2) === url) {
            hrefs[i].nextSibling.className = isDel ? 'fbtn_add' : 'fbtn_cancel' ;
        }
      }
  },
  'showTip' : function (name){
     var J_siteEdit_ipt_tip = $('J_siteEdit_ipt_tip');
    
     clearTimeout(this.tipTimer);
     J_siteEdit_ipt_tip.innerHTML = this.errText.tips[name][0];
     J_siteEdit_ipt_tip.className = this.errText.tips[name][1];
     J_siteEdit_ipt_tip.style.display = '';
     this.tipTimer = setTimeout(function (){
        J_siteEdit_ipt_tip.style.display = 'none';
     },this.tipTimeout);
  },
  'inSites' : function (url){
      var ret = -1,
          ul = $('J_siteEdit_weblist'),
          hrefs = ul.getElementsByTagName('A'),
          len = hrefs.length,
          i = 0,
          link;

    for(; i<len; i++) {
      link = hrefs[i].getAttribute('href',2).toLowerCase();
      if (url.toLowerCase() === link || (url +'/') === link || ('http://0.0.0.'+url.substring(7)+'/') === link) {
          return i;
      }
    }
    return ret;
  },
  'verify' : function(url,name,isfromRecommend,target){
    var arr = this.genArr(), siteClicks = T.siteClicks;
    if(arr.length >= 12) {
      if (isfromRecommend) {
          this.showRecommendTip(target);
      }else{
        $('J_p_fav_tip_em').innerHTML = this.errText.bottom.overflow;
      }
      siteClicks.sites = arr;
      siteClicks.save();
      return;
    }

    var name = name ||  this.websiteName.value,
        url =  url || this.websiteURL.value,
        subStr = function(str, size){
          var curSize = 0, arr = [];
          for(var i = 0, len = str.length; i < len; i++){
            arr.push(str.charAt(i));
            
            if (str.charCodeAt(i) > 255){
              curSize += 2;
              if(size === curSize || size === curSize - 1){
                return arr.join('');
              }
            }else{
              curSize++;
              if(size === curSize){
                return arr.join('');
              }
            }
          }
          return arr.join('');
        };

    name = name.trim();
    url = url.trim();
    if ( name.length < 1 || name === this.defaultWebsiteName) {
          this.showTip('nameIsEmpty');
          return false;
    }
    if (url.length < 1 || url.trim() === this.defaultwebsiteURL) {
        this.showTip('urlIsEmpty');
        return false;
    }
    if(url.substring(0, 7) != 'http://' && url.substring(0, 8) != 'https://' && url.substring(0, 6) != 'ftp://'){
       url = 'http://'+url;
    }
    if (this.inSites(url)!=-1) {
          if (!isfromRecommend) {
               this.showTip('urlExisted');
               this.websiteURL.select();
          }
          return false;
    }
    if (!isfromRecommend) {
         this.websiteName.value = name;
         this.websiteURL.value = url;
     }
    return true;
  },
  'genArr' : function (){
      var ul = $('J_siteEdit_weblist'),
          hrefs = ul.getElementsByTagName('A'), 
          i = 0,
          len = hrefs.length,
          arr = [],
          link,
          siteClicks = T.siteClicks;

      for(; i< len ; i++) {
           link =  hrefs[i];           
           arr.push(link.getAttribute('href',2)+siteClicks.DELIMITER+escape(link.innerHTML)); 
      }
      return arr;
  },
  'delegatePop' : function (){
      var self = this , 
          siteClicks = T.siteClicks;

      $('J_popBox_wrap').onclick =  function (e){
        var e = e || event, target = e.target || e.srcElement;

        if (target.id === 'J_siteEdit_btn_add') { //添加
            if (!self.verify()) {
                self.stop(e);
                return;
            }
            self.p_push(self.websiteURL.value,self.websiteName.value);
            self.websiteName.value = self.defaultWebsiteName;
            self.websiteURL.value = self.defaultwebsiteURL;
            $('J_siteEdit_ipt_tip').style.display = 'none';
            self.stop(e);
            clickCount('popup_add');
            return;
        }

        if (target.nodeName === 'INS' &&　target.title === '删除'　) { //删除
            self.delOne(target);
            self.stop(e);
            return;
        }

        if (target.id === 'J_siteEdit_btn_close') { //关闭
            self.closePop();
            self.stop(e);
            return;
        }

        if (target.innerHTML === '登录帐号' || target.innerHTML === '保存到帐号') { //保存到帐号
          T.getScript('/Skins/mb/css/sites_login_20130903.js',{callback : function (){
             self.closePop();
             self.preSites = T.siteClicks.sites;
             T.siteLogin.renderLogin();
           }});
           self.stop(e);
           if (target.innerHTML === '登录帐号' ) {
                clickCount('siteEdit_dlzh');
           }else{
                clickCount('siteEdit_bcdzh');
           }
           return;
        }

        if (target.className === 'fbtn_add' ) { //收藏网址
            if (!self.verify(target.previousSibling.href,target.previousSibling.innerHTML,true,target)) {
                self.stop(e);
                return;
            }
           self.p_push(target.previousSibling.href,target.previousSibling.innerHTML);
           self.showRecommendTip(target,true);
           target.className = 'fbtn_cancel';
           clickCount('fav'+target.previousSibling.href);
           self.stop(e);
           return;
        }

       if (target.className === 'fbtn_cancel' ) { //取消收藏
           var _index;
           if ((_index = self.inSites(target.previousSibling.href))!==-1) {
              self.delOne($('J_siteEdit_weblist').getElementsByTagName('INS')[_index]);
           }
           target.className = 'fbtn_add';
           if (self.currTip && self.currTip.parentNode) {
               self.currTip.parentNode.removeChild(self.currTip);
               self.currTip = null
           }
           self.stop(e);
           return;
        }

        if (target.nodeName === 'LI' && target.parentNode.id === 'J_nav_left' && target.className !== 'cur' ) { //切换推荐
           var dl = $('J_sort_con').getElementsByTagName('DL');
            target.className = 'cur';
            $('J_nav_left').getElementsByTagName('LI')[self.curr].className = '';
            dl[self.curr].style.display = 'none';
            self.curr = parseInt(target.getAttribute('data-value'));
            dl[self.curr].style.display = 'block';
           return;
        }
      }

       self.websiteName.onfocus = self.websiteURL.onfocus = function (){
          this.style.color = self.clickColor;
           if ((this.id === 'websiteName' && this.value.trim() === self.defaultWebsiteName) || (this.id === 'websiteURL' && this.value.trim() === self.defaultwebsiteURL)) {
              this.value = '';
           }
        };
        
        self.websiteName.onblur = self.websiteURL.onblur = function (){
           this.style.color = self.defaultColor;
           if (this.value.trim() === '') {
              this.value = this.id === 'websiteName' ? self.defaultWebsiteName : self.defaultwebsiteURL;
           }
         };
  }
};