/**
 * ajaxmethods.js - Client request helper for Dojo Ajax XHR, communicates with
 *                  customised Controller Plugin for Ajax in Zend Framework
 *                  Mainly using fetchView function in Onclick or similar event
 *                  to only render necessary content panes per request
 * @author Patrik Högberg
 * @version 1.0
 */

//Is this a bookmarked xhr: request (internal AJAX states) loded directly from user browser
if (window.location.hash.indexOf("/") == 1) {
	//Redirect browser to new location, to its normal URL page
	window.location = window.location.hash.substr(1);
}

//Check if we just returned from an external login, reload to base URL
if (window.location.href.indexOf("/user/loginreturn") > 0) {
	//Redirect browser to new location, to its normal URL page
	window.location = window.location.href.substr(unescape(window.location.href).indexOf("user/loginreturn"));
}

//Initialize application scope variables
var _am_state = {
		walkHistory: false,
		startUrl: window.location,
		changeUrl: true
};
var _am_menuout = 0;
var _am_menuvisible = '';
var _am_menulast = '';
var _am_loading = 0;
var _am_divtransition = 0;
var _am_dynscripts = new Array();
var _am_events = new Array();
var _am_fielddata = "";
var _am_connections = [];
var _am_popup ='';
var _am_timeout = 60000;
var _am_progress = 0;
var _am_albumimages = false;
var _am_albumslideshow = false;

function hashChanged(hash) {
	if (_am_state.changeUrl != hash) {
		if (!hash) hash = _am_state.startUrl;
		_am_state.walkHistory = true;
		fetchView(hash);
		_am_state.changeUrl = hash;
	}
}

function updateView(data, element) {
	if (!data) return;
	if (data.script_before) eval(data.script_before);
	if (typeof(data.stylesheets) != "undefined") updateExternalStyles(data.stylesheets);
	if (data.htopcontent && dojo.byId("headertopinfo"))
		dojo.byId("headertopinfo").innerHTML = data.htopcontent;
	if (data.menucontent) {
		if (data.menuchannel && dojo.byId("headerdmenu_" + data.menuchannel)) {
			for (i = 0; i < _am_events['tabs'].length; i++)
				dojo.disconnect(_am_events['tabs'][i]);
			_am_events['tabs'].length = 0;
			dojo.byId("headerdmenu_" + data.menuchannel).innerHTML = data.menucontent;
			attachEvents();
		} else if (dojo.byId("menucontentback1"))
			dojo.byId("menucontentback1").innerHTML = data.menucontent;
	}
	if (data.tabscontent) {
		if (_am_events['tabs']) {
			for (i = 0; i < _am_events['tabs'].length; i++)
				dojo.disconnect(_am_events['tabs'][i]);
			_am_events['tabs'].length = 0;
		}
		var tabscontent = dojo.byId("headertabscontainer");
		if (!tabscontent) tabscontent = dojo.byId("headertabscontainer_fb");
		if (tabscontent) tabscontent.innerHTML = data.tabscontent;
		attachEvents();
	}
	if (data.usercontent && dojo.byId("headerusers"))
		dojo.byId("headerusers").innerHTML = data.usercontent;
	if (typeof(data.viewcontent) != "undefined") {
		if (typeof(element) != "undefined") {
			var viewNode = dojo.byId(element);
			//Do not save history on these requests
			data.url = ""; 
		} else {
			var viewNode = dojo.byId('viewcontent');
		}
		var companyNode = dojo.byId('companyspace');
		if (companyNode) {
			var spaceNode3 = dojo.byId('mainspace3');
			if (data.hidecompany) {
				dojo.addClass(viewNode, 'viewcontent_company');
				companyNode.style.display = 'none';
				spaceNode3.style.display = 'none';
			}else {
				dojo.removeClass(viewNode, 'viewcontent_company');
				companyNode.style.display = '';
				spaceNode3.style.display = '';
			}
		}
		if (viewNode) {
			dojo.fadeIn({node:viewNode, duration:100}).play();
			if (viewNode.id == 'viewcontent') unloadDynObjects();
			resetScripts();
			viewNode.innerHTML = data.viewcontent;
			if (viewNode.id == 'viewcontent') {
				initialiseDijits(data.dijits);
				//Scroll content in view
				var tabsNode = dojo.byId("headertabscontainer");
				if (!tabsNode) tabsNode = dojo.byId("headertabscontainer_fb");
				if (dijit && dijit.scrollIntoView) dijit.scrollIntoView(tabsNode);
				//var topInView = dojo.byId("headertabscontainer").offsetTop;
				//if (document.body.parentNode.scrollTop > (topInView+10))
				//	window.scrollTo(0, topInView-5);
			}
			addScripts(data.viewcontent);
		}
	}
	if (data.footcontent) {
		var footer = dojo.byId("footer");
		if (footer) footer.innerHTML = data.footcontent;
	}
	if (data.title) document.title = data.title;
	if (data.script_after) eval(data.script_after);
	if (data.url) {
		if (dojo.hash && !_am_state.walkHistory) {
			_am_state.changeUrl = data.url
			dojo.hash(data.url);
		}
		_am_state.walkHistory = false;
	}
}

