//window.name = "mainwindow";

/* Browser detect */

var mouseX;
var mouseY;

var popupmenutarget;

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
var eFocus, eFocus_form, eFocus_field;

qtipargs = {
	style: 		{ name: 'light', border: { color: '#666', radius: 5, width: 3 }, tip: true },
	show: 		{ delay: 0, ready: true, solo: true, when: { event: "focus" }, effect: { length: 0 } },
	hide: 		{ when: { event: "unfocus" }, fixed: true },
	position: 	{ corner: { target: "bottomMiddle" }, adjust: { screen: true, mouse: false } },
	content: 	{ text: "<img src='/bilder/spinner.gif' />", url: false, title: { text: false, button: false } },
	api:		{
		//beforeShow: function() { this.loadContent(this.options.content); }
		beforeRender: function(){ $("div.qtip").remove(); }
		//onHide: function(){ $(element).qtip("destroy"); }
	}
};


function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('iphone')){
	browser = "Mobile Safari"
	version = "iPhone"
}
else if (checkIt('ipod')){
	browser = "Mobile Safari"
	version = "iPod"
}
else if (checkIt('ipad')){
	browser = "Mobile Safari"
	version = "iPad"
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

/* Settings */

var hideTimeout;
var showTimeout;
var shown_layers = new Array();
var admin_edit_id;
var ajax_object;
var url,div2update;
var ajax_fitContent = false;
var ajaxReturnData = "";
var current_adminsquare = 1;

function image(query) {

	var myWidth = (screen.availWidth > 800) ? (screen.availWidth - 100) : screen.availWidth;		// if 800x600 or less, take up
	var myHeight = (screen.availHeight > 600) ? (screen.availHeight - 100) : (screen.availHeight - 70);	// the whole screen.
	if (myWidth > 1024){ myWidth = 1024; }
	if (myHeight > 768){ myHeight = 768; }
	var myLeft = Math.round((screen.availWidth - myWidth) / 2);
	var myTop = Math.round((screen.availHeight - myHeight) / 2)-25;

	if (myTop < 0) { myTop = 0; }	// bugfix for Opera
	if (screen.availHeight < 600) { myTop-=20; }

	var url = '/atlas/imagepopup.php?'+query + "&width=" + myWidth + "&height=" + myHeight;

	var slideWindow = window.open(url, 'slideshow', 'scrollbars=no,titlebar=no,location=no,status=no,toolbar=no,resizable=no,width='+myWidth+',height='+myHeight+',top='+myTop+',left='+myLeft);

	slideWindow.focus();
}
function visa(url,name){
	var nWindow = window.open(url,name,'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=400,height=600');
	nWindow.focus();
	nd();
}
function newwindow(url){
	var nWindow = window.open(url);
	nWindow.focus();
	nd();
}


function bvisa(url,name){
	var nWindow = window.open(url,name,'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=450,height=550');
	nWindow.focus();
	nd();
}
function svisa(url,name,height,width){
	var nWindow = window.open(url,name,'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width='+width+',height='+height);
	nWindow.focus();
	nd();
}
function documentation(modules, keyword, show, id){
	var nWindow = window.open("http://www.eklundh.com/atlas/help/popup/documentation.php?modules=" + modules + "&id=" + id + "&show=" + show + "&keyword=" + keyword,"documentation",'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=820,height=600');
	nWindow.focus();
	nd();
}
function quicklink(what){
	if (parent.opener){
		var el = parent.opener;
		while ( el.opener && el.name != "mainwindow") el = el.opener;
		el.location = what;
		el.focus();
	} else {
		window.open(what);
	}
}
function friendpopup(){ svisa('/member/friendspopup.php','favpop',350,250); }
function online(){ svisa('/atlas/online/','online',400,650); }
function newonline(){ svisa('/atlas/online/popup.php','online',400,240); }

function highlight(which,color){
	if (document.all||document.getElementById){
		which.style.background=color;
	}
}
function show(which, timeout) {
	nd();
	var objLayer = document.all ? document.all[which] : document.getElementById(which);
	clearTimeout(hideTimeout);
	if (objLayer){
		if (timeout) {
			showTimeout = setTimeout("show('"+which+"')", (timeout*500));
		} else {
			objLayer.style.display="block";
		}
	} else {
		alert("No such object: " + which + objLayer);
	}
}
function hide(which,timeout) {
	nd();
	var objLayer = document.all ? document.all[which] : document.getElementById(which);
	if (timeout) {
		hideTimeout = setTimeout("hide('"+which+"')", (timeout*500));
	} else {
		objLayer.style.display="none";
	}
}
function toggle(stuff) {
	nd();
	var a = stuff.split(',');
	var which;
	var objLayer;
	for (var i = 0; i < a.length; i++){
		which = a[i];
		objLayer = document.all ? document.all[which] : document.getElementById(which);
		if (objLayer.style.display == "none" || objLayer.style.display == ""){
			objLayer.style.display="block";
		} else {
			objLayer.style.display="none";
		}
		if (document.getElementById("toggle_"+which)){
			togglesrc("toggle_"+which, "/bilder/flip/flipnone.gif", "/bilder/flip/flipblock.gif");
		}
	}
}



function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImages() {
	if (document.images) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document.getElementById(changeImages.arguments[i]).src = changeImages.arguments[i+1];
		}
	}
}

