// =========== DEBUG
try {
	console.debug('APB start');
} catch (e) {
	console = {
		debug: function () {},
		log: function () {},
		warn: function () {},
		error: function () {},
		info: function () {}
	}
}

/* ====== BEGRÄNSA INDATA ====== */

function constrain (e, type) {
	var key;
	var keychar;
	if (!e) var e = window.event;
	if (e.keyCode) key = e.keyCode;
	else if (e.which) key = e.which;
	keychar = String.fromCharCode(key);
	if ( isNavKey(key) || isModifierKey(e) ) return true;
	else {
		if (type=="phone") {
			return (("0123456789- ").indexOf(keychar) > -1) ;
		} else if (type=="numeric") {
			return (("0123456789").indexOf(keychar) > -1) ;
		} else if (type=="time") {
			return (("0123456789.:").indexOf(keychar) > -1) ;
		} else if (type=="date") {
			return (("0123456789.-").indexOf(keychar) > -1) ;
		} else if (type=="username") {
			return (("abcdefghijklmnopqrstuvwxyzåäöéABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖÉ_1234567890").indexOf(keychar) > -1) ;
		} else return false;
	}
}

function isUsername(username) {
	return (username.test(/^[a-zåäöéüA-ZÅÄÖÉÜ]{1}[a-zåäöéüA-ZÅÄÖÉÜ_0-9]{1,11}$/));
}

function isModifierKey(e) {
	return (e.metaKey || e.ctrlKey);
}
function isNavKey(key) {
	return (
			(key==null) ||
			(key==0) ||
			(key==8) ||     // backspace
			(key==9) ||     // tab
			(key==13) ||    // enter
			(key==16) ||    // shift
			(key==17) ||    // ctrl
			(key==18) ||    // alt
			(key==19) ||    // pause/break
			(key==20) ||    // caps lock 
			(key==27) ||    // escape
			(key==33) ||    // page up
			(key==34) ||    // page down
			(key==35) ||    // end
			(key==36) ||    // home
			(key==37) ||    // left arrow
			(key==38) ||    // up arrow
			(key==39) ||    // right arrow
			(key==40) ||    // down arrow
			(key==45) ||    // insert 
			(key==46) ||    // delete 
			(key==91) ||    // left windows 
			(key==92) ||    // right windows 
			(key==93) ||    // select key 
			(key==144) ||   // num lock 
			(key==145) ||   // scroll lock 
			(key==224) ||   // mac command 
			(key==63232) || // safari "ascii" up arrow 
			(key==63233) || // safari "ascii" down arrow 
			(key==63234) || // safari "ascii" left arrow 
			(key==63235) || // safari "ascii" right arrow 
			(false) 
		   );
}

function isEnter(e) {
	var key;
	if (!e) var e = window.event;
	if (e.keyCode) key = e.keyCode;
	else if (e.which) key = e.which;
	return (key==13);
}

function nextInput(e, who) {
	var key;
	if (!e) var e = window.event;
	if (e.keyCode) key = e.keyCode;
	else if (e.which) key = e.which;

	if (typeof document.selection != "undefined") {
		// IE
		var range = document.selection.createRange();
		var selectedText = range.text;
	} else if (typeof who.selectionStart != "undefined") {
		// Gecko
		var start = who.selectionStart;
		var end = who.selectionEnd;
		var selectedText = who.value.substring(start, end);
	}

	if (who.value.length == who.maxLength && !isNavKey(key) && selectedText.length == 0) {
		inputs = document.getElementsByTagName("input");
		for (i=0; i<inputs.length; i++) {
			if (inputs[i] == who) {
				if (inputs[i+1]) {
					inputs[i+1].focus();
				}
			}
		}
	}
}

/* ====== BEGRÄNSA TEXTLÄNGDER ====== */

function checkInputAll (e, who, where, type, max) {
	var key;
	if (!e) var e = window.event;
	if (e.keyCode) key = e.keyCode;
	else if (e.which) key = e.which;
	updateLength(who, where, max);
	return (who.value.length < max || isNavKey(key) || isModifierKey(e) ); 
}

function updateLength(who, where, max) {
	var timestamp;
	number = document.getElementById(where + "CharLenNumber");
	scale = document.getElementById(where + "CharLenScale");
	scaleDiv = document.getElementById(where + "CharLen");
	number.innerHTML = who.value.length + " av " + max + ""; 
	if (who.value.length >= max) {
		number.className = "error";
		scale.style.width = "100%";
		if (max > 200) scaleDiv.style.display = "block";
	} else {
		percent = parseInt(who.value.length / max * 100);
		if (percent > 100) percent = 100;
		if (percent > 80) {
			if (max > 200) scaleDiv.style.display = "block";
		} else {
			if (max > 200) scaleDiv.style.display = "none";
		}
		scale.style.width = percent + "%";
		number.className = "";
	}
}