function addScripts(content) {
	try {
		var findScripts = /(?:<script.*?>)((?:\s|.)*?)(?:<\/script>)/img;
		var findScriptContent = /(<script.*?>)((?:\s|.)*?)(<\/script>)/im;
		var findSrcTag = /src=["'](.*?)['"]/i;
		//Create an array containing all script tags (with content) found in the supplied string
		var scriptContent = content.match(findScripts);
		if (scriptContent) {
			for (var s = 0; s < scriptContent.length; s++) {
				var thisScript = scriptContent[s];
				var scriptOpening = thisScript.match(findScriptContent)[1];
				var scriptText = thisScript.match(findScriptContent)[2];
				var scriptSrc = scriptOpening.match(findSrcTag);
				//alert(scriptSrc);
				var newScript = document.createElement('script');
				newScript.type			= 'text/javascript';
				newScript.language		= 'JavaScript';
				newScript.text			= scriptText;
				//alert(thisScript + " " + newScript.text);
				if (scriptSrc) newScript.src = scriptSrc[1];
				document.getElementsByTagName("head")[0].appendChild(newScript);
				_am_dynscripts[_am_dynscripts.length] = newScript;
			}
		}
	} catch(e) {
		alert(e);
	}
}

function resetScripts() {
	for (var i = 0; i < _am_dynscripts.length; i++) {
		if (_am_dynscripts[i] && _am_dynscripts[i].parentNode)
			_am_dynscripts[i].parentNode.removeChild(_am_dynscripts[i]);
	}
	_am_dynscripts.length = 0;
}

function updateExternalStyles(stylesheets) {
	if (document.styleSheets) {

		//Remove loaded stylesheets that are not in the calling object
		for (var i = document.styleSheets.length-1; i >= 0; i--) {
			var sheet = document.styleSheets[i];
			if (sheet.href) {
				var found = false;
				for (var j = 0; j < stylesheets.styles; j++) {
					newhref = eval('stylesheets.style' + j + '.href');
					if (sheet.href.indexOf(newhref) != -1) {
						found = true;
						break;
					}
				}
				if (!found && sheet.ownerNode) {
					//sheet.ownerNode.parentNode.removeChild(sheet.ownerNode);
				}
			}
		}

		//Add missing stylesheets
		for (var i = 0; i < stylesheets.styles; i++) {
			newhref = eval('stylesheets.style' + i + '.href');
			newmedia = eval('stylesheets.style' + i + '.media');
			var found = false;
			for (var j = 0; j < document.styleSheets.length; j++) {
				var sheet = document.styleSheets[j];
				if (sheet.href && sheet.href.indexOf(newhref) != -1) {
					found = true;
					break;
				}
			}
			if (!found) {
				var ss = document.createElement("link");
				ss.type = "text/css";
				ss.rel = "stylesheet";
				ss.href = escape(newhref);
				ss.media.mediaText = newmedia;
				document.getElementsByTagName("head")[0].appendChild(ss);
			}
		}
	}
}

function initialiseDijits(dijits) {
	if (dijits) {
		dojo.forEach(dijits, function(info) {
			dojo.require(info.params.dojoType);
	        var n = dojo.byId(info.id);
	        if (null != n) {
	            dojo.attr(n, dojo.mixin({id: info.id}, info.params));
	        }
	    });
		if (dojo.parser.parse) dojo.parser.parse();
	}

}

function unloadDynObjects() {
	if (dijit.registry) 
		dijit.registry.forEach(function(w) {
			w.destroy();
		});
	//if (typeof(fileUploader) != undefined) { fileUploader.destroy(); }
	//dojo.io.script.remove('tinyMCE');
	if (tinyMCE)
		try {
			tinyMCE.execCommand("mceRemoveControl", false, "profile_text");
		} catch (e) {
			;
		}
}

