// float-window
// vote-records
// application
// app.js
// report
// ajaxlogin
// jquery.poshytip.min


function buffer(fun, ms, context){
   var buffer;
   return function(){
    if(buffer) return;
    buffer = setTimeout(function(){
       fun.call(this)
       buffer = undefined;
    }, ms);
   };
}

(function(){
    var oDiv=document.getElementById("float");
    if ( oDiv == undefined ) return false;
    var H=0,iE6;
    var Y=oDiv;
    while(Y){H+=Y.offsetTop;Y=Y.offsetParent};
    iE6=window.ActiveXObject&&!window.XMLHttpRequest;
    function myscroll(){
        var s=document.body.scrollTop||document.documentElement.scrollTop;
        if (s >H ){
            oDiv.className = "div1 div2";
            if(iE6){oDiv.style.top=(s-H)+"px";}
        }
        else
            oDiv.className = "div1";    
    }
    if(!iE6 || true){
        window.onscroll= buffer(myscroll,150,this );
    }
    
})();

function AddBookmar() {
    var url = "http://www.qiushibaike.com",
    name = "绯椾簨鐧剧";
    if (window.sidebar && window.sidebar.addPanel) {
        window.sidebar.addPanel(name, url, '');
    } else if (window.opera && window.print) {
        var e = document.createElement('a');
        e.setAttribute('href', url);
        e.setAttribute('title', name);
        e.setAttribute('rel', 'sidebar');
        e.click();
    } else if (window.external) {
        try {
            window.external.AddFavorite(url, name);
        }
        catch(e) {}
    }
    else {
        alert("鏀惰棌鏂瑰紡:璇峰湪鑿滃崟涓€夋嫨涔︾灏嗘湰绔欏姞鍏�,鏂逛究浠ュ悗鏌ョ湅(蹇嵎閿�:CTRL+D)");
    }
}

var VoteHistory = {
	_Historys : null,
	_IsValid  : null,
	// set/get state for article
	// return 1,0,-1 for state up, normal, down
	voteState : function (article_id,state){
		if (!this.isValid()) return 0;
		if(state == null){
			return this._Historys[article_id];
		}else{
			this._Historys[article_id] = state;	//TODO: state 0(currently not available)
			this.saveHistory();
		}
	},

	isValid : function(){
		if(this._IsValid == null)
			this._IsValid = window.localStorage ? true : false;
		return this._IsValid;
	},

	// only read once
	readHistory : function(){
		this._Historys = window.localStorage.getItem('vote_history')
		this._Historys = JSON.parse(this._Historys)
		if(this._Historys == null) this._Historys ={}
	},

	saveHistory : function(){
		if ( this._Historys == null) return
		var maxItems = 500;
		var getKeys = function(obj){
		   var keys = [];
		   for(var key in obj){
		      keys.push(key);
		   }
		   return keys;
		}
		var keys = getKeys(this._Historys);
		if(keys.length > maxItems){
			var removes = keys.length - maxItems;
			for(i =0;i<removes;i++)
				delete this._Historys[keys[i]];
		}
		var data = JSON.stringify(this._Historys);
		window.localStorage.setItem('vote_history',data);
	},

	_init : function(){
		if(this.isValid() ) this.readHistory();
	},

	updateArticleStates : function(){
		if(! this.isValid() ) return;
		articles = [];
		$.each($('div[id^=qiushi_counts_]'),function(){articles.push(+this.id.replace('qiushi_counts_',''))});
		$.each(articles, function(i){
			var id = articles[i];
			var v = VoteHistory.voteState(id);
			if (v != undefined ){
				  var posscore = parseInt($('#up-'+id).text()),
			          negscore = parseInt($('#dn-'+id).text()),
			          d = (v>0?'up':'dn');
			      v>0 ? posscore++ : negscore--;
			      hidevotelink(id, d, posscore, negscore);
			}

		});
	}
};

VoteHistory._init();
//$(document).ready(function(){ VoteHistory._init(); VoteHistory.updateArticleStates();});