/* ====== BEGRÄNSA DUBBELKLICK ====== */

function showWaitForm(btnId, waitId) {
	document.getElementById(btnId).disabled = true;
	showWait(waitId);
}

function showWait(id) {
	document.getElementById(id).style.visibility = "visible";
}

function hideWait(id) {
	document.getElementById(id).style.visibility = "hidden";
}

/* ====== GENVÄGAR ====== */

function go(url) {
	document.location.href = url;
}

function focus(obj) {
	obj = $(obj);
	if (!obj) return;
	if (obj.getPosition().y + obj.getSize().y < $(window).getSize().y) obj.focus(); 
}

function toggleObject (whoId) {
	who = document.getElementById(whoId);
	if(!who) return;
	if (who.style.display == 'none') {
		who.style.display = 'block';
	} else {
		who.style.display = 'none';
	}
}

function toggleVisibility (who) {
	if (typeof who == "string") who = document.getElementById(who);
	if(!who) return;
	if (who.style.visibility == 'hidden') {
		who.style.visibility = 'visible';
	} else {
		who.style.visibility = 'hidden';
	}
}

function hideAndShow(id1, id2) {
	if (typeof id1 == "string") id1 = document.getElementById(id1);
	if (typeof id2 == "string") id2 = document.getElementById(id2);
	id1.style.display = "none";
	id2.style.display = "block";
}


function chTri (agent, obj) {
	if (typeof obj == "string") obj = document.getElementById(obj);
	if (!obj) return false;
	obj = $(obj);
	if (agent.className == 'triO') {
		agent.className = 'triC';
		$(obj).slide('out');
		$(obj).fade('out');
	} else {
		agent.className = 'triO';
		obj.style.display="block";
		$(obj).slide('hide');
		$(obj).slide('in');
		$(obj).fade('in');
		try {
			Apberget.pageLoaded.delay(1000);
		} catch (e) {}
	}
}

function getStyle(el, cssRule) {
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(el, "").getPropertyValue(cssRule);
	}
	else if(el.currentStyle) {
		cssRule = cssRule.replace(/-(\w)/g, function (strMatch, p1) { return p1.toUpperCase(); });
		strValue = el.currentStyle[cssRule];
	}
	return strValue;
}

/* ====== TEXTVERKTYG ====== */

var lastAPMLMenu = null;
var lastAPMLButton = null;
var APMLTimer;

function toggleAPMLMenu(who, input) {
	if (typeof input == "string") input = document.getElementById(input);
	if (who) {
		who = document.getElementById(who);
		var m = document.getElementById(who.id + "_menu");
		if (m.style.display == "block") {
			clearTimeout(APMLTimer);
			m.style.display = "none";
			who.className="";
			toggleAPMLMenu(null, input);
		} else {
			if (lastAPMLMenu) lastAPMLMenu.style.display = "none";
			if (lastAPMLButton) lastAPMLButton.className="";
			m.style.display = "block";
			// m.style.left = findPosX(who) - findPosX(document.getElementById('apb_content')) + "px";
			// m.style.top = findPosY(who) - findPosY(document.getElementById('apb_content')) + 18 + "px";
			left_offset = 0;
			if (Browser.Engine.webkit) left_offset = 3;
			m.style.left = who.getPosition().x + left_offset + "px";

			top_offset = 0;
			if (Browser.Engine.webkit) top_offset = 3;
			m.style.top = who.getPosition().y + 18 + top_offset + "px";
			who.className="m";
			lastAPMLMenu = m;
			lastAPMLButton = who;
			clearTimeout(APMLTimer);
			APMLTimer = setTimeout("toggleAPMLMenu()", 15000);
		}
	} else if(lastAPMLMenu) {
		clearTimeout(APMLTimer);
		lastAPMLMenu.style.display = "none";
		lastAPMLMenu = null;
		lastAPMLButton.className="";
		lastAPMLButton = null;
	}
}

var lastAPMLInput;

function openAPMLBrowser (input, type) {
	lastAPMLInput = input;
	browser_win(type);		
}
function APMLBrowserResult (tag) {
	if (lastAPMLInput) insert(lastAPMLInput, tag);
	lastAPMLInput = null;
}

