// Singleton class to hold Globals
var VOTESG = new function() {
    this.killtimer = 0;
    this.vObj = new Object();
    // this values is used to stop ajax calls when rollover mouseover on the votes popup 
    this.mouseOverFire = { cid : 0 };
}

function VotesThumb() {
    this.df_url = $('#df_url').attr('src');

    if(document.getElementById('votepopup_up')){
        this.hoverEffect('votepopup_up','bright');
        this.hoverEffect('votepopup_down','bright');
    }

    if(document.getElementById('rated_chart_small')){
        this.entryEffect('rated_chart_small','hltcell')
    }

    // these are id mapping to template: footer
    this.votesID = ['v_txt_original','v_txt_funny','v_txt_poetic','v_txt_colorful','v_txt_wrong','v_txt_offensive','v_txt_lame','v_txt_confused'];
    this.cid = '';  // cid : commend id 
    this.vote_value = '';  //vote value: e.g. funny, wrong
}

// INHERITANCE 
VotesThumb.prototype = new General();

// Summary: Ajax 
// params: a - event object that made event
//         action - text string e.g. none
//         c - parent of event object
VotesThumb.prototype.entryAjax = function(a,action,c){
  //alert('This link will display Ajax generated results for ' + a.getElementsByTagName('DD')[1].innerHTML + ' uses of the word.')
    var dm = this.getDomain();

    // get dd parent
    var parentId = a.parentNode;
    var c = $(parentId).attr('cid');
    // ajax is the file name
    var php_file = '/ajax/';
    // VOTE : typoe of vote: funny
    var choice = "VOTE/" + a.firstChild.nodeValue + "/";
    // CID: commend id
    var cid = "CID/" + c + "/";
    var url = dm + php_file + choice + cid;
    var tmpThis = this;

    //this.ajaxCall(url, ['setTotalThumbs', 'setRatedChart']);

    if (action){
        if (action == 'none'){
             this.kill(c)
        }
    }
}

//Summary: Set the rate chart during page load
VotesThumb.prototype.rateChartOnload = function() {
    var ref = window.location.href;
    var pattern = /(http:\/\/[^\/]+)/;
    var result = ref.match(pattern);
    var dm = result[1];
    var wid = $('#rated_chart_small').attr('chart_id'); 
    var username = $('#rated_chart_small').attr('user'); 

    var key = '';
    var value = '';
    if (username) {
        key = "USER/";
        value = username + "/"; 
    } else if (wid) {
        key = "WID/";
        value = wid + "/";
    }

    var url = dm + '/ajax/' + key + value; 
    this.ajaxCall(url, ['setRatedChart']); 
}


// Summary: Set the new proper number for total votes
// param: msg - { cid : 12, thumbs_up : 33, thumbs_down : 40 }
VotesThumb.prototype.setTotalThumbs = function(msg) {
  var cid = msg['cid'];
  var tbm_up = msg['thumbs_up'];
  var tbm_down = msg['thumbs_down'];

  // main total votes
  var main_tbm_up = 'main_ttl_cmtv_tbm_up_' + cid;
  var main_tbm_down = 'main_ttl_cmtv_tbm_down_' + cid;

  var mainUpObj = document.getElementById(main_tbm_up);
  var mainDownObj = document.getElementById(main_tbm_down);

  if (mainUpObj) {
      // set the overall total thumb up value
      mainUpObj.firstChild.nodeValue = tbm_up;
  }

  if (mainDownObj) {
       // set the overall total thumb down value
      mainDownObj.firstChild.nodeValue = tbm_down;
  }

  // acitivity total votes
  var activity_tbm_up = 'activity_cmtv_up_' + cid;
  var activity_tbm_down = 'activity_cmtv_down_' + cid;
  var actUpObj = document.getElementById(activity_tbm_up);
  var actDownObj = document.getElementById(activity_tbm_down);

  if (actUpObj) {
      actUpObj.firstChild.nodeValue = tbm_up;
  }

  if (actDownObj) {
      actDownObj.firstChild.nodeValue = tbm_down;
  }

  var act_ttl_cmtv_tbm_up = '#act_ttl_cmtv_tbm_up_' + cid;
  var fact_ttl_cmtv_tbm_up = '#fact_ttl_cmtv_tbm_up_' + cid;
  var act_ttl_cmtv_tbm_down = '#act_ttl_cmtv_tbm_down_' + cid;
  var fact_ttl_cmtv_tbm_down = '#fact_ttl_cmtv_tbm_down_' + cid;

  $(act_ttl_cmtv_tbm_up).text(tbm_up);
  $(fact_ttl_cmtv_tbm_up).text(tbm_up);
  $(act_ttl_cmtv_tbm_down).text(tbm_down);
  $(fact_ttl_cmtv_tbm_down).text(tbm_down);

}

