var popups = new Array();
var lastCaller = document;
var ratings = new Array();
var mouseovercount = 0;
var popupindex = 0;
var mouseoverobj = document;
var root = '';
var popups_enabled = true;

$.ajaxSetup({
	type: "GET",
	cache: false,
	data: "",
	dataType: "html"
});

$(document).ready(function() {            
	$(".fixedpopup").draggable({
			handle: 'h2'
	});
	
	// Line breaks in titles
	$("[title]").each(function() {
		var title = $(this).attr("title");
		if(title) {
			$(this).attr("title", title.replace(/\[br\]/, " " + String.fromCharCode(10)));
		}
	});
	
	$('#mylists').sortable(
		{
			items: '.dragwrap', // the type of element to drag
			handle: 'h2', // the element that should start the drag event
			opacity: 0.9, // opacity of the element while draging
			scroll: true, // don't scroll the page while draging
			zindex: 49,			
			update: function(event, ui) {
				var result = serialize(this);
				$.post("_admin_lists.php?action=sort", result, function(msg) {
					status(msg);
				});						
			}
		}
	);
	
	$("#mylists").disableSelection();
		
	//edit_init();
	sortmylists();
});



Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};


function sortmylists() {
	$('.mylist').sortable(
		{
			items: '.bookmini', // the type of element to drag					
			opacity: 0.9, // opacity of the element while draging
			scroll: false, // don't scroll the page while draging
			connectWith: '.mylist',	
			dropOnEmpty: true,
			zindex: 50,
			start: function(event, ui) { 
				hideall();
				disablepopups();				
				
				// Hack to prevent click to propogate after drop in FF
				$(".bookmini a").click(function (event) {
					event.preventDefault(); 
				});
					
				
				var bookid = $(ui.item[0]).attr('bookid');
				var listid = $(this).attr('listid');
				$(".mylist[listid!=" + listid + "] .bookmini[bookid=" + bookid + "] .cover").addClass("warning");

			},
			receive: function(event, ui) {
				if($(this).find(".bookmini[bookid=" + $(ui.item[0]).attr('bookid') + "]").size() > 1) {
					// The same book is only allowed to be added once.
					$('.mylist').sortable( "cancel" );
					status("Listan innnehåller redan bookid=" + $(ui.item[0]).attr('bookid'));
				} else {
					var liststatus = "";
					$.get("_admin_lists.php", "action=addtolist&listid=" + $(this).attr('listid') + "&bookid=" + $(ui.item[0]).attr('bookid'), function(msg) {
						liststatus += msg + " ";
						status(liststatus);						
					});
					$.get("_admin_lists.php", "action=removefromlist&listid=" + ui.sender.attr('listid') + "&bookid=" + $(ui.item[0]).attr('bookid'), function(msg) {
						liststatus += msg + " ";
						status(liststatus);	
					});
				}
			},
			update: function(event, ui) {						
				var result = serialize(this);
				var listid = $(this).attr('listid');
								
				$.post("_admin_lists.php?action=sortlist&listid=" + listid, result, function(msg) {
					status(msg);
				});				
			},
			stop: function(event, ui) { 
				enablepopups();	
				$(".warning").removeClass("warning");
				$(".bookmini").css("z-index", "0");
				// Hack to prevent link from triggerin on drop in FF
				setTimeout(
					function() {
						$(".bookmini a").unbind("click")
					},
					10
				);
			}

		}
	);
	$(".mylist").disableSelection();
}

function setRoot(newRoot) {
	root = newRoot;
}

function registerPopup(obj) {
	if(obj) {
		popups.push(obj);
	}
}

function registerRating(obj, bookid) {
	if(obj) {
		if (ratings[bookid.toString()]) {
			ratings[bookid.toString()].push(obj);
		} else {
			ratings[bookid.toString()] = [obj];
		}
	}
}

