// this is such a hack...

// SNAKES ON A MOTHERFUCKIN' PLAAAAANE!

var current_line = [];
var current_line_no = 0;

// setupsy...
function init() {
	
	// the head of SLJ...
	var a = $('MoreLink');
	a.onmouseover = function() {
		$('SLJ').src = $('evilSLJ').src;
	};
	a.onmouseout = function() {
		$('SLJ').src = $('origSLJ').src;
	};
	a.onmousedown = function() {
		$('SLJ').src = $('snakeSLJ').src;
	};
	a.onmouseup = function() {
		$('SLJ').src = $('origSLJ').src;
	};
	a.onclick = show_next_line;
	
	show_line(0);
	
	// sorry, no msie support yet.  thanks bill.
	try {
		if (navigator.userAgent.match(/MSIE/)) {
			fucking_msie(true);
		}
	}
	catch(e) {
		// nah.
	}
}

// submit an entry if valid
function submit_entry() {

	// bail if called badly.
	if (!$('Entry')) {
		return false;
	}
	
	// get form values
	var line = trim($('LineInput').value);
	var author = trim($('AuthorInput').value);
	var url = trim($('URLInput').value);
	
	// treat true empties as mistakes.
	if (!line) {
		return false;
	}
	
	// treat effective empties as.... what?  guess i actually want to allow
	// smileys....
	if (!line.match(/[a-zA-Z]/) && line.length < 3) {
		$('LineInput').value = '';
		$('LineLink').firstChild.nodeValue = '...';
		return false;
	}
	
	// replace the current line with this line (keep up appearances in the session).
	var entry = [
		0,
		line,
		0,
		0,
		author,
		url
	];
	lines[current_line_no] = entry;
	current_line = entry;
	// reset the links (obviously need to refactor this)
	$('LineLink').onclick = show_line_info;
	$('LineLink').title = 'About this line...';
	
	// server will clean up semi-valid entries, handle anonymity, etc.
	// we just want to escape things.
	var data = {
		line: line,
		author: author,
		url: url
	};
	
	// dispatch the request (we don't care about the answer)
	post('/submit.cgi',data);
	
	// remember the user.
	createCookie('a',author,365);
	createCookie('u',url,365);
	
	// pseudo-zap the form (we don't want to destroy it before its submit is done).
	$('Entry').style.display = 'none';
	
	// don't actually submit the form.
	return false;
	
}

// preview an entry in "Real Time" (TM)
function preview_entry() {
	
	if ($('LineInput')) {
		$('LineLink').firstChild.nodeValue = $('LineInput').value;
	}
	
}