var preloadFlag = false;
function preloadImages(images) {
	if (document.images) {
		var a = images.split(',');
		for (var i = 0; i < a.length; i++){
			{a[i]}_over = newImage(a[i]);
			
		}
		preloadFlag = true;
	}
}


function visByClass(className, state){
	if (state){
		$("." + className).show();
	} else {
		$("." + className).hide();
	}
}

function bbe(l){
	top.location=l;
	hide("atlas_files");
	hide("atlas_timeline");
	hide("atlas_errors");
	hide("atlas_mysql");
	hide("atlas_images");
	current_adminsquare = 1;
}

function iframeHeight(tName, mazSize){
	var the_height = document.getElementById(tName).contentWindow.document.body.scrollHeight;
	document.getElementById(tName).height = the_height;
}


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


function toggle_block(which) {
	var objLayer = document.getElementById(which);
	state = (objLayer.style.display == 'none') ? 'block' : 'none';
	objLayer.style.display = state;
	createCookie('visState_'+which, state, 365);
	if (document['flip_'+which]){
		document['flip_'+which].src = '/bilder/flip'+state+'.png';
	}
}
function getkey() {
	if (window.event.keyCode == 65 && window.event.ctrlKey){
		toggle("adminsquare");
	}
}
function togglesrc(id, a, b){
	var what = document.getElementById(id);
	var ha = "http://" + document.domain + a;
	var hb = "http://" + document.domain + b;
	//alert(what.src + " - " + a + " - " + b);
	what.src = what.src == hb ? ha : hb;
}
function activate_input(me, value){
	if (me.value == value) me.value = '';
	me.style.color = "black";
}
function deactivate_input(me, value){
	if (me.value == ''){
		me.value = value;
		me.style.color = "#999";
	}
}



function addlink(form, field){
	if (form && field){
		var arean = document.forms[form].elements[field];
	} else {
		var arean = eFocus
		var form = eFocus_form;
		var field = eFocus_field;
	}
	
	
	var allt = arean.value;

	if( document.selection ){
		var range = document.selection.createRange();
		var stored_range = range.duplicate();
		stored_range.moveToElementText(arean);
		stored_range.setEndPoint( 'EndToEnd', range );
		selstart= stored_range.text.length - range.text.length;
		selstop= selstart + range.text.length;
	}else{
		var selstart= arean.selectionStart;
		var selstop= arean.selectionEnd;
	}
	

	var nyall=''; 
	for(i=0 ; i< allt.length; i++){
		if(i >= selstart && i < selstop){
			nyall+=allt.charAt(i);
		} 
	}
	visa('/atlas/linkpopup2.php?formname=' + form + '&fieldname=' + field + '&fieldvalue=' + nyall,'addlink');
}

	
function styletext(form, field, what){
	var tags= new Array();

	switch (what) {
		case 'bold':
			var starttag='<b>';
			var stoptag='</b>';
			break;
		case 'italic':
			var starttag='<i>';
			var stoptag='</i>';
			break;		
		case 'square':
			var starttag='<square>';
			var stoptag='</square>';
			break;		
		case 'quote':
			var starttag='<quote>';
			var stoptag='</quote>';
			break;		
	}
	if (form && field){
		var arean = document.forms[form].elements[field];
	} else {
		var arean = eFocus
	}
	var allt= arean.value;
	// IE specialare..
	if( document.selection ){
		var range = document.selection.createRange();
		var stored_range = range.duplicate();
		stored_range.moveToElementText(arean);
		stored_range.setEndPoint( 'EndToEnd', range );
		selstart= stored_range.text.length - range.text.length;
		selstop= selstart + range.text.length;
	}else{
		var selstart= arean.selectionStart;
		var selstop= arean.selectionEnd;
	}
	var nyall=''; 
	for(i=0 ; i< allt.length; i++){
		if(i==selstart){
			nyall+=starttag+allt.charAt(i);
			var opentag='yes';
		}else if(i==selstop){
			if(opentag=='yes'){
				nyall+=stoptag+allt.charAt(i);
				opentag='no';
			}
		}
		else{
			nyall+=allt.charAt(i);
		} 
	}
	if(opentag=='yes'){
			nyall+=stoptag;
			opentag='no';
	}
	arean.value=nyall;
	arean.focus();
	
	var caretpos=selstop+starttag.length+stoptag.length;
	if(arean.caretPos){
		arean.caretPos=caretpos;
	}else{
		arean.selectionStart=caretpos;
		arean.selectionEnd=caretpos;
	}
}