function fetchView(fetchUrl, mItem, formid) {
	if (_am_loading) return false;
	var hostname = window.location.protocol.toLowerCase() + "//" + window.location.host.toLowerCase();
	if (fetchUrl.indexOf("://") > 0 && fetchUrl.toLowerCase().indexOf(hostname) == -1) return false;
	
	var mItem = dojo.byId(mItem);
	var imgNew = dojo.byId('_am_img_status');
	
	var postParams = { 
		url: fetchUrl,
		form: formid,
		content: {'menu_channel':_am_menuvisible.substr(12)},
		handleAs: "json",
		load: function(data) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			if (data.status && data.status == "redirect") {
				var winRef = window.open(data.location, "_am_popup");
				//fetchView("/");
			} else {
				var nodeCollection = dojo.query('li[class~="selected"]', 'menucontent');
				dojo.forEach(nodeCollection, function(node, index, arr) {
					dojo.removeClass(node, "selected");
				});
				var node = dojo.byId("_am_img_status");
				if (node) mItem.removeChild(node);
				if (!data.menuchannel) {
					//Try to retrieve the channel for this page to update the menu accordingly
					var menuNode = dojo.byId("headerdmenucontainer");
					//alert(menuNode);
					if (menuNode) {
						var hostname = window.location.protocol + "//" + window.location.host;
						if (fetchUrl.indexOf(hostname) == 0) var url = fetchUrl.substr(hostname.length);
						else url = fetchUrl;
						url = url.split("/");
						if (url.length>2) url = "/" + url[1] + "/" + url[2];
						else if (url.length == 2) url = "/" + url[1];
						else url = url = url[0];
						var nodes = dojo.query('a[href$="' + url + '"]', "headerdmenucontainer");
						dojo.forEach(nodes, function(node, index, arr) {
							//alert(node + ' ' + index + ' ' + arr);
							//_am_menuvisible = node.parentNode.parentNode.parentNode.id;
							//alert(node.parentNode.parentNode.parentNode.parentNode.parentNode.id);
							_am_menuvisible = node.parentNode.parentNode.parentNode.parentNode.parentNode.id;
						});
					}
				}
				updateView(data);
				//if (!data.menucontent && mItem) {
				//	if (mItem.childNodes.length > 0) {
				//		var node = dojo.byId("_am_img_status");
				//		if (node) mItem.removeChild(node);
				//	}
				//}
			}
		},
		error: function(error, ioArgs) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			var msg = "HTTP status code: " + ioArgs.xhr.status;
            if (error.message) msg = msg + "<br>Error Message:  " + error.message;
            if (error.fileName) msg = msg + "<br>File Name:  " + error.fileName;
            if (error.lineNumber) msg = msg + "<br>Line Number:  " + error.lineNumber;
            if (error.stack) msg = msg + "<br><hr>SERVER RESPONSE<hr>" + nl2br(str_replace('\\n', '', error.stack));
            console.debug(msg);
			dojo.byId("viewcontent").innerHTML = msg;
			if (mItem && imgNew) mItem.removeChild(imgNew);
		}, 
		timeout: _am_timeout,
		headers: { 
			"X-Requested-With": "XMLHttpRequest" 
		},
		preventCache:true
	};

	//Detect button used to fetch view.
	if (dojo && dojo.byId("viewcontent")) {
		//Get the event object
		var event = window.event || function(cx) {
			if (typeof Event != "undefined" && cx) {
				for(var ii=0; ii<cx.arguments.length; ii++)
					if (cx.arguments[ii] instanceof Event) return cx.arguments[ii];
				return arguments.callee(cx.caller);
			}
			return null;
		} (arguments.callee.caller);

		//Detect which mouse button
		var button = "LEFT";
		if (event)
			if (event.which == null && event.button)
				/* IE case */
				button = (event.button < 2) ? "LEFT" :
						((event.button == 4) ? "MIDDLE" : "RIGHT");
			else if (event.metaKey) button = "MIDDLE";
			else if (event.which) button = (event.which < 2) ? "LEFT" :
						((event.which == 2) ? "MIDDLE" : "RIGHT");

		if (button == "LEFT") {
			//Normal click, update loading in progress status
			if (mItem && !imgNew) {
				imgNew = document.createElement('img');
				imgNew.id = '_am_img_status';
				imgNew.src = '/images/status/working_small.gif';
				imgNew.width = 16;
				imgNew.height = 16;
				imgNew.style.position = 'absolute';
				imgNew.style.top = (mItem.offsetTop - mItem.offsetTop) + "px";
				imgNew.style.left = (mItem.offsetWidth - 20) + "px";
				mItem.appendChild(imgNew);
			}
			//Create the XHR request;
			_am_loading = setTimeout('_am_loading = 0;', _am_timeout);
			if (postParams.length<2000) dojo.xhrGet(postParams);
			else dojo.xhrPost(postParams);
			setTimeout('showSlowAction();', 500);
			//Prevent the normal link to be processed
			if (event)
				if (event.preventDefault)
					event.preventDefault();
				else
					event.returnValue= false;
			return false;
		} else return true;
	}
}

function showSlowAction(viewNode) {
	if (_am_loading != 0) {
		if (!viewNode) viewNode = dojo.byId('viewcontent');
		else viewNode = dojo.byId(viewNode);
		dojo.fadeOut({node: viewNode, duration:100,
			onEnd: function() {
				//Scroll content in view
				try {
					var tabsNode = dojo.byId("headertabscontainer");
					if (!tabsNode) tabsNode = dojo.byId("headertabscontainer_fb");
					if (dijit) dijit.scrollIntoView(tabsNode);
				} catch(e) {
					;
				}
				//var topInView = dojo.byId("headertabscontainer").offsetTop;
				//if (document.body.parentNode.scrollTop > (topInView+10))
				//	window.scrollTo(0, topInView-5);
				
				//Fade in progress information until content have completely been retrieved
				if (_am_loading != 0) {
					dojo.fadeIn({node:viewNode, duration:100}).play();
					var w = viewNode.offsetWidth / 2;
					var p = "<div style='position:absolute; display:none; border:silver 2px solid; height:5px; width:200px; left:" + (w-100) + "px; top:120px;'><div id='submit_progress' style='height:5px; width:0px; background-color:silver;'></div></div><br>";
					viewNode.innerHTML = p + "<img style='margin:" + w + "px;' src='/images/status/progress.gif' />";
					//viewNode.innerHTML = "<img style=\'margin:200px;\' src=\'/images/status/progress.gif\' />";
				}
			}
		}).play();
	}
}

function dojoloaded() {
	//Subscribe to hash changes
	dojo.subscribe("/dojo/hashchange", this, hashChanged);
}

function submitForm(targeturl, formid, param, viewNode, params) {
	if (_am_loading) return false;
	_am_loading = setTimeout('_am_loading = 0;', _am_timeout);
	if (!params) params = {'content_option':param};
    dojo.xhrPost ({
		url: targeturl,
		handleAs: "json",
		content: params,
		form: formid,
		load: function (data) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			if (data.result && data.result == "resubmit") {
				clearTimeout(_am_progress);
				updateProgress(data.timeleft, data.scale);
				submitForm(targeturl, null, param, viewNode, data.params);
			} else {
				updateView(data, viewNode);
			}
		},
		error: function (error) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			dojo.byId("viewcontent").innerHTML = error;
			console.error('Url: ', targeturl);
		    console.error('Error: ', error);
		},
		timeout: _am_timeout,
		headers: {
			"X-Requested-With": "XMLHttpRequest"
		}

    });

	if (formid != null) {
		if (typeof(viewNode) == 'undefined') viewNode = 'viewcontent';
		//dojo.fadeOut({node: viewNode, duration:300,
		//	onEnd: function() {
				//Scroll content in view
				var tabsNode = dojo.byId("headertabscontainer");
				if (!tabsNode) tabsNode = dojo.byId("headertabscontainer_fb");
				if (dijit) dijit.scrollIntoView(tabsNode);
				//var topInView = dojo.byId("headertabscontainer").offsetTop;
				//if (document.body.parentNode.scrollTop > (topInView+10))
				//	window.scrollTo(0, topInView-5);

				//Fade in progress information until content have completely been retrieved
		//		if (_am_loading != 0) {
		//			dojo.fadeIn({node:viewNode, duration:300}).play();
		//			var n = dojo.byId(viewNode);
		//			var w = n.offsetWidth / 2;
		//			var p = "<div style='position:absolute; display:none; border:silver 2px solid; height:5px; width:200px; left:" + (w-100) + "px; top:120px;'><div id='submit_progress' style='height:5px; width:0px; background-color:silver;'></div></div><br>";
		//			n.innerHTML = p + "<img style='margin:" + w + "px;' src='/images/status/progress.gif' />";
		//		}
		//	}
		//}).play();
		setTimeout('showSlowAction(dojo.byId("' + viewNode + '"));', 500);
	}

    return false;
}

