// ==UserScript==
// @name        Netflix Randomize Queue
// @namespace   http://arantius.com/misc/greasemonkey/
// @description	Shuffle all the movies in your netflix queue into a random order.
// @include     http://www.netflix.com/Queue*
// @require     http://arantius.com/misc/greasemonkey/imports/dollarx.js
// @version     1.4
// ==/UserScript==

//
// Originally written by Anthony Lieuallen of http://arantius.com/
// Licensed for unlimited modification and redistribution as long as
// this notice is kept intact.
//
// If possible, please contact me regarding new features, bugfixes
// or changes that I could integrate into the existing code instead of
// creating a different script.  Thank you
//

//
// Version History
//
// 1.4 - May 17, 2009
//       Fix compatibility.  Notify user of incompatibility with drag-and-drop
//       queue mode.
// 1.3 - March 15, 2008
//       Simplify, no delete-checkbox overloading.  Improve shuffle algorithm.
// 1.2 - Match Netflix's new visual style.
//
// 1.1 - When no movies are selected, user is presented with the option
//       to randomize them all.
//

function randomize(event) {
	event.preventDefault();

	var boxes=$x("//form[@name='MainQueueForm']//input[@class='o' and @value]");
	
	// Pick all the values out of the boxes.
	var values=[];
	for (var i=0, box=null; box=boxes[i]; i++) {
		values[values.length]=box.value;
	}

	// Fill the boxes with random values.
	for (var i=0, box=null; box=boxes[i]; i++) {
		var j=Math.floor(values.length*Math.random());
		boxes[i].value=values[j];
		values.splice(j, 1);
	}

	//submit form by "clicking" the right button
	updateButtons[0].click();
}

//find disabled buttons
var disabledButtons=$x('//input[@disabled="disabled"]');
if (0!=disabledButtons.length) {
	alert('Randomize Netflix Queue does not work with drag-and-drop mode on!');
	return;
}

//find 'update' buttons and add 'randomize' buttons
var updateButtons=$x("//input[@type='submit' and starts-with(@name, 'updateQ')]");
for (var i=0, el=null; el=updateButtons[i]; i++) {
	var row=el.parentNode.parentNode;
	var cont1=el;
	while (cont1 && cont1.tagName && 'DIV'!=cont1.tagName) {
		cont1=cont1.parentNode;
	}
	if (!cont1) return;

	// Clone the update button.
	var cont2=cont1.cloneNode(true);
	// Fix it up.
	cont2.childNodes[0].removeAttribute('id');
	cont2.style.right='12em';
	// Fix up the input inside it.
	var inp=cont2.getElementsByTagName('input')[0];
	inp.type='button';
	inp.value='Randomize Your Queue';
	inp.addEventListener('click', randomize, true);
	// Put it in the document.
	cont1.parentNode.insertBefore(cont2, cont1);
}