// application.js
(function($){$.setCookie=function(name,value,options){if(typeof name==='undefined'||typeof value==='undefined')
return false;var str=name+'='+encodeURIComponent(value);if(options.domain)str+='; domain='+options.domain;if(options.path)str+='; path='+options.path;if(options.duration){var date=new Date();date.setTime(date.getTime()+options.duration*24*60*60*1000);str+='; expires='+date.toGMTString();}
if(options.secure)str+='; secure';return document.cookie=str;};$.delCookie=function(name){return $.setCookie(name,'',{duration:-1});};$.readCookie=function(name){var value=document.cookie.match('(?:^|;)\\s*'+name.replace(/([-.*+?^${}()|[\]\/\\])/g,'\\$1')+'=([^;]*)');return(value)?decodeURIComponent(value[1]):null;};$.CooQueryVersion='v 2.0';})(jQuery);
function shareToSina(id){
  var s=screen,d=document,e=encodeURIComponent,a=$('#article'+id),u=$('.permlink', '#qiushi_counts_'+id).attr('href');
  var f='http://v.t.sina.com.cn/share/share.php?',p=['url=',e(u),'&title=',e('绯椾簨'+id),'&appkey=2924220432'].join('');
  var a=function(){
    if(!window.open(f+p,'mb',['toolbar=0,status=0,resizable=1,width=620,height=450,left=',(s.width-620)/2,',top=',(s.height-450)/2].join('')))u=f+p;
  };
  if(/Firefox/.test(navigator.userAgent)){setTimeout(a,0)}else{a()}
}
new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

var l = window.location.href;
var currentUser;
function showAnimation(containerId, actionValue){
    var obj = $('#'+containerId),
        pos = obj.offset(),
        ani = $('<div id="vote-ani" class="'+(actionValue > 0 ? "pos" : "neg")+'" style="font-size:10px;z-index:1000">'+(actionValue > 0 ? "+1" : "-1")+"</div>");
    ani.appendTo('body');
//    pos.top += $(document).scrollTop()+5;
//    pos.left += $(document).scrollLeft()+30;
	  pos.top += 7;
	  pos.left += 30;
	  if(actionValue < 0 )
	     pos.left += 5;
    ani.offset(pos).css('display', 'block').animate({'font-size': '64px', opacity: 0, left: "-=40px"}, 350, 'linear', function(){ani.remove()});
}

function SelfXY(){
    var yScrolltop;
    var xScrollleft;
    if (self.pageYOffset || self.pageXOffset) {
        yScrolltop = self.pageYOffset;
        xScrollleft = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){     // Explorer 6 Strict
        yScrolltop = document.documentElement.scrollTop;
        xScrollleft = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
        yScrolltop = document.body.scrollTop;
        xScrollleft = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScrollleft + event.clientX ,yScrolltop + event.clientY)
    return arrayPageScroll;
}

var _Base64 = {

	// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	 // private method for UTF-8 encoding
_utf8_encode : function (string) {
		       string = string.replace(/\r\n/g,"\n");
		       var utftext = "";

		       for (var n = 0; n < string.length; n++) {

			       var c = string.charCodeAt(n);

			       if (c < 128) {
				       utftext += String.fromCharCode(c);
			       }
			       else if((c > 127) && (c < 2048)) {
				       utftext += String.fromCharCode((c >> 6) | 192);
				       utftext += String.fromCharCode((c & 63) | 128);
			       }
			       else {
				       utftext += String.fromCharCode((c >> 12) | 224);
				       utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				       utftext += String.fromCharCode((c & 63) | 128);
			       }

		       }

		       return utftext;
	       },
        // private method for UTF-8 decoding
        _utf8_decode : function (utftext) {
                var string = [];
        var i = 0, l = utftext.length;
                var c = 0, c1 = 0, c2 = 0, c3 = 0;
                while(i < l) {
                        c = utftext.charCodeAt(i);
                        if (c < 128) {
                                string.push(String.fromCharCode(c));
                                i++;
                        }else if((c > 191) && (c < 224)) {
                                c2 = utftext.charCodeAt(i+1);
                                string.push(String.fromCharCode(((c & 31) << 6) | (c2 & 63)));
                                i += 2;
                        }else{
                                c2 = utftext.charCodeAt(i+1);
                                c3 = utftext.charCodeAt(i+2);
                                string.push(String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)));
                                i += 3;
                        }

                }

                return string.join('');
        },
	  // public method for encoding
	  encode : function (input) {
		  var output = "";
		  var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		  var i = 0;

		  input = _Base64._utf8_encode(input);

		  while (i < input.length) {

			  chr1 = input.charCodeAt(i++);
			  chr2 = input.charCodeAt(i++);
			  chr3 = input.charCodeAt(i++);

			  enc1 = chr1 >> 2;
			  enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			  enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			  enc4 = chr3 & 63;

			  if (isNaN(chr2)) {
				  enc3 = enc4 = 64;
			  } else if (isNaN(chr3)) {
				  enc4 = 64;
			  }

			  output = output +
				  this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
				  this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		  }

		  return output;
	  },
	  // public method for decoding
        decode : function (input) {
                var output = [];
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;

                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        var l = input.length;
                while (i < l) {
                        enc1 = this._keyStr.indexOf(input.charAt(i++));
                        enc2 = this._keyStr.indexOf(input.charAt(i++));
                        enc3 = this._keyStr.indexOf(input.charAt(i++));
                        enc4 = this._keyStr.indexOf(input.charAt(i++));

                        chr1 = (enc1 << 2) | (enc2 >> 4);
                        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                        chr3 = ((enc3 & 3) << 6) | enc4;

                        output.push(String.fromCharCode(chr1));

                        if (enc3 != 64) {
                                output.push(String.fromCharCode(chr2));
                        }
                        if (enc4 != 64) {
                                output.push(String.fromCharCode(chr3));
                        }
                }

                return this._utf8_decode(output.join(''));

        }
}