function adjustToScreen(callertop, callerheight, height, valign) {
	
	callerheight = callerheight ? callerheight : 16;
	
	var yoffset = 0;
	var innerheight = 0;
	
	if (window.pageYOffset) // for Firefox
		yoffset = window.pageYOffset;
	
	if (document.body.scrollTop) // for Explorer		
		yoffset = document.body.scrollTop;

	if (document.documentElement.scrollTop) // for Explorer	 7	
		yoffset = document.documentElement.scrollTop;
			
	
	if (self.innerWidth) {
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth) {
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body) {
	    frameWidth = document.body.clientWidth;
	    frameHeight = document.body.clientHeight;
	}
			
	// Is Popup above top if adjusted?
	if (callertop + (valign == 'middle' ? callerheight / 2 : 0) - height < yoffset) {	
		// Place popup below caller
		
		// Is popup below frame if placed bellow
		if (callertop + (valign == 'middle' ? callerheight / 2 : 0) + height > yoffset + frameHeight) {
			//Frame above top. Will not fit below either, place at frame top
			callertop = yoffset + 5;
			
		} else {
			//Frame above top. Place below
			callertop = callertop + (valign == 'middle' ? callerheight / 2 : callerheight);				
		}
	} else {		
		// Place popup above caller		
		
		// Check if popup is below frame
		if (callertop + (valign == 'middle' ? callerheight / 2 : 0) > yoffset + frameHeight ) {
			//Frame below bottom of frame, place above frame bottom
			callertop = yoffset + frameHeight - height - 5;			
		} else {
			//Will fit above, place above
			callertop = callertop + (valign == 'middle' ? callerheight / 2 : 0) - height;			
		}
	}	
	
	return callertop;
}

function adjustToScreenEX(caller, popup, align) {
	
	caller.height = caller.height ? caller.height : 16;
	
	var yoffset = 0;	
	
	if (window.pageYOffset) // for Firefox
		yoffset = window.pageYOffset;
	
	if (document.body.scrollTop) // for Explorer		
		yoffset = document.body.scrollTop;

	if (document.documentElement.scrollTop) // for Explorer	 7	
		yoffset = document.documentElement.scrollTop;
			
	var frameWidth = 0;
	var frameHeight = 0;
	
	if (self.innerWidth) {
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth) {
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body) {
	    frameWidth = document.body.clientWidth;
	    frameHeight = document.body.clientHeight;
	}
			
	/*
		Adjust vertically
	*/
	
	// Is Popup above top if adjusted?
	if (caller.top + (align.v == 'middle' ? caller.height / 2 : 0) - popup.height < yoffset) {	
		// Place popup below caller
		
		// Is popup below frame if placed bellow
		if (caller.top + (align.v == 'middle' ? caller.height / 2 : 0) + popup.height > yoffset + frameHeight) {
			//Frame above top. Will not fit below either, place at frame top
			popup.top = yoffset + 5;
			
		} else {
			//Frame above top. Place below
			popup.top = caller.top + (align.v == 'middle' ? caller.height / 2 : caller.height);				
		}
	} else {		
		// Place popup above caller		
		
		// Check if popup is below frame
		if (caller.top + (align.v == 'middle' ? caller.height / 2 : 0) > yoffset + frameHeight ) {
			//Frame below bottom of frame, place above frame bottom
			popup.top = yoffset + frameHeight - height - 5;			
		} else {
			//Will fit above, place above
			popup.top = caller.top + (align.v == 'middle' ? caller.height / 2 : 0) - popup.height;			
		}
	}	
	
	
	/*
		Adjust horizontally
	*/

	// Is Popup outside right border if adjusted?
	if (caller.left + (align.h == 'outer' ? caller.width : 0) + popup.width > frameWidth) {	
		// Place popup to the left of caller
		
		// Is Popup outside left border if place to the left?
		if (caller.left +(align.h == 'outer' ? 0 : caller.width) - popup.width < 0) {
			//Frame outside left border. Will not fit below either, place at frame top
			popup.left = yoffset + 5;
			
		} else {
			//Frame above top. Place below
			caller.top = caller.top + (align.v == 'middle' ? caller.height / 2 : caller.height);				
		}
	} else {		
		// Place popup above caller		
		
		// Check if popup is below frame
		if (caller.top + (align.v == 'middle' ? caller.height / 2 : 0) > yoffset + frameHeight ) {
			//Frame below bottom of frame, place above frame bottom
			caller.top = yoffset + frameHeight - height - 5;			
		} else {
			//Will fit above, place above
			caller.top = caller.top + (align.v == 'middle' ? caller.height / 2 : 0) - popup.height;			
		}
	}	
	
	
	return popup;
}