function updateProgress(timeleft, scale) {
	var submit_progress = dojo.byId('submit_progress');

	if (submit_progress) {
		submit_progress.parentNode.style.display = "block";
		var steps = submit_progress.parentNode.clientWidth / scale;
		//if (!timeleft) timeleft = Math.round((submit_progress.parentNode.clientWidth - submit_progress.clientWidth) / steps);
		if (submit_progress.parentNode.clientWidth - (timeleft * steps) >= submit_progress.parentNode.clientWidth) {
			submit_progress.parentNode.style.display = "none";
			_am_progress = 0;
		} else {
			submit_progress.parentNode.style.display = "block";
			submit_progress.style.width = (submit_progress.parentNode.clientWidth - (timeleft * steps)) + "px";
			_am_progress = setTimeout("updateProgress(" + (timeleft-1) +", " + scale + ")", 1000);
		}
	}
}

function submitLogin(targeturl, formid) {
	dojo.byId('LoginButton').disabled = true;
	var form = dojo.byId(formid);
	if (_am_loading) return false;
	_am_loading = setTimeout('_am_loading = 0;', _am_timeout);
	var loginNode = dojo.byId('fieldset-login_group');
	var statusMessage = dojo.byId('statusMessageWaiting').value;

	dojo.fadeOut({node: loginNode, duration:100,
		onEnd: function() {
			if (_am_loading != 0) {
				dojo.fadeIn({node:loginNode, duration:100}).play();
				loginNode.innerHTML = statusMessage + "<br><br><img style='margin-left:200px;' src='/images/status/progress.gif' />";
			}
		}
	}).play();

	dojo.io.iframe.send({
		url: targeturl,
		method: "get",
		handleAs: "text",
		form: form,
		load: function (data, ioArgs) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			handleLogin(dojo.fromJson(data));
		},
		error: function (error, ioArgs) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			dojo.fadeIn({node:loginNode, duration:300}).play();
			var errorMessage = dojo.byId('errorMessage').value;
			if (dojo.byId('debugError')) errorMessage = errorMessage + '<hr>Message: ' + error.message + '<hr>fileName: ' + error.fileName;
			loginNode.innerHTML = errorMessage;
		}
	});
	return false;
}

function ajaxForward (targeturl) {
	if (_am_loading) return false;
	_am_loading = setTimeout('_am_loading = 0;', _am_timeout);
	dojo.xhrGet ({
		url: targeturl,
		handleAs: "json",
		handle: function (data) {
			clearTimeout(_am_loading);
			_am_loading = 0;
			updateView(data);
		},
		timeout: _am_timeout,
		headers: {
			"X-Requested-With": "XMLHttpRequest"
		}

	});
	return false;
}

function handleLogin(data) {
	//alert('Mode: ' + data.mode + ' Param: ' +data.param+ ' External: '+data.external);
	//if (data.mode == 'setup_needed') {
		if (!data.external) ajaxForward(data.param);
		else window.location.href = data.param;
	//}
}

function showDiv(nodeId, hideClass, relativeNode, noFade) {
	if (hideClass) {
		var nodeCollection = dojo.query('*[class="' + hideClass + '"]');
		dojo.forEach(nodeCollection, function(node, index, arr) {
			if (nodeId != node.id) if (node.style.display != "none") hideDiv(node, "", noFade);
		});
	}
	var node = dojo.byId(nodeId);
	if (node && node.style.display == "none") {
		if (noFade) {
			node.style.display= "inline";
		} else {
			_am_divtransition = dojo.fadeIn({
				node: node,
				onBegin: function() {
					addOffset = 15;
					if (relativeNode) node.style.top = addOffset + relativeNode.offsetTop + relativeNode.offsetParent.offsetTop + "px";
					if (relativeNode) {
						var relPos = dojo.position(relativeNode, true);
						var relPos2 = dojo.position(relativeNode.parentNode.parentNode.parentNode.parentNode.parentNode, true);
						//alert(relPos.y - relPos2.y);
						node.style.top = addOffset + (relPos.y-relPos2.y) + "px";
						//dojo.style(node, {top:(relPos.y - relPos2)+'px'});
					}					node.style.display= "inline";
				},
				duration: 300
			});
			_am_divtransition.play();
		}
	} else {
		hideDiv(nodeId, "", noFade);
	}
	return false;
}

