var is_ie = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
var is_ie7 = 0;
var is_ie8 = 0;
var debug = 0;

if (is_ie && /msie.7/i.test(navigator.userAgent)) is_ie7 = true;
if (is_ie && /msie.8/i.test(navigator.userAgent)) is_ie8 = true;

/* Dynamically include another javascript file */
function require( file ) {
	var s = document.createElement("script");
	s.setAttribute("type", "text/javascript");
	s.setAttribute("src", file);
	document.getElementsByTagName("HEAD")[0].appendChild(s);
}

function screenlog() {
	if (!Elem('log')) {
		var log = newElem('log', { 'id' : 'log', 'style' : 'position: absolute; right: 0; top: 0; background-image: -webkit-gradient(linear, left top, left bottom,from(#333),to(#000)); background-color: black; color: white; padding: 10px; font: 11pt courier new; opacity: 0.7; text-shadow: #cccccc 1px 1px 1px; max-width: 300px' }, 'Debug output');
		var body = document.getElementsByTagName("BODY");
		if (body.length) {
			body[0].appendChild(log);
		} else {
			document.documentElement.appendChild(log);
		}
		if (is_ie7) {
			log.style.position = 'absolute';
			log.style.right = '0px';
			log.style.top = '0px';
			log.style.background = 'black';
			log.style.color = 'white';
		}
		return log;
	}
}

if (!("console" in window)) {
    window.console = { log: function () {} }; 
} 

function warn(what) {
	if (console && console.log) console.log(what);
	if (debug) {
		var log = Elem('log');
		if (!log) { log = screenlog() }; //return;

		if (typeof(what) == 'object') {
			warn("(OBJ.DUMP)");
			for (var i in what) {
				warn(i + ": " + what[i]);
			}
			warn("(OBJ.DUMP)");
			return;
		}

		if (log.childNodes.length == 0) {
			log.appendChild( newText( what ) );
			log.appendChild( newElem( 'br' ) );
		} else {
			log.insertBefore( newText( what ), log.childNodes[0] );
			log.insertBefore( newElem( 'br' ), log.childNodes[1] );
		}
	}
}

function Elem(elem) {
	return document.getElementById(elem);
}

function q(what) {
	return encodeURIComponent(what);
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if(node == null )
	  node = document;
	if(tag == null )
	  tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (var i = 0, j = 0; i < elsLen; i++) {
	  if ( pattern.test(els[i].className) ) {
		classElements[j] = els[i];
		j++;
	  }
	}
	return classElements;
}

function emptyElem(elem) {
	if (typeof(elem) == 'string') elem = Elem(elem);
	if (!elem || !elem.childNodes) return;
	while (elem.childNodes.length) {
		elem.removeChild( elem.childNodes[0] );
	}
}

function unescapeHTML(html) {
	return html.split("&amp;").join("&").split( "&lt;").join("<").split("&gt;").join(">").split('&quot;').join('"');
}

function escapeHTML(html) {
	return html.split("&").join("&amp;").split( "<").join("&lt;").split(">").join("&gt;").split('"').join("&quot;");
}

function newText(content) {
	return document.createTextNode( content );
}

function newElem(name, attrs, content) {
	if (!name) return newText( content );
	
	var e = document.createElement(name);
	for (key in attrs) {
		if (key == 'style' && typeof(attrs[key]) == 'object') {
			for (style in attrs[key]) {
				e.style[style] = attrs[key][style];
			}
		} else {
			e.setAttribute(key, attrs[key]);
		}
		if (key == 'class') { // IE 7 and below need this :(
			e.className = attrs[key];
		}
	}

	/* This processes elements created with JavaScript the same way
	 * as static HTML ones in core.js */
	if (name.toUpperCase() == 'INPUT') inputHandler(e);
	if (name.toUpperCase() == 'FORM') formHandler(e);

	for (var i=2, ic = arguments.length; i < ic; i++) {
		elemAppend(e, arguments[i]);
	}
	return e;
}

function elemAppend(e, content) {
	if (!content) return;

	if (typeof(content) == 'string' || typeof(content) == 'number') {
		e.appendChild( document.createTextNode( content ) );
	//} else if (typeof(content) == 'object' && content.length) {
	} else if (typeof content.length === 'number' && (!content.propertyIsEnumerable || !(content.propertyIsEnumerable('length'))) && typeof content.splice === 'function') {
		for (var j=0, jc=content.length; j < jc; j++) {
			elemAppend(e, content[j]);
		}
	} else {
		e.appendChild( content );
	}
}

function progressMeter( percent, target ) {
	var elem = null;
	if (target) elem = Elem(target);
	var label = "UPLOADING";
	if (percent >= 100) {
		percent = 100;
		label = "DONE";
	}
	var progress = newElem('div', {	'id' : target, 'class' : 'progressMeter' }, 
		newElem('div', { 'class' : 'progressBar progressBarBg' }, newElem('div', { 'class' : 'progressBarLabel' }, label))
	);
	var width = (percent / 5 * 6);
	var pp = progress.appendChild(newElem('div', { 'class' : 'progressBar' },
		newElem('div', { 'class' : 'progressBarLabel' }, label)
	));
	pp.style.clip = 'rect(0px,' + width + 'px,50px,0px)';

	if (elem) {
		elem.parentNode.insertBefore(progress, elem);
		elem.parentNode.removeChild(elem);
	}
	return progress;
}

/* Shortcuts */
function br(params) { return newElem("br", params) }

function http_process (req, callback) {
		if (req.readyState == 4) {
			this.activerequest = null;
			if (req.status != 200 && req.status != 0 && req.status != 304) {
				if (req.status == 400) {
					closeDialogue();
					dialogue("ERROR","Session expired");
					this.failed = 1;
				} else if (req.status == 404) {
					closeDialogue();
					dialogue("ERROR", "Server error (404)");
					this.failed = 1;
				} else if (req.status == 500) {
					closeDialogue();
					dialogue("ERROR","Server error");
					this.failed = 1;
				}
			} else {
				if (callback) {
	warn("REQ");
	warn(req);
					var obj = JSON.parse(req.responseText);
					callback( obj );
				}
			}
		}
}