/* AJAX */

function createAjaxObject(){
	if (browser == "Internet Explorer"){
		var ajaxobject=new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		var ajaxobject=new XMLHttpRequest();
	}
	return ajaxobject;
}
function ajax(formName,url,div,fC,close){
	nd();
	if (fC == 1){
		ajax_fitContent = true;
	}
	div2update=div;
	show(div);
	//if (document.getElementById(div2update).style.display == "none") document.getElementById(div2update).style.display = "block";
	
	var theDiv = document.getElementById(div);
	if (close == 1 && theDiv.innerHTML != ''){
		theDiv.innerHTML = "";
		hide(div);
	} else {
		ajax_object=createAjaxObject();
		if (formName != ""){
			var origForm=document.forms[formName];
			var encodedQuerystring= ajax_createQuerystring(formName);
			ajax_object.onreadystatechange= ajax_handleRequest;
			ajax_object.open("POST",url,true);
			ajax_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ajax_object.send(encodedQuerystring);
		} else {
			ajax_object.onreadystatechange=ajax_handleRequest;
			ajax_object.open("POST",url,true);
			ajax_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ajax_object.send(null);
		}
	}
}

function ajax_createQuerystring(formName){
	var encodedParams=new Array();
	origForm= document.forms[formName];
	for(var i=0; i<origForm.elements.length; i++){
		var str=escape(origForm.elements[i].name);
		str += "=";
		str += escape(origForm.elements[i].value);
		encodedParams.push(str);
	}
	return encodedParams.join("&");
}
function ajax_handleRequest(){
	var obj = document.getElementById(div2update)
	if(ajax_object.readyState == 1){
		obj.innerHTML="<div style='padding: 10px;'><center><img src='/bilder/spinner.gif' width='20' height='20' /><br /><span class='mrubrik'>Loading...</span></center></a>";
	} else if(ajax_object.readyState == 2){
		obj.innerHTML="<div style='padding: 10px;'><center><img src='/bilder/spinner.gif' width='20' height='20' /><br /><span class='mrubrik'>Done loading...</span></center></a>";
	} else if(ajax_object.readyState == 3){
		obj.innerHTML="<div style='padding: 10px;'><center><img src='/bilder/spinner.gif' width='20' height='20' /><br /><span class='mrubrik'>Almost ready...</span></center></a>";
	} else if(ajax_object.readyState == 4){
		if(ajax_object.status == 200){
			obj.innerHTML="<a name='ajaxtop'></a>" + ajax_object.responseText + "<a name='ajaxbottom'></a>";
			if (ajax_fitContent){
				//fitContent();
				top.location = "#ajaxtop";
				ajax_fitContent = false;
			}
		}else{
			obj.innerHTML='Error loading results!';
		}
	}
}



/* Fit content */
function fitContent(){
	if (window.innerWidth){
		iWidth = window.innerWidth;
		iHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)){
		iWidth = document.documentElement.clientWidth;
		iHeight = document.documentElement.clientHeight;
	} else {
		iWidth = document.body.clientWidth;
		iHeight = document.body.clientHeight;
	}
	var x,y;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight
	if (test1 > test2) {
		x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	} else {
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}		
	//alert("height: " + iHeight + ", width: " + iWidth + " -- new height: " + y + ", width: " + x);
	if (y > iHeight){
		window.resizeBy((x-iWidth), (y-iHeight));
	}
}
function addtoPop(pop){
	if (pop.options[pop.selectedIndex].value == "addtopop"){
		var value = prompt("Value to add");
		var len = pop.length;
		pop.options[len] = new Option(value, value);
		pop.selectedIndex = len;
	}
}