function monitorMouseOver(e){
	var evt = (e)?e:event;

	var obj = (evt.srcElement)?evt.srcElement:evt.target;
	
	mouseoverobj = obj;	
	
	// Safari hack: To allow the user to click on the dropdown, skip mouse over for HTML tags
	if(obj.tagName == "HTML")
		return true;
	
	var allobj = $(obj).parents().andSelf();
	
	if (allobj.filter('.avgrating').size()) {			
		showrating(allobj.filter('.avgrating').get(0), allobj.filter('.avgrating').attr("bookid"));
		hide("#userpopup");
		return true;
	}	
	
	if (allobj.filter('.userlink').size()) {			
		showUser(allobj.filter('.userlink').get(0), allobj.filter('.userlink').attr("userid"));
		hideall("userpopup");
		return true;
	}

	if (allobj.filter('.cover').size()) {	
		showbook(allobj.filter('.cover').get(0), allobj.filter('.cover').attr("bookid"));
		hideall("bookpopup");
		return true;
	}

	
	if(allobj.filter('.popup').size() + allobj.filter('.addicon').size()) {
		// Do not close popup
		return true;	
	}

	hideall();	

	return true;	

	
	


/*	
	
	while(obj != null){
		if((obj.className == "popup") || (obj.className == "addicon")) {
			// Do not close popup
			return true;			
		}
		
		if (obj.className == "cover") {	
			showbook(obj, getAttributeValue(obj.attributes, "bookid"));
			hideall("bookpopup");
			return true;
		}
		
		if (obj.className == "userlink") {			
			showUser(obj, getAttributeValue(obj.attributes, "userid"));
			hideall("userpopup");
			return true;
		}
		
		if (obj.className == "avgrating") {			
			showrating(obj, getAttributeValue(obj.attributes, "bookid"));
			hide("#userpopup");
			return true;
		}
		
		obj = obj.parentNode;
	}
*/	

}
document.onmouseover = monitorMouseOver;

function monitorClick(e){
	var evt = (e)?e:event;

	var obj = (evt.srcElement)?evt.srcElement:evt.target;

	while(obj != null){
		if((obj.id == "addtolistpopup") || (obj.className == "addicon")) {
			return true;
		}		
		obj = obj.offsetParent;
	}
	
	hide("addtolistpopup");
	
	return true;

}
document.onClick = monitorClick;

function hideall( skip ) {
	
	skip = skip ? skip : 0;
	var popups = $(".popup[id!=" + skip + "]");
	hide(popups);
	popups.attr("bookid", 0);
	popups.attr("userid", 0);
	
}

function updateRating( id, r ) {
	var bookid = id.toString();
	var rating = r.toString();
		
	ajaxcall( "[id=rating_" + bookid + "]", root + '_updaterating.php?bookid=' + bookid + '&rating=' + rating );

	updateAvgRating( id )	
	
	hide("#starbubble");
	
}

function updateAvgRating( id ) {
	var bookid = id.toString();	

	ajaxcall( "[id=avgrating_" + bookid + "]", root + '_update_avg_rating.php?bookid=' + bookid );
		
}

function addComment(cid, type, show_profile_pictures) {	
	cid = cid.toString();
	type = type.toString();
	
	
	$(".commentform .error").html('');
	
	var comment = $(".commentform [name=comment]").val();
	if(comment.length == 0) {
		$(".commentform [name=comment]").nextAll('.error').html('Du måste fylla i en kommentar');
		return;
	}
		
	var name = $(".commentform [name=name]").val();
	if(name.length == 0) {
		$(".commentform [name=name]").nextAll('.error').html('Du måste fylla i ett namn');
		return;
	}	
	
	var captcha_code = $(".commentform [name=captcha_code]").val();
	
	$.ajax({
		type: "POST",
		url: root + "_admin_comments.php?action=add&cid="+cid+"&type="+type,
		data: "comment="+encodeURIComponent(comment)+"&name="+encodeURIComponent(name)+"&code=" + encodeURIComponent(captcha_code),
		beforeSend: function() {			
			$(".commentform [name]").attr('disabled', '1');
		},
		success: function(msg) {
			$(".commentform [name]").removeAttr('disabled');			
			$(".commentform [name=captcha_code]").val('');
			
			var commentid = parseInt(msg);
			
			if(commentid) {			
				var nocomments = $(".feedlist[ctype="+type+"][cid="+cid+"]").find('.nocomments');				
				
				$.get(root + "_admin_comments.php?output=comment&commentid="+commentid+"&type="+type+"&show_profile_pictures="+show_profile_pictures+"&root="+encodeURIComponent(root)+"&lastcomment="+nocomments.size(), function(msg) {											
					$(".feedlist[ctype="+type+"][cid="+cid+"]").prepend(msg);
					
					$("#comment_"+commentid).hide();					
					$("#comment_"+commentid).show('blind');	

					$(".commentform [name=comment]").val('');					
					$(".commentform [name=comment]").css('height', '50px');
					var morecomments = $(".morecomments[ctype="+type+"][cid="+cid+"]");
					if(morecomments.size()) {
						morecomments.attr("index", parseInt(morecomments.attr("index")) + 1);
					}
				});
				nocomments.remove();
			} else {
				
				// Clear captcha code
				document.getElementById("captcha").src = root + 'securimage/securimage_show.php?' + Math.random();				
				
				try {
					var error = eval('(' + msg + ')'); // Create error message
					if(error) {
						if(error.type == 'comment') {
							$(".commentform [name=comment]").nextAll('.error').html(error.msg);	
						}
						
						if(error.type == 'name') {
							$(".commentform [name=name]").nextAll('.error').html(error.msg);	
						}	
						
						if(error.type == 'captcha_code') {
							$(".commentform [name=captcha_code]").nextAll('.error').html(error.msg);
						}
						
						if(error.type == 'status') {
							status(error.msg);	
						}					
						
					} else {	
						status(msg);
					}
				} catch(e) {
					status(e.toString() + " | " + msg);
				}
			}
		},
		error: function(err) {
			status(err);
		}
	});

}