/**
 *  閫熷害鏍囪
 *
 */

function SpeedTester(){
    this.displayControlId = "divSpeed";

    this.goodColor = "#33CC33";
    this.averageColor = "#3300FF";
    this.badColor = "#FF0033";

    this.goodMessage = "浠呯敤{0}绉掑氨杞藉叆浜嗘暣涓〉闈紝鎮ㄧ殑缃戠粶鐪熸";
    this.averageMessage = "杞藉叆鏁翠釜椤甸潰鐢ㄤ簡{0}绉掞紝鎮ㄧ殑缃戠粶椹┈铏庤檸";
    this.badMessage = "灞呯劧鐢ㄤ簡{0}绉掓墠鎶婃暣涓〉闈㈣浇鍏ヨ繘鏉ワ紝瀹炲湪鏄姳姝�";
    this.goodSpeed = 10000;
    this.averageSpeed = 50000;
    this.badSpeed = 100000;

    this.beginTest = function()    {
        this.startTime = new Date();

        window.onload = function(){
            var displayControl =document.getElementById(SpeedTester.displayControlId);
            if(!displayControl)return;
            SpeedTester.endTime = new Date();

            var spentTime = SpeedTester.endTime - SpeedTester.startTime;

            if (spentTime <= SpeedTester.goodSpeed){
                displayControl.style.backgroundColor = SpeedTester.goodColor;
                displayControl.title = SpeedTester.goodMessage.replace("{0}", spentTime / 1000);
            }else if (spentTime <= SpeedTester.averageSpeed){
                displayControl.style.backgroundColor = SpeedTester.averageColor;
                displayControl.title = SpeedTester.averageMessage.replace ("{0}", spentTime / 1000);
            }else{
                displayControl.style.backgroundColor = SpeedTester.badColor;
                displayControl.title = SpeedTester.badMessage.replace("{0}", spentTime / 1000);
            }
        }
    }
}

SpeedTester = new SpeedTester();
SpeedTester.beginTest();

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;
    }
    return false;
}

function watch(id){
  $('#favorite-'+id).children('a').attr('href', '/articles/remove_favorite/'+id).html('鍙栨秷鍥磋').removeClass('star').addClass('stared');
}

function unwatch(id){
  $('#favorite-'+id).children('a').attr('href', '/articles/add_favorite/'+id).html('鍥磋').removeClass('stared').addClass('star');
}

$(function(){
    $('.favorite-button').click(function(){
      if ( $(this).children('a').attr('href')!="/login" ){
        new $(this).load($(this).children('a').attr('href'));
        return false;}
    else
        return true;
    });
    $('input.numeric').keydown(function(e){
        var k = e.keyCode;
        if(((k>47)&&(k<58)) ||
            (k == 8) ||
            (k == 46)||
            (k == 13)||
            (k>=96 && k<=105)){
            //            event.returnValue = true;
            return true;
        } else {
            e.returnValue = false;
            return false;
        }
    });
});