function hlgrade(i, nr, max, size){
	for (a=1;a<=max;a++){
		if (a <= nr ){
			// Den här ska vi tända
			document.getElementById(i + "_" + a).src = "/media/atlas/ratings/grades/grade_" + size + ".png";
		} else {
			// Den här ska vi släcka
			document.getElementById(i + "_" + a).src = "/media/atlas/ratings/grades/nograde_" + size + ".png";
		}
	}
}

function setCol(form, field, color){
	document.forms[form].elements[field].value = color;
	document.getElementById("colcont_" + field).style.backgroundColor = color;
}

// Returnera data från ett ajax-script

function dateblur(field){
	if (field.value != ""){
		ajax_object=createAjaxObject();
		ajax_object.onreadystatechange=function(){
			if (ajax_object.readyState == 4){
				if (ajax_object.status == 200){
					date = ajax_object.responseText
					if (date == "error"){
						alert(field.value + " could not be parsed into a date");
						field.value = "";
						field.focus();
						field.style.borderWidth = "3px";
						field.style.borderColor = "red";
					} else {
						field.value = date;
					}
				} else {
					alert("Error loading AJAX request");
				}
			}		
		}
		ajax_object.open("GET","/atlas/plain/datecheck.php?date=" + escape(field.value),true);
		ajax_object.send(null);
	}
}


function toggle_hidden(tone, tform, tfield, tvalue){
	var tF = document.forms[tform].elements[tfield];
	if (tone.checked){
		tF.value = "";
	} else {
		tF.value = tvalue;
	}
}

function check_publish(me, field, form, value){
	
	if (me.checked){
		document.forms[form].elements[field].value = value;
		show('publish_' + form + '_' + field);
	} else {
		document.forms[form].elements[field].value = '';
		hide('publish_' + form + '_' + field);
	}
}


/* RESIZE */
function resize_open(div){
	//window.status = "over";
	var theDiv = document.getElementById(div);
	var sHeight = theDiv.scrollHeight;
	var sWidth = theDiv.scrollWidth;
	var tHeight = theDiv.style.height;
	var tWidth = theDiv.style.width;
	tHeight = Number(tHeight.replace("px", ""));

	if (tHeight < sHeight){
		var diff = sHeight - tHeight;
		var step = Math.round(diff / 3);
		//alert(Math.round(step));
		showTimeout = setTimeout("resize('" + div + "', '" + sHeight+ "', 'open', '" + step+ "')", 500);
		//resize(div,sHeight,"open",step);
	}
}
function resize_close(div, target){
	//window.status = "out";
	theDiv = document.getElementById(div);
	var tHeight = theDiv.style.height;
	tHeight = tHeight.replace("px", "");
	tHeight = Number(tHeight);
	//alert(tHeight + " - " + target);

	if (tHeight > target){
		//showTimeout = setTimeout("resize('" + target+ "', 'close')", 2000);
		var diff = tHeight - target;
		var step = Math.round(diff / 3);
		//alert(step);
		resize(div,target,"close",step);
	}
}

function resize(div, target, dir, step){
	//alert(target);
	
	var theDiv = document.getElementById(div);
	if (showTimeout){
		clearTimeout(showTimeout);
	}
	var tHeight = theDiv.style.height;
	tHeight = tHeight.replace("px", "");
	tHeight = Number(tHeight);
	if (dir == "open"){
		if (tHeight < target){
			//alert(tHeight + " ska bli " + target + " i fem steg dar varje steg ar " + step + ", nästa blir alltså: " + (tHeight + Number(step)) + "px");
			//window.status = step;
			if (tHeight + Number(step) > target){
				step = (target - tHeight);
			}
			theDiv.style.height = (tHeight + Number(step)) + "px";
			showTimeout = setTimeout("resize('" + div + "', '" + target+ "', '" + dir+ "', '" + step+ "')", 50);
		}
	} else {
		if (tHeight > target){
			if (tHeight - Number(step) < target){
				step = (tHeight - target);
			}
			theDiv.style.height = (tHeight - Number(step)) + "px";
			showTimeout = setTimeout("resize('" + div + "', '" + target+ "', '" + dir+ "', '" + step+ "')", 50);
		}
	}
}