function removeComment( commentid ) {
	commentid = commentid.toString();

	$.ajax({
		type: "GET",
		url: root + "_admin_comments.php",
		data: "action=remove&commentid="+commentid,
		beforeSend: function() {			
			stripLinks("#comment_"+commentid);
		},
		success: function(msg) {
			var comment = $("#comment_"+commentid);
			
			var morecomments = comment.parents('.feedlist:first').next('.morecomments');			
			if(morecomments.size()) {
				// Update morecomments link
				morecomments.attr("index", parseInt(morecomments.attr("index")) - 1);
			}
			
			if(comment.parents('.feedlist:first').find('.comment:visible').size() > 1) {
				
				if(comment.hasClass('lastcomment')) {
					comment.prevAll('.comment:visible:first').addClass('lastcomment');
				}
					
			} else {
				if(morecomments.size() == 0) {
					// Hide parent comment
					comment.parents('.comment').hide('blind');
				}
			}
			comment.hide('blind');
			status(msg);
		},
		error: function(err) {
			status(err);
		}
	});
}

function nextCommentPage(caller, display_for_userid, show_profile_pictures, trim) {
	
	var cid = parseInt($(caller).attr('cid'));
	var type = $(caller).attr('ctype');
	var index = parseInt($(caller).attr('index'));
	var pagesize = parseInt($(caller).attr('pagesize'));
	
	$.ajax({
		type: "GET",
		url: root + "_admin_comments.php",
		data: "output=more&cid="+cid+"&type="+type+"&display_for_userid="+display_for_userid+"&trim="+trim+"&index="+index+"&pagesize="+pagesize+"&show_profile_pictures="+show_profile_pictures+"&root="+encodeURIComponent(root),
		beforeSend: function() {			
			
		},
		success: function(msg) {
			
			var comments = $(".feedlist[ctype="+type+"][cid="+cid+"]").append("<div index='" + index + "' style='display:none;'></div>");			
			var container = comments.find("div:last"); // Select the added div
			comments.find('.lastcomment').removeClass('lastcomment');
			container.prepend(msg); // Add the result to the div
			container.show('blind'); 			
						
			if(container.find("#more").size()) {
				if(parseInt(container.find("#more").val())) {				
					$(caller).attr("index", index + pagesize); // Update link to next page
				} else {
					$(caller).remove();	// Remove link since there are no more comments
				}
			}
		},
		error: function(err) {
			status(err);
		}
	});


}

function showaddtolist(caller, id) {
	var bookid = id.toString();
	var popup = document.getElementById("addtolistpopup");
	var listdiv = getElementBelowById(popup, "addtolist");
	
	var pos = abspos(caller);
	popup.style.left = (pos[0] + 10).toString() + "px";
	popup.style.top = (pos[1] + 5).toString() + "px";

	listdiv.innerHTML = "";	
	ajaxcall(listdiv, root + "_addtolist.php?bookid=" + bookid );

	show(popup);
}

function infolog(obj) {
	if(obj) {
		window.console.log("id: " + obj.id + " tag: " + obj.tagName + " class: " + obj.className);
	}
}