function open_form(id){
    $('#quickform-' + id).show();
    $('#reply-'+id).hide();
}

function close_form(id){
    $('#quickform-' + id).hide();
    $('#reply-'+id).show();
}

function reply(id){
    var f = $('#quickform-' + id);
    $.ajax({
        type: "POST",
        url: f.attr('action'),
        data: f.serialize(),
        success: function(){
            $('#comment-'+id)
        }
    })
    close_form(id);
    return false;
}


function hidevotelink(id, d, p, n){
    var posscore,negscore;
    if(typeof p === 'undefined'){
        posscore = parseInt($('#up-'+id).text());
    }else{
        posscore = p;
    }
    if(typeof n === 'undefined'){
        negscore = parseInt($('#dn-'+id).text());
    }else{
        negscore = n;
    }

	$('#up-'+id).html(posscore) ;
	$('#dn-'+id).html(negscore) ;
	if( d == 'up')
		$('#vote-up-'+id).find('a').addClass('voted');
	else
		$('#vote-dn-'+id).find('a').addClass('voted');
	$('#vote-up-'+id).find('a').addClass('disable');
	$('#vote-dn-'+id).find('a').addClass('disable');
}

var voteQueue=[];
function vote2(id, v){
    if($('#up-'+id).hasClass('disable') || $('#dn-'+id).hasClass('disable') )  return;
    if(currentUser){
      var posscore = parseInt($('#up-'+id).text()),
          negscore = parseInt($('#dn-'+id).text()),
          d = (v>0?'up':'dn');
      showAnimation('vote-'+d+'-'+id, v);
      $.getJSON( 'http://www.qiushibaike.com/new3/vote/'+mkvotestr(id,currentUser.id,v) ) ;
      v>0 ? posscore++ : negscore--;
      hidevotelink(id, d,posscore, negscore);
      VoteHistory.voteState(id,v);
    }else{
      //voteQueue.push(v>0?id:-id);
      showLoginForm();
      $(document).bind('after_logged_in', function(){
        vote2(id, v);
      })
    }
}


function getCurUsr( data )
{

  if(data && data.user)
    currentUser=data.user;
  else
	currentUser = null;
  vote2m( curId, curV );
}
function mkvotestr( aid, uid , v )
{
	return v>0?_Base64.encode(aid+'+'+uid) : _Base64.encode(aid+'-'+uid);
}

var	curId;
var	curV;
function vote2m(id, v){
     	if( !currentUser )
    	{
		if( $.readCookie('auth_token') )
		{
			curId = id;
			curV = v;
			$.getJSON('/session.js?'+(new Date().getTime()), getCurUsr);
		}
		else
			window.location.href = '/login';
	}
      else{
	var posscore = parseInt($('#pos-score-'+id).text()),
       negscore = parseInt($('#neg-score-'+id).text()),
          d = (v>0?'up':'dn');
      showAnimation(d+'-'+id, v);
    //  $.get('/articles/'+id+'/'+d);
      v>0 ? posscore++ : negscore--;
      hidevotelink(id, posscore, negscore);
	$.get( '/new3/vote/='+mkvotestr(id,currentUser.id,v) ) ;
	}

      //voteQueue.push(v>0?id:-id);
}

var COMMENT_WARNING=    '璇蜂笉瑕佸彂琛ㄤ笌鏈唴瀹规棤鍏崇殑璇勮锛屾偍鏈変簡璐﹀彿灏辨槸鏈夎韩浠界殑浜轰簡锛屾垜浠彲璁よ瘑鎮ㄣ€�';
function clear_warning(e){
    var t = $(this);
    t.focus();
    if($.trim(t.val()) == COMMENT_WARNING){
        t.val('');
	t.removeClass('original');
    }
    t.blur(function(){
        var t=$(this);
        if($.trim(t.val())==''){
            t.val(COMMENT_WARNING);
            t.addClass('original');
        }
    });
}