function hideDiv(nodeId, codeAfter, noFade) {
	var node = dojo.byId(nodeId);
	if (node) {
		if (noFade) {
			node.style.display = "none";
		} else {
			_am_divtransition = dojo.fadeOut({
				node: node,
				onAnimate: function(values){
					if (node && node.style.display == "none") {
						//_am_divtransition.stop();
						this.stop();
					}
				},
				onBegin: function() {
					//if (relativeNode) node.style.top = 30 + relativeNode.offsetParent.offsetParent.offsetTop + "px";
					//if (relativeNode && relativeNode.parentNode.nodeName == "DIV") var addOffset = 25;
					//else var addOffset = 30;
					addOffset = 15;
					if (relativeNode) node.style.top = addOffset + relativeNode.offsetTop + relativeNode.offsetParent.offsetTop + "px";
					if (relativeNode) {
						var relPos = dojo.position(relativeNode, true);
						var relPos2 = dojo.position(relativeNode.parentNode.parentNode.parentNode.parentNode.parentNode, true);
						//alert(relPos.y - relPos2.y);
						node.style.top = addOffset + (relPos.y-relPos2.y) + "px";
						//dojo.style(node, {top:(relPos.y - relPos2)+'px'});
					}
					node.style.display= "inline";
				},
				onEnd: function() {
					if (node) node.style.display = "none";
					if (codeAfter) eval(codeAfter);
				},
				duration: 300
			});
			_am_divtransition.play();
		}
	}
	return false;
}

function animateClick(node) {
	if (dojo) {
		var endColor = node.style.backgroundColor;
		dojo.animateProperty({
			node: node,
			delay: 0,
			properties:{
				backgroundColor: {start: "#dad8d2", end:"#FFF"}
			},
			duration:150,
			onEnd: function() {node.style.backgroundColor = endColor;}
		}).play();

	}
}

function tabClick(e) {
	var href = "/";
	try {
		if (this.href) {href = this.href;}
		else if (e.target.href) {href = e.target.href;}
		if (href == "") href = "/";
		animateClick(e.target);
		fetchView(href);
	} catch (e) {
		console.log("Error loading XHR (" + e + ") in onclick event handler!");
	}
	if (e.preventDefault) e.preventDefault();
	else if (window.event) window.event.returnValue = false;
}

function tabOver(e) {
	var id = "";
	try {
		if (this.id) {id = this.id;}
		else if (e.target.id) {id = e.target.id;}
		if (id != "") {
			id = 'headerdmenu_' + id.substr(8);
			//console.log("tabOver: " + _am_menuvisible + " == " + id + " " + _am_menuout);
			if (_am_menuvisible == id && _am_menuout) {
				clearTimeout(_am_menuout);
				_am_menuout = 0;
			} else {
				dojo.query(".headerdmenu").forEach(function(n) {
					if (n.id != id)	hideDiv(n.id, "", true);
				});
				if (_am_menuvisible != "" && _am_menuvisible != id && dojo.byId(_am_menuvisible) && dojo.byId(_am_menuvisible).style.display != "none")
					hideDiv(_am_menuvisible, "", true);
				if (dojo.byId(id)) dojo.byId(id).style.display = "none";
				setTimeout("showDiv('" + id + "'); _am_menuvisible = '" + id + "';", 1);
				//console.log("tabOver: Shown");
			}
		}
	} catch (e) {
		console.log("Error while displaying menu (" + e + ") in onmouseover event handler!");
	}
	if (e.preventDefault) e.preventDefault();
	else if (window.event) window.event.returnValue = false;
}

function tabOut(e) {
	var id = "";
	try {
		if (this.id) {id = this.id;}
		else if (e.target.id) {id = e.target.id;}
		if (id != "") {
			//console.log("tabOut: " + 'headerdmenu_' + id.substr(8) + " " + _am_menuout);
			if (_am_menuout) clearTimeout(_am_menuout);
			_am_menuout = setTimeout('_am_menuout = 0; hideDiv("headerdmenu_' + id.substr(8) + '", "", true);', 200);
		}
	} catch (e) {
		console.log("Error while hiding menu (" + e + ") in onmouseout event handler!");
	}
	if (e.preventDefault) e.preventDefault();
	else if (window.event) window.event.returnValue = false;
}

function closeMenu(e) {
	var id = "";
	try {
		if (this.id) { id = this.id; }
		else if (e.target.id) { id = e.target.id; }
		if (id != "") {
			console.log("tabOut: " + 'headerdmenu_' + id.substr(11) + " " + _am_menuout);
			if (_am_menuout) clearTimeout(_am_menuout);
			hideDiv("headerdmenu_" + id.substr(11), "", true);
		}
	} catch (e) {
		console.log("Error while hiding menu (" + e + ") in onmouseout event handler!");
	}
	e.preventDefault();
}

function menuOver(e) {
	var id = "";
	try {
		if (this.id) {id = this.id;}
		else if (e.target.id) {id = e.target.id;}
		if (id != "") {
			if (_am_menuout) {
				clearTimeout(_am_menuout);
				_am_menuout = 0;
			}
		}
	} catch (e) {
		console.log("Error while hiding menu (" + e + ") in onmouseout event handler!");
	}
	if (e.preventDefault) e.preventDefault();
	else if (window.event) window.event.returnValue = false;
}

function menuOut(e) {
	var id = "";
	try {
		if (this.id) {id = this.id;}
		else if (e.target.id) {id = e.target.id;}
		if (id != "") {
			if (!_am_menuout) _am_menuout = setTimeout('hideDiv("' + id +'", "_am_menuout = 0;", true);', 200);
		}
	} catch (e) {
		console.log("Error while hiding menu (" + e + ") in onmouseout event handler!");
	}
	if (e.preventDefault) e.preventDefault();
	else if (window.event) window.event.returnValue = false;
}