function addtolist(caller, id) {
	var listid = 0;
	var bookid = id.toString();
	caller.disabled = true;
		
	listid = caller.options[caller.selectedIndex].value;
	
	ajaxcall( null , root + "_admin_lists.php?action=addtolist&bookid=" + bookid + "&listid=" + listid );
	ajaxcall("[id=booklists][bookid=" + bookid + "]", root + "_admin_lists.php?bookid=" + bookid + "&listid=" + listid + "&output=popup&root=" + root );
	ajaxcall("[id=addtolist][bookid=" + bookid + "]", root + "_admin_lists.php?bookid=" + bookid + "&listid=" + listid + "&output=addtolistpopup&root=" + root );
	ajaxcall(".mylist[listid=" + listid + "]", 							  root + "_admin_lists.php?bookid=" + bookid + "&listid=" + listid + "&output=list&root=" + root );
	
}

function removefromlist(caller, listid, bookid) {	

	ajaxcall( null , root + "_admin_lists.php?action=removefromlist&bookid=" + bookid + "&listid=" + listid );
	ajaxcall("[id=booklists][bookid=" + bookid + "]", root + "_admin_lists.php?bookid=" + bookid + "&listid=" + listid + "&output=popup&root=" + root );
	ajaxcall("[id=addtolist][bookid=" + bookid + "]", root + "_admin_lists.php?bookid=" + bookid + "&listid=" + listid + "&output=addtolistpopup&root=" + root );
	ajaxcall(".mylist[listid=" + listid + "]", 							  root + "_admin_lists.php?bookid=" + bookid + "&listid=" + listid + "&output=list&root=" + root );
	
}



function showbook(caller, id) {	
	if((id != null) & popups_enabled) {
		
		var bookid = id.toString();
		
		if ( $('#bookpopup').attr('bookid') != bookid ) {														
			ajaxcallpopup('#bookpopup', root + "_bookpopup.php", "bookid=" + bookid + "&root=" + root, caller, adjustPopup );
			$('#bookpopup').attr("bookid", bookid);			
		}
		
	}
}

function showUser(caller, id) {	
	if((id != null) & popups_enabled) {

		var userid = id.toString();
		
		if ( $('#userpopup').attr('bookid') != userid ) {														
			ajaxcallpopup('#userpopup', root + '_userpopup.php', 'userid=' + userid + '&root=' + root, caller, adjustPopupToLink );
			$('#userpopup').attr("bookid", userid);			
		}
		
	}
}

function showrating(caller, id) {
	if((id != null) & popups_enabled) {
		
		var bookid = id.toString();
		if ( $('#ratingpopup').attr('bookid') != bookid ) {														
			ajaxcallpopup('#ratingpopup', root + "_ratingpopup.php", "bookid=" + bookid + "&root=" + root, caller, adjustPopupToLink );
			$('#ratingpopup').attr("bookid", bookid);			
		}
	}
}

function logoutUser() {	
	document.logoutform.submit();
}

function updateTags( caller ) {
		
	var oldvalue = caller.value;
	setTimeout( function() {		
		var newvalue = caller.value;
		if( newvalue == oldvalue) {		
			ajaxcall("#listoftags", root + "_updatetags.php?query=" + newvalue);	
		}
	}, 200);
}

function getOrter( caller ) {
	var kommunid = caller.options[caller.selectedIndex].value;
	var fortid = document.getElementById("fortid");
	fortid.innerHTML = "<select disabled></select>";
	
	ajaxcall( fortid, root + "_getorter.php?kommunid=" + kommunid.toString() );
}

function updateRows(caller) {
	var ruler = document.getElementById("ruler");
	ruler.innerHTML = caller.value.replace(/>/g, '&gt;').replace(/</, '&lt;').replace(/   /g, ' &nbsp; ').replace(/  /g, ' &nbsp;').replace(/\n/g, '<br>') + '|'; // Add a character for IE to resize on new line	
	caller.style.height = ruler.offsetHeight.toString() + "px";	
}

function updatePreview( caller ) {	
	var oldvalue = caller.value;
	setTimeout( function() {
		var newvalue = caller.value;
		if(oldvalue == newvalue) {
		
			html("#listwidgetpopup #preview", newvalue);
		}
	}, 1000);
}

function showListWidgetPopup( caller, listid ) {

	var htmlcode = '<iframe src="http://www.bok.nu/listwidget.php?listid=' + listid.toString() + '&amp;type=1&amp;num=10" width="100%" height="110" scrolling="no" frameborder="0"></iframe>';
	$("#embedcode").val(htmlcode);
	html("#listwidgetpopup .contents #preview", htmlcode);
	
	setpopupposition( "#listwidgetpopup" );	
	show("#listwidgetpopup");
}	