function postComment(){
    var e =$(this),f = this.form, fe = $(f);
    var v = $.trim(fe.find('.comment_input').val());
    if(v == '' || v == COMMENT_WARNING){
        return false;
    }

    $.post(f.action, fe.serialize(), function(data){
        e.val('鍙戣〃璇勮').attr('disabled', false);
        fe.find(".comment_input").val('').height('50px');
        var u = $('#r'+fe.attr('data-article_id'));
        if(u.size()>0){
			u.append(data);
		}
        else{
          $(data).insertBefore(fe);
        }
    });
    this.value = ('姝ｅ湪鍙戣〃');
    this.disabled = true;

    return false;
}
function article_comments_path(id){
  return '/comment/'+id;
}
function showall(id){
  $('.hide', '#qiushi_comments_'+id).toggle();
}
$(function(){
    $('#comment_submit').live('click', postComment);
    $('.comment_input').live('click', clear_warning).live('mouseover', clear_warning);
    var hash=window.location.hash;
    if(hash.indexOf('#c-') === 0){
        $(hash).click();
    }
});

$(document).keypress(function(e){
  if(e.ctrlKey && e.which == 13 || e.which == 10) {
    var o=e.target;
    if(o.form){
        var f=$(o.form).find('input.comment_submit');
        postComment.call(f[0]);
    }
  }
});


function loadScores(){
    var ids=[];
    $('.article').each(function(i,e){
        var id = parseInt($(e).attr('id').replace('article', ''));
        if(!isNaN(id) && id > 0){
            ids.push(id);
        }
    })
    if(ids.length == 0)return;
    $.getJSON('/scores', {ids:ids.join(' ')}, function(data, status){
        $.each(data, function(id, value){
            var s = value.score;
            $('#pos-score-'+id).text(s.pos);
            $('#neg-score-'+id).text(s.neg);
            if(value.rated){
                hidevotelink(id,s.pos,s.neg);
            }
            if(typeof value.watched != 'undefined'){
              if(value.watched){watch(id);}else{unwatch(id);}
            }
            if(s.public_comments_count==0){
                $('#c-'+id).text('鏆傛棤璇勮');
            }else{
                $('#c-'+id).text(s.public_comments_count+'鏉¤瘎璁�');
            }
        });
    })
}
$(loadScores);

/*
$(function(){
$('.comment').live('mouseenter', function(){
  $('.comment-score a', this).attr('visibility', 'display');
}).live('mouseleave', function(){
  $('.comment-score a', this).attr('visibility', 'hidden');
})
})*/
function comment_vote(id,s){
  var se = $('#comment-'+id+' .score');
  se.text(parseInt(se.text())+s);
  $('#comment-score-'+id+' a').css('visibility', 'hidden');
  if('jStore' in jQuery){
    if(jQuery.jStore.CurrentEngine.get('c'+id)){return}
    jQuery.jStore.CurrentEngine.set('c'+id, true);
  }
  $.post('/comments/'+id+(s > 0 ? '/up' : '/dn'));
  //return false;
}

$(function(){
  $('.comment').live('mouseenter', function(){
    $(this).addClass('hover');
    if(currentUser){
      $(this).children('.reply').css('visibility','visible');
      $(this).children('.report').css('display','inline');
    }
  }).live('mouseleave', function(){
    $(this).removeClass('hover');
    $(this).children('.reply').css('visibility', 'hidden')
    $(this).children('.report').css('display','none');
  })
})
function replyComment(comment_id, article_id, floor){
  var form = $('form', '#qiushi_comments_'+article_id), c = $('#comment-'+comment_id);
  $('input[name=comment[parent_id]]',form).val(comment_id);

  var t = $('textarea', form),o = t.val();
  nv = '鍥炲'+floor+'L:'+ (o == COMMENT_WARNING ? '' : o);
  t.val(nv);
  $.scrollTo(form, 1000);
  t.focus();
  t.setCursorPosition(nv.length);
}

//floorlink support
function gotofloor(id,fl){
  var comment=$('#comment-'+id),f=comment.siblings('.floor-'+fl);
  if(f.size() > 0){ $.scrollTo(f, 1000) }
}