// show the entry form thingy
function show_entry() {
	
	kill_line_info();
	kill_entry(); // just in case.
	
	// set the linelink to preview-ish nothingness.
	$('LineLink').onclick = function() {return void(0);};
	$('LineLink').title = 'This would be your line...';
	$('LineLink').firstChild.nodeValue = '...';
	
	// create the div
	var div = create('div',null,{id: 'Entry'},
		create('p',null,{className: 'close'},
			create('a','[ close ]',{
				href: 'javascript:void(0);',
				onclick: function() {
					kill_entry();
					show_line(current_line_no);
				}
			})
		)
	);
	
	// do we have an author and a url to use?
	//  (...and maybe some funny anonymous monikers...)
	
	var author = readCookie('a');
	var url = readCookie('u');
	if (!author) {
		author = 'Anonymous';
	}
	if (!url) {
		url = 'http://www.linesonaplane.com/';
	}
	// add the form stuff.
	var line_inp = create('input',null,
		{
			id: 'LineInput',
			type: 'text',
			name: 'line',
			value: '',
			onkeyup: preview_entry,
			onchange: preview_entry
		}
	);
	// ...might have a problem with maxlength... but at 256, fuck it.
	var author_inp = create('input',null,
		{
			id: 'AuthorInput',
			type: 'text',
			name: 'author',
			value: author,
			onfocus: function() {
				if (this.value && this.value == 'Anonymous') {
					this.value = '';
				}
				this.select();
			}
		}
	);
	var url_inp = create('input',null,
		{
			id: 'URLInput',
			type: 'text',
			name: 'url',
			value: url,
			onfocus: function() {
				if (this.value && this.value == 'http://www.linesonaplane.com/') {
					this.value = '';
				}
				this.select();
			},
			onchange: function() {
				// very lazy cleanup
				this.value = this.value.replace(/\s/g,'');
				if (this.value && !this.value.match(/^http\:\/\//)) {
					this.value = 'http://' + this.value;
				}
				if (this.value.match(/^http\:\/\/[\w\.\-]+\.\w+$/)) {
					this.value += '/';
				}
			}
		}
	);
	
	var f = create('form',null,
		{
			onsubmit: function() {return submit_entry();}
		}
	);
	
	f.appendChild(create('p','What should Samuel L. Jackson say in the sequel to Snakes on a Plane?'));
	f.appendChild(create('p',null,null,line_inp));
	
	var p = create('p','Name:',null,author_inp);
	p.appendChild(create(null,'URL:'));
	p.appendChild(url_inp);
	f.appendChild(p);
	div.appendChild(f);
	f.appendChild(create('p',null,null,create('input',null,{type: 'submit', value: 'Ssssssssubmit!', className: 'submit'})));
	
	// vamos!
	document.body.appendChild(div);
	
}

// zap the entry thingy
function kill_entry() {

	if ($('Entry')) {
		$('Entry').parentNode.removeChild($('Entry'));
		
		// also reset the linelink.
		$('LineLink').onclick = show_line_info;
		$('LineLink').title = 'About this line...';
		
	}
	
}
// vote for something...
function vote(id,approve) {

	if (!id) {
		return;
	}
	
	
	// ok, it's pretty easy to cheat here.  i *might* make it a little harder.
	var data = {id: id, approve: approve ? '1' : '0'};
	
	// ajaxy...
	post('/vote.cgi',data);
	
	// and the keksz
	var votes = [];
	var c = readCookie('v');
	if (c) {
		votes = c.split(/\,/);
	}
	votes.push(id + '=' + (approve ? 'yes' : 'no'));
	createCookie('v',votes.join(','),365);

	kill_line_info(); // note to self: do fades on these.
	
	console.log('voted ' + approve + ' for ' + id);
	console.log(readCookie('v'));
	
}


// check whether someone has voted on a given line; returns vote.
// this just uses cookies, so it's obviously insecure, but i wanna keep load down.
function voted(id) {
	
	var c = readCookie('v');
	if (c) {
		var votes = c.split(/\,/);
		for (var i=0; i<votes.length; i++) {
			if (parseInt(votes[i]) == id) {
				var parts = votes[i].split(/\=/);
				return parts[1];
			}
		}
	}
	return null;
}

// show info (including rating) for the current line
function show_line_info() {
	
	kill_line_info();
	
	if (!current_line) {
		return; // could have clicked early, etc.
	}
	if ($('LineInfo')) {
		return; // lazy on excess clickies
	}
	
	// extract the parts (in array to save space)
	var id = current_line[0];
	var line = current_line[1];
	var yes = current_line[2];
	var no = current_line[3];
	var author = current_line[4];
	var url = current_line[5];
	if (!author || !author.match(/\S/)) {
		author = 'Anonymous';
	}
	
	// create the div
	var div = create('div',null,{id: 'LineInfo'},
		create('p',null,{className: 'close'},
			create('a','[ close ]',{
				href: 'javascript:void(0);',
				onclick: kill_line_info
			})
		)
	);
	
	// and put in the basic info.
	var p = create('p');
	if (url && url != 'http://www.linesonaplane.com/') {
		p.appendChild(create('a',author,{
			className: 'author',
			href: url,
			title: 'Visit ' + author + ' at ' + url
		}));
	}
	else {
		p.appendChild(create('span',author,{className: 'author'}));
	}
	p.appendChild(create(null,' thinks Samuel L. Jackson should say '));
	p.appendChild(create('span','\u201C' + line + '\u201D',{className: 'line'}));
	div.appendChild(p);
	
	// also the counts so far.
	var praise = ['awesome','a good idea','super cool','dandy','peachy','just the thing'];
	var insults = ['lame','not gonna fly','dumb','stupid','toast'];
	var t = yes > 1 ? yes + ' people think' : yes ? 'One person thinks' : 'Nobody thinks';
	t += ' that\'s ' + praise[parseInt(Math.random()*praise.length)] + ', and ';
	t += no > 1 ? no + ' people say ' : no ? 'one says ' : 'nobody says ';
	t += 'it\'s ' + insults[parseInt(Math.random()*insults.length)] + '.  ';
	if (id) {
		t += 'But it\'s only entry number ' + id + ', so that could change.';
	}
	div.appendChild(create('p',t,{className: 'score'}));
	
	// now the voting bit, if applicable.
	var v = voted(id);
	if (v) {
		
		// voted (per the cookie), so cutesy note.
		var t = 'It looks like you thought it was ';
		if (v == 'yes') {
			t += praise[parseInt(Math.random()*praise.length)] + '.';
		}
		else if (v == 'no') {
			t += insults[parseInt(Math.random()*insults.length)] + '.';
		}
		else {
			// damn.
			t = 'But the voting thing might be broken anyway.';
		}
		div.appendChild(create('p',t));
	}
	else if (id) {
		
		// didn't vote (per the cookie), so they may.
		
		var p = create('p','What do you think?',{id: 'Vote'});
		var ul = create('ul');
		var yes_a = create('a','Yessss!',{
			id: 'VoteYes',
			href: 'javascript:void(0);',
			title: 'Gotta love it!',
			onclick: function() {vote(id,true);}
		});
		var no_a = create('a','Noooo!',{
			id: 'VoteNo',
			href: "javascript:void(0);",
			title: 'Thumbs down on this.',
			onclick: function() {vote(id,false);}
		});
		ul.appendChild(create('li',null,null,no_a));
		ul.appendChild(create('li',null,null,yes_a));
		p.appendChild(ul);
		div.appendChild(p);
	}
	// go speed racer!
	document.body.appendChild(div);
	
}

// zap that info thing...
function kill_line_info() {
	if ($('LineInfo')) {
		$('LineInfo').parentNode.removeChild($('LineInfo'));
	}
}

// show the next line, wrapping.
function show_next_line() {
		
	if (current_line_no >= lines.length - 1) {
		current_line_no = 0;
		show_line(0);
	}
	else {
		current_line_no ++;
		show_line(current_line_no);
	}
	
}

// show a line from the list.
function show_line(i) {
	
	kill_entry(); // just in case.
	kill_line_info(); // otherwise, messy.
	
	current_line = lines[i];
	if (!current_line) {
		throw 'lines exceeded: ' + i;
	}
	
	var a = $('LineLink');
	a.firstChild.nodeValue = current_line[1]; // 1 is the line itself.
	
}

// do a simple ajax-esque post
function post(url,data) {
	
	var p = [];
	for (var a in data) {
		p.push(esc(a) + '=' + esc(data[a]));
	}
	var data_string = p.join('&');
	
	var req = getXMLHttpRequest();
	req.open('POST',url,true);
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	req.send(data_string); // i don't care your base, i don't care your gun.
	
}

// going for *simple* here...
function create(e,txt,attr,kid) {

	if (!e) {
		return document.createTextNode(txt);
	}
	
	var elem = document.createElement(e);
	if (txt) {
		elem.appendChild(document.createTextNode(txt));
	}
	if (attr) {
		for (var a in attr) {
			elem[a] = attr[a];
		}
	}
	if (kid) {
		// only one for now.
		elem.appendChild(kid);
	}
	
	return elem;
}

function $(e) {
	
	if (typeof(e) == 'string') {
		return document.getElementById(e);
	}
	else {
		return e;
	}
	
}

function trim(s) {
	
	s = s.replace(/^\s+/,'');
	s = s.replace(/\s+$/,'');
	return s;

}

function esc(s) {
	
	s = escape(s);
	return s.replace(/\+/g,'%2B');
	
}

// from quirksmode, thanks man:
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// adapted from mochikit:
function getXMLHttpRequest() {
    var self = arguments.callee;
    if (!self.XMLHttpRequest) {
        var tryThese = [
            function () { return new XMLHttpRequest(); },
            function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
            function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
            function () { return new ActiveXObject('Msxml2.XMLHTTP.4.0'); },
            function () {
                throw new MochiKit.Async.BrowserComplianceError("Browser does not support XMLHttpRequest");
            }
        ];
        for (var i = 0; i < tryThese.length; i++) {
            var func = tryThese[i];
            try {
                self.XMLHttpRequest = func;
                return func();
            } catch (e) {
                // pass
            }
        }
    }
    return self.XMLHttpRequest();
}

// good lord, what a piece of fucking shit MSIE is.  so for now, no support.
function fucking_msie(what) {

	// for spoofers, or for testing, a way out:
	if (what == false) {
		$('Line').style.display = 'block';
		$('Actor').style.display = 'block';
		$('Menu').style.display = 'block';
		$('Sorry').style.display = 'none';
		return;
	}
	
	// hide everything.
	$('Line').style.display = 'none';
	$('Actor').style.display = 'none';
	$('Menu').style.display = 'none';
	
	// ...and put in a sorry notice.
	var d = create('div',null,{id:'Sorry'});
	d.appendChild(create('h2','Sorry, Lines on a Plane only works with modern browsers.'));
	d.appendChild(create('p','...and it looks like you are using a broken old browser.'));
	d.appendChild(create('p','...like, eh, maybe Microsoft Internet Explorer.'));
	d.appendChild(create('p','Four out of five dentists surveyed recommend upgrading to Firefox, which is quick and easy.'));
	d.appendChild(create('a','http://www.mozilla.com/firefox/',{href: 'http://www.mozilla.com/firefox/'}));
	d.appendChild(create('p','The other dentist is a luddite.'));
	
	d.appendChild(create('p','If your mom, babysitter or IT department won\'t let you upgrade, all five dentists recommend throwing a prolonged tantrum.'));
	d.appendChild(create('p','Dentists know a thing or two about tantrums.'));
	
	d.appendChild(create('p','If you\'re spoofing the user agent or something, and you\'re sure this should work, you can try the following link.'));
	
	d.appendChild(create('a','I really really want to try it even though it probably won\'t work.',{href: 'javascript:fucking_msie(false);'}));
	
	document.body.appendChild(d);

}