function attachEvents() {
	if (!_am_events['tabs']) _am_events['tabs'] = new Array;
	if (_am_events['tabs'].length == 0) {
		dojo.query(".headertab a").forEach(function(n) {
			_am_events['tabs'][_am_events['tabs'].length] = dojo.connect(n, "onclick", tabClick);
			_am_events['tabs'][_am_events['tabs'].length] = dojo.connect(n, "onmouseover", tabOver);
			_am_events['tabs'][_am_events['tabs'].length] = dojo.connect(n, "onmouseout", tabOut);
			var menu_node = dojo.byId('headerdmenu_' + n.id.substr(8));
			if (menu_node) {
				//menu_node.style.left = parseInt((n.parentNode.offsetLeft - 13) - n.parentNode.parentNode.offsetLeft) + 'px';
				menu_node.style.left = ((dojo.coords(n.parentNode).x - 13) - dojo.coords(n.parentNode.parentNode).x) + 'px';
				var newtab_node = dojo.byId('headerdmenutab_' + n.id.substr(8));
				var newtabclose_node = dojo.byId('closedmenu_' + n.id.substr(8));
				var newtabarrow_node = dojo.byId('headerdmenutabarrow_' + n.id.substr(8));
				newtab_node.style.width = parseInt(n.parentNode.offsetWidth + 4) + 'px';
				newtab_node.innerHTML = n.parentNode.innerHTML;
				_am_events['tabs'][_am_events['tabs'].length] = dojo.connect(newtab_node, "onclick", tabClick);
				newtabclose_node.style.width = parseInt(230 - n.parentNode.offsetWidth - 4) + 'px';
				newtabarrow_node.style.left = parseInt(8 + (n.parentNode.offsetWidth / 2)) + 'px';
			}
		});
		dojo.query(".headerdmenutabright").forEach(function(n) {
			_am_events['tabs'][_am_events['tabs'].length] = dojo.connect(n, "onmouseover", closeMenu);
		});
	}
	if (!_am_events['dmenu']) _am_events['dmenu'] = new Array;
	if (_am_events['dmenu'].length == 0) {
		dojo.query(".headerdmenu").forEach(function(n) {
			hideDiv(n.id, "", true);
			_am_events['dmenu'][_am_events['dmenu'].length] = dojo.connect(n, "onmouseover", menuOver);
			_am_events['dmenu'][_am_events['dmenu'].length] = dojo.connect(n, "onmouseout", menuOut);
		});
	}
}