var createFloorLink=function (id, fi){
 $('#fl-'+id+'-'+fi).click(function(e){
   var a = $(this).attr('id').split('-');
   gotofloor(parseInt(a[1]),parseInt(a[2]));
   e.preventDefault();
 }).poshytip({
   className: 'tip-twitter',
 	alignX: 'center',
	showTimeout: 1,
	allowTipHover: false,
	fade: false,
	slide: false,
//	hideTimeout: 50000,
    content: function(){
       var htmlc = $('#comment-'+id).parents('div').contents('.floor-'+fi).html() ;
	return htmlc;
   }
 })
}

function floorLink(){
    $('.comment-block').each(function(i,e){
      e = $(e);
      lz = $(this.parentNode.parentNode.parentNode).find('.author>a');
      lx = e.find(".userlogin>a")
      if (lz.length>0 && lx.length>0)
	if(lx[0].href==lz[0].href){
		e.find(".userlogin").attr('class','userlogin hostname')
	}
      
      var b = e.find('.body');
      var content = b.html();
 	  var id = parseInt(e.attr('id').replace('comment-',''));
      content=content.replace(/(\d+)(f|F|L|l|妤�)/g, function(o,i){
        if($.browser.msie){
        setTimeout("createFloorLink("+id+", "+i+")", 200);
        }else{
        setTimeout(createFloorLink, 200, id, i);
        }
        return "<a href='#comment-"+id+"' id='fl-"+id+"-"+i+"'>"+o+"</a>";
      });

      b.html(content);
    });
}

//$(floorLink);

//app.js
function article_comments_path(id){
  return '/comment/'+id;
}
function loadComments(e){
  var l=$(this);
  var id = /\d+/.exec(l.attr('id'));
  if(!id) return;
  id=id[0];
  var comments_el = $('#qiushi_comments_'+id);
  if(comments_el.size() == 0){
      var xx = l.html();
      l.text('...');
      $.get(article_comments_path(id), null, function(data){

	      $('#qiushi_counts_'+id).after(data).toggleClass('qiushi_counts_afterclick');
		$("#l"+id).height( $('#r'+id).height() ) ;
          comments_el.show();
          l.html(xx).trigger('loaded');
          // l.html(xx);
          if(typeof decrypt == 'function'){l.ready(decrypt)}
          l.ready(floorLink);
      });
  }else{
      comments_el.toggle();
	$('#qiushi_counts_'+id).toggleClass('qiushi_counts_afterclick');
  }
//  window.location.hash = l.attr('id');
  l.blur();
  e.preventDefault();
}
function showall(id){
  $('.hide', '#qiushi_comments_'+id).toggle();
}
function closeComments(e){
	var l = $(this) ;
	var id = /\d+/.exec( l.attr('id' )) ;
	id = id[0];
	$('#qiushi_comments_'+id).toggle() ;
	window.location.hash = '#qiushi_counts_'+id;
}


function dbclose(e)
{
	$(this).toggle();
	var l = $(this) ;
	var id = /\d+/.exec( l.attr('id' )) ;
	id = id[0];
	window.location.hash = '#qiushi_counts_'+id;
}

var	qiushiMap = {};
var	qiushiOff = 2;
var	theme = 'hot' ;
var	bMore = true;

function tagRepl()
{
	var	ret = 0 ;
	$(".untagged").each( function(i){

		$(this).toggleClass('untagged') ;
		if( qiushiMap[$(this).attr("id")] )
			$(this).hide();
		else {
			qiushiMap[$(this).attr("id")] = 1;
			ret ++ ;
		}

	});
}