// Summary: Rating menu display
// params: a - object
//         myclass - css class name
//         b - this event object
VotesThumb.prototype.entryEffect = function(a,myclass,b){
  if(a == 'rollover'){
    b.className = myclass;
  }else if(a == 'rollout'){
    b.className = '';
  }else{
    var dllist = document.getElementById(a).getElementsByTagName('DL');
    var dllength = dllist.length;
    var tmp_this = this;
    for (i=0;i<dllength;i++){
      dllist[i].onmouseover = function() {tmp_this.entryEffect('rollover','hltcell',this)}
      dllist[i].onmouseout = function() {tmp_this.entryEffect('rollout','hltcell',this)}
      if (a != 'rated_chart_small') {
          dllist[i].onclick = function() {tmp_this.entryAjax(this)}
      }
    }
  }
}

//Vote popup menu actions and effects
VotesThumb.prototype.hoverEffect = function(a,myclass,b){
  if(a == 'rollover'){
    b.className = myclass;
  }else if(a == 'rollout'){
    b.className = '';
  }else{
    var dllist = document.getElementById(a).getElementsByTagName('DD');
    var dllength = dllist.length
    var tmp_this = this;
    for (i=0;i<dllength;i++){
        dllist[i].onmouseover = function() {tmp_this.hoverEffect('rollover','bright',this);}
        dllist[i].onmouseout = function() {tmp_this.hoverEffect('rollout','bright',this);}
        if (a != 'rated_chart_small') {
            dllist[i].onclick = function() {tmp_this.entryAjax(this,'none',this.parentNode);}
        }
    }
  }

}
//Find Position of any element
VotesThumb.prototype.findPos = function(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft;
    curtop = obj.offsetTop;
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft;
      curtop  += obj.offsetTop;
    }
  }
  return [curleft,curtop];
}

VotesThumb.prototype.votepopup = function(box,id,a){
  var myelement = document.getElementById(box);
  var pos = this.findPos(a);
  var tmp_this = this;
  myelement.style.top = pos[1];
  myelement.style.left = pos[0];
  //$(myelement).show();
  myelement.style.display = 'block';
  this.myelement = myelement;
  //myelement.onmouseover = function(){tmp_this.cancelkilltimer(myelement);};
  myelement.onmouseover = associateObjWithEvent(this, 'setMouseoverEventWrapper');
  myelement.onmouseout = function(){tmp_this.kill(myelement);};
  myelement.onclick = function(){tmp_this.kill(myelement,1);};
}

// Summary: Set the popup events
// params: a - this object of the element
VotesThumb.prototype.setPopupVotesEvent_ = function(a) {
  var args = {};
  args['vote_type'] = $(a).attr('value');

  var tmp = this;
  var len = this.votesID.length;

  for (var x = 0; x < len; x++) {
      var ele = '#' + this.votesID[x];
      $(ele).bind("click", function() {
                      tmp.setupParams(args,this);
                      return false; }
                     );

  }
   
}