function http_json_request(url, method, content, callback) {
	var req = null;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else {
		req = new ActiveXObject("Msxml2.XMLHTTP");
		if (!req) req = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (!method) method = 'GET';
	if (!content) content = '';

	content = JSON.stringify( content );

	req.onreadystatechange = function() { http_process(req, callback); };
	req.open(method, url, true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	req.setRequestHeader("Accept", "text/x-json; q=1.1, text/plain");
	req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	req.send( content );
	return 1;
}

function http_request (url, method, content, callback) {
	var req = null;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else {
		req = new ActiveXObject("Msxml2.XMLHTTP");
		if (!req) 
			req = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (!method) method = 'GET';

	//alert('foo');
	if (content && typeof(content) != 'string') {
		var sep = '?';
		if (window.user && window.user.session) {
			content['session'] = window.user.session;
		}
		for (var i in content) {
			if (typeof(content[i]) == 'string') {
				url += sep;
				url += i + '=' + q(content[i]);
				sep = '&';
			}
		}
		content = '';
	} else {
		if (window.user && window.user.session) {
			session = window.user.session;
			if (method == 'POST') { 
				if (content) {
					content = content + '&session=' + session;
				} else {
					content = 'session='+session;
				}
			} else if (method == 'GET') {
				if (url.indexOf("?")) {
					url = url + '&session=' + session;
				} else {
					url = url + '?session=' + session;
				}
			}
		}
	}
	if (!content) content = '';
	req.onreadystatechange = function() { http_process(req, callback); };
	req.open(method, url, true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	req.setRequestHeader("Accept", "text/x-json; q=1.1, text/plain");
	req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	req.send( content || '' );
	return 1;
}

/*** COOKIE HANDLING ***/

Cookies = function() {
	this.parse();
};

Cookies.prototype = {
	cookies : {},
	parse : function() {
		var a_all_cookies = document.cookie.split( ';' );
		var cookie_name = '';

		for ( i = 0; i < a_all_cookies.length; i++ ) {
			var cookie = a_all_cookies[i].split( '=' );
			var name = cookie[0].replace(/^\s+|\s+$/g, '');
			var val = "";

			if ( cookie.length > 1 ) {
				val = unescape( cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			this.cookies[ name ] = val;
		}
	},
	set : function (name, value, expires, path, domain, secure) {
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );

		if ( expires ) // in days
			expires = expires * 1000 * 60 * 60 * 24;
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name + "=" + escape( value ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
		this.cookies[ name ] = value;
	},
	get : function (name) {
		return this.cookies[ name ];
	}
};

function elem_xy (elem) {
	var x = 0, y = 0;
	while (elem.offsetParent) {
		x = x + elem.offsetLeft;
		y = y + elem.offsetTop;
		elem = elem.offsetParent;
	}
	x = x + elem.offsetLeft;
	y = y + elem.offsetTop;

	return { x: x, y: y };
};


function addOnLoad(fns) {
	for (var i=0, ic = arguments.length; i < ic; i++) {
		var fn = arguments[i];

		if (typeof window.addEventListener != 'undefined') {
			window.addEventListener('load', fn, false);
		} else if(typeof document.addEventListener != 'undefined') {
			document.addEventListener('load', fn, false);
		} else if(typeof window.attachEvent != 'undefined') {
			window.attachEvent('onload', fn);
		} else {
			if (typeof window.onload == 'function') {
				var old = onload;
				window.onload = function() {
					old();
					fn();
				};
			} else {
				window.onload = fn;
			}
		}
	}
}

/* Returns top frame (breaks out of iframes)
 * If cross domain, goes to the top read/write-able frame */

function get_top_frame() {
	var win = window;
	var done = 0;
	while (win.parent && win.parent != win && !done) {
		try {
			win.parent.document; // Firefox => catch
			win.parent.document.getElementsByTagName("body"); // Opera => catch
			if (!win.parent.document) { // Safari
				done = 1;
			} else {
				win = win.parent;
			}
		}
		catch(e) {
			done = 1;
		}
	}
	return win;
}

function dialogue( title, content, buttons, scripts ) {
	var win = get_top_frame();

	if (!buttons) {
		buttons = { 'OK' : closeDialogue };
	}

	/* ifdialogue evaluates a function and if it returns the name of one of the
	   buttons, that action is done immediately without showing the dialogue */
	if (scripts && scripts['ifdialogue']) {
		var res = scripts['ifdialogue']();
		if (res && buttons[res]) {
			buttons[res]();
			return;
		}
	}

	body = win.document.getElementsByTagName("BODY");
	body = body[0];

	var div = body.appendChild( newElem('div', { 'id' : 'dlpbmw' }) );
	var overlay = div.appendChild( newElem('div', { 'class' : 'overlay overlay2' } ) );
	
	var mbox = div.appendChild( newElem('div', { 'class' : 'dbox' },
		newElem('div', { 'class' : 'dboxtitle' }, title)
	) );
	var content_box = mbox.appendChild( newElem('div', { 'class' : 'dboxcontent' } ) );
	content_box.appendChild( newElem('div', {}, content) );

	for (var btn in buttons) {
		var b = content_box.appendChild( newElem('button', { 'class' : 'dboxbutton' }, btn ));
		if (buttons[btn] == 'close') {
			b.onclick = function(e) { Elem('dlpbmw').parentNode.removeChild( Elem('dlpbmw')) };
		} else if (typeof(buttons[btn]) == 'function') {
			b.onclick = buttons[btn];
		}
	}
	if (scripts && scripts['onload']) {
		scripts['onload']();
	}
	win.scrollTo(0,0);

	document.onkeyup = function(e) {
		if (!e) e = window.event;
		if (e.keyCode == 27) closeDialogue();
		if (e.keyCode == 13 && buttons['OK']) {
			buttons['OK']();
		}
	}
}

function closeDialogue() {
	if (Elem('dlpbmw')) 
		Elem('dlpbmw').parentNode.removeChild( Elem('dlpbmw'));
	document.onkeyup = null;
}


/* Active code (run for every page that loads this file) */

addOnLoad( 
	/* Popups */
	function(e) {
		var arr = getElementsByClass("popup");
		for (var a=0, ac=arr.length; a < ac; a++) {
			arr[a].onclick = function(e) {
				if (!e) e = window.event;
				var elem = e.srcElement || e.currentTarget;
				var height = 350;
				var width = 500;
				var query = elem.href.split('?')[1];
				if (query) {
					var sizes = query.split('&');
					for (var i = 0; i < sizes.length; i++) {
						if (sizes[i].split('=')[0] == 'popupheight') 
							height = sizes[i].split('=')[1];
						if (sizes[i].split('=')[0] == 'popupwidth') 
							width = sizes[i].split('=')[1];
					}
				}
				window.open(elem.href, '_blank', 'height=' + height + ',width='+width+',status=yes,toolbar=no,menubar=no,location=no,resizable=yes');
				return false;
			}
		}
	},
	function() {
		var arr = document.getElementsByTagName("button");
		for (var i=0,ic=arr.length; i<ic; i++) {
			if (arr[i].getAttribute("href")) {
				arr[i].onclick = function(e) {
					if (!e) e = window.event;
					var elem = e.srcElement || e.currentTarget;
					document.location = elem.getAttribute("href");
					return false;
				};
			}
		}
	},
	function() { // Default INPUT / TEXTAREA grayed out messages
		var inputs = document.getElementsByTagName("INPUT");
		var tas = document.getElementsByTagName("TEXTAREA");
		var elems = [];
		for (var i=0, ic=inputs.length; i<ic; i++) { elems.push( inputs[i] ); }
		for (var i=0, ic=tas.length; i<ic; i++) { elems.push( tas[i] ); }

		for (var i=0, ic=elems.length; i<ic; i++) {
			inputHandler( elems[i] );
		}
		var forms = document.getElementsByTagName("FORM");
		for (var i=0, ic=forms.length; i<ic; i++) {
			formHandler( forms[i] );
		}
	}, function() { // Admin editable help boxes
		activateAdminEditable();
	}
);

function formHandler(elem) {
	var old = elem.onsubmit;
	if (typeof old == 'function') {
		elem.onsubmit = function(e) {
			cleanForms();
			old();
		};
	} else {
		elem.onsubmit = function(e) {
			cleanForms();
		};
	}
}

function  inputHandler(elem) {
	if (elem.getAttribute("defaulttext")) {
		if (elem.value == "") {
			elem.value = elem.getAttribute("defaulttext");
			elem.style.color = 'silver';
		}
		// Firefox: keeps values in fields when you reload; avoid text turning black
		if (elem.value == elem.getAttribute("defaulttext")) {
			elem.style.color = 'silver';
		}
		elem.onfocus = function(e) {
			if (!e) e = window.event;
			var elem = e.srcElement || e.currentTarget;
			if (elem.value == elem.getAttribute("defaulttext")) {
				elem.value = '';
			}
			elem.style.color = 'black';
		}
		elem.onblur = function(e) {
			if (!e) e = window.event;
			var elem = e.srcElement || e.currentTarget;
			if (elem.value == "") {
				elem.value = elem.getAttribute("defaulttext");
				elem.style.color = 'silver';
			}
		}
	}
}

function activateAdminEditable(topElem) {
	var arr = getElementsByClass('adminEditableIcon', topElem);
	for (var i=0, ic=arr.length; i < ic; i++) {
		arr[i].onclick = function(e) {
			if (!e) e = window.event;
			var elem = e.srcElement || e.currentTarget;
			var id = elem.id.substring(5);
			if (Elem(id).style.display == 'block') {
				Elem(id).style.display = 'none';
			} else {
				Elem(id).style.display = 'block';
			}
		};

	}

	if (!window.is_admin || !is_admin) return;

	var arr = getElementsByClass('adminEditable', topElem);
	for (var i=0, ic=arr.length; i < ic; i++) {
		var box = arr[i];

		box.onclick = function(e) {
			if (!e) e = window.event;
			var elem = e.srcElement || e.currentTarget;
		
			if (elem.className != 'adminEditable' && elem.parentNode && elem.parentNode != elem) {
				elem.parentNode.onclick({ srcElement : elem.parentNode });
				return;
			}

			if (Elem('form_' + elem.id)) return;

			var value = elem.innerHTML;
			value = value.split("<br/>").join("\n");
			value = value.split("<br>").join("\n");

			var af = elem.appendChild(
				newElem('div', { 'class' : 'adminInputForm', 'id' : 'form_' + elem.id })
			);
			af.onclick = function(e) { }
			af.appendChild(
					newElem('h2', {}, 'Edit info box')
			);
			var ta = af.appendChild(
					newElem('textarea', {}, value)
			);
			var btn = af.appendChild(
					newElem('button', {}, 'Submit')
			);
			var btnc = af.appendChild(
					newElem('button', {}, 'Cancel')
			);
			btnc.onclick = function(e) {
				setTimeout("Elem('form_" + elem.id + "').parentNode.removeChild( Elem('form_" + elem.id + "') )",500);
			};
			btn.onclick = function(e) {
				var value = ta.value;
				value = value.split("\n").join("<br/>");
				var content = 'content=' + q( value ) + '&id=' + q( elem.id );
				http_request('/connect/update_help', 'POST', content, function(obj) {
					if (obj.status == 'OK') {
						//dialogue("Update succeeded", "The help content has been updated");
						elem.innerHTML = value;
					} else {
						dialogue("Update failed", "The help update request failed with status code " + obj.status);
					}
				});
			}
		};
	}
}

function cleanForms() {
	var inputs = document.getElementsByTagName("INPUT");
	var tas = document.getElementsByTagName("TEXTAREA");
	var elems = [];
	for (var i=0, ic=inputs.length; i<ic; i++) { elems.push( inputs[i] ); }
	for (var i=0, ic=tas.length; i<ic; i++) { elems.push( tas[i] ); }
	for (var i=0, ic=elems.length; i<ic; i++) {
		var dt = elems[i].getAttribute("defaulttext");
		if (dt && dt == elems[i].value) {
			elems[i].value = '';
		}
	}
}

function checkImageReady( params ) {
	if (!params.type) params.type = '160x90';

	http_request("/connect/thumbnail/" + params.collection + "/" + params.id + "/" + params.type + "/?session=" + params.session, 'GET', '', function(obj) {
		if (obj.image) {
			Elem(params.image).src = obj.image;
			if (params.show) 
				Elem(params.show).style.display = 'inline';
		} else {
			var params_s = "{ collection: " + params.collection + ", id: " + params.id + ", type: '" + params.type + "', session: '" + params.session + "', image: \"" + params.image + "\"";
			if (params.show) 
				params_s = params_s + ", show: \"" + params.show + "\"";
			params_s = params_s + "}";
			setTimeout("checkImageReady(" + params_s + ")", 10000);
		}
	});
}


	function displayAsset(asset) {
		//var win = window;
		var body = document.getElementsByTagName('BODY');
		////body = win.document.getElementsByTagName("BODY");
		body = body[0];

		if (!asset.id || !asset.url || !asset.primarytype) {
			warn(asset);
			warn("Insufficient information provided");
			dialogue("Error", "Sorry, due to a technical error we cannot show you this file at this time.");
			return;
		}

		if (!asset.collection) {
			/* This will be converted to collection / object_id server side */
			asset.collection = 0;
			asset.object_id = asset.id;
		}

		var div = body.appendChild( newElem('div', { 'id' : 'pvpbmw' }) );
		var overlay = div.appendChild( newElem('div', { 'class' : 'overlay overlay2' } ) );
		overlay.onclick = function(e) {
			//pbmw = win.document.getElementById('pvpbmw');
			var pbmw = document.getElementById('pvpbmw');
			pbmw.parentNode.removeChild( pbmw );
		};

		var preview = div.appendChild( newElem('div', { 'class' : 'preview' } ) );
		if (asset.primarytype == 'image') {
			preview.appendChild( newElem('img', { 'src' : asset.url } ) );
		} else {
			preview.style.width = '660px';
			preview.appendChild( newElem('div', { 'id' : 'videopreview' }) );
			var base = window.location.href.substr(0, window.location.href.lastIndexOf('/'));
			/* "Collection" 0 makes the backend look up object representations */
			var width = 660;
			var height = 372;
			var xml_config = "/mash/asset/" + width + "/" + height + "/" + asset.collection + "/" + asset.object_id;
			warn("XML config " + xml_config);
			var flashVars = {
				config    : xml_config,
				story     : 0,
				base      : base,
				session	  : this.session,
				userid    : com.user || 0,
				width	  		: width,
				height			: height,
				scale			: 'showall'
			};
			var flashParams = {
				allowFullScreen : "true",
				width	  		: width,
				height			: height,
				scale			: 'showall',
				wmode			: 'transparent'
			};
			swfobject.embedSWF("/flash/moviemasher/com/moviemasher/core/MovieMasher/stable.swf", 'videopreview', width + 40, height + 40, "9.0.0","#FFFFFF", flashVars, flashParams);
		}
		var pl = preview.appendChild( newElem('div', { 'class' : 'previewlinks' },
			newElem('a', { 'href' : '/lib/edit/' + asset.id }, 'Edit' )
			,' | '
		));
		var plcl = pl.appendChild( newElem('a', { 'href' : '#' }, 'Close' ) );
		plcl.onclick = function(e) {
			var pbmw = document.getElementById('pvpbmw');
			pbmw.parentNode.removeChild( pbmw );
			//Elem('pbmw').parentNode.removeChild( Elem('pbmw') );
		};

	}



function closeWindow() {
	var body = window.document.getElementsByTagName("BODY");
	body = body[0];

	var b_class = body.getAttribute("class");
	b_class = b_class.replace(" winPrint", "");

	if (com.oldelem) com.update_plan();
	com.mode = '';
	com.layout = null;
	com.save = null;
	Elem('pbmw').parentNode.removeChild(Elem('pbmw'));
	if (Elem('redock')) Elem('redock').style.display = 'none';
	if (Elem('dock')) Elem('dock').style.display = 'none';
	if (Elem('wrapper').style.display == 'none') {
		history.go(-1);
	}
	document.onkeyup = null;
	com.updatefrequence = 2500;
	com.update();
}

newWindow = function(params) { /* Compatibility function */
	var win = new cWindow( params );
	return Elem('winCont');
}


function nice_storage( num ) {
	var m = 0;
	var out = num;
	var units = ['bytes','KB','MB','GB','TB'];
	while (num / 1000 > 1) { m++; num/=1000; }
	return num.toFixed(1) + " " + units[m];
}

function showUploader(params) {
	if (!params || !params.story) {
		dialogue("Create.tv API error", ["showUploader() called without required parameters", br(), "Example usage: showUploader({ story: 99999 })"]);
		return;
	}

	var win = newWindow({ title : "Upload a file", 'width' : '400px', 'height' : '140px' });
	
	win.style.overflow = 'hidden';

	if (!params.studio) {
		showUploader2(params,win,'asset');
		return;
	}
	
	win.appendChild( newElem('div', { 'id' : 'selectupload' }, 
		newElem('h2', {}, 'What do you want to upload?'),
		newElem('div', { 'id' : 'uploadtypes', 'class' : 'uploadtypes' },
			newElem('div', { 'class' : 'uploadtype', 'id' : 'assetUpload' },
					newElem('img', { 'src' : '/images/asset.png', 'title' : 'Video/audio/image assets', 'alt' : 'Assets', 'id' : 'assetUploadImg' } ),
					newElem('label', {}, ' Video/audio/ image assets')
			),
			newElem('div', { 'class' : 'uploadtype', 'id' : 'editUpload' },
				newElem('img', { 'src' : '/images/edit.png', 'title' : 'Finished edit', 'alt' : 'Finished edit', 'id' : 'editUploadImg' } ),
				newElem('label', {}, 'Finished edit')
			),
			newElem('div', { 'class' : 'uploadtype', 'id' : 'docUpload' },
				newElem('img', { 'src' : '/images/doc.png', 'title' : 'Attached document', 'alt' : 'Attached document', 'id' : 'docUploadImg' } ),
				newElem('label', {}, 'Document attachment')
			)
		)
	));


	Elem('assetUpload').onclick = function(e) {	showUploader2(params, win, 'asset'); };
	Elem('editUpload').onclick = function(e) { showUploader2(params, win, 'edit'); };
	Elem('docUpload').onclick = function(e) { showUploader2(params, win, 'document'); };

	return;
}

function showUploader2(params, win, filetype) {
	if (Elem('selectupload')) Elem('selectupload').style.display = 'none';
	if (filetype == 'asset') {
		Elem('innerbasewin').style.width = '882px';
		Elem('innerbasewin').style.height = '180px';
		var box = Elem('winCont').appendChild( newElem('div') );
		//box.appendChild( newElem('script', { 'src' : '/js/swfobject.js' } ) );
		box.appendChild( newElem('div', { 'id' : 'uploader' }, 'Flash object initialising'));
		var fl_params = {
			scale:"noscale",
			salign:"lt",
			allowFullScreen:"true",
			bgColor:"#FFFFFF"
		}
		var flashVars = {
			featureXML:  "data:",
			session:     com.session,
			storyID: params.story,
			quota_total:  com.quota.total,
			quota_used:   com.quota.used,
			
			progressURL:     "/library/upload_progress/",
			feidProgressURL: "/library/feid_progress/",
			deleteURL:       "/library/delete_asset/",
			uploadURL:       "/library/upload_asset/",
			saveURL:         "/collection/save_mix/"
		}
		swfobject.embedSWF("/flash/flashUploader1.swf", "uploader", "852", "172", "9.0.124", false, flashVars,fl_params);
		return;
	}

	var quotabox = null;
	if (com && com.quota.used) {
		quotabox = win.appendChild(
			newElem('div', { 'style' : 'position: absolute; top: 127px; right: 10px; color: gray; z-index: 7;' },
				com.quota.used_nice + " of " + com.quota.total_nice + " used"
			)
		);
	}


	var iframe = win.appendChild( newElem('iframe', { 'id' : 'upload_iframe', 'width' : '250', 'height' : '120', 'style' : 'border: none' }) );
	var doc = iframe.contentDocument;
	if (!doc) doc = iframe.contentWindow.document;
	doc.open();
	doc.write("<html><head></head><body></body></html>");

	var docel = doc;
	window.doc1 = doc;
	if (docel.documentElement) 
		docel = doc.documentElement;

	window.doc2 = docel;
	docel = docel.getElementsByTagName("BODY")[0];
	docel.style.background = 'white';
	
	var filetypes = { 
		'edit' : 'Finished edit',
		'asset' : 'Image/video/audio asset',
		'document' : 'Attached document'
	};

	var upload_id = com.session + "_" + new Date().getTime();

	docel.appendChild( newElem('link', { 'href' : '/css/newstyle.css', 'rel' : 'stylesheet' }) );
	docel.appendChild(
		newElem('form', { 'enctype' : 'multipart/form-data', 'method' : 'POST', 'action' : '/studio/upload_document/' + params.story + '/' + upload_id + "/?progress_id=" + upload_id, 'style' : 'font-family: sans-serif; font-size: 10pt', 'id' : 'uploadform' },
			newElem('div', {},
				newElem('label', { 'for' : 'filetype' }, 'Type of file: '),
				newElem('span', {}, filetypes[filetype]),
				br(),
				br(),
				newElem('div', { 'style' : 'font-weight: bold' }, 'Please choose your file:'),
				newElem('input', { 'type' : 'hidden', 'id' : 'filetype', 'name' : 'filetype', 'value' : filetype }),
				newElem('input', { 'type' : 'hidden', 'name' : 'id', 'value' : upload_id }),
				newElem('input', { 'type' : 'file', 'name' : 'file', 'id' : 'file' }),
				br(),
				newElem('input', { 'type' : 'submit', 'id' : 'submit', 'value' : 'Upload file' })
			)
		)
	);
	Elem('upload_iframe').style.position = 'relative'; // FF 3.5
	if (is_ie7) {
		docel.getElementById('uploadform').setAttribute("encoding", "multipart/form-data"); // IE 7
		docel.getElementById('uploadform').method = "POST";
	}

	doc.getElementById('submit').onclick = function(e) {
		/* This covers the upload box */
		if (quotabox) quotabox.style.display = 'none';
		if (!doc.getElementById('file').value) {
			dialogue("Error","You need to choose a file to upload");
			return false;
		}
		win.style.height = '250px';
		win.appendChild( newElem('div', { 'class' : 'progressInfo' },
			newElem('b', {}, 'Upload progress'),
			br(),
			progressMeter(5, 'uploadprogress'),
			br(),
			newElem('div', { 'id' : 'ulbox' },
				newElem('input', { 'type' : 'hidden', 'name' : 'object_id', id : 'object_id', value: ''}),
				newElem('input', { 'type' : 'hidden', 'name' : 'upload_id', id : 'upload_id', value: upload_id}),
				newElem('label', { 'style' : 'font-weight: bold' }, 'Type: '), 
				filetypes[doc.getElementById('filetype').value],
				br(),
				newElem('label', { 'style' : 'font-weight: bold' }, 'Name: '), 
				newElem('input', { 'type' : 'text', 'value' : doc.getElementById('file').value, 'id' : 'filename' }),
				br(),
				br(),
				newElem('label', { 'style' : 'font-weight: bold' }, 'Description: '), 
				newElem('div', { 'id' : 'tacar' },
				newElem('textarea', { 'id' : 'description', 'cols' : 40, 'rows' : 5 }),
				br(),
				newElem('input', { 'type' : 'submit', 'value' : '   Save   ', 'id' : 'saveBtn' }),
				newElem('input', { 'type' : 'submit', 'value' : '   Abort upload   ', 'id' : 'abortBtn' })
				)
			),
			br()
		) );
		Elem('description').style.margin = '0px';
		Elem('description').style.padding = '0px';
		Elem('description').style.width = '250px';
		Elem('tacar').style.background = 'white';
		setTimeout("check_progress('" + upload_id + "', " + params.story + ")", 500);
		Elem('filename').onchange = function(e) {
			Elem('saveBtn').disabled = null;
		};
		Elem('description').onchange = function(e) {
			Elem('saveBtn').disabled = null;
		};
		Elem('saveBtn').onclick = function(e) {
			var filename = Elem('filename').value;
			var description = Elem('description').value;
			var oid = Elem('object_id').value;
			var uid = Elem('upload_id').value;
			var params = "filename=" + q(filename) + "&description=" + q(description);
			if (oid) {
				params = params + "&oid=" + oid;
			} else {
				params = params + "&uid=" + uid;
			}
			http_request('/studio/change_details', 'POST', params, function(res) {
				if (res.status == 'OK') {
					if (oid) {
						closeWindow();
					} else {
					}
				} else {
					dialogue("ERROR", "Something went wrong while saving");
				}
			});
		};
		Elem('abortBtn').onclick = closeWindow;
	};
}

function check_progress(id, story) {
	http_request("/UpdateProgress?progress_id=" + id, "GET", null, function(res) {
		if (res.size) {
			progressMeter( res.received/res.size * 100, 'uploadprogress' );
		}

		if (res.received == res.size) {
			if (Elem('saveBtn')) {
				Elem('saveBtn').value = '   Save/Close   ';
				Elem('abortBtn').value = '   Upload more   ';
				Elem('abortBtn').onclick = function() {
					showUploader({ story: story, studio: 1 });
				}
				update_object_id( story );
			}
		} else {
			setTimeout("check_progress(\"" + id + "\", " + story + ")", 100);
		}
	});
}

function update_object_id( story ) {
	/* We need to keep looking for this since the progress indicator only indicates
	   having uploaded everything, not when we get a response back from the server */
	var iframe = Elem('upload_iframe');
	if (!iframe) return;
	var doc = iframe.contentDocument;
	if (!doc) doc = iframe.contentWindow.document;
	var el = doc.getElementById('objectid');
	if (el) {
		var obj_id = el.getAttribute("value");
		Elem('object_id').value = obj_id;
		/* For the upload & play page only */
		if (window.addTile) {
		  http_request('/connect/thumbnail/'+story+"/"+obj_id, 'POST', null, function(obj) {
			if (obj.status == 'OK') addTile(obj.object);
		  });
		}
	}	else {
		setTimeout("update_object_id(" + story + ")", 300);
	}
}

var locals = {};
function set_local(id,val) {
	locals[id] = val;
}

function get_local(id, def) {
	return locals[id] || def;
}

function showMixer(mix) {
	var base = window.location.href.substr(0, window.location.href.lastIndexOf('/'));
	var flashVars = {
		preloader : "../../flash/moviemasher/com/moviemasher/display/Preloader/stable.swf",
		config    : "/mash/" + com.story,
		story     : com.story,
		base      : base,
		session		: com.session
	};
	if (mix && typeof(mix) == 'object') {
		flashVars.config = flashVars.config + '?mashid=' + mix.mashid;
	} else if (mix) {
		flashVars.config = flashVars.config + '?mashidx=' + mix;
	}
	http_request("/studio/load_mixes/" + com.story, 'GET', {}, function(res) {
		var win = newWindow({ title : 'Mixer', width : '1100px' }); // , 'height' : '750px' 
		com.updatefrequence = 0;
		win.appendChild( newElem('div', { 'id' : 'mixer' }, "Loading mixer..." ) );

		var flashParams = {
			allowFullScreen : "true"
		};
		swfobject.embedSWF("../../flash/moviemasher/com/moviemasher/core/MovieMasher/stable.swf", "mixer", "1050", "850", "9.0.0", "#FFFFFF", flashVars, flashParams);

		if (res.status == 'OK') {
			var m = win.appendChild( newElem("div", { 'style' : 'text-align: left; margin-top: 2em' }) );
			m.style.textAlign = 'left';
			m.style.marginTop = '2em';
			m.appendChild( newElem('h2', null, 'Mix versions') );
			for (var i=res.mixes.length - 1; i>=0; i--) {
				var mix = res.mixes[i];
				var div = m.appendChild( newElem("div", { 'class' : 'revbox', 'id' : 'mix' + i }));
				div.onclick= function(e) {
					if (!e) e = window.event;
					var elem = e.srcElement || e.currentTarget;
					showMixer(elem.id.substring(3));
				}
				div.appendChild( newElem('div', { 'class' : 'floatRight' },
					newElem('span', { 'class': 'mixeditbtn'}, "Edit")
				));
				div.appendChild( newElem("a", { 'href' : '/profile/' + q( mix.author ) }, 
					newElem('img', { 'src' : mix.avatar || '/images/default/profile_40.gif', 'width' : 40, 'height' : 40, 'class' : 'mixAvatar' })
				));
				div.appendChild( newElem("div", {}, "Saved by ",
					newElem("a", { href : '/profile/' + q( mix.author ) }, mix.author),
					br(),
					"At " + mix.saved
				));
			}
		}
	});
}

function showPreview( mix ) {
	if (!mix) mix = 0;
	var win = newWindow({ title : 'Preview edit', width : '940px', 'height' : '401px' }); 
	win.appendChild(newElem("div", { 'id' : 'mixer' }));
	com.updatefrequence = 0;
	var base = window.location.href.substr(0, window.location.href.lastIndexOf('/'));

	var flashVars = {
		preloader : "../../flash/moviemasher/com/moviemasher/display/Preloader/stable.swf",
		config    : "/mash/player/" + com.story,
		story     : com.story,
		base      : base,
		session		: com.session
	};
	if (typeof(mix) == 'object') {
		flashVars.config = flashVars.config + '?mashid=' + mix.mashid;
	} else if (mix > 0) {
		flashVars.config = flashVars.config + '?mashidx=' + mix;
	} else if (mix < 0) {
		flashVars.config = flashVars.config + '?nomash=1';
	}
	warn(flashVars.config);
	var flashParams = {
		allowFullScreen : "true"
	};
	swfobject.embedSWF("../../flash/moviemasher/com/moviemasher/core/MovieMasher/stable.swf", "mixer", "900", "380", "9.0.0", "#FFFFFF", flashVars, flashParams);
}

function reportContent(id) {
	var content = [
		'Please tell us why you find this comment objectionable',
		newElem('br'),
		newElem('textarea',{ 'id' : 'reporttext', 'cols' : 45, 'rows' : 7 }, '')
	];
	if (!com.user) {
		content.push( newElem('div', {}, 
			newElem('br'),
			'Please supply your e-mail address so we can get back to you',
			newElem('br'),
			newElem('input', { 'type' : 'text', 'size' : '40', 'id' : 'repemail' } )
		));
	}
	dialogue("Report objectionable comments", content, {
		'Send report' : function() {
			var params = "report=" + encodeURIComponent(Elem('reporttext').value);

			if (Elem('repemail')) 
				params = params + '&email=' + encodeURIComponent( Elem('repemail').value );

			http_request('/groups/report_comment/' + id, 'POST', params, function(obj) {
				closeDialogue();
				var content = [
						"Your report has now been submitted to the Create.tv team",
						newElem('br'),
						"Thank you for helping us improve our service"
				];
				dialogue("Thank you", content, { 'OK' : closeDialogue });
			});
		},
		'Cancel' : closeDialogue
	});
}

function helpbox(params) {
	var par = params.par;
	var id = params.id;
	warn('Connect to /connect/help_box/' + q(id));
	http_request('/connect/help_box/' + q(id), 'POST', {}, function(obj) {
		if (obj.status == 'OK') {
			par.appendChild(
				newElem('img', { 'src' : '/images/info.png', 'class' : 'adminEditableIcon', 'id' : 'icon_' + id })
			);
			par.appendChild(
				newElem('div', { 'class' : 'adminEditable', 'id' : id }, obj.content )
			);
		}
	});
	/* This needs to be delayed or won't otherwise always work */
	setTimeout(function() {
		activateAdminEditable(par);
	}, 250);
}

/* cWindow */
cWindow = function(params) {
	var body = window.document.getElementsByTagName("BODY");
	body = body[0];

	var b_class = body.getAttribute("class");
	b_class = b_class + " winPrint";
	body.setAttribute("class", b_class);
	body.setAttribute("className", b_class);

	if (!params.width) params.width = '1020px';
	if (!params.height) params.height = '100%';

	if (Elem('pbmw')) {
		closeWindow();
	}

	var div = body.appendChild( newElem('div', { 'id' : 'pbmw' }) );
	var overlay = div.appendChild( newElem('div', { 'class' : 'overlay' } ) );
	var space = Elem('pbmw').appendChild(
		newElem('div', { 'style' : 'position: absolute; position: fixed; top: 20px; left: 0px; right: 0px; bottom: 140px; text-align: center; z-index: 9999999;', 'id' : 'baseWindow' },
			newElem('div', { 'style' : 'margin: auto; background: white; width: ' + params.width + '; height: ' + params.height + ';', 'id' : 'innerbasewin' },
				newElem('div', { 'style' : 'width: 100%; background: #7BA810; color: white; margin-bottom: 10px; font-weight: bold; font-size: 10pt; position: relative; padding: 2px 0px', 'id' : 'innerbwin' }, 
					newElem('img', { 'src' : '/images/icons/delete.png', 'style' : 'position: absolute; right: 7px; top: 3px;', 'id' : 'boxclose'}),
					newElem('span', { 'id' : 'winTitle' }, params.title)
				),
				newElem('div', { 'id' : 'winCont' })
			)
		)
	);
	if (params.height == '100%') {
		if (Elem('dock')) {
			Elem('winCont').style.height = (document.documentElement.clientHeight - 165) + 'px';
		} else {
			Elem('winCont').style.height = (document.documentElement.clientHeight - 105) + 'px';
		}
	}
	Elem('innerbasewin').style.width = params.width;
	Elem('innerbasewin').style.height = params.height;

	if (Elem('dock')) {
		Elem('redock').style.display = 'block';
		Elem('dock').style.display = 'block';

		var width = 0;
		for (var i=0, ic=Elem('dock').childNodes.length; i<ic; i++) {
				var nodes = Elem('dock').childNodes[i];
				if (nodes.clientWidth) 
						width = width + nodes.clientWidth;
		}
//			Elem('dock').style.paddingLeft = (( Elem('dock').clientWidth - width) /2) + 'px';
		Elem('dock').style.width = width + 'px';
		Elem('dock').style.marginLeft = (((document.documentElement.clientWidth - width) / 2) - 15) + 'px';
		Elem('redock').style.width = width + 'px';
		Elem('redock').style.marginLeft = (((document.documentElement.clientWidth - width) / 2) - 15) + 'px';
	}

	Elem('boxclose').onclick = function(e) {
		closeWindow();
	};

	var px = params.height.indexOf("px");
	if (px > 0) {
		Elem('baseWindow').style.top = (((document.documentElement.clientHeight - params.height.substring(0, px) ))/2 - 40) + 'px';
	}

	document.onkeyup = function(e) {
		if (!e) e = window.event;
		if (e.keyCode == 27) {
			var bx = Elem('boxclose');
			if (bx) bx.onclick();
		}
	}

	warn(params);

	if (params.help) {
		helpbox({ 'par': Elem('winCont'), 'id': params.help });
	}
	this.body = Elem('winCont');
}

cWindow.prototype = {
	body: null,
	'adjustHeight' : function() {
		var win = Elem('winCont');
		var height = 20;
		var width = 20;
		for (var i=0, ic=win.childNodes.length; i<ic; i++) {
			height = height + win.childNodes[i].scrollHeight;
		}
		if (height > document.documentElement.clientHeight - 200) {
			height = document.documentElement.clientHeight - 200;
		}
		warn(height);
		Elem('innerbasewin').style.height = height + 'px';
		Elem('winCont').style.height = height + 'px';
		//Elem('baseWindow').style.overflow = 'hidden';
		warn(height);


		var top = Math.floor(( document.documentElement.clientHeight - height - 100) /2 ) + 'px';
		warn(top);
		Elem('baseWindow').style.top = top;
	},
	'setTitle' : function(title) {
		emptyElem('winTitle');
		Elem('winTitle').appendChild( newText( title ) );
	}
};

function login (funcs) {
	if (!funcs) funcs = {};

	/*if (!funcs.success) funcs.success = function(e) { window.location.reload(); };
	if (!funcs.failure) funcs.failure = function(e) { dialogue("Error", "Login failed"); } */

	var win = new cWindow({ title : 'Please log in or register', 'width' : '400px', 'height' : '320px' });

	win.body.appendChild(
		newElem('div', { 'class' : 'loginbox', 'id' : 'loginbox' }, 
			newElem('div', { 'id' : 'loginsignup' },
				newElem('div', { 'class' : 'loginmsg', 'id' : 'loginmsg' },
					'Hi! Please login or complete a short registration to proceed...', br()
				),
				newElem('div', { 'class' : 'bc' },
					newElem('label', { 'for' : 'username' }, 'Username'),
					newElem('input', { 'type' : 'text', 'id' : 'username' })
				),
				newElem('div', { 'class' : 'bc' },
					newElem('label', { 'for' : 'password' }, 'Password'),
					newElem('input', { 'type' : 'password', 'id' : 'password' })
				),
				newElem('div', { 'id' : 'regdetails' },
					newElem('div', { 'class' : 'bc' },
						newElem('label', { 'for' : 'password2' }, 'Repeat your password'),
						newElem('input', { 'type' : 'password', 'id' : 'password2' })
					),
					newElem('div', { 'class' : 'bc' },
						newElem('label', { 'for' : 'email' }, 'E-mail address'),
						newElem('input', { 'type' : 'text', 'id' : 'email' })
					),
					newElem('div', { 'class' : 'dc' },
						br(),
						newElem('input', { 'type' : 'checkbox', 'id' : 'terms' }),
						newElem('label', { 'for' : 'terms' }, 'I accept Create.tv\'s ',
							newElem('a', { 'href' : '/terms/', 'target' : '_blank' } , 'terms and conditions')
						)
					)
				),
				br(),
				newElem('button', { 'id' : 'loginbtn' }, 'Log in'),
				newElem('button', { 'id' : 'registerbtn' }, 'Register'),
				newElem('div', { 'id' : 'rempassword' },
					br(),
					"Can't remember your password? ",
					br(),
					newElem('a', { 'id' : 'rempwlink', 'href' : '#' }, "Click here and we'll send you a new one")
				)
			),
			newElem('div', { 'id' : 'rempwblock' },
				newElem('div', { 'class' : 'loginmsg', 'id' : 'pwremmsg' },
					'Please enter your e-mail address below and we will send you a new password', br()
				),
				br(),
				newElem('div', { 'class' : 'bc' },
					newElem('label', { 'for' : 'pw_email' }, 'E-mail'),
					newElem('input', { 'type' : 'text', 'id' : 'pw_email' })
				),
				br(),
				newElem('button', { 'id' : 'pwrembtn' }, 'Send login details')
			)
		)
	);
	win.adjustHeight();

	var arr = getElementsByClass("bc");
	for (var i=0, ic=arr.length; i<ic; i++) {
		arr[i].getElementsByTagName("INPUT")[0].onfocus = function(e) {
			if (!e) e = window.event;
			var elem = e.srcElement || e.currentTarget;
			elem.onblur = function(e) {
				if (!e) e = window.event;
				var elem = e.srcElement || e.currentTarget;
				elem.onkeydown = null;
			};
			elem.onkeyup = function(e) {
				if (!e) e = window.event;
				var elem = e.srcElement || e.currentTarget;
				elem.parentNode.getElementsByTagName("LABEL")[0].style.display = 'none';
				if (!elem.value.length) {
					elem.parentNode.getElementsByTagName("LABEL")[0].style.display = 'block';
				}
				if (e.keyCode == 13 && win.defaultBtn) {
					win.defaultBtn.click();
				}
			}
		}
	}

	Elem('pwrembtn').style.width = '250px';

	Elem('username').focus();
	win.defaultBtn = Elem('loginbtn');

	Elem('rempwlink').onclick = function(e) {
		Elem('loginsignup').style.display = 'none';
		Elem('rempwblock').style.display = 'block';
	};
	Elem('pwrembtn').onclick = function(e) {
		var params = "email=" + encodeURIComponent( Elem('pw_email').value );
		http_request( '/ideas/login_reminder/', 'POST', params, function( obj ) {
			if (obj.status == 'OK') {
				closeWindow();
				closeDialogue();
				dialogue("Login reminder sent", "We have now sent you an e-mail with your username and a new password");
			} else if (obj.status == 'NO_SUCH_USER') {
				closeDialogue();
				dialogue("Account not found", "We couldn't find any users with the e-mail address " + Elem('pw_email').value);
				
			}
		});
	}

	Elem('registerbtn').onclick = function(e) {
		Elem('regdetails').style.display = 'block';
		Elem('rempassword').style.display = 'none';
		win.adjustHeight();
		Elem('loginbtn').style.display = 'none';
		win.defaultBtn = Elem('registerbtn');
		win.body.scrollTop = 300;
		if (Elem('username').value) {
			Elem('password2').focus();
		} else {
			Elem('username').focus();
		}

		Elem('registerbtn').onclick = function(e) {
			if (!Elem('password').value || !Elem('username').value || !Elem('email').value) {
				alert('You need to fill in all fields');
				return false;
			}
			if (Elem('password').value != Elem('password2').value) {
				alert('Passwords do not match');
				return false;
			}

			var username = Elem('username').value;
			var password = Elem('password').value;
			if (!Elem('terms').checked) {
				debugger;
				Elem('loginmsg').innerHTML = '<span style="color: red">You need to accept Create.tv\'s terms of use</span>';
				return;
			}
			//Elem('mustterms').style.display = 'none';
			var email = Elem('email').value;
			var params = "username=" + encodeURIComponent( username ) + "&password=" + encodeURIComponent( password ) + "&email=" + encodeURIComponent( email );;
			http_request( '/ideas/signup/', 'POST', params, function( obj ) {
				if (obj.status == 'OK') {
					window.location = "/user/home";
				} else if (obj.status == 'EMAIL_TAKEN') {
					var msg = Elem('loginmsg');
					emptyElem(msg);
					msg.appendChild(newElem("span", { 'style' : 'color: red' }, 'An account has already been registered with this e-mail address.'));
					msg.appendChild(newElem('div', { 'id': 'logdet', 'style':'text-decoration:underline; font-size: smaller; color: red; cursor: pointer' }, 'Click here to request your login details'));

					Elem('logdet').onclick = function() {
						http_request( '/ideas/login_reminder/', 'POST', params, function( obj ) {
							closeDialogue();
							dialogue("Login reminder sent", "We have now sent you an e-mail with your username and a new password");
						});
					}

				} else if (obj.status == 'EMAIL_INVALID') {
					Elem('loginmsg').innerHTML = '<span style="color: red">Missing or invalid e-mail address</span>';
					Elem('email').focus();
				} else if (obj.status == 'USERNAME_TAKEN') {
					Elem('loginmsg').innerHTML = '<span style="color: red">Someone has already taken this username</span>';
					Elem('username').focus();
				} else if (obj.status == 'USERNAME_INVALID') {
					Elem('loginmsg').innerHTML = '<span style="color: red">Missing or invalid username, must be at least 4 characters</span>';
					Elem('username').focus();
				} else if (obj.status == 'PASSWORD_BAD') {
					Elem('loginmsg').innerHTML = '<span style="color: red">Please make sure your password is at least 7 characters long</span>';
					Elem('password').focus();
				} else {
					Elem('loginmsg').innerHTML = '<span style="color: red">Generic error: ' + obj.status + '</span>';
					Elem('username').focus();
				}
			});
		};
	};

	Elem('loginbtn').onclick = function(e) {
		var username = Elem('username').value;
		var password = Elem('password').value;
		var params = "username=" + encodeURIComponent( username ) + "&password=" + encodeURIComponent( password );
		http_request( '/ideas/login/', 'POST', params, function( obj ) {
			if (obj.status == 'OK') {
				if (window.location.pathname == '/error/login' || window.location.pathname == '/') {
					window.location = "/user/home";
				} else {
					window.location.reload();
				}
			} else {
				Elem('loginmsg').innerHTML = '<span style="color: red">Invalid login details.<br/>Please try again</span>';
			}
		});
	};
}

function abc() {
	alert('Bang');
}

/* Universal object clone method */
function cloneObject(obj) {
	var newObj = (obj instanceof Array) ? [] : {};
	for (i in obj) {
		if (i == 'clone') 
			continue;
		if (obj[i] && typeof obj[i] == "object") {
			newObj[i] = obj[i].clone();
		} else {
			newObj[i] = obj[i]	
		}
	} 
	return newObj;
};


YmogenFacebook = function(params) {
	this.api = params.api;
	if (params.session && params.session.session_key) params.session = params.session.session_key;
	this.session = params.session;
}

YmogenFacebook.prototype = {
	connect : function(func, callback) {
		http_request('http://api.connect.facebook.com/restserver.php', 'GET', {
			method : func,
			session_key : this.session,
			api_key : this.api,
			format: 'json'
		}, callback);
	}
};

function query_params() {
	var url = location.search.substring(1, location.search.length);
	if (url.length == 0) return;
	url = url.replace(/\+/g, ' ');

	var params = {};
	var args = url.split('&'); 

	for (var i=0, ic=args.length; i<ic; i++) {
		var arr = args[i].split('=');
		var key = decodeURIComponent( arr[0] );
		if (arr.length == 1) {
			if (!params[key]) params[key] = null;
			continue;
		}
		var value = decodeURIComponent( arr[1] );
		if (params[key]) {
			if (typeof(params[key]) == 'string') {
				params[key] = [ params[key], value ];
			} else {
				params[key].push( value );
			}
		} else {
			params[key] = value;
		}
	}
	return params;
}

function uri_with(newparams, allow_multiple, extra) {
	var url = document.location.href;

	if (typeof(newparams) == 'string') {
		url = newparams;
		newparams = allow_multiple;
		allow_multiple = extra;
	}

	if (allow_multiple == null) allow_multiple = 0;
	if (newparams == null) newparams = {};
	var idx = url.indexOf("?");
	if (idx > 0) {
		url = url.substring(0,idx);
	}
	var qp = build_params(newparams, allow_multiple);
	if (qp)	url = url + '?' + qp;
	return url;
}

function build_params(newparams, allow_multiple) {
	if (allow_multiple == null) allow_multiple = 0;

	var url = "";
	var sep = "";
	var params = query_params();
	var comp = [];
	for (var key in params) {
		if (newparams[key] && !allow_multiple) continue;
		
		if (typeof(params[key]) == "string") {
			url = url + sep + q(key) + '=' + q(params[key]);
			sep = '&';
		} else {
			for (var i=0, ic=params[key].length; i<ic; i++) {
				url = url + sep + q(key) + '=' + q(params[key][i]);
				sep = '&';
			}
		}
	}
	for (var key in newparams) {
		if (typeof(newparams[key]) == "string") {
			url = url + sep + q(key) + '=' + q(newparams[key]);
			sep = '&';
		} else {
			for (var i=0, ic=newparams[key].length; i<ic; i++) {
				url = url + sep + q(key) + '=' + q(newparams[key][i]);
				sep = '&';
			}
		}
	}
	return url;
}



require('/js/sprintf.js');

Calendar = function() {
}

Calendar.prototype = {
	me: null,
	close : function() {
		if (this.me == null) return;
		this.me.parentNode.removeChild( this.me );
		this.me = null;
	},
	display : function(par, aday, callback) {
		emptyElem(par);
		if (aday == null) aday = new Date();
		var today = new Date();

		var year = aday.getFullYear();
		var month = aday.getMonth() + 1;
		var months = [
			null,
			{ 'name' : 'January', 'length' : 31 },
			{ 'name' : 'February', 'length' : 28 },
			{ 'name' : 'March', 'length' : 31 },
			{ 'name' : 'April', 'length' : 30 },
			{ 'name' : 'May', 'length' : 31 },
			{ 'name' : 'June', 'length' : 30 },
			{ 'name' : 'July', 'length' : 31 },
			{ 'name' : 'August', 'length' : 31 },
			{ 'name' : 'September', 'length' : 30 },
			{ 'name' : 'October', 'length' : 31 },
			{ 'name' : 'November', 'length' : 30 },
			{ 'name' : 'December', 'length' : 31 }
		];
		if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
			months[2].length = 29;
		for (var i=1; i<=12; i++) {
			months[i].firstday = new Date(year, i - 1, 1).getDay() || 7;
		}
		
		par.appendChild(
			newElem('table', { 'class' : 'calendar' },
				newElem('tr',{},
					newElem('td', { 'class' : 'prevmonth' }, '<'),
					newElem('td', { 'colspan' : 5 }, months[month].name + ' ' + year),
					newElem('td', { 'class' : 'nextmonth' }, '>')
				),
				newElem('tr', { 'class' : 'weekdays'},
					newElem('td', {}, 'M'),
					newElem('td', {}, 'T'),
					newElem('td', {}, 'O'),
					newElem('td', {}, 'T'),
					newElem('td', {}, 'F'),
					newElem('td', {}, 'S'),
					newElem('td', {}, 'S')
				)
			)
		);
		var cal = par.getElementsByTagName("TABLE")[0];
		this.me = cal;
		var day = 0;
		var selected = null;
		while (day < months[month].length) {
			var row = [];
			var wday = 1;
			if (day == 0) wday = months[month].firstday;
			while (wday <= 7) {
				day++;
				pars = { 'class' : 'day'};
				if (month-1 == today.getMonth() && day == today.getDate())
					pars['class'] = 'day today';
				row[wday - 1] = newElem('td', pars, 
					newElem('input', { 'type' : 'hidden', 'value' : year + '-' + month + '-' + day }),
					day
				);
				wday++;
			}
			for (var i=0;i<7;i++) {
				if (row[i] == null) row[i] = newElem('td', {});
			}
			cal.appendChild( newElem('tr', {}, row) );
		}

		var _this = this;
		cal.childNodes[0].childNodes[0].onclick = function(e) {
			_this.display(par, new Date(year, month - 2, 1), callback);
		};

		cal.childNodes[0].childNodes[2].onclick = function(e) {
			_this.display(par, new Date(year, month, 1), callback);
		};
		var days = getElementsByClass("day");
		for (var i=0, ic=days.length; i<ic; i++) {
			days[i].onclick = function(e) {
				if (!e) e = window.event;
				var elem = e.srcElement || e.currentTarget;

				if (selected) {
					selected.style.background = 'white';
					selected.style.color = 'black';
				}
				selected = elem;
				selected.style.background = 'black';
				selected.style.color = 'white';

				var dt = elem.getElementsByTagName("INPUT")[0].value;
				var arr = dt.split('-');
				var mydate = new Date(Number(arr[0]), Number(arr[1]-1), Number(arr[2]));
				callback({
					'date':	mydate,
					'string' : sprintf("%04d-%02d-%02d", mydate.getFullYear(), mydate.getMonth() + 1, mydate.getDate() )
				});
			}
		}
	}
};