function showMore()
{
	$("#loadingBar").show();
	$("#loadError").hide();


	$.ajax( {
		type :"GET" ,
		url :  '/'+theme+'/5/page/'+ qiushiOff++ +'?more',
		dataType : "html",

		success:function( data ) {
			$(".qiushiData").append(data);
			$("#loadingBar").hide();
			if( tagRepl() <= 0 )
				$("#loadError").show();
		},
		 error:function (xhr, ajaxOptions, thrownError){
			qiushiOff -- ;
			$("#loadingBar").hide();
			$("#loadError").show();
                }
	});

}
function truncTitle( text )
{
	var i = 0 ;
	var ret = 0;
	var str = text.replace( /[ \-=\n]+/g, ' ' );
	return  str.substring(0,20) ;

}
function shareQiushi()
{
	var l = $(this) ;
	var id = /\d+/.exec( l.attr('id' )) ;
	id = id[0];
	var node = $('#qiushi_tag_'+id+' div.content' ) ;
	var pic = $('#qiushi_tag_'+id+' div.thumb img' ) ;
	var title = truncTitle( node.text() ) ;

	var msg = {msg:title, title:"绯椾簨鐧剧", pic: pic?"":pic.attr("src"),
		desc:node.text(), param:"" };
	qplus.system.shareApp( msg );

	alert( title ) ;
}
$(function(){
    $('a.qiushi_comments').live( "click", loadComments);
	$('a.more').click( showMore ) ;
    $('a.closebtn').live( "click", closeComments) ;
    $('div.comments-close').live( "click", closeComments) ;
    $('a.sharebtn').live( "click", shareQiushi) ;
    $('div#loadError').live( "click", showMore) ;
    $("div.block").hover(function(){
	$(this).find("li.uptip span").fadeIn(300);}, function(){$(this).find( "li.uptip span" ).fadeOut(300);});
    // $('div.comments').live("dblclick",  dbclose );
//	$('a#logintop').click( showLoginForm ) ;
});

$(document).ready(function (){
	$("a").bind("focus",function() {
		if(this.blur) {this.blur()};
	});
	var regex = /\/(\w+)/.exec( document.URL ) ;
	if( regex )
		theme = regex[1];

});

//report
var showReport;
$(function(){
  showReport = function(comment_id){
    var el = $('#comment-'+comment_id+' .report'), o = el.offset(), cmt=$('#comment-'+comment_id);
    o.top += el.height();
    o.left += el.width();
    $('#report-form').trigger('close');
    cmt.addClass('highlight');
    $('#report-form input[name=comment_id]').val(comment_id);
    $('#report-form').css('display', 'block').offset(o);
  }
  $('#report-form').bind('close', function(){
    $(this).css('display', 'none');
    $('.highlight').removeClass('highlight');
  });
  $('#report-form form').submit(function(){
    var cmt_id = this.comment_id.value, a = this.action = '/new4/comments/report',
        f = $(this);
    submit_button=$('button[type=submit]', this).attr('disabled', 'disabled');
    $.post(a, f.serialize(), function(){
     // submit_button.attr('disabled', '');
	submit_button.removeAttr( 'disabled' ) ;
      $('#report-form').trigger('close');
	$('#report-form').find('input[type=radio]').prop('checked',false);
    });
   submit_button.removeAttr( 'disabled' ) ;
   $('#report-form').trigger('close');
   $('#report-form').find('input[type=radio]').prop('checked',false);
    return false;
  });
  $('#close-form').click(function(event){
    event.preventDefault();
    $('#report-form').trigger('close');
  });
});


//ajax login
/* after logged in, the document will receive 'after_logged_in' event */
function showLogin(){
	
  if($.browser.msie){
    document.styleSheets[0].addRule('.login', 'display:block !important');
  }else{
    document.styleSheets[0].insertRule('.login{display:block !important;}',0);
  }
  
  showLogout('none');
}

function showSuggest(){
  if($.browser.msie){
    document.styleSheets[0].addRule('.suggest-form', 'display:inline !important');
  }else{
    document.styleSheets[0].insertRule('.suggest-form{display:inline !important;}',0);
  }
}

function showLogout(type){
  type = type || 'inherited';
  if($.browser.msie){
    document.styleSheets[0].addRule('.logout', 'display:'+type+' !important');
  }else{
    document.styleSheets[0].insertRule('.logout {display:'+type+' !important;}',0);
  }
}