// Summary: Set the popup events
// params: a(optional) - this object of the element
VotesThumb.prototype.setPopupVotesEvent = function(a) {
  var tmp = this;
  var len = this.votesID.length;
  var guest = $(a).attr('guest');

  for (var x = 0; x < len; x++) {
      var ele = document.getElementById(this.votesID[x]);
      // asociate event with each event call
      if(ele) {

          if(guest) {
             ele.onclick = associateObjWithEvent(this,'hideVotesContainer');
          } else {
              // do not use the jquery bind, or click causing strange issue with events calls
             ele.onclick = associateObjWithEvent(this,'setupParams');
          }
      }
  }
}


// Summary: Hide the votes container when in guest mode
// params: e - Event Object
//         thisObj - object element on event
VotesThumb.prototype.hideVotesContainer = function(e, thisObj) {
   $('#votepopup_menu').hide();
}

// Summary: Wrapper for onmouse over
VotesThumb.prototype.setMouseoverEventWrapper = function(e, thisObj) {
    this.setupParams(e, thisObj);
    VOTESG.voteBoxOn = 1; 
    // cancelkilltimer is needed to ensure the box does not close when highlighting 
    // votes categories in the <div id="votepopup_menu"> 
    this.cancelkilltimer(this.myelement);
}

// Summary: Hide the thanks for voting popup up
VotesThumb.prototype.hideThanksPopup = function() {
    //$('#vote_thanks').hide('slow');
    $('#vote_thanks').fadeOut('slow');
}

// Summary: Display the thanks for voting popup
// params: thisObj - this event element object
VotesThumb.prototype.showThanksPopup = function(thisObj) {
    var pos = $('#votepopup_menu').offset();

    $("#vote_thanks").css( { "left": pos.left + "px", "top":pos.top + "px", "position": "absolute", "z-index":"1000" } );
    $('#vote_thanks').show();
}

// Summary: Stop propagation
// params: pE - event object
VotesThumb.prototype.stopEvent = function(pE) {
    if (!pE) {
        if (window.event)
            pE = window.event;
        else
            return;
    }
    if (pE.cancelBubble != null) {
        pE.cancelBubble = true;
    }
    if (pE.stopPropagation) {
        pE.stopPropagation();
    }
    if (pE.preventDefault) {
        pE.preventDefault();
    }
    if (window.event) {
        pE.returnValue = false;
    }
    if (pE.cancel != null) {
        pE.cancel = true;
    }
}


// Summary: Setup the params to make ajsxcall
// params:  e - event object
//          thisObj - object of the event element:
VotesThumb.prototype.setupParams = function(e,thisObj) {
  var dm = this.getDomain();
  var cid = this.cid;
  e = e || window.event;
  var value = $(thisObj).attr('value');
  var url = '';

  // make sure these two values exist before making ajaxCall when voting
  if (cid && value) {
      url = dm + "/ajax" + "/VOTE/" + value + "/CID/" + cid;
      // reset when a votes is made
      VOTESG.mouseOverFire['cid'] = 0;
      this.ajaxCall(url, ['setTotalThumbs', 'setRatedChart']);
      this.toggleThanksPopup(thisObj);
  } else if (cid && !value) {
      //get total of cid votes only
      url = dm + "/ajax" + "/CIDVOTE/" + cid;
      // only call ajax once onmouseover
      if(VOTESG.mouseOverFire['cid'] != cid ) {
          //this.ajaxCall(url, ['setTotalThumbs', 'setVotePopupChart']);
          this.ajaxCall(url, ['setVotePopupChart']);
      }
      // save already fired cid when on mouseover
      VOTESG.mouseOverFire['cid'] = cid;
  }
}


// Summary: toggle to show, hide the thank you popup
// params: thisObj - the event object element
VotesThumb.prototype.toggleThanksPopup = function(thisObj) {
    var sec = 2000; // 1000 mili/ 1 sec
    var tmp = this;
    this.showThanksPopup(thisObj);

    // after sec, then hide
    setTimeout(function() { tmp.hideThanksPopup();},
                           sec);
}