function expandentry( caller ) {
	var expanded = $(caller).attr("expanded");
	
	if (expanded="0") {
		var entryid = $(caller).attr("entryid");
		caller.className = "";
		ajaxcall( caller, root + "_getentry.php?entryid=" + entryid.toString() );	
		$(caller).attr("expanded", "1");
		
	}
}

function setpopupposition( popup ) {

	var yoffset = 0;
	if (window.pageYOffset) // for Firefox
		yoffset = window.pageYOffset;
	
	if (document.body.scrollTop) // for Explorer		
		yoffset = document.body.scrollTop;

	if (document.documentElement.scrollTop) // for Explorer	 7	
		yoffset = document.documentElement.scrollTop;
	
	$(popup).find(".contents").css("marginTop", (yoffset + 50).toString() + "px");	
}

function shownewlistpopup() {	
	$("#newlistpopup").find("#listname").val("");
	setpopupposition( "#newlistpopup" );	
	show("#newlistpopup");	
}

function showrenamelistpopup( listid ) {	
	$("#renamelistpopup").attr("listid", listid);
	$("#renamelistpopup").find("#listname").val($("#mylists_" + listid + " .bluebold").text());	
	setpopupposition( "#renamelistpopup" );	
	
	show("#renamelistpopup");	
}

function showbuybookpopup( bookid, isbn ) {	

	var url = "http://www.pocketdirekt.se/pocket_order.php?aterforsaljarID=8bf1211fd4b7b94528899de0a43b9fb3&direkt="+isbn+"100606";	
	ajaxcall(null, root + "_store.php?bookid=" + bookid + "&store=PocketDirekt&url=" + encodeURIComponent(url));	
	html($("#buybookpopup").find("#pdflash"), "<iframe width='720' height='300' frameborder='0' scrolling='no' src='"+url+"'>");
	$("#buybookpopup").children(".contents").css("width","720px");
	setpopupposition( "#buybookpopup" );	
	show("#buybookpopup");	
}

function showloginpopup() {	
	setpopupposition( "#loginpopup" );	
	
	show("#loginpopup");	
}



function newlist() {
	var listname = $("#newlistpopup #listname").val();	
	
	if (listname) {
		$.get(root + "_admin_lists.php?action=new&listname=" + encodeURIComponent(listname), function (msg) {
			//msg = jQuery.trim(msg);
			var listid = parseInt(msg);
			if(listid > 0) {
				$.get(root + "_admin_lists.php?output=mylist&listid=" + listid, function (msg) {
					$("#mylists").prepend(msg);
					sortmylists();
					status("Skapade listan " + listname);
				});
			} else {
				// Error
				msg = jQuery.trim(msg);
				alert(msg);
			}
			
		});	
	}
	
	hide("#newlistpopup");	
}

function deletelist( listid, listname ) {
	var answer = confirm("Är du säker på att du vill ta bort " + listname + "?"); 
	
	if(answer) {		
		ajaxcall( null, root + "_admin_lists.php?action=delete&listid=" + listid.toString() );
		$("#mylists_" + listid).remove();
	}
}

function renamelist( ) {
	var listid = $("#renamelistpopup").attr("listid");
	var listname = $("#renamelistpopup").find("#listname").val();	
	
	if (listname && (listname != "" )) {	
		var oldname = $("#mylists_" + listid + " .bluebold").text();
		if(oldname !== listname) {
		
			$.get(root + "_admin_lists.php?action=rename&listid=" + listid + "&listname=" + encodeURIComponent(listname), function(msg) {
				msg = jQuery.trim(msg);
				if(msg.length > 0) {
					// Error
					alert(msg);
				} else {
					// List has been renamed
					html("#mylists_" + listid + " .bluebold", listname);
					status("Bytte namn på " + oldname + " till " + listname)
				}			
			});	
		}
	} else {
		status("Inget namn angivet");
	}
	hide("#renamelistpopup");
}

function showsearchuserpopup() {	
	
	var popup = getElementById("searchuserpopup");
	var contents = getElementBelowById(popup, "contents");
	getElementBelowById(contents, "name").value = "";
	getElementBelowById(contents, "searchresult").innerHTML = "";
	
	setpopupposition( "#searchuserpopup" );
	show("#searchuserpopup");
}