function insert(input, tagBefore, tagAfter, atEnd) {
	/*
		atEnd: om ingen markering: infoga ej tagBefore + markör bakom tagAfter. Bra för citattecken
		kolla IE.
	*/

	if (typeof input == "string") input = document.getElementById(input);
	if (!tagAfter) tagAfter="";
	var st;
	if(input.scrollTop) st = input.scrollTop;
	input.focus();
	if (typeof document.selection != "undefined") {
		var range = document.selection.createRange();
		var selectedText = range.text;
		if (selectedText.length == 0 && atEnd) {
			range.text = selectedText + tagAfter;
		} else {
			range.text = tagBefore + selectedText + tagAfter;
		}
		range = document.selection.createRange();
		if (selectedText.length == 0) {
			range.move("character", -tagAfter.length);
		} else {
			range.moveStart("character", tagBefore.length + selectedText.length + tagAfter.length);      
		}
		range.select();
	}
	/* Gecko */
	else if (typeof input.selectionStart != "undefined") {
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var selectedText = input.value.substring(start, end);
		if (selectedText.length == 0 && atEnd) {
			input.value = input.value.substr(0, start) + selectedText + tagAfter + input.value.substr(end);
		} else {
			input.value = input.value.substr(0, start) + tagBefore + selectedText + tagAfter + input.value.substr(end);
		}
		var pos;
		if (selectedText.length == 0) {
			if (atEnd) pos = start + tagAfter.length; 
			else pos = start + tagBefore.length;
		} else {
			pos = start + tagBefore.length + selectedText.length + tagAfter.length;
		}
		input.selectionStart = pos;
		input.selectionEnd = pos;
	}
	toggleAPMLMenu('', input);
	if(st) input.scrollTop = st;
}

/* ====== BEKRÄFTA SKADLIG ÅTGÄRD ====== */

function delImage(date) {
	if (date) {
		return confirm ("Vill du ta bort din personliga bild?\n\nOBS! Du kan ändå inte ladda upp en ny bild förrän " + date + "!");
	} else {
		return confirm ("Vill du ta bort din personliga bild?\n\nOBS! Du behöver inte ta bort din bild för att ladda upp en ny!");
	}
}

function delImageUploaded() {
	return confirm ("Vill du ta bort din uppladdade bild och använda din gamla istället?");
}

function delLoc(name, address) {
	return confirm ("Vill du ta bort platsen »" + name + "« (" + address + ")?");
}
function delDiary(name) {
	return confirm ("Vill du ta bort diarieinlägget »" + name + "«?");
}

function cancelFriend(user) {
	return confirm ("Vill du sluta vänta på att bli vän med »" + user + "«?\n\n»"+user+"« kommer inte meddelas om detta.");
}

function delUser(user) {
	return confirm ("Vill du ta bort användaren »" + user + "« från din vänlista?\nDu kommer inte längre vara vän med »" + user + "« om du fortsätter.\n\n»"+user+"« kommer inte meddelas om detta.");
}

function delUserCom(user) {
	if (user) {
		return confirm ("Vill du radera kommentaren som »"+user+"« har skrivit om dig?");
	} else {
		return confirm ("Vill du radera kommentaren?");
	}
}

/* ====== ETIKETTER  ====== */

function toggleCloud(args) {
	var cloud = document.getElementById('tagCloudText');
	toggleObject('tagCloud');
	if (cloud && !cloud.done) getCloud(cloud, args);
}
function getCloud(cloud, args) {
	makeRequest('http://' + HOST + WWW_PATH + '/ajax.php?type=tag_cloud&'+args);
}

function parseTagCloud(data, url) {
	if (data == "-1") return "<i class='noValue'>Inga etiketter</i>";
	var tags = data.split(",");	
	var html = "";
	for (i=0; i<tags.length; i++) {
		var tag = tags[i].split(":");
		var size = $pick(['10px', '12px', '14px', '18px', '24px', '32px'][tag[1]], '12px');	
		var fade = $pick(['text', 'gray', 'grayer'][tag[2]], 'text');
		html += '<a href="'+url+'&tags=' + tag[0] + '" class="'+fade+'" style="font-size: ' + size + '">' + tag[0] + '</a> ';
	}
	return html;
}
/* ====== POPUP-FÖNSTER ====== */
var ApbPopups = {
	apb_image: '',
	apb_browser: '',
	apb_user_image: '',
	apb_gb: '',
	apb_gb_reply: '',
	apb_gb_history: '',
	apb_group_member: '',
	apb_friend: '',
	apb_question: '',
	apb_refill: '',
	apb_link: '',
	apb_agreement: ''
};

function popup (url, name, w, h, scroll, resize, steps) {
	if (!scroll) scroll = 'yes';
	if (!resize) resize = 'yes';
	var margin = {x: 100, y: 140};
	width = w.toInt().limit(100, screen.width-margin.x);
	height = h.toInt().limit(100, screen.height-margin.y);
	if (steps) {
		diff = ((w-width)/steps).ceil();
		width = w-diff*steps;
	}
	var pos = {top: (screen.height-height)/8, left: (screen.width-width)/2};
	var settings = 'height='+height+',';
	settings += 'width='+width+',';
	settings += 'dependent=yes,';
	settings += 'top='+pos.top+',';
	settings += 'left='+pos.left+',';
	settings += 'scrollbars='+scroll+',';
	settings += 'resizable='+resize+'';
	if ($defined(ApbPopups[name])) {
		if (ApbPopups[name]) ApbPopups[name].close();
		ApbPopups[name] = window.open(url, name, settings);
		ApbPopups[name].focus();
	} else {
		var infowin = window.open(url, name, settings);
		infowin.focus();
	}
}