VotesThumb.prototype.kill = function(a,t){
   if (!t) t = 500;
   VOTESG.killtimer = setTimeout(function() { closeVotepopup(a); }, t);

}

VotesThumb.prototype.cancelkilltimer = function(a){
  if(VOTESG.killtimer){
    clearTimeout(VOTESG.killtimer);
		VOTESG.killtimer = null;
  }
}


// Summary: Set teh cid as an attribute for the div container
// e.g. <div cid='12' />
// params: box - id of the attribute
//         id - args
//         a - the event this object the element
VotesThumb.prototype.setVoteList = function(box,id,a) {
   var vote = document.getElementById(box);
   var idObj = a.id;
   var pattern = /_(\d+)$/;
   if (vote) {
      var results = idObj.match(pattern);
      if (results) {
          var cid = results[1];
          this.cid = cid;
          // set the cid (comment id) to the dl attribute so can be used to send the ajax request
          $(vote).attr({'cid':cid});
      }
   }
}


// Summary: Set the rated number count
// params: msg - json object 
VotesThumb.prototype.setRatedChart = function(msg) {
  // chart_id : holds word id
  var chart_id = $('#rated_chart_small').attr('chart_id');
  // jquery declaration to get the id element
  var url = '';

  var char_list = msg['rated_chart'];
  for (var x in char_list) {
      var ele = '#' + chart_id + '_num_' + x;
      var elew = '#' + chart_id + '_w_' + x;
      var cnt = char_list[x];
      
      if (!cnt) {
          $(ele).attr('class','gtxt num');
          $(elew).attr('class','gtxt');
          $(elew).children(':first-child').attr('href', 'javascript:void%200');
      } else {
          $(ele).attr('class','num');
          $(elew).attr('class','');
          var url = this.df_url + x;
          $(elew).children(':first-child').attr('href', url);
      }
      // set the total thumb entry count for the rate chart
      $(ele).text(char_list[x]);
  }
}


// Summary: Set the popup chart
// params: msg - json object
VotesThumb.prototype.setVotePopupChart = function(msg) {
    var str = 'v_txt_cnt_';
    var rated_chart = msg['total_rated_chart'];
    if (rated_chart) {
       for (var x in rated_chart) {
           var ch_id = '#' + str + x;
           var cnt = rated_chart[x]; 
           $(ch_id).text(cnt);
       }
    }  
}


// Summary: Set the rated number count
// params: msg - json object 
VotesThumb.prototype.setRatedChart2 = function(msg) {
  var rateObj = document.getElementById('rated_chart_small');
  if (rateObj) {
      var chart_id = rateObj.getAttribute('chart_id');
  }

  var char_list = msg['rated_chart'];
  for (var x in char_list) {
      var ele =  chart_id + '_num_' + x;
      var eleObj = document.getElementById(ele);
      if (eleObj) {
          eleObj.firstChild.nodeValue = char_list[x];
      }
  }

}

// Summary: Some reason timeout does not like object classes
function closeVotepopup(a){
    if(a) a.style.display = 'none';
}

function votepopup(box,id,a) {
    var instanceStr = VOTESG.vObj instanceof VotesThumb;

    // insure VOTESG.vObj is initialize to VotesThumb()
    if (!instanceStr) {
      VOTESG.vObj = new VotesThumb();
    }

    VOTESG.vObj.setVoteList(box,id,a);
    VOTESG.vObj.votepopup(box,id,a);
    VOTESG.vObj.setPopupVotesEvent(a);    
}

try {
    $(document).ready(function(){
                    var chart = document.getElementById('rated_chart_small'); 
                    
                    // only call the js if chart exist
                    if (chart) {
                    VOTESG.vObj = new VotesThumb();
                    VOTESG.vObj.rateChartOnload();
                    }
                    });

} catch (e) {
    alert ('ERROR WITH JQUERY READY STATE');

}