function maximize(div){
	var thediv = document.getElementById(div);
	var sHeight = thediv.scrollHeight;
	var tHeight = thediv.style.height;
	tHeight = Number(tHeight.replace("px", ""));
	if (tHeight < sHeight){
		thediv.style.height = sHeight + "px";
	}
	
}
function collapse(div, theheight){
	var thediv = document.getElementById(div);
	var tHeight = thediv.style.height;
	tHeight = Number(tHeight.replace("px", ""));
	thediv.style.height = theheight + "px";
}



function pausecomp(millis){
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); } 
	while(curDate-date < millis);
}

function popform(myform, url, width, height){
	if (! window.focus) return true;
	svisa(url, 'pform', height, width);
	myform.target = "pform";
	return true;
}

function toggle_adminsquare(){
	var adminsquares = new Array();
	adminsquares[1] = 'atlas_files';
	adminsquares[2] = 'atlas_timeline';
	adminsquares[3] = 'atlas_mysql';
	adminsquares[4] = 'atlas_errors';
	adminsquares[5] = 'atlas_images';
	
	var adminsquares_count = adminsquares.length
	//alert(adminsquares_count);
	
	window.status = current_adminsquare;
	
	if (current_adminsquare > 0){
		show(adminsquares[current_adminsquare]);
	} else {
		hide(adminsquares[adminsquares_count-1]);
	}
	if (current_adminsquare > 1){
		hide(adminsquares[current_adminsquare-1]);
	}
	
	if (current_adminsquare == adminsquares_count-1){
		current_adminsquare = 0;
	} else {
		current_adminsquare++;
	}
}