function browser_win (type) {
	w = 490;
	h = 440;
	var url= 'http://' + HOST + WWW_PATH + "/php/popups/browser.php?type="+type+"&title=Bläddrare";
	popup(url, 'apb_browser', w, h, 'yes', 'no');
}
function album_win (image, name, w, h) {
	w = 700;
	h = 925;
	popup(image + '&title=Albumbild', name, w, h, 'yes', 'yes');
}
function image_popup (args) {
	var url = 'http://' + HOST + WWW_PATH + "/php/popups/image.php?"+args;
	var steps = 82;
	steps = 86;
	popup(url, 'apb_image', 850+6*steps, 1000, 'yes', 'yes', steps);
}
function image_win(url, w, h) {
	popup(url, 'apb_show_image', parseInt(w)+12, parseInt(h)+12, 'no', 'no');
}
function uimages_win(puid) {
	var url= 'http://' + HOST + WWW_PATH + "/php/cave/user_images.php?uid="+puid+"&title=Användarbilder";
	var name="apb_user_image";
	popup (url, name, 300, 110, "no", "no");
}

function gb_win(username) {
	var url= 'http://' + HOST + WWW_PATH + "/php/popups/gb.php";
	if (username) url += "?username="+username;
	var name="apb_gb";
	popup (url, name, 500, 450, "yes", "yes");
}
function gb_reply_win(id) {
	var url= 'http://' + HOST + WWW_PATH + "/php/popups/gb_reply.php?id="+id;
	var name="apb_gb_reply";
	popup (url, name, 420, 350, "yes", "yes");
}
function gb_history_win(id) {
	var url= 'http://' + HOST + WWW_PATH + "/php/popups/gb_history.php?id="+id+"&title=GB-historik";
	var name="apb_gb_history";
	popup (url, name, 400, 400, "yes", "no");
}
function send_msg_popup(to) {
	var url= 'http://' + HOST + WWW_PATH + "/php/cave/send_message.php?to="+to+"&title=Meddelande";
	var name="apb_message_" + to;
	popup (url, name, 300, 300, "yes", "yes");
}
function group_member_zoom_win(pid, uid) {
	var url= 'http://' + HOST + WWW_PATH + "/php/groups/member_zoom.php?uid="+uid+"&pid="+pid+"&title=Medlemsinfo";
	var name="apb_group_member";
	popup (url, name, 400, 400, "yes", "yes");
}
function rel_zoom_win(uid, rel) {
	var url= 'http://' + HOST + WWW_PATH + "/php/cave/rel_zoom.php?uid="+uid+"&rel="+rel+"&title=Relation";
	var name="apb_friend";
	popup (url, name, 400, 335, "yes", "yes");
}
function stuff_zoom_win(uid, item) {
	var url= 'http://' + HOST + WWW_PATH + "/php/cave/stuff_zoom.php?uid="+uid+"&id="+item+"&title=Sak";
	var name="apb_stuff_" + item;
	popup (url, name, 418, 350, "yes", "yes");
}
function q_answer_win(uid, id) {
	var url= 'http://' + HOST + WWW_PATH + "/php/popups/q_answer.php?uid="+uid+"&id="+id+"&title=Fråga";
	var name="apb_question";
	popup (url, name, 400, 335, "yes", "yes");
}
function new_item_win(uid, item) {
	var url= 'http://' + HOST + WWW_PATH + "/php/cave/stuff_new.php?uid="+uid+"&item="+item+"&title=Ny+sak";
	var name="apb_new_stuff_" + item;
	popup (url, name, 510, 468, "yes", "yes");
}
function refill_win() {
	var url= "http://" + HOST + "/refill/refill.php"; 
	var name="apb_refill";
	popup (url, name, 450, 500, "yes", "yes");
}
function link_win (pid) {
	var name="apb_link";
	var h = screen.height-180;
	var url= "http://" + HOST + WWW_PATH + "/php/misc/click_link.php?pid=" + pid + "&title=Länk&h=" + h; 
	popup (url, name, 1050, h, "yes", "yes");
}
function movielink_win (pid) {
	var name="apb_movielink";
	var url= "http://" + HOST + WWW_PATH + "/php/misc/movie_tip.php?pid=" + pid; 
	popup (url, name, 1050, 770, "yes", "yes");
}
function agreement_win () {
	var url= "http://" + HOST + WWW_PATH + "/agreement.html"; 
	var name="apb_agreement";
	popup (url, name, 400, 450, "yes", "yes");
}