function nl2br(str, is_xhtml) { 
    breakTag = '<br />';
    if (typeof is_xhtml != 'undefined' && !is_xhtml) {
        breakTag = '<br>';
    }
    return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
    return sa ? s : s[0];
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function normalize_string(s) {
	var a = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýýþÿ\u0154\u0155';
	var b = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuuyybyrr';
    for (var i = 0; i < a.length; i++) {
		var sRegExInput = new RegExp(a.substr(i, 1), "g");
        s = s.replace(sRegExInput, b.substr(i, 1));
    }
	s = s.toLowerCase();
	s = s.replace(/[^a-z0-9\-_\s]/g, '');
	s = s.replace(/[\s_][\s_]*/g, '_');
	return s;
}

function replyMessage(msgId, title) {
	var nodeList = dojo.query('*[name="content"]');
	if (nodeList.length > 0) {
		var contentNode = nodeList[0];
		var messageNode = dojo.byId(msgId);
		if (messageNode) {
			//var s = messageNode.innerHTML.replace(/\<br\s*?.*?\>/gi, "\n");
			var s = messageNode.innerHTML.replace(/\<br[^>]*?>/gi, "\n");
			//Remove any quotes from the source message
			s = s.replace(/(<div[\s\S]class=['"]?quote_title['"]?>([^>]+?)>)/ig, "");
			s = s.replace(/(<div[\s\S]class=['"]?quote_message['"]?>([^>]+?)>)/ig, "");
			s = s.replace(/(<div[\s\S]class=['"]?quote['"]?>([^>]+?)>)/ig, "");
			//Remove all html tags
			s = s.replace(/(<([^>]+)>)/ig, "");
			//Replace &nbsp; with normal space
			s = s.replace(/&nbsp;/ig, " ");
			//Trim string
			s = trim(s);
			//Remove triple line breaks
			s = s.replace(/\n\s*\n\s*\n/g, "\n\n");
			//Convert linebreaks to html breaks
			s = s.replace(/\n/g, "<br />");
			if (tinyMCE) {
				tinyMCE.triggerSave();
				s = "&nbsp;<div class='quote'>" + "<div class='quote_title'>" + title + "</div>" + "<div class='quote_message'>" + s + "</div></div>";
				s = (contentNode.value==''?'':'<br />') + s + "<br clear='all' />";
				tinyMCE.execCommand('mceInsertRawHTML', false, s);
			} else {
				contentNode.value=contentNode.value+(contentNode.value==''?'':'\r\n')+author+' skrev '+published+' följande:\r\n[citat]\r\n'+content+'\r\n[/citat]\r\n';
				contentNode.focus()
			}
		var topPos = 0;
		node = dojo.byId('forum_thread_reply_form');
		if (node.offsetParent)
			do {topPos += node.offsetTop;}
			while (node = node.offsetParent)
		}
		window.scrollTo(null, topPos);
	}
	return false;
}

function switchAds() {
	var MAX_used = "";
	var params = "?r=switch";
	var ifrm = dojo.byId('comp_frame');
	if (ifrm.contentDocument)
		if (ifrm.contentDocument.MAX_used) MAX_used = ifrm.contentDocument.MAX_used;
	if (document.referrer) params += "&referer=" + escape(document.referrer);
	if (MAX_used) params += "&max_used=" + escape(MAX_used);
	ifrm.src = "/scripts/compframe.php" + params;
	return false;
}


function albumView(image, url, animate) {
	if (image && _am_albumimages && _am_albumimages.id[image-1]) {
		if (!_am_albumimages.current || image != _am_albumimages.current) {
			_am_albumimages.current = image;
			image = image - 1;
			dojo.byId("photo_image").href = _am_albumimages.image[image];
			if (!animate) dojo.byId("photo_normalimage").src = _am_albumimages.normalimage[image];
			else {
				dojo.fadeOut({
					node: "photo_normalimage",
					onEnd: function() {
						dojo.byId("photo_normalimage").src = _am_albumimages.normalimage[image];
						dojo.fadeIn({node:"photo_normalimage", duration:200}).play();
					},
					duration: 200
				}).play();
			}
			dojo.byId("photo_normalimage").alt = _am_albumimages.description[image];
			dojo.byId("photo_normalimage").title = _am_albumimages.description[image];
			dojo.byId("photo_itemtitle").innerHTML = sprintf(_am_albumimages.photoitemtitle, _am_albumimages.current, _am_albumimages.id.length);
			dojo.byId("photo_zoom").href = _am_albumimages.image[image];
			dojo.byId("photo_description").innerHTML = _am_albumimages.description[image] + "&nbsp;";
			dojo.byId("photo_views").innerHTML = sprintf(_am_albumimages.photoviewstitle, _am_albumimages.views[image]);
			dojo.byId("photo_created").innerHTML = _am_albumimages.created[image];
			dojo.byId("photo_updated").innerHTML = _am_albumimages.updated[image];
			if (_am_albumimages.roomtitle[image].length > 0) {
				dojo.byId("photo_roomdisplay").style.display = "inline";
				dojo.byId("photo_roomtitle").innerHTML = _am_albumimages.roomtitle[image];
				if (_am_albumimages.styletitle[image] == "") var style = "";
				else var style = sprintf(_am_albumimages.photostyletitle, _am_albumimages.styletitle[image]);
				dojo.byId("photo_styletitle").innerHTML = style;
			} else {
				dojo.byId("photo_roomdisplay").style.display = "none";
			}
			if (_am_albumimages.tags[image].length > 0) {
				dojo.byId("photo_tagsdisplay").style.display = "inline";
				dojo.byId("photo_tags").innerHTML = _am_albumimages.tags[image];
			} else {
				dojo.byId("photo_tagsdisplay").style.display = "none";
			}
			dojo.byId("imagereplynr").value = _am_albumimages.id[image];
			dojo.byId("imagereplylabel").innerHTML = _am_albumimages.replylabel[image];

			dojo.xhrGet ({
				url: "/user/albumshown/album/" + _am_albumimages.album + "/image/" + _am_albumimages.id[image],
				headers: {"X-Requested-With": "XMLHttpRequest"}
			});

			albumPaginator();
		}
		return false;
	} else {
		return fetchView(url);
	}
}

function albumPaginator() {
	if (dojo.byId("photo_pages")) {
		var pageRange = 5;
		if (_am_albumimages.current) var startPage = _am_albumimages.current - Math.round(((pageRange - 1) / 2));
		else var startPage = 1;
		if (startPage < 1) startPage = 1;
		var endPage = startPage + (pageRange - 1);
		if (endPage > _am_albumimages.id.length) {
			endPage = _am_albumimages.id.length;
			if (endPage-startPage < (pageRange - 1)) startPage = endPage - (pageRange - 1);
			if (startPage < 1) startPage = 1;
		}
		var link = "/user/albumview/album/" + _am_albumimages.album + "/image/";
		var pages = "";
		for (var i=startPage; i <= endPage; i++) {
			if (i == _am_albumimages.current) pages += "<a class='current' href=\"" + link + i + "\" onclick=\"return albumView(" + i + ", this.href);\">" + i + "</a> ";
			else pages += "<a href=\"" + link + i + "\" onclick=\"return albumView(" + i + ", this.href);\">" + i + "</a> ";
		}
		dojo.byId("photo_pages").innerHTML = pages;

		//Remove old onclick events
		dojo.forEach(_am_connections, dojo.disconnect);
		_am_connections.length = 0;

		//Reconnect onclick events
		dojo.byId("paginate_previous").onclick = "";
		if (_am_albumimages.current > 1) {
			dojo.byId("paginate_previous").href = link + (_am_albumimages.current - 1);
			_am_connections[_am_connections.length] = dojo.connect(dojo.byId("paginate_previous"), "onclick", function (e) {
				albumView(_am_albumimages.current - 1, this.href);
				if (e.preventDefault) e.preventDefault();
				else window.event.returnValue = false;
			});
			dojo.byId("paginate_previousimg").className = "";
		} else {
			dojo.byId("paginate_previous").href = link + "1";
			_am_connections[_am_connections.length] = dojo.connect(dojo.byId("paginate_previous"), "onclick", function (e) {
				albumView(1, this.href);
				if (e.preventDefault) e.preventDefault();
				else window.event.returnValue = false;
			});
			dojo.byId("paginate_previousimg").className = "disabled";
		}

		dojo.byId("paginate_next").onclick = "";
		if (_am_albumimages.current < _am_albumimages.id.length) {
			dojo.byId("paginate_next").href = link + (_am_albumimages.current + 1);
			_am_connections[_am_connections.length] = dojo.connect(dojo.byId("paginate_next"), "onclick", function (e) {
				albumView(_am_albumimages.current + 1, this.href);
				if (e.preventDefault) e.preventDefault();
				else window.event.returnValue = false;
			});
			dojo.byId("paginate_nextimg").className = "";
		} else {
			dojo.byId("paginate_next").href = link + _am_albumimages.id.length;
			_am_connections[_am_connections.length] = dojo.connect(dojo.byId("paginate_next"), "onclick", function (e) {
				albumView(_am_albumimages.id.length, this.href);
				if (e.preventDefault) e.preventDefault();
				else window.event.returnValue = false;
			});
			dojo.byId("paginate_nextimg").className = "disabled";
		}
	}
}

function albumSlideshow(image) {
	if (_am_albumimages.id.length > 1) {
		if (image > _am_albumimages.id.length) image = 1;
		var link = "/user/albumview/album/" + _am_albumimages.album + "/image/" + image;
		albumView(image, link, true);
		if (!_am_albumslideshow) {
			dojo.byId("photo_slideshowtitle").innerHTML = _am_albumimages.stoptitle;
			dojo.byId("photo_slideshowlink").onclick = "";
			if (dojo.byId("photo_slideshowlink").userClick)
				dojo.disconnect(dojo.byId("photo_slideshowlink").userClick);
			dojo.byId("photo_slideshowlink").userClick = dojo.connect(dojo.byId("photo_slideshowlink"), "onclick", function (e) {
				if (e.preventDefault) e.preventDefault();
				else window.event.returnValue = false;
				albumSlideshowStop();
			});
		}
		_am_albumslideshow = setTimeout("albumSlideshow(" + (image + 1) + ")", 3000);
	}
	return false;
}

function albumSlideshowStop() {
	clearTimeout(_am_albumslideshow);
	_am_albumslideshow = false;
	dojo.byId("photo_slideshowtitle").innerHTML = _am_albumimages.slideshowtitle;
	dojo.disconnect(dojo.byId("photo_slideshowlink").userClick);
	dojo.byId("photo_slideshowlink").userClick = dojo.connect(dojo.byId("photo_slideshowlink"), "onclick", function (e) {
		if (e.preventDefault) e.preventDefault();
		else window.event.returnValue = false;
		albumSlideshow(_am_albumimages.current);
	});
}

function albumSlimbox() {
	if (_am_albumimages.current) var startImage = _am_albumimages.current - 1;
	else var startImage = _am_albumimages.initial - 1;
	var images = [];
	for (var i = 0; i < _am_albumimages.id.length; i++) {
		if (startImage == i) var script = "";
		else var script = "<script type='text/javascript'>albumView(" + (i+1) + ", '" + _am_albumimages.image[i] + "');</script>";
		images[images.length] = [_am_albumimages.image[i], _am_albumimages.description[i] + script];
		//images[images.length] = [_am_albumimages.image[i], _am_albumimages.description[i] +'<br /><a href="' + _am_albumimages.image[i] + '">Download this image</a>' + "<script type='text/javascript'>alert('Hello')</script>"];
	}
	jQuery.slimbox(images, startImage, {overlayOpacity:0.5, overlayFadeDuration:200, resizeDuration:100, imageFadeDuration:200});
	return false;
}

/*************************************************************
 * tinyMCE auto resize fancy editor
 *************************************************************/
function setAutoResize(ed)
{
    //Function to fix iframe to document height
    fitEditor = function(ed)
    {
        var editorID = ed.id;
        var tble, frame, doc, docHeight, frameHeight;

        frame = dojo.byId(editorID+"_ifr");
        if ( frame != null )
        {
            //get the document object
            if (frame.contentDocument) doc = frame.contentDocument;
            else if (frame.contentWindow) doc = frame.contentWindow.document;
            else if (frame.document) doc = frame.document;

            if ( doc == null )
            return;

            //prevent the scrollbar from showing
            doc.body.style.overflow = "hidden";

            //Fixes the issue of the table leaving empty space below iframe
            tble = frame.parentNode.parentNode.parentNode.parentNode;
            tble.style.height = 'auto';

            frameHeight = parseInt(frame.style.height);

            //Firefox
            if ( doc.height ) docHeight = doc.height;
            //MSIE
            else docHeight = parseInt(doc.body.scrollHeight);

            //MAKE BIGGER
            if ( docHeight > frameHeight ) frame.style.height = (docHeight + 20) + "px";
            //MAKE SMALLER
            else if ( docHeight < frameHeight ) frame.style.height = Math.max((docHeight + 20), 200) + "px";
        }
    };

    //add fitEditor function to tinyMCE events
    ed.onSetContent.add( fitEditor );
    ed.onChange.add( fitEditor );
    ed.onKeyPress.add( fitEditor );

//Remaining bug: (Chrome and Opera) editor grows but doesn't shrink
}

/*************************************************************
 * printf function
 *************************************************************/
sprintfWrapper = {

	init : function () {

		if (typeof arguments == "undefined") {return null;}
		if (arguments.length < 1) {return null;}
		if (typeof arguments[0] != "string") {return null;}
		if (typeof RegExp == "undefined") {return null;}

		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;

		while (match = exp.exec(string)) {
			if (match[9]) {convCount += 1;}

			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);

		if (matches.length == 0) {return string;}
		if ((arguments.length - 1) < convCount) {return null;}

		var code = null;
		var match = null;
		var i = null;

		for (i=0; i<matches.length; i++) {

			if (matches[i].code == '%') {substitution = '%'}
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}

			newString += strings[i];
			newString += substitution;

		}
		newString += strings[i];

		return newString;

	},

	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}

sprintf = sprintfWrapper.init;

/******************************************
 * DEBUGGING FUNCTIONS
 *****************************************/

function var_dump(element, limit, depth)
{
	depth = depth?depth:0;
	limit = limit?limit:1;
	returnString = '<ol>';
	for(property in element)
	{
		//Property domConfig isn't accessable
		if (property != 'domConfig')
		{
			returnString += '<li><strong>'+ property + '</strong> <small>(' + (typeof element[property]) +')</small>';
			if (typeof element[property] == 'number' || typeof element[property] == 'boolean')
				returnString += ' : <em>' + element[property] + '</em>';
			if (typeof element[property] == 'string' && element[property])
				returnString += ': <div style="background:#C9C9C9;border:1px solid black; overflow:auto;"><code>' +
									element[property].replace(/</g, '<').replace(/>/g, '>') + '</code></div>';
			if ((typeof element[property] == 'object') && (depth <limit))
				returnString += var_dump(element[property], limit, (depth + 1));
			returnString += '</li>';
		}
	}
	returnString += '</ol>';
	return returnString;
}

