var local = false;

// IE needs special treatment to work. it's a very special browser...
var browserName = navigator.appName.toLowerCase();
var isIE = browserName.indexOf("msie") != -1 || browserName.indexOf("explorer") != -1;

// refresh portlets every 5 mins
//var REFRESH_RATE = 300000;
var REFRESH_RATE = 300000;

function getElementsByClassName(className, node) {
	node = node || document.getElementsByTagName("body")[0];
	var elements = [];
	var exp = new RegExp('\\b' + className + '\\b');
	var kids = node.getElementsByTagName("*");
	for (var i = 0; i < kids.length; i++) {
		if (exp.test(kids[i].className)) {
			// only except spaces as word boundaries
			if (className.length != kids[i].className.length
					&& kids[i].className.indexOf(className + " ") == -1
					&& kids[i].className.indexOf(" " + className) == -1
					&& kids[i].className.indexOf(" " + className + " ") == -1) {
				// matches, but is not a distinct classname
				continue;
			}
			elements.push(kids[i]);
		}
	}
	return elements;
}

function clear (container) {
	while (container.firstChild) {
		container.removeChild(container.firstChild);
	}
}

function copy (obj) {
	var copy = {};
	for (var name in obj) {
		// shallow copy
		copy[name] = obj[name];
	}
	return copy;
}

function getTabs(tabcount) {
	tabcount = tabcount || 0;
	var str = "";
	for ( var i = 0; i < tabcount; i++) {
		str += "\t";
	}
	return str;
}

function toString(obj, tabcount) {
	tabcount = tabcount || 0;
	var str = "{\n";
	var first = true;
	for ( var name in obj) {
		var val = obj[name];
		if (typeof val == "object" && val) {
			// do not attempt circular references
			if (val && (val.id || val.nodeType)) {
				val = val || {
					"id" :"ref:node"
				};
				val = val.id;
			} else {
				val = toString(val, tabcount + 1);
			}
		}
		if (!first) {
			str += ",\n";
		}
		str += getTabs(tabcount + 1) + name + " : " + val;
		first = false;
	}
	str += "\n" + getTabs(tabcount) + "}\n";
	return str;
}

Object.prototype.toString = function() {
	return toString(this, 0);
};


	            	function selectTab(name){
				// deselect all to start with
				var tabs = ["home", "forum", "ladder", "user-created"];
				for (var i = 0; i < tabs.length; i++) {
					setTabSelectedClass(tabs[i], false);
				}
				// select tab
		                setTabSelectedClass(name, true);
				// fire link
				var link = document.getElementById(name + "-link");
				if (link && link.href) {
					if (link.target) {
						window.open(link.href);
					} else {
						document.location.href = link.href;
					}
				//	
				//	link.click();
				}
        		}
			
			function setTabSelectedClass(name, selected) {
				// parent tab
				var tab = document.getElementById(name + "-tab");
				if (tab) {
					tab.className = "tab" + (selected ? "-selected" : "");
				}
				// child tabs
				var parts = ["left", "center", "right"];
				for (var i = 0; i < parts.length; i++) {
					var id = name + "-tab-" + parts[i];
	                var div = document.getElementById(id);
	                if (div) {
						div.className = "tab-" + parts[i] + (selected ? "-selected" : "");
					}
				}
			}
			
			function hoverTab (name) {	
				setTabHoverClass(name, true);
			}
			
			function unhoverTab (name) {
				setTabHoverClass(name, false);
			}
			
			function setTabHoverClass(name, hover) {
				// parent tab
				var tab = document.getElementById(name + "-tab");
				if (tab) {
					if (tab.className == "tab-selected") {
						return;
					}
					tab.className = "tab" + (hover ? "-hover" : "");
				}
				// child tabs
				var parts = ["left", "center", "right"];
				for (var i = 0; i < parts.length; i++) {
					var id = name + "-tab-" + parts[i];
	                var div = document.getElementById(id);
	                if (div) {
						div.className = "tab-" + parts[i] + (hover ? "-hover" : "");
					}
				}
			}			
			
			function selectContent(name) {
				var id = "content-" + name;
                var div = document.getElementById(id);
                if (div) {
					var content = document.getElementById("content");
					content.innerHTML = div.innerHTML;
				}
			}