function loadLoginCookie(){
    
    var user_id = $.readCookie('_qqq_user_id');
    var user = $.readCookie('_qqq_user');
    if(user_id && user){        
        try{
          user = '{"unread_messages_count": 0, "user": {"login": "'+_Base64.decode(user)+'"}}';          
          user = eval('('+user+')');
          if(user_id)   user.user.id = parseInt(user_id)            
          loadLogin(user);
          return user;
        }catch(e){

        }
    }
    if($.readCookie('_qqq_auth_token') || $.readCookie('_qqq_session'))
        return $.getJSON('/session.js?'+(new Date().getTime()), loadLogin);
    else
        return '{}'
}
function loadLogin(data){
  if(data && data.user){
    currentUser=data.user;
    $('.username').text(currentUser.login);
    //$('.login').toggleClass( "hidden" );
    showLogout('none');
    if(data.unread_messages_count > 0){
	$('#unread_messages_count').text(data.unread_messages_count);
	document.title = '鎮ㄦ敹鍒�'+data.unread_messages_count+'涓皬绾告潯 | '+document.title;
	$('#unread_messages_count').css('display','');
    }
    else{
	$('#unread_messages_count').hide();
    }
    if(data.unread_notifications_count && data.unread_notifications_count > 0){
      $('#unread_notifications_count').text(data.unread_notifications_count);
    }
    showLogin();
    VoteHistory.updateArticleStates();
    queryNewMessage();
  }else{
    currentUser=null;
    showLogout();
  }
}
$(loadLoginCookie);
function showLoginForm(){
  $('#login-form').lightbox_me({
  centered: true,
  onLoad: function() {
      $('#login').focus()
      }
  });
}
function showSuggestForm(){
  $('#suggest-form').lightbox_me({
  centered: true,
  onLoad: function() {
      $('#suggest-text').focus()
      }
  });
}
function startQueryNewMessage()
{
	$(document).ready(function() {
		setInterval('queryNewMessage()',5*60*1000);
	});
}
var msg_regexp = new RegExp('鎮ㄦ敹鍒癨\d+涓皬绾告潯');
function queryNewMessage(){
	if(currentUser){	
        	$.ajax({
                    type: "GET",
                    url: "/new4/messages?query_new_msg=" + Math.floor(Math.random()*316661),
                    dataType: "text",
                    success: function(msg) {
			newmsg = parseInt(msg);
                    	if(newmsg && newmsg>0){
				$('#unread_messages_count').text(newmsg);
				reg_result = msg_regexp.exec(document.title)
				if(reg_result){
					document.title = document.title.replace(reg_result,'鎮ㄦ敹鍒�'+newmsg+'涓皬绾告潯')
				}
				else{
					document.title = '鎮ㄦ敹鍒�'+newmsg+'涓皬绾告潯 | '+document.title;
				}
				$('#unread_messages_count').css('display','');
			}
                    }
        	});
	}
}
$(startQueryNewMessage);
$(function(){
  $('.need-login').click(function(e){
    e.preventDefault();
    showLoginForm();
  });
  $('#login-form button[type=submit]').click(function(e){
    e.preventDefault();
    var form = $(this);
    var name = $(this.form).find('input#login').val();
    var pass = $(this.form).find('input#password').val();
    if(name.length ==0 || pass.length ==0) return false;
    this.disabled=true;
    this.value='姝ｅ湪鐧诲綍...';
    $(this.form).submit();
    return false
  });

  $('#suggest-form button[type=submit]').click(function(e){
    e.preventDefault();
    this.disabled=true;
    this.value='姝ｅ湪鎻愪氦...';
    $(this.form).submit();
    return false
  });

  $('#suggest-form form').submit(function(e){
    e.preventDefault();
    var form = $(this);
    $.post('/new4/suggest', form.serialize(), function(data){

	$('#suggest-form').trigger('close');
      $('button[type=submit]', form).attr('disabled', '').val('鎻愪氦寤鸿');
      $('#suggest-text')[0].value = '';
  	$('#suggest-form button[type=submit]').attr("disabled", false ) ;

    }, 'json')
    return false;
  })
  $('#login-form form').submit(function(e){
    e.preventDefault();
    var form = $(this);
    $.post('/session.js', form.serialize(), function(data){
      $('button[type=submit]', form).attr('disabled', '').val('鐧诲綍');

    	$('#login-form button[type=submit]').attr("disabled",false);
      if('error' in data){
        form.children('#error').text(data['error']);
	form.find('.inputbox input').addClass('error');
	$('#login-form').effect("shake",{times:3,distance:10},100);
      }else{
        if($.browser.msie){
          document.styleSheets[0].removeRule('.logout');
        }else{
          if(document.styleSheets[0].cssRules[0].selectorText == '.logout'){
            document.styleSheets[0].deleteRule(0);
          }
        }
        loadLogin(data);
        $('#login-form').trigger('close');
        $(document).trigger('after_logged_in');
      }
    }, 'json')
    return false;
  })
});