function searchuser( n ) {
	var name = $("#searchuserpopup #name").val();
	if (name != "" ) {
		$("#searchuserpopup #searchresult").html('<div class="loading" style="width:100%;height:100px;padding:5px;"></div>');					
		n = n ? n : 0;
		ajaxcall( "#searchuserpopup #searchresult", root + "_usersearch.php?name=" + encodeURIComponent(name) + "&n=" + n.toString() );		
	}
	
}

function searchemail( ) {

	var email = $("#searchuserpopup #email").val();
	if (email != "" ) {
		$("#searchuserpopup #searchresult").html('<div class="loading" style="width:100%;height:100px;padding:5px;"></div>');			
		ajaxcall( "#searchuserpopup #searchresult", root + "_usersearch.php?email=" + encodeURIComponent(email) );	
	}
	
}



oldError = '';

function switchReportError(errorType) {
	var newError = errorType;

	if (oldError && oldError != newError) {
		getElementById(oldError).style.display = 'none';
	}

	if (!oldError || oldError != newError) {
		getElementById(newError).style.display = '';
	}

	oldError = newError;
}

function submitDivForm(divId, formId, scriptName) {
	div_obj = getElementById(divId);
	form_obj = getElementById(formId);

	// Read all form values from the error report
	submit_url = root + scriptName + '?';
	for (var i = 0; i < form_obj.elements.length; i++) {
		submit_url += (i ? '&' : '') + escape(form_obj.elements[i].name) + '=' + escape(form_obj.elements[i].value);
	}

	ajaxcall(div_obj, submit_url);
}

function submitReport(divId, formId) {
	submitDivForm(divId, formId, '_report.php');
}

function initCall( ajaxCallObj ) {
		
	if ( ajaxCallObj.type == PRICE ) {
		ajaxCallObj.obj.innerHTML = "<img src = '" + root + "./img/working.gif'/>&nbsp;H&auml;mtar b&auml;sta pris...";
	}
}

function status( msg ) {
	getElementById("statusbar").innerHTML = "&gt;&gt; " + msg;
}

function adjustPopup( popup, caller, v, h ) {	
	
	v = v ? v : 'right';
	h = h ? h : 'middle';
		
	if ( popup && caller ) {		
		var pos = abspos(caller);		
		$(popup).css("left", ( pos.left + (v == 'left' ? 0 : caller.offsetWidth) ).toString() + "px");
		
		$(popup).css("top", adjustToScreen( pos.top, caller.clientHeight, $(popup).height(), h ).toString() + "px");		
		return $(popup).height();
		
	} else {
		msg = "Error: ";
		
		if ( caller == null ) {
			msg += "Caller not found ";
		}
		
		if ( popup == null ) {
			msg += "Popup not found";
		}
		
		status( msg );	
		return false;
	}
	
}

function adjustPopupToLink( popup, caller ) {	
	return adjustPopup( popup, caller, 'left', 'border' )
}

function followUser(userid, stat) {
	$.ajax({
		type: "GET",
		url: root+"_userpopup.php",
		data: "userid=" + userid + "&follow=" + stat,
		cache: false,		
		success: function (msg) {
			//alert("#userpopup .contents " + $("#userpopup .contents").size());
			//ajaxcall(getElementBelowById(getElementById("userpopup"), "contents"), root+"_userpopup.php?userid="+userid+"&root="+root);	
			ajaxcall("#userpopup .contents", root+"_userpopup.php?userid="+userid+"&root="+root);	
			
		}		
		/*error: function (err) {
			alert("Något gick snett, kontakta en administratör om problemet kvarstår.");
		}*/
	});

	ajaxcall("#followfeed", root+"_updatefollow.php?type=feed");
	ajaxcall("#follows" , root+"_updatefollow.php?type=follows");
}

function ajaxcall( obj, url, callback ) {
	if($(obj).size()) {
		$.ajax({
			type: "GET",
			url: url,
			cache: false,
			data: "",
			dataType: "html",
			success: function(response){
				if(obj) {
					// IE hack since $().html is not working
					html(obj, response);

				} else {
					status(response);
				}
				
			}
		});
	}
}