function reload_parent(next){
	var el = parent.opener;
	var count = 1;
	while ( el.opener && el.name != 'mainwindow' && count < 10){
		el = el.opener;
		count++;
	}
	el.location = el.location;
	if (!next){
	
	} else if (next == "close"){
		window.close();
	} else {
		top.location = next;
	}
}
function em(s, t){
	s = s.replace(/[<>\s\!\|\)\(\']/g, "");
	s = s.rot13();
	text = t ? t : s;
	document.write("<a href='mailto:" + s + "'>" + text + "</a>");
}

String.prototype.rot13 = function(){
	return this.replace(/[a-zA-Z]/g, function(c){
		return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
	});
};

function datepicker(what){
	//$(what).blur(function(){ return true; });
	$(what).removeAttr("onblur");
	
	
	$(what).datepicker({
		firstDay: 1,
		closeText: 'X',
		weekHeader: 'V',
		showWeeks: true,
		changeFirstDay: false,
		dateFormat: 'yy-mm-dd',
		onClose: function(date){
			datepicker_close(what, date);
		}
	});
	$(what).datepicker("show");
}
function datepicker_close(what, value){
	//alert(value);
	$(what).datepicker("destroy");
	$(what).blur();
	//$(what).attr("value", value);
	$(what).blur(function(){ dateblur(this) });
}
function setCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}

function dialog(url,t,w,h){
	$("#atlasdialog").remove();
	var windowwidth = $(document.body).width();
	var windowheight = $(document.body).height();

	if (!w || w == 1){ w = 400; }
	if (!h || h == 1){ h = 500; }
	if (!t){ t = "Alert"; }

	if (mouseX && mouseY){
		var posX = mouseX;
		var posY = mouseY;
		if ((posX + w) > windowwidth) posX = (windowwidth - w - 50);
		if ((posY + h) > windowheight) posY = (windowheight - h - 50);
	} else {
		posY = 200;
		posX = 200;
	}
	

	//console.log(mouseX + " x " + mouseY + " // " + posX + " x " + posY);
	$("body").append("<div id='atlasdialog'></div>");

	$("#atlasdialog").html("<img src='/bilder/spinner.gif'>");
	$("#atlasdialog").show();
	$("#atlasdialog").dialog({
		modal: false,
		width: w,
		autoOpen: false,
		position: [posX, posY],
		//title: t,
		closeOnEscape: true,
		height: 10,
		buttons: {
			"Avbryt" : function(){
				$(this).dialog("close");
			}
		},
		close: function(){
			$("#atlasdialog").remove();
		}
	});
	$("#atlasdialog").dialog("open");

	$.get(url, function(data){
		$("#atlasdialog").html(data);
		prime_dialog();
	});
}
function prime_dialog(){
	//var buttons = $("#atlasdialog").dialog("option", "buttons");
	var buttons = {};
	//console.log(buttons);
	//$("#atlasdialog script").each(function(){
	//	$("#atlasdialog").dialog("option", "title", $(this).text());
	//	$(this).remove();
	//});
	
	
	$("#atlasdialog title").each(function(){
		$("#atlasdialog").dialog("option", "title", $(this).text());
		$(this).remove();
	});
	$("#atlasdialog a[href=reload]").each(function(){
		var e = $(this);
		buttons[e.text()] = function(){ $("#atlasdialog").dialog("close"); top.location = top.location; }
		e.remove();
	});
	$("#atlasdialog a[href=autoreload]").each(function(){
		top.location = top.location;
		var e = $(this);
		buttons[e.text()] = function(){ $("#atlasdialog").dialog("close"); top.location = top.location; }
		e.remove();
	});

	$("#atlasdialog form.dialog").submit(function(){
		$("#atlasdialog").html("<img src='/bilder/spinner.gif'>");
		$.post($(this).attr("action"), $(this).serialize(), function(data){
			$("#atlasdialog").html(data);
			prime_dialog();
		});
		return false;
	});

	$("#atlasdialog form.dialog input[type=submit]").each(function(){
		var e = $(this);
		var f = $("#atlasdialog form.dialog");
		buttons[e.attr("value")] = function(){
			$("#atlasdialog").html("<img src='/bilder/spinner.gif'>");
			$.post(f.attr("action"), f.serialize(), function(data){
				$("#atlasdialog").html(data);
				prime_dialog();
			});
		}
		e.remove();
	});

	$("#atlasdialog a[href=closedialog]").each(function(){
		var e = $(this);
		buttons[e.text()] = function(){
			$("#atlasdialog").dialog("close");
		}
		e.remove();
	});

	$("#atlasdialog a[target=dialogbutton]").each(function(){
		var e = $(this);
		buttons[e.text()] = function(){
			$("#atlasdialog").html("<img src='/bilder/spinner.gif'>");
			$.get(e.attr("href"), function(data){
				$("#atlasdialog").html(data);
				prime_dialog();
			});
		}
		e.remove();
	});

	$("#atlasdialog a.dialog").click(function(){
		var e = $(this);
		$.get(e.attr("href"), function(data){
			$("#atlasdialog").html(data);
			prime_dialog();
		});
		return false;
	});
	$("#atlasdialog a.dialogbutton").each(function(){
		var e = $(this);
		buttons[e.text()] = function(){
			top.location = e.attr("href");
		}
		e.remove();
	});


	
	
	


	
	$("#atlasdialog").dialog("option", "buttons", buttons);


	var height = document.getElementById("atlasdialog").scrollHeight;
	//console.log(height);
	$("#atlasdialog").height(height);
	$("#atlasdialog").dialog("option", "height", (height+90));

	
}

function edit_css(type, element){
	if (type == "margins"){
		var dialog = $("<div title='Margins'></div>").load("/atlas/ajax/admin/css/margins.php");
		dialog.find("div.marginslider").slider({
			max: 40,
			min: 0,
			step: 5,
			value: 0,
			slide: function(event, ui){
				if (dialog.find("#slideall").attr("checked")){
					dialog.find("div.marginslider").slider("option", "value", ui.value);
					dialog.find("div.margin_preview").text(ui.value +" px");
					element.css("margin", ui.value +"px");
				} else {
					var p = $(this).attr("id").split("_");
					$(this).parent("div.margin_slider").next("div.margin_preview").text(ui.value +" px");
					element.css("margin-"+p[1], ui.value +"px");
				}
			}
		});
		dialog.dialog({
			width: 250,
			modal: true,
			close: function(){
				dialog.find("div.marginslider").slider("destroy");
				dialog.dialog("destroy");
			},
			buttons: {
				"Ok": function(){
					$(this).dialog("close");
				}
			}
		});
	} else if (type == "fonts"){
		dialog("/atlas/ajax/admin/css/fonts.php");
	}
}

function load_stylesheet(file){
	var isloaded = false;
	$('link[rel=stylesheet]').each(function(){
		if ($(this).attr("href") == file){
			isloaded = true;
		}
	});
	if (!isloaded){
		$("head").append("<link rel='stylesheet' type='text/css' href='" + file + "'>");
	}
}

function edit_layout(){
	$.getScript("/atlas/include/javascript/functions/editlayout.js");
}



function progress(text, show, progress){
	$("#atlas_progress_text").text(text);
	if (show){
		$("#atlas_progress").css("background-color", "#CC0000");
		$("#atlas_progress").show();
		if (progress){
			$("#atlas_progress_bar").progressbar({
				value: progress
			});
		}
	} else {
		$("#atlas_progress").css("background-color", "#006633");
		$("#atlas_progress_bar").progressbar("destroy");
		$("#atlas_progress").fadeOut(4000);
	}
}

function positionmenu(menu, item, space){
	// menu and item are jQuery DOM items

	if (!space) space = 15;

	var windowwidth = $(document.body).width();
	var windowheight = $(document.body).height();

	var offset = item.offset();
	var height = item.outerHeight();
	var width = item.outerWidth();

	//console.log(offset, width, height);
	
	var mwidth = menu.outerWidth();
	var mheight = menu.outerHeight();
	
	//console.log(windowheight, windowwidth, width, height, mwidth, mheight);

	var arrow = {
		icon: "top"
	};


	// First, the left side
	var left = offset.left-4; // position left-aligned with the parent
	arrow["left"] = 4;
	
	if ((offset.left + width + mwidth) > (windowwidth - 10)){
		var left = (offset.left + width) - mwidth + 6; // right-aligned with the parent
		arrow["left"] = mwidth - 22 - 6; // right-aligned with the parent

	}
	
	
	
	// Now, the top side
	var top = offset.top + height + space;  // position under parent
	arrow["top"] = -11;
	
	if ((top + mheight) > (windowheight - 11)){
		var top = offset.top - mheight - space - 11; // over the parent
		arrow["icon"] = "bottom";
		arrow["top"] = mheight-2;
	}
	
	//console.log(top, left);
	
	//console.log(arrowclass);
	
	menu.css("top", top);
	menu.css("left", left);
	
	// Arrow
	
	
	//console.log(arrow, top, left);
	menu.find(".tooltip_arrow").remove();
	var thearrow = $("<img src='/bilder/pointer/menu_" + arrow["icon"] + ".png' width='22' height='11' border='0' class='tooltip_arrow' />");
	menu.append(thearrow);
	thearrow.css("left", arrow["left"]);
	thearrow.css("top", arrow["top"]);
	

}

function popupmenu(what, element){
	var a = qtipargs;
	a["content"]["title"]["text"] = false;
	a["content"]["title"]["button"] = false;
	if (document.getElementById(what)){
		a["content"]["url"] = false;
		a["content"]["text"] = $("#" + what);
	} else {
		a["content"]["text"] = "<img src='/bilder/spinner.gif' />";
		a["content"]["url"] = what;
	}
	$(element).qtip(a);
	return false;
}



function intval (mixed_var, base) {
    var tmp;
    var type = typeof( mixed_var );
    if (type === 'boolean') {
        return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var) ) {
        return Math.floor(mixed_var);
    } else {
        return 0;
    }
}

function adminmode(){
	//console.log("yeah");
	//$(".admin").toggle("blind", { direction: "vertical" }, 500);
	if ($("a.adminmode.atlasbutton").hasClass("active")){
		$(".admin").hide("blind", { direction: "vertical" }, 100);
		$("a.adminmode.atlasbutton").removeClass("active");
		setCookie("adminlinks_visible", "false", 10);
	} else {
		$(".admin").show("blind", { direction: "vertical" }, 100);
		$("a.adminmode.atlasbutton").addClass("active");
		setCookie("adminlinks_visible", "true", 10);
	}
}

function reload_module(view, query, func){
	var page = location.pathname
// 	if ($("form#" + query)){
// 		$.post(page, $("form#" + query).serialize(), function(data){
// 			$("#module_" + view).html(data);
// 		});
// 	} else {
		var url = page + "?loadjs=true&ajax=true&load_module_data=" + view + "&" + query;
		progress("Loading...", 1);
		$.get(url, function(data){
			$("#module_" + view).html(data);
			progress("Done");

			if (func){
				//exec(func;
			}
		});
// 	}
	return false;
}

function log(text){
	if (console){
		console.log(text);
	}
}