if (typeof($) == 'undefined') {
  var $ = function (o) {
	  return document.getElementById(o);
  };
}
var VoteMachine = function () {
	var b = document.getElementsByTagName('input');
	for (var i =0; i<b.length;i++) {
		var o = b[i];
		if (o.getAttribute('type') == 'hidden'
        && o.getAttribute('name') == 'node_id') {
			VoteMachine.node_id = o.getAttribute('value');
		}
		if (o.getAttribute('type') == 'submit' && o.getAttribute('name') == 'sexisgreat') {
			o.setAttribute('value', 'blab!');
		}
		if (o.getAttribute('type') != 'radio') continue;
		var n = o.getAttribute('name');
		if (n.substr(0,6) != 'vote__') continue;
		if (o.getAttribute('value') != 1) continue;
		n = n.substr(6);

    //Are we revoting?
    var revote = /\brevote\b/.test(o.className);
    var prevvote = 0;
    if(revote){
      if(o.disabled){ // we only do this stuff if the value is 1
        prevvote = 1;
      }
      else{
        prevvote = -1;
      }
    }

		var f = o.parentNode.parentNode;
		f.setAttribute('id', 'header' + n);
		f.innerHTML = '';
		var s = document.createElement('span');
		f.appendChild(s);

    var up, down, flip;
    if(!revote){
		  up = document.createElement('input');
		  up.setAttribute('type', 'button');
		  up.setAttribute('value', 'Up');
		  up.setAttribute('title', 'Vote up');
		  up.setAttribute('name', n);
		  up.onclick = VoteMachine.vote;
		  up.votefield = s;

		  down = document.createElement('input');
		  down.setAttribute('type', 'button');
		  down.setAttribute('value', 'Down');
		  down.setAttribute('title', 'Vote down');
		  down.setAttribute('name', n);
		  down.onclick = VoteMachine.vote;
		  down.votefield = s;
    }
    else{
		  flip = document.createElement('input');
		  flip.setAttribute('type', 'button');
      if(prevvote == 1){
		    flip.setAttribute('value', 'Flip down');
      }
      else{
        flip.setAttribute('value', 'Flip up');
      }
		  flip.setAttribute('name', n);
		  flip.onclick = VoteMachine.vote;
		  flip.votefield = s;
    }

		var bw = document.createElement('span');
		f.appendChild(bw);
    if(!revote){
		  bw.innerHTML = ' ';
		  bw.appendChild(up);
		  bw.appendChild(down);
    }
    else{
      bw.appendChild(flip);
    }
	}

};

VoteMachine.vote = function () {
	this.req = new XMLHTTP;
	var x = this;
  var revote = (x.value.substr(0,4) == "Flip");
	x.parentNode.style.display = 'none';
  x.votefield.oldInnerHTML = x.votefield.innerHTML;
  if(revote){
    x.votefield.innerHTML = ' Flipping vote...';
  }
  else{
	  x.votefield.innerHTML = 'Voting...';
  }
	this.req.callback = function (o) {
		var r = o.responseXML.getElementsByTagName('reputation')[0];

    // Vote may have failed (e.g. out of votes) - fail gracefully
    if (!r) {
      // Restore old elements (including old fail warning, potentially)
      x.votefield.innerHTML = x.votefield.oldInnerHTML;
      // Add failure notice if one is not already present
      var failNotes = $$('#voteinfo_' + x.name + ' .votefail');
      if (failNotes.length == 0) {
        var failText = '<span class="votefail warning">Voting attempt failed.</span>';
        x.votefield.innerHTML = failText + x.votefield.innerHTML;
      }
      x.parentNode.style.display = 'block';
    }

    var voteinfo = document.getElementById("voteinfo_"+x.name);

    var uv = 1*(r.getAttribute('up'));
    var dv = 1*(r.getAttribute('down'));
    var totalv = uv + dv;
    var rating;
    if(totalv != 0){
      rating = Math.round(100*uv/(totalv));
    }
    else{
      rating = 0;
    }


		voteinfo.innerHTML = '<span class="votescast" title="' + rating + '% upvotes, of ' + totalv + 
			' votes."><abbr title="reputation">'
      		+ 'Rep</abbr>: ' + r.firstChild.nodeValue + ' ( +'
    		+ r.getAttribute('up') + ' / -' + r.getAttribute('down') +' ) '
			+ '(<a href="/node/superdoc/Reputation+Graph?id=' + x.name
			+ '" title="graph of reputation over time">Rep Graph</a>) ('
			+ (r.getAttribute('cast') == '1' ? '+' : '-') + ')'
			+ '</span>' ;



		var votes = document.getElementById('votesleft');
		votes.innerHTML = new Number(votes.innerHTML) - 1;
	};

  var thevote;
  if(this.value == 'Up' || this.value == 'Flip up'){
    thevote = '1';
  }
  else{
    thevote = '-1';
  }

	var v = '/index.pl?' + document.cookie + "&node_id=" + this.name
       	  + "&op=vote&displaytype=xmltrue&vote__" + this.name + "="
          + thevote;

  this.req.send(v);

};

var KillingMachine = function() {
	var b = $('killbutton');
	if (!b) {
		return;
	}
	var b2 = $('QuickKill');
	if (b2) {
		return;
	}
	this.button = document.createElement('input');
	this.button.setAttribute('type', 'button');
	this.button.setAttribute('value','QuickKill selected');
	this.button.setAttribute('id','QuickKill');
	b.parentNode.insertBefore(this.button, b);
	this.button.onclick = function () {
		if ( typeof(arguments[0])=='number' ) {
			var killnodeid = arguments[0] ;
			var o = $('adminheader'+killnodeid).getElementsBySelector('*[name]');
			var button = $('x'+killnodeid);
		}
		else {
			killnodeid = false ;
			o = this.form.getElementsBySelector('*[name]');
			button = this;
		}
		var x = new Object();
		for (var i=0;i<o.length;i++) {
			var n = o[i].getAttribute('name');
			if ((typeof(n) == 'undefined') || !n || !n.length) continue;
			if (n.substr(0,8) == 'killnode') {
				n = n.substr(8);
				if (typeof(x['node' + n]) == 'undefined') {
					var xx = x['node' + n] = new Object();
					xx.node_id = n;
				}
				xx.kill = o[i].checked || killnodeid ;
				continue;
			}
			if (n.substr(0,9) == 'instakill') {
				n = n.substr(9);
				if (typeof(x['node' + n]) == 'undefined') {
					var xx = x['node' + n] = new Object();
					xx.node_id = n;
				}
				xx.instakill = o[i].checked;
				continue;
			}
			if (n.substr(0,10) == 'killreason') {
				n = n.substr(10);
				if (typeof(x['node' + n]) == 'undefined') {
					var xx = x['node' + n] = new Object();
					xx.node_id = n;
				}
				xx.reason = o[i].value;
				continue;
			}
		}
		var str = '?op=massacre&displaytype=xmltrue&node_id=' + VoteMachine.node_id + '&';
		var killnum=0;
		for (var q in x) {
			var j = x[q];
			if (j.kill) {
				var r = prompt("Kill reason for id " + j.node_id + ":", j.reason);
				if ( r && r.length) {
					killnum++;
					var s = "publickiller" + j.node_id + "=1&hidewu" + j.node_id + "=1&killnode" + j.node_id + "=1&killreason" + j.node_id + "=" + escape(r) + "&";
					str += s;
					if (j.instakill) {
						str += "instakill" + j.node_id + "=1&";
					}
				}
			}
		}
		if (killnum <1) {
			alert("No nodes selected to axe");
			return;
		}
		var req = new XMLHTTP;
		button.disabled = 1;
		button.setAttribute('value', 'Killing...');
		req.callback = function (o) {
			var w = o.responseXML.getElementsByTagName('writeup');
			for (var i=0;i<w.length;i++) {
				if (w[i].getAttribute('marked') == '1') {
					var h = $('adminheader' + w[i].getAttribute('node_id'));
					if (h) {
						h.innerHTML = 'Marked for destruction';
					}
				}
			}
			button.disabled = false;
			button.setAttribute('value', 'QuickKill');
		};
		req.send(str);
		return false;
	};
 	$$('.admin input[value=QuickKill]').each(function(x){
		x.value='QuickKill this' ;
		x.id = x.name ;
		x.setAttribute('onclick',"$('QuickKill').onclick(" + x.name.substr(1) + ")" ); } );
};


var XMLHTTP = function() {
  this.xmlhttp=false;
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
   // JScript gives us Conditional compilation, we can cope with old IE version
   // and security blocked creation of the objects.
   try {
   this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
   try {
   this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
   this.xmlhttp = false;
   }
   }
   @end @*/
  if (!this.xmlhttp) {
    if(typeof XMLHttpRequest!='undefined')
      this.xmlhttp = new XMLHttpRequest();
    else
		  alert("Your browser is too old or something. QuickVote won't work for you");
  }
	this.callback = function (x){};
};

XMLHTTP.prototype.send = function (uri) {
  this.xmlhttp.open("GET", uri, true);
  var x = this; //safari gets confused by 'this'
  this.xmlhttp.onreadystatechange = function() {
	  if (x.xmlhttp.readyState==4) {
	    if (x.xmlhttp.status == '200')
	    {
			  x.callback(x.xmlhttp);
	    }
	    else if (typeof(x.xmlhttp.status) != 'undefined'){
			  alert(x.xmlhttp.status + ' : ' + x.xmlhttp.statusText);
		  } else {
			  alert('That vote might not have had time to register (though it probably did).');
		  }
	  }
	};
  this.xmlhttp.send(null);
};


// Wrap in anonymous block to avoid making unnecessary globals

{
  var voteOnLoadActions = function() {
	if ( window.E2AJAX ) return ;
      VoteMachine();
      if ($('zensheet')) {
        var k = new KillingMachine();
      }
  };

  Event.observe(window, 'load', voteOnLoadActions);
}