function ajaxcallpopup( popup, url, data, caller, adjustfunc ) {
	if(popup) {
		$.ajax({
		type: "GET",
		url: url,		
		data: data,
		dataType: "html",
		cache: false,
		beforeSend: function(req) {
			
			// Check if mouseoverobj == caller or is child of caller
			if ((caller == mouseoverobj) || ($(caller).find('*').index(mouseoverobj) != -1)) {
				$(popup).children(".contents").attr("style", "width:32px;height:32px;padding:5px;");
				$(popup).children(".contents").html('<div class="loading"></div>');
				
				if(adjustfunc(popup, caller)) show( popup );
				
			} else {				
				$(popup).children(".contents").empty();				
				$("#bookpopup").attr("bookid", 0);
				$("#userpopup").attr("userid", 0);
				hide(popup);
				
				return false;
			}
		},
		success: function(response) {
			if(popup) {		
				// Check if mouseoverobj == caller or is child of caller			
				if ((caller == mouseoverobj) || ($(caller).find('*').index(mouseoverobj) != -1)) { // mouse still hovering over cover
					
					hide(popup);
					//$(popup).children(".contents").attr("style", " ");
					$(popup).children(".contents").removeAttr("style");
					
					// IE hack since html() doesn't work
					html($(popup).children(".contents"), response);

					adjustfunc(popup, caller);			
					
					// Readjust after images have loaded
					if($(popup).find("img").size()) {
						$(popup).find("img").bind("load", function() {
							if(popups_enabled) {
								if(adjustfunc(popup, caller)) { 
									show( popup );
								}
							}
						});
					} else {
						status("No image was found in popup");
						if(adjustfunc(popup, caller)) show( popup );
					}
									
				} else {
					$(popup).children(".contents").empty();				
					$("#bookpopup").attr("bookid", 0);
					$("#userpopup").attr("userid", 0);
					hide(popup);
				}
				
			}
		},
		error: function(response) {
			status(response);
		}
		});

	}
}

function disablepopups() {
	popups_enabled = false;
}

function enablepopups() {
	popups_enabled = true;
}

function serialize( obj, o ) {		
		var str = []; o = o || {};
		var items = $(obj).children($(obj).sortable('option', 'items'))
		
		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
			if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
		});

		return str.join('&');
}

// IE hack since html() doesn't work
function html(obj, contents) {
	var elements = $(obj).get();
	for (var i = 0; i < elements.length; i++) {
		elements[i].innerHTML = contents;
	}
	
	$(obj).find("[title]").each(function() {
		var title = $(this).attr("title");
		if(title) {
			$(this).attr("title", title.replace(/\[br\]/, " " + String.fromCharCode(10)));
		}
	});
}

function closepopup( caller ) {
	hide($( caller ).closest(".fixedpopup"));
}

function stripLinks( caller ) {
	$(caller).find('a').each(function () {
		$(this).replaceWith($(this).html());
	});
}

function htmlentities (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
 
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function html_entity_decode (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
 
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
 
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

function jqtostring(obj) {
	var o = "";
	obj.each(function() {		
		o += this.tagName + (this.className ? '.' + this.className : '') + ' | ';
	});
	return o;
}

function edit_change(caller) {
	var editable = $(caller).parents('.editable');
	
	if(editable.size()) {
		
		$('.editable').switchClass('editable-disabled', 'editable');
			
		editable.addClass('editing');
		
		var changetab = $(caller).parents('.changetab');
		changetab.html("<a onclick='edit_cancel(this);'>Avbryt</a> | <a onclick='edit_sendchange(this);'>Skicka in ändringen</a>");
		
		var bookid = parseInt(editable.attr('bookid'));
		if(bookid) {			
			var attribute = editable.attr('attribute');
			if(attribute) {
				status(attribute);
			}
		}
	}
}

function edit_init() {
	// Add change tab
	$('.editable-disabled').append("<div style='clear:both;'></div><div class='changetab' style='display:none;clear:both;'></div>");		
	$('.editable-disabled').hover(
		function() { // hover
			if($(this).hasClass('editable')) {				
				$(this).addClass('edithover');
				$(this).find('.changetab').show();
			}
		},
		function() { // out
			if(!$(this).hasClass('editing')) {
				if($(this).hasClass('edithover')) {				
					$(this).removeClass('edithover');
					$(this).find('.changetab').hide();
				}
			}
		}
	);
	
	edit_cancel();
	
}

function edit_cancel() {	
	$('.editing').removeClass('editing');
	
	var changetab = $('.changetab');
	changetab.hide();	
	changetab.html("<a onclick='edit_change(this);'>Ändra</a>");		
	$('.editable-disabled').switchClass('editable', 'editable-disabled');	
	$('.editable').removeClass('edithover');
}