var hideMenuTimeouts = {}; 

function showMenus (menuIds) {
	for (var i = 0; i < menuIds.length; i++) {		
		showMenu(menuIds[i]);
	}
}
			
function showMenu(menuId, caller) {	
	if (hideMenuTimeouts[menuId]) {
		clearTimeout(hideMenuTimeouts[menuId]);
	}
	var menu = document.getElementById(menuId);
	if (caller) {
		menu.style.left = caller.clientLeft;
	}
	menu.className = "header-menu";
}			

function hideMenus (menuIds) {
	for (var i = 0; i < menuIds.length; i++) {		
		hideMenu(menuIds[i]);
	}
}

function hideMenu (menuId) {
	hideMenuTimeouts[menuId] = setTimeout(function(){
		var menu = document.getElementById(menuId);
		menu.className = "header-menu-hidden"
	}, 500);
}

//Emulate XMLHttpRequest
if (!window.XMLHttpRequest) {
	XMLHttpRequest = function() {
		var list = [ "Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0",
				"MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
		var impl;
		for ( var i = 0; i < list.length; i++) {
			try {
				imple = new ActiveXObject(list[i]);
			} catch (e) {
				// YUM!! that one didn't work
			}
			return impl;
		}
		throw "Failed to find Active X implementation from list: " + list;
	};
};

function httpPostParams(url, params) {
	var paramString = "";
	for (var name in params) {
		paramString += (paramString ? "&" : "") + name + "=" + encodeURIComponent(params[name]);
	}
	var response = new XMLHttpRequest();
	response.open("POST", url, false);
	response.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	response.setRequestHeader("Content-length", paramString.length);
	response.setRequestHeader("Connection", "close");
	response.send(paramString);
	// check code (200-299 is ok)
	var code = response.status;
	if ((code < 200 || code > 299) && code != 0) {
		throw "Failed to save. URL: '" + url + "' returned HTTP " + code;
	}
	var txt = response.responseText;
	return txt;
}

function httpGet(url) {
    var response = new XMLHttpRequest();
    response.open("GET", url, false);
    response.send("");	
    // check code (200-299 is ok)
    var code = response.status;
    if ((code < 200 || code > 299) && code != 0) {
    	throw "Failed to save. URL: '" + url + "' returned HTTP " + code;
    }
    var txt = response.responseText;
    return txt;
}

function jsonGet(url) {
    var txt = httpGet(url);
    return eval("(" + txt + ")");
}

var columns = [document.getElementById("column1"), 
               document.getElementById("column2"), 
               document.getElementById("column3")];

var defaultWidgetSettings = {
	color : "grey",
	alpha : 100
}

var stubWidget = {
	color: defaultWidgetSettings.color,
	alpha: defaultWidgetSettings.alpha,
	html : "<img src='../img/loading.gif' class='loading-img'/>"
};

var widgetElements = [];
var refreshInterval;

function getProfile() {
	var url = local ? "profile.json" : "services/getprofile.php";
	var profile = jsonGet(url);
	if (!profile) {
		return profile;
	}
	//var profile = profiles && profiles.length > 0 ? profiles[0] : null;
	// URI decode all keys and values
	for (var name in profile) {
		profile[name] = decodeURIComponent(profile[name]);
	}
	return profile;
}

function updateProfileValue(key, value) {
	var action = value ? "key" : "remove";
	var url = "services/setprofilevalue.php?" + action + "=" + encodeURIComponent(key);
	if (value) {
		url += "value=" + encodeURIComponent(value);
	}
	httpGet(url);
}

function getWidgetInstance(instanceId) {
	var url = local ? "widget.json" : "services/getwidgets.php?instanceID=" + instanceId;
	var widgets = jsonGet(url);
	// this appears to be returning all!!!
	if (!widgets) {
		return null;
	}
	for (var i = 0; i < widgets.length; i++) {
		if (widgets[i].instanceID == instanceId) {
			return widgets[i];
		}
	}
	return null;
//	return widgets && widgets.length > 0 ? widgets[0] : null;
}

function getWidget(widgetId) {
	var url = local ? "widget.json" : "services/getwidgets.php?widgetID=" + widgetId;
	var widgets = jsonGet(url);
	// this appears to be returning all!!!
	if (!widgets) {
		return null;
	}
	for (var i = 0; i < widgets.length; i++) {
		if (widgets[i].widgetID == widgetId) {
			return widgets[i];
		}
	}
	return null;
//	return widgets && widgets.length > 0 ? widgets[0] : null;
}

function getWidgets() {
	var url = local ? "testdata.json" : "services/getwidgets.php";
	var widgets = jsonGet(url);
	return widgets;
}

function getAvailableWidgets() {
	var url = local ? "widgetList.json" : "services/widgetlist.php?filter=unused";	
	var widgets = jsonGet(url);
	return widgets;
}

function addWidgetInstance(widgetId) {
	var url = "services/setwidget.php?widgetID=" + encodeURIComponent(widgetId);
	httpGet(url);	
}

function updateWidget(widget) {
	var url = "services/setwidget.php";
	var params = {};
	var ignore = ["reload", "dirty"];
	for (var name in widget) {
		// ignore list
		for (var i =0; i < ignore.length; i++) {
			if (name == ignore[i]) {
				continue;
			}
		}
		// dont have widgetID and instanceID
		if (name == "widgetID" && widget.instanceID) {
			continue;
		}
		var val = widget[name];
		val = (name == "removed" || name == "min") ? (val ? "1" : "0") : val;
		params[name] = val;
	}
	httpPostParams(url, params);
	if (widget.reload) {
		window.location.reload(true);
	}
}

function initWidgets(widgets) {	
	var currentX = 0;
	for (var i = 0; i < widgets.length; i++) {
		// set default color and alpha
		if (!widgets[i].color) {
			widgets[i].color = defaultWidgetSettings.color;
			widgets[i].dirty = true;
		}
		if (!widgets[i].alpha) {
			widgets[i].alpha = defaultWidgetSettings.alpha;
			widgets[i].dirty = true;
		}
		// min is coming back as a "0" string
		if (widgets[i].min) {
			widgets[i].min = widgets[i].min == "0" ? false : true;
		}
	}	
	return widgets;
}

function layoutWidgets(widgets) {
	// make sure values are set
	var layout = [];
	for (var i = 0; i < columns.length; i++) {
		layout.push([]);
	}
	// assign widgets to a column and then sort by y
	var currentX = 0;
	for (var i = 0; i < widgets.length; i++) {
		var oldX = widgets[i].x;
		widgets[i].x = widgets[i].x || currentX;
		currentX = widgets[i].x >= currentX ? widgets[i].x + 1 : currentX;		
		widgets[i].x = widgets[i].x % columns.length;
		layout[widgets[i].x].push(widgets[i]);
		if (widgets[i].x != oldX) {
			widgets[i].dirty = true;
		}
	}
	// now order each column by y
	for (var i = 0; i < columns.length; i++) {
		// order (bubble sort is easy)
		var tmp;
		for (var j = 0; j < layout[i].length; j++) {
			var oldY = layout[i][j].y;
			for (var k = j + 1; k < layout[i].length; k++) {
				if (layout[i][j].y > layout[i][k].y) {
					// swap 'em
					tmp = layout[i][j];
					layout[i][j] = layout[i][k];
					layout[i][k] = tmp;
				}
			}
			if (layout[i][j].y != j) {
				layout[i][j].y = j;
				layout[i][j].dirty = true;
			}
		}
	}
	return layout;
}

function refreshWidget(element) {
	element.content.innerHTML = "<div style='width: 160px; margin: 20px;'><center><h3>Loading</h3><img src='img/loading.gif'/></center></div>";
	var widget = element.state;
	var content = element.content;
	var loaded = getWidgetInstance(widget.instanceID);
	var html = loaded.html;
	content.innerHTML = html;
}

function createWidgetElement(widget) {
	// widget
	var element = document.createElement("li");
	element.className = "widget color-" + widget.color;
	element.state = widget;
	// header
	var head = document.createElement("div");
	head.className = "widget-head";
	element.appendChild(head);
	// title
	var title = document.createElement("h3");
	title.appendChild(document.createTextNode(widget.title));
	if (widget.titleURL) {
		title.onmouseover = function () {
			this.style.cursor = "pointer";
		};
		title.onmouseout = function () {
			this.style.cursor = "default";
		};
		title.onclick = function () {
			window.open(widget.titleURL, "_blank");
		}
	}
	head.appendChild(title);
	// content
	var content = document.createElement("div");
	content.className = "widget-content";
	element.appendChild(content);
	element.content = content;
	content.innerHTML = widget.html;
	// opacity
	element.style.opacity = parseFloat(widget.alpha / 100);
	element.style.filter = "alpha(opacity=" + parseInt(widget.alpha || 0) + ")";
	return element;
}

function loadWidgets() {
	var widgets = getWidgets();
	widgets = initWidgets(widgets);
	var toSave = [];
	widgetElements = [];
	var layout = layoutWidgets(widgets);
	for (var x = 0; x < layout.length; x++) {
		for (var y = 0; y < layout[x].length; y++) {
			var element = createWidgetElement(layout[x][y]);
			columns[x].appendChild(element);
			widgetElements.push(element);
			if (element.state.dirty) {
				toSave.push(element.state);
			}			
		}
	}
	// have any been dirtied? save them in background
	for (var i = 0; i < toSave.length; i++) {
		saveWidget(toSave[i]);
		toSave[i].dirty = false;
	}
	// clear any existing refresh intervals
	if (refreshInterval) {
		clearInterval(refreshInterval);
	}
	// create interval to refresh content
	refreshInterval = setInterval(function () {
		for (var i = 0; i < widgetElements.length; i++) {
			refreshWidget(widgetElements[i]);
		}
	}, REFRESH_RATE);
}

function saveWidget(widget) {
	if (!widget.dirty) {
		return false;
	}
	var container = {};
	for (var name in widget) {
		if (name == "html") {
			continue;
		}
		container[name] = widget[name];
	}
	updateWidget(container);
	widget.dirty = false;
	return true;
}

function addRssWidget(form) {
	var elements = form.elements || [];
	var widget = {};
	for (var i = 0; i < elements.length; i++) {
		if (!(elements[i].name && elements[i].value)) {
			continue;
		}
		widget[elements[i].name] = elements[i].value;
	}
	widget.title = widget.title || "RSS Feed";
	// title URL must have authority (http://)
	if (widget.titleURL && !(widget.titleURL.indexOf("http://") == 0 || widget.titleURL.indexOf("https://") == 0)) {
		widget.titleURL = "http://" + widget.titleURL;
	}
	valid = widget.feed;
	if (valid) {
		updateWidget(widget);
		// close form
		document.getElementById('custom-window').style.top = '-1000px';	
		// reload
		window.location.reload(true); 	
	} else {
		alert("You must specify an RSS Feed!");
	}
	return false;
}

function addWidget(stub) {
/*
	var widget = copy(stubWidget);
	widget.title = stub.title;
	widget.x = 0;
	widget.y = 0;
	widget.widgetID = stub.widgetID;
	// which column?
	var col = columns[0];
	var colKids = getElementsByClassName("widget", col);
	for (var i = 0; i < columns.length; i++) {
		var kids = getElementsByClassName("widget", columns[i]); 
		if (kids.length < colKids.length) {
			col = columns[i];
			colKids = kids;
			widget.x = i;
			widget.y = kids.length;
		}
	}
	// turn into element and append to col
	var element = createWidgetElement(widget);
	col.appendChild(element);
	// load content in background
	loadWidgetContent(widget.widgetID, element, 
		function (widget, element) {
			setTimeout(function () {iNettuts.initElement(element)}, 100);
			setTimeout(function () {saveWidget(widget)}, 500);			
		}
	);
*/
	// add to my list and reload (all)
	addWidgetInstance(stub.widgetID);
	// reload dashboard
	//reloadDashboard();	
	//reload breaks drag/drop
	window.location.reload(true);
}

function loadWidgetContent(widgetId, element, callback) {
	var loaded = getWidget(widgetId);
	var stub = element.state;
	stub.title = loaded.title;
	stub.html = loaded.html;
	stub.dirty = true;
	var newElement = createWidgetElement(stub);	
	element.parentNode.replaceChild(newElement, element);
	callback(stub, element);
}

function updateWidgetPositions() {
	// run through the columns - see if anything changed
	var toSave = [];
	// (getElementByClassName returns elements in correct order)
	var cols = getElementsByClassName("column");
	for (var x = 0; x < cols.length; x++) {
		var kids = getElementsByClassName("widget", cols[x]);
		for (var y = 0; y < kids.length; y++) {
			var state = kids[y].state;
			if (state && (state.x != x || state.y != y)) {
				state.x = x;
				state.y = y;
				state.dirty = true;
				toSave.push(state);
			}
		}		
	}
	// save changes
	for (var i = 0; i < toSave.length; i++) {
		saveWidget(toSave[i]);
	}	
}

function loadAvailableWidgetList() {
	var widgets = getAvailableWidgets();
	var ul = document.getElementById("window-list");
	clear(ul);
	// user may already have all added
	if (!widgets && widgets.length < 1) {
		ul.appendChild(document.createTextNode("No more to add"));
		return;
	}
	// load em
	for (var i = 0; i < widgets.length; i++) {
		var li = document.createElement("li");
		var a = document.createElement("a");
		a.href = "#";
		a.stub = widgets[i];
		a.onclick = function () {
			addWidget(this.stub);
			return false;
		};
		a.appendChild(document.createTextNode(widgets[i].title));
		li.appendChild(a);
		ul.appendChild(li);
	}
	// add 'custom window' option
	var li = document.createElement("li");
	var a = document.createElement("a");
	a.href = "#";
	a.stub = widgets[i];
	a.onclick = function () {
		// show custom window form		
		document.getElementById('custom-window').style.top = '0px';
		document.getElementById('change-background').style.top = '-1000px';
		return false;
	};
	a.style.fontWeight = "bold";
	a.appendChild(document.createTextNode("Custom Window"));
	li.appendChild(a);
	li.style.borderTop = "1px dashed #fff";
	ul.appendChild(li);	
}

function clearBackground() {
	updateProfileValue("background");
	var bg = document.getElementById("background");
	if (bg) {
		bg.parentNode.removeChild(bg);
	}
	document.getElementById('change-background').style.top = '-1000px';
}

function clearDashboard() {
	for (var i = 0; i < columns.length; i++) {
		clear(columns[i]);
	}
}

function reloadDashboard() {
	clearDashboard();	
	initDashboard();
	setTimeout(function () {iNettuts.init();}, 750);
}

function initDashboard() {
	loadWidgets();
	var profile = getProfile();
	var welcome = document.getElementById("welcome");
	if (profile == null) {
		// welcome note
		if (welcome) {
			welcome.style.opacity = 0.9;
			welcome.style.filter = "alpha(opacity=90)";
		}
	} else {
		// welcome
		if (welcome) {
			welcome.parentNode.removeChild(welcome);
		}
		// background		
		if (profile.background) {
			var img = document.createElement("img");
			img.id = "background";
			img.className = "background";
			img.src = profile.background;
			document.body.appendChild(img);
		}
	}
}


