// load user settings, or localized default, or in the last case, anonymous default
if (user!==undefined && user*1 > 0) {
	$.jspeed.create(user);
} else {
	$.ajax({
		async: false,
		global: false,
		url:  "inc/fav-" +geoip+ ".js",
		type: "get",
		dataType: "json",
		success: function(e){ $.jspeed.createAnon(e); },
		error: function(XMLHttpRequest, textStatus, errorThrown){
			if (XMLHttpRequest.status==404) {// if there is no file for this GEOIP, get fav-default.js
				$.ajax({
					async: false,
					global: false,
					url:  "inc/fav-default.js",
					type: "get",
					dataType: "json",
					success: function(e){ $.jspeed.createAnon(e); }
				});
			}
		}
	});
}
var defTab = $.jspeed.jget.defaulttab(),
	currFol = defTab,
	oCurr = $.jspeed.jget.o(currFol),
	nPar = oCurr.folder_id;
// goToTab(); go to clicked tab
var goToTab = function(id) {
	oCurr = $.jspeed.jget.o(id);
	nPar = oCurr.folder_id;
	currFol = id;
	createTabs();
	createSpeedlinks();
};
// setLoader(); blocks user interactions and shows loading message
var setLoader = function() {
	$("#loaderdiv").show();
	if (!$("#loaderOverlay").length) {$("body").append($('<div/>').attr('id','loaderOverlay'));}
};
// removeLoader(); reverses setLoader() effect
var removeLoader = function() {
	$("#loaderdiv").hide();
	if ($("#loaderOverlay").length) {$("#loaderOverlay").remove();}
};
// initAnonymous(); ask for login if authenticated user not found
var initAnonymous = function() {
	if (user===undefined || user*1===0) {
		$(".subaction, .subactiontab, #sladdurl, li.add").unbind().click(function(){
			register.create(); // init anonymous clicks
		});
	}
};
// showSharingOptions(); show modal containing sharing options
var showSharingOptions = function() {
	setLoader();
	$.ajax({
		type:"POST",
		url:"ajax/sharing.php",
		data:"id="+ user +"&",
		async:false,
		success:function(msg){
			if (msg.length>0) { // este user ya tiene direccion
				$("<div/>").attr({id:"fav"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><div id="optshar1"><h3 class="orange">'+ key.share4 +':</h3><a href="http://www.zombol.com/favorites/' + msg + '" target="_blank" class="blue">http://www.zombol.com/favorites/' + msg + '</a><br /><br />'+ key.share5 +'<br /><br /><div align="center"><input type="submit" value="'+ key.share6 +'" id="agregapublico" />&nbsp;<input type="button" id="canceladdp" value="'+ key.cancel +'" /></div></div>').appendTo(".imgprecache").modal({
					overlayId:"noteOverlay",
					containerId:"setQuicklinks",
					onShow:function() {
						var h = parseInt( $("#setQuicklinks").css("height"),10 ),
								t = parseInt( $("#setQuicklinks").css("top"),10 ),
								pos = h  / 2 - 36;
								$("#setQuicklinks").css({top:(t - pos)+"px"});
								removeLoader();
						$("#noteOverlay").click(function(){$.modal.close();$('#fav').remove();});
						$(document).keyup(function(e){if(e.which==27){$.modal.close();$('#fav').remove();}});
						$("#agregapublico").click(function(){ // agregar pestaņa a un alias ya creado
							setLoader();
							$(this).attr("disabled","disabled");
							//oFold = $.jspeed.jget.o(id);
							oFold = $.jspeed.jget.o(currFol);
							oFold.shared = "1";
							if ($.jspeed.getSharedParent(oFold.folder_id)) {
								nPar = oFold.folder_id;
								$.modal.close();
								$("#fav").remove();
								createTabs();
								alert(key.share7);
							} else {
								if ($.jspeed.jupdate(oFold) && $.jspeed.save()) {
									$.modal.close();
									$("#fav").remove();
									$.jspeed.setChildsShared(oFold, "0");
									if ($.jspeed.savePublicShare()) {
										$.ajax({
											type:"POST",
											url:"ajax/sharing.php",
											data:"id="+ user +"&np="+ msg +"&f="+ currFol +"&",
											async:true
										});
										alert(key.share22 +"\nhttp://www.zombol.com/favorites/"+ msg);
									} else {
										alert(key.share7);
									}
									createTabs();
								}
							}
							removeLoader();
						});
						$("#canceladdp, #modal-close").click(function(){removeLoader();$.modal.close();$("#fav").remove();});
					}
				});
			} else { // crear nuevo alias, etc
				$("<div/>").attr({id:"fav"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif" /></span><br /><div id="optshar1"><h3 class="orange">'+ key.share8 +'</h3>http://www.zombol.com/favorites/<input type="text" class="newgroup" value="" maxlength="30" /><br /><br />'+ key.share9 +' <em>'+ username.toLowerCase() +'</em> &nbsp;'+ key.share10 +' <br /><em>http://www.zombol.com/favorites/'+ username.toLowerCase() +'</em><br /><br /><div align="center"><input type="submit" value="'+ key.share11 +'" id="creapublico" />&nbsp;<input type="button" id="cancelcreap" value="'+ key.cancel +'" /></div></div>').appendTo(".imgprecache").modal({
					overlayId:"noteOverlay",
					containerId:"setQuicklinks",
					onShow:function() {
						var h = parseInt( $("#setQuicklinks").css("height"),10 ),
								t = parseInt( $("#setQuicklinks").css("top"),10 ),
								pos = h  / 2 - 36;
						$("#setQuicklinks").css({top:(t - pos)+"px"});
						removeLoader();
						$(".newgroup").focus();
						$("#creapublico").click(function(){
							var npage = $(".newgroup").val();
							if (npage.length>0) {
								setLoader();
								$(this).attr("disabled","disabled");
								//oFold = $.jspeed.jget.o(id);
								oFold = $.jspeed.jget.o(currFol);
								oFold.shared = "1";
								if ($.jspeed.getSharedParent(oFold.folder_id)) {
									nPar = oFold.folder_id;
									$.modal.close();
									$("#fav").remove();
									createTabs();
									alert(key.share7);
								} else {
									if ($.jspeed.jupdate(oFold) && $.jspeed.save()) {
										$.modal.close();
										$("#fav").remove();
										$.jspeed.setChildsShared(oFold, "0");
										if ($.jspeed.savePublicShare(npage)) {
											$.ajax({
												type:"POST",
												url:"ajax/sharing.php",
												data:"id="+ user +"&np="+ npage +"&f="+ currFol +"&",
												async:true
											});
											alert(key.share13 +":\nhttp://www.zombol.com/favorites/"+ npage);
										} else {
											alert(key.share7);
										}
										createTabs();
									}
								}
								removeLoader();
								/* TODO: procesar respuestas y mostrar fdbk */
							} else {
								$(".newgroup").focus();
							}
						});
						$("#cancelcreap, #modal-close").click(function(){removeLoader();$.modal.close();$("#fav").remove();});
						$(".newgroup").keyup(function(e){ if (e.which==13) { $("#creapublico").click(); } });
					}
				});
			}
		}
	});
};
// unshareTab(); removies sharing from a tab
var unshareTab = function(tid) {
	if (confirm(key.unshare +"\n"+ key.deleteB +".")) {
		setLoader();
		oFold = $.jspeed.jget.o(tid);
		oFold.shared = "0";
		if ($.jspeed.jupdate(oFold) && $.jspeed.save()) {
			$.jspeed.savePublicShare();
			createTabs();
			alert(key.share20);
		}
		removeLoader();
	}
};
// makeIconsHoverable(); show or hide maintenance icons in tab / titlebar
var makeIconsHoverable = function() {
	// hovering tabs
	$("#folderow li").hover(
		function(){
			if ($(this).attr('id').substr(4)==currFol) { $("a.action",this).show(); }
			$("div.title",this).css("textDecoration","underline");
		},
		function(){
			$("a.action",this).hide();
			$("div.title",this).css("textDecoration","none");
		}
	);
	// hovering favorites and subfolders
	$(".slbox, .folbox").hover(
		function(){
			$("a.action",this).show();
			$("div.title",this).css("textDecoration","underline");
		},
		function(){
			$("a.action",this).hide();
			$("div.title",this).css("textDecoration","none");
		}
	);
};
// manageTabClicks(); manage clicks on tabs row
var manageTabClicks = function() {
	$("#folderow li .tabtitle").click(function(){
		var oTab = $(this).parent(),
		f = oTab.attr("id").substr(4);
		if (oTab.attr("class")!="active") {goToTab(f);}
	});
};
// manageTabIconClicks(); manage clicks on top row tab's option icon
var manageTabIconClicks = function() {
	$("#folderow li .holder a").click(function(e){
		var a = this.id.substr(0,4),
			id = this.id.substr(4);
		// prevent showing options on unfocused tabs
		if (id!=currFol) {goToTab(id);} else {
			// show box with links to config settings
			if (a=='etab') {
				boxid = "set_"+id;
				$("body").append($("<div/>").attr('id',boxid));
				var pos = $("#fold"+id).offset(),
					hoffset = $("#fold"+id).width()+4,
					voffset = $(document).scrollTop()-16;
				$.modal($("#opts"+id),{
					overlayId:"noteOverlay",
					containerId:"settFolderContainer",
					opacity:1,
					position:[pos.top-voffset, pos.left+hoffset],
					onShow:function(dialog) {
						$("a[id^='set']").attr("href","javascript"+":void(0)");
					}
				});
				$("#noteOverlay").click(function(){$.modal.close();$('#'+boxid).remove();});
				$(document).keyup(function(e){if(e.which==27){$.modal.close();$('#'+boxid).remove();}});
				// functions for each link
				if (user!==undefined && user*1 > 0) {
					// //show sharing options
					$("a[id^='set9_']").click(function(){
						$.modal.close();
						$('#'+boxid).remove();
						showSharingOptions();
					});
					// //rename tab
					$("a[id^='set5_']").click(function(){
						$.modal.close();
						$('#'+boxid).remove();
						var closeRenamer = function() {
							removeLoader();
							$.modal.close();
							$("#renm1").remove();
						};
						var renameTab = function(eid, nn) {
							if (nn.length>0) {
								$("#rename1, #cancelr1").attr("disabled","disabled");
								setLoader();
								var oEl = $.jspeed.jget.o(eid);
								oEl.title = nn;
								if ($.jspeed.jupdate(oEl) && $.jspeed.save()) {
									$("#fsp"+eid).html(nn);
									closeRenamer();
								}
							}
						};
						$("<div/>").attr({id:"renm1"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><h3 class="orange">'+ key.renameA +':</h3><div class="cntInput"><input type="text" id="newname" class="input-modal" value="' + $("#fsp"+id).html() + '" /></div><div align="center"><br /><input type="button" id="rename1" value="'+ key.renameB +'" />&nbsp;<input type="button" id="cancelr1" value="'+ key.cancel +'" /></div>').appendTo(".imgprecache").modal({
							overlayId:"noteOverlay",
							containerId:"setQuicklinks",
							onShow:function() {
								var h = parseInt( $("#setQuicklinks").css("height"),10 ),
								t = parseInt( $("#setQuicklinks").css("top"),10 ),
								//             v---- 36 de sumar paddingTop y paddingBottom
								pos = h  / 2 - 36;
								$("#setQuicklinks").css({top:(t - pos)+"px"});
								$("#noteOverlay, #cancelr1, #modal-close").click(function(){closeRenamer()});
								$("#newname").focus().select().keyup(function(e){
									if(e.which==13 && $("#newname").length>0){
										renameTab(id, $("#newname").val());
										closeRenamer();
									} else if(e.which==27) {
										closeRenamer();
									}
								});
								$("#rename1").click(function(){
									renameTab(id, $("#newname").val());
									closeRenamer();
								});
							}
						});
					});
					// //duplicate tab
					$("a[id^='set7_']").click(function(){
						$.modal.close();
						$('#'+boxid).remove();
						setLoader();
						var oEl = $.jspeed.jget.o(id);
						if ($.jspeed.jduplicate(oEl.folder_id, id) && $.jspeed.save()) {
							createTabs();
							removeLoader();
						}
					});
					// //create subfolder
					$("a[id^='set8_']").click(function(){
						var addnsf = function(nn){
							if (nn.length>0) {
								$("#addnfolder, #canceladd").attr("disabled","disabled");
								setLoader();
								var oNew = {"id":null,"title":nn,"notes":"","order":"","type":"f","shared":"0","folder_id":"","childs":[]};
								if ($.jspeed.jset(id, oNew) && $.jspeed.save()) {
									$.modal.close();
									$("#addsubf").remove();
									var oFold = $.jspeed.jget.o(id);
									if ($.jspeed.getSharedParent(oFold.id)) {
										$.jspeed.savePublicShare();
									}
									createSpeedlinks();
								}
								removeLoader();
							}
						};
						$(this).parent().after($(document.createElement('div')).attr('id','addsubf'));
						$.modal.close();
						$('#'+boxid).remove();
						$("<div/>").attr({id:"addsubf"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><h3 class="orange">'+ key.createB +':</h3><div class="cntInput"><input type="text" class="input-modal" maxlength="20" value="" /></div><br /><input type="button" id="addnfolder" value="'+ key.createA +'" /> <input type="button" id="canceladd" value="'+ key.cancel +'" />').appendTo(".imgprecache").modal({
							overlayId:"noteOverlay",
							containerId:"setQuicklinks",
							onShow:function(dialog) {
								var h = parseInt( $("#setQuicklinks").css("height"),10 ),
								t = parseInt( $("#setQuicklinks").css("top"),10 ),
								pos = h  / 2 - 36;
								$("#setQuicklinks").css({top:(t - pos)+"px"});
								$(".input-modal").focus().keyup(function(e){if(e.which==13){
									addnsf($(".input-modal").val());
								}});
								$("#addnfolder").click(function(){
									addnsf($(".input-modal").val());
								});
							}
						});
						$("#noteOverlay, #canceladd, #modal-close").click(function(){removeLoader();$.modal.close();$("#addsubf").remove();});
						$(document).keyup(function(e){if(e.which==27){removeLoader();$.modal.close();$("#addsubf").remove();}});
					});
					// //delete top folder
					$("a[id^='set6_']").click(function(){
						setLoader();
						$.modal.close();
						$('#'+boxid).remove();
						if (confirm(key.deleteA +"\n"+ key.deleteB +".")) {
							var oFold = $.jspeed.jget.o(id);
							if ($.jspeed.jremove(id) && $.jspeed.save()) {
								$("#fold"+id).remove();
								if (oFold.shared=='1' || $.jspeed.getSharedParent(oFold.folder_id)) {
									$.jspeed.savePublicShare();
								}
								if (id==currFol && id!=defTab) {
									goToTab(defTab);
								}
							}
							removeLoader();
						}
					});
					// //move to subfolder
					$("a[id^='set11_']").click(function(){
						var oEl=$.jspeed.jget.o(id),
							aryPaths = $.jspeed.jget.ftree(),
							ops = '<option value="">'+ key.selectA +'</option>',
							rec = 'folder';
						for (var i in aryPaths) {
							var path=aryPaths[i][0], targid=aryPaths[i][1];
							if ((oEl.type=='s' && targid!=oEl.folder_id) || (oEl.type=='f' && targid!=oEl.id && targid!=oEl.folder_id)) {
								ops += '<option value="'+ targid +'">'+ path +'</option>';
							}
						}
						$.modal.close();
						$('#'+boxid).remove();
						$("<div/>").attr({id:"moveto"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><h3 class="orange">'+ key.speedLinkD +' tab '+ $("#fsp"+id).html().toUpperCase().bold()+' '+ key.speedLinkE +':</h3><select id="movto">'+ ops +'</select><br /><div align="center"><br /><input type="button" id="movfolder" value="'+ key.speedLinkF +'" />&nbsp;<input type="button" id="cancelmov" value="'+ key.cancel +'" /></div>').appendTo(".imgprecache").modal({
							overlayId:"noteOverlay",
							containerId:"setQuicklinks",
							onShow:function() {
								var h = parseInt( $("#setQuicklinks").css("height"),10 ),
								t = parseInt( $("#setQuicklinks").css("top"),10 ),
								pos = h  / 2 - 36;
								$("#setQuicklinks").css({top:(t - pos)+"px"});
							}
						});
						$("#noteOverlay, #cancelmov, #modal-close").click(function(){$.modal.close();$("#moveto").remove();});
						$(document).keyup(function(e){if(e.which==27){$.modal.close();$("#moveto").remove();}});
						$("#movfolder").click(function(e){
							var tg = $("#movto").val();
							if (tg!=='') {
								oEl.folder_id = tg;
								setLoader();
								$("#movfolder, #cancelmov").attr("disabled","disabled");
								if ($.jspeed.jremove(id) && $.jspeed.jset(tg,oEl) && $.jspeed.save()) {
									$.modal.close();
									$("#moveto").remove();
									var oFold1 = $.jspeed.jget.o(nPar);
									var oFold2 = $.jspeed.jget.o(tg);
									if ($.jspeed.getSharedParent(oFold1.folder_id) || $.jspeed.getSharedParent(oFold2.folder_id) || oFold1.shared=='1' || oFold2.shared=='1') {
										$.jspeed.savePublicShare();
									}
									createTabs();
									createSpeedlinks();
									alert(key.speedLinkA +' '+rec+' '+ key.speedLinkB);
									removeLoader();
								} else {
									alert(key.speedLinkC +' '+rec);
									removeLoader();
								}
							}
						});
					});
				} else {
					$(".subactiontab").click(function(){ // init anonymous clicks
						$.modal.close();
						$('#'+boxid).remove();
						register.create();
					});
				}
			}
		}
	});
	$("#folderow li .vholder").click(function(e){
		// prevent showing unshare option on unfocused tab
		var id = $(this).children(0).attr('id').substr(4),
			pos = $("#utab"+id).offset(),
			hoffset = $("#utab"+id).width(),
			voffset = $(document).scrollTop()-12,
			box4id = "sharset_"+id;
		if (id!=currFol) {goToTab(id);} else {
			$("body").append($(document.createElement('div')).attr('id',box4id));
			$.modal($("#"+box4id),{
				overlayId:"noteOverlay",
				containerId:"settFolderContainer",
				opacity:1,
				position:[pos.top-voffset, pos.left+hoffset],
				onShow:function(dialog) {
					$("#"+ box4id).html('<a id="set10_'+ id +'" class="subactiontab" href="javascript:void(0)">'+ key.optionK +'</a>');
					$("a[id^='set10_']").click(function(){
						$.modal.close();
						$('#'+box4id).remove();
						unshareTab(id);
					});
				}
			});
			$("#noteOverlay").click(function(){$.modal.close();$('#'+box4id).remove();});
			$(document).keyup(function(e){if(e.which==27){$.modal.close();$('#'+box4id).remove();}});
		}
	});
};
// manageSpeedLinkClicks(); manage actions on subfolder and speedlinks icons
var manageSpeedLinkClicks = function() {
	$(".slbox .container img").hover(
		function(){window.status = $(this).prev().text()+'/';},
		function(){window.status = '';}
	).click(
		function(){window.open($(this).prev().html());}
	);
	$(".folbox .container").click(function(){goToTab($(this).parent().attr('id').substr(3));});
	$("#ulSpeedLinks").sortable({
		opacity:0.5,
		distance:10,
		handle:$(".slbox,.folbox"),
		placeholder:"slplaceholder",
		update:function(e,ui){
			setLoader();
			var orden = $("#ulSpeedLinks").sortable("serialize"), pos, oEl;
			var aryOrd = orden.split('&');
			for (var i in aryOrd) {
				pos = aryOrd[i].split('[]=');
				oEl = $.jspeed.jget.o(pos[1]);
				oEl.order = String(parseInt(i,10)+1);
				$.jspeed.jupdate(oEl);
			}
			if($.jspeed.save()){ removeLoader(); }
		}
	});
	$("#slsubmit").click(function(){addNewSpeedlink();});
	$("#sladdurl").keyup(function(e){if(e.which==13 && $(this).val().length>0){addNewSpeedlink();}});
	$(".titlebar .action").click(function(){
		var a = this.id.substr(0,4),
		id = this.id.substr(4),
		t = $(this).parent().parent().attr('class')=='folbox' ? 'F' : 'S',
		rec = t=='F' ? 'folder' : key.favorite,
		pre = t=='F' ? 'fo_' : 'sl_';
		// delete speedlink
		if(a=='drop'){
			if (confirm(key.deleteC +" "+ rec +"?\n"+ key.deleteB +".")) {
				setLoader();
				var oFold = $.jspeed.jget.o(id);
				if ($.jspeed.jremove(id) && $.jspeed.save()) {
					$("#"+pre+id).remove();
					if ($.jspeed.getSharedParent(oFold.folder_id)) {
						$.jspeed.savePublicShare();
					}
					removeLoader();
				}
			}
		// show box with links to config settings
		} else if (a=='edit') {
			var box3id = "set_"+id,
				pos = $(this).parent().offset(),
				hoffset = $("#edit"+id).width()+180,
				voffset = $(document).scrollTop()-20;
			$.modal($("#settings_"+id),{
				overlayId:"noteOverlay",
				containerId:"settingsContainer",
				opacity:1,
				position:[pos.top-voffset, pos.left+hoffset],
				onShow:function(dialog) {
					$("#settingsContainer").html($("#settings_"+id).html());
					$("a[id^='set']").attr("href","javascript"+":void(0)");
				}
			});
			$("#noteOverlay").click(function(){$.modal.close();$('#'+box3id).remove();});
			$(document).keyup(function(e){if(e.which==27){$.modal.close();$('#'+box3id).remove();}});
			// functions for each link
			if (user!==undefined && user*1 > 0) {
				// //reorder A-Z o Z-A
				$("a[id^='set1_']").click(function(){
					$(this).after('&nbsp;&nbsp; <span class="minilnk" id="az">A-Z</span>&nbsp;<span class="minilnk" id="za">Z-A</span>');
					$(".minilnk").click(function(){
						$.modal.close();
						$('#'+box3id).remove();
						setLoader();
						var oFold = $.jspeed.jget.o(id);
						if ($.jspeed.jsort(currFol,this.id==='az') && $.jspeed.save()) {
							if ($.jspeed.getSharedParent(oFold.folder_id)) {
								$.jspeed.savePublicShare();
							}
							createSpeedlinks();
							removeLoader();
						}
					});
				});
				// //rename
				$("a[id^='set2_']").click(function(){
					$.modal.close();
					$('#'+box3id).remove();
					var ot = t=='F' ? $('#tf_'+id).html() : $('#ts_'+id).html();
					$("<div/>").attr({id:"renm2"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><h3 class="orange">'+ key.createG +' '+ rec +':</h3><div class="cntInput"><input type="text" id="newname" class="input-modal" value="'+ ot +'" /></div><div align="center"><br /><input type="button" id="rename1" value="'+ key.speedLinkH +'" />&nbsp;<input type="button" id="cancelr1" value="'+ key.cancel +'" /></div>').appendTo(".imgprecache").modal({
						overlayId:"noteOverlay",
						containerId:"setQuicklinks",
						onShow:function() {
							var hei = parseInt( $("#setQuicklinks").css("height"),10 ),
									top = parseInt( $("#setQuicklinks").css("top"),10 ),
									pos = hei  / 2 - 36;
									$("#setQuicklinks").css({top:(top - pos)+"px"});
							var renameSL = function(eid, nn) {
								if (nn.length>0) {
									var oEl = $.jspeed.jget.o(eid);
									oEl.title = nn;
									setLoader();
									$("#rename1, #cancelr1").attr("disabled","disabled");
									if ($.jspeed.jupdate(oEl) && $.jspeed.save()) {
										if ($.jspeed.getSharedParent(oEl.folder_id)) {
											$.jspeed.savePublicShare();
										}
										$('#t'+ t.toLowerCase() +'_'+eid).html(nn);
										$.modal.close();
										$("#renm2").remove();
										removeLoader();
									}
								}
							};
							$("#noteOverlay, #cancelr1, #modal-close").click(function(){$.modal.close();$("#renm2").remove();});
							$("#newname").focus().select().keyup(function(e){
								if(e.which==13 && $("#newname").length>0){
									renameSL(id, $("#newname").val());
								} else if(e.which==27){
									$.modal.close();$("#renm2").remove();
								}
							});
							$("#rename1").click(function(){renameSL(id, $("#newname").val());});
						}
					});
				});
				// //change parent folder (move to)
				$("a[id^='set3_']").click(function(){
					var oEl=$.jspeed.jget.o(id),
					aryPaths = $.jspeed.jget.ftree(),
					ops='<option value="">'+ key.selectA +'</option>';
					if (oEl.type=='f') { ops+='<option value="0">/</option>'; }
					for (var i in aryPaths) {
						var path=aryPaths[i][0], targid=aryPaths[i][1];
						if ((oEl.type=='s' && targid!=oEl.folder_id) || (oEl.type=='f' && targid!=oEl.id && targid!=oEl.folder_id)) {
							ops += '<option value="'+ targid +'">'+ path +'</option>';
						}
					}
					$.modal.close();
					$('#'+box3id).remove();
					var mt = t=='F' ? '#tf_' : '#ts_';
					$("<div/>").attr({id:"moveto"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><h3 class="orange">'+ key.speedLinkD +' '+ rec +' '+ $(mt+id).html().toUpperCase().bold()+' '+ key.speedLinkE +':</h3><select id="movto">'+ ops +'</select><div align="center"><br /><input type="button" id="movfolder" value="'+ key.speedLinkF +'" />&nbsp;<input type="button" id="cancelmov" value="'+ key.cancel +'" /></div>').appendTo(".imgprecache").modal({
						overlayId:"noteOverlay",
						containerId:"setQuicklinks",
						onShow:function() {																						
							var h = parseInt( $("#setQuicklinks").css("height"),10 ),
							t = parseInt( $("#setQuicklinks").css("top"),10 ),
							pos = h  / 2 - 36;
							$("#setQuicklinks").css({top:(t - pos)+"px"});
						}
					});
					$("#noteOverlay, #cancelmov, #modal-close").click(function(){$.modal.close();$("#moveto").remove();});
					$(document).keyup(function(e){if(e.which==27){$.modal.close();$("#moveto").remove();}});
					$("#movfolder").click(function(e){
						var tg = $("#movto").val(),
						oFold1 = $.jspeed.jget.o(nPar),
						oFold2 = $.jspeed.jget.o(tg);
						if (tg!=='') {
							oEl.folder_id = tg;
							setLoader();
							$("#movfolder, #cancelmov").attr("disabled","disabled");
							if ($.jspeed.jremove(id) && $.jspeed.jset(tg,oEl) && $.jspeed.save()) {
								$.modal.close();
								$("#moveto").remove();
								if ($.jspeed.getSharedParent(oFold1.folder_id) || $.jspeed.getSharedParent(oFold2.folder_id) || oFold1.shared=='1' || oFold2.shared=='1') {
									$.jspeed.savePublicShare();
								}
								createTabs();
								createSpeedlinks();
								removeLoader();
								alert(key.speedLinkA +' '+rec+' '+ key.speedLinkB);
							} else {
								removeLoader();
								alert(key.speedLinkC +' '+rec);
							}
						}
					});
				});
				// //add or edit note
				$("a[id^='set4_']").click(function(){
					var current_note = $("#ntxt_"+id).html(),
						box2id = "nt_"+id,
						mt = t=='F' ? '#tf_' : '#ts_',
						pos = $(mt+id).offset(),
						hoffset = $(mt+id).width()+20,
						voffset = $(document).scrollTop()-14;
					$.modal.close();
					$('#'+box3id).remove();
					$("#"+box2id).modal({
						overlayId:"noteOverlay",
						containerId:"noteContainer",
						position:[pos.top-voffset, pos.left+hoffset],
						onShow:function(dialog) {
							$("#noteContainer").html('<textarea id="note_'+ id +'" class="editnote" rows="5" cols="14">'+ current_note +'</textarea><img src="'+general.baseUrl+'/images/closenote.gif" alt="" title="'+ key.iclose +'" class="closenote" />').animate({"width":"143px", "height":"96px"}, "fast", "linear", function(){$('#note_'+ id).focus();});
						}
					});
					$(document).keyup(function(e){if(e.which==27){$.modal.close();$('#'+box2id).remove();}});
					$("#noteOverlay, .closenote").click(function(){
						var newnote = $("#note_"+id).val();
						if (newnote != $("#ntxt_"+id).html()) {
							setLoader();
							$("#ntxt_"+id).html(newnote);
							$("#set4_"+id).html(newnote==='' ? key.optionF : key.optionI);
							var oEl = $.jspeed.jget.o(id);
							oEl.notes = newnote;
							if ($.jspeed.jupdate(oEl) && $.jspeed.save()) {
								if ($.jspeed.getSharedParent(oEl.folder_id) || oEl.shared==1) {
									$.jspeed.savePublicShare();
								}
								removeLoader();
							}
						}
						$.modal.close();
						$('#'+box2id).remove();
					});
				});
				// end functions for each link
			} else {
				$(".subaction").click(function(){ // init anonymous clicks
					$.modal.close();
					$('#'+box3id).remove();
					register.create();
				});
			}
		}
	});
};
// addNewTab(); manage clicks on "Create tab"
var addNewTab = function(){
	var createFolder = function() {
		$("<div/>").attr({id:"addf"}).html('<span id="modal-close" class="cursor"><img src="'+ general.baseUrl +'/images/modal-close.gif"/></span><br /><h3 class="orange">'+ key.renameC +':</h3><div class="cntInput"><input type="text" class="input-modal" maxlength="20" value="" /></div><br /><input type="button" id="addnfolder" value="'+ key.createA +'" /> <input type="button" id="canceladd" value="'+ key.cancel +'" />').appendTo(".imgprecache").modal({
			overlayId:"noteOverlay",
			containerId:"setQuicklinks",
			onShow:function(dialog) {
				var h = parseInt( $("#setQuicklinks").css("height"),10 ),
				t = parseInt( $("#setQuicklinks").css("top"),10 ),
				pos = h  / 2 - 36;
				$("#setQuicklinks").css({top:(t - pos)+"px"});
			}
		});
		$("#noteOverlay, #canceladd, #modal-close").click(function(){$.modal.close();$("#addf").remove();});
		$(document).keyup(function(e){if(e.which==27){$.modal.close();$("#addf").remove();}});
		function addit(v) {
			if (v.length>0) {
				setLoader();
				$("#addnfolder, #canceladd").attr("disabled","disabled");
				var oNew = {"id":null,"title":v,"notes":"","order":"","type":"f","shared":"0","folder_id":"","childs":[]};
				if ($.jspeed.jset(nPar, oNew) && $.jspeed.save()) {
					$.modal.close();
					$("#addf").remove();
					var oFold = $.jspeed.jget.o(nPar);
					if ($.jspeed.getSharedParent(oFold.id)) {
						$.jspeed.savePublicShare();
					}
					createTabs();
					removeLoader();
				}
			}
		}
		$(".input-modal").focus().keyup(function(e){if(e.which==13){
			addit(this.value);
		}});
		$("#addnfolder").click(function(){
			addit($(".input-modal").val());
		});
	};
	$("#addtab").click(createFolder);
};
// addNewSpeedlink(); manage "Add speedlink" link click
var addNewSpeedlink = function(){
	var newsl = $("#sladdurl").val();
	if (newsl.length>0) {
		setLoader();
		$("#sladdurl").attr("readonly", "readonly");
		$("#slsubmit").hide().after('<img src="'+general.baseUrl+'/images/loader_big.gif" alt="Loading..." id="loadprog" />');
		$.ajax({
			type:"POST",
			url:"ajax/addspeedlink.php",
			data:"url="+ encodeURIComponent(newsl) +"&",
			dataType:"json",
			success:function(oRes){
				if (oRes.result=='ERROR') {
					alert(key.speedLinkError);
				} else {
					var oNew = {"id":null,"title":oRes.title,"notes":"","order":"","url":oRes.url,"type":"s","folder_id":currFol};
					if ($.jspeed.jset(currFol, oNew) && $.jspeed.save()) {
						var oFold = $.jspeed.jget.o(currFol);
						if ($.jspeed.getSharedParent(oFold.id)) {
							$.jspeed.savePublicShare();
						}
						createSpeedlinks();
					}
				}
				$("#loadprog").remove(); //replaceWith('<input type="button" id="slsubmit" value="'+ key.createA +'" />');
				$("#slsubmit").show();
				$("#sladdurl").removeAttr("readonly").val('');
				removeLoader();
			}
		});
	}
	return false;
};
// createTabs(); create xhtml for tabs row
var createTabs = function(){
	// .id, .title, .notes, .order, .type (f/s), .childs, .folder_id
	var xhtml = '';
	var oTabs = $.jspeed.jget.folders(nPar);
	if (nPar>0) {
		xhtml += '<li class="up" title="'+ key.optionG +'" onclick="goToTab('+ nPar +')" /></li>';
	}
	for (var i in oTabs) {
		var id = oTabs[i].id,
		title = oTabs[i].title;
		xhtml += '<li id="fold'+ id;
		if (currFol==id) {xhtml += '" class="active';}
		xhtml += '">';
		xhtml += '<div id="fsp'+ id +'" class="tabtitle">'+ title +'</div>';
		if (oTabs[i].shared=='1') {
			xhtml += '<div class="vholder"><a id="utab'+ id +'"><img src="'+general.baseUrl+'/images/shared.gif" class="icon" alt="'+ key.share24 +'" title="'+ key.share24 +'" /></a></div>';
		}
		xhtml += '<div class="holder"><a id="etab'+ id +'" class="action"><img src="'+general.baseUrl+'/images/fedit.gif" class="icon" alt="'+ key.optionE +'" title="'+ key.optionE +'" /></a></div>';
		xhtml += '<span id="opts'+ id +'" class="hidden">';
		if (oTabs[i].id!=defTab && !$.jspeed.getSharedParent(oTabs[i].folder_id)) {
			if (oTabs[i].shared=='0') {
				xhtml += '<a id="set9_'+ id +'" class="subactiontab">'+ key.optionJ +'</a>';
			}
		}
		xhtml += '<a id="set5_'+ id +'" class="subactiontab">'+ key.optionA +'</a>';
		xhtml += '<a id="set7_'+ id +'" class="subactiontab">'+ key.optionB +'</a>';
		xhtml += '<a id="set11_'+ id +'" class="subactiontab">'+ key.speedLinkI +'</a>';
		xhtml += '<a id="set8_'+ id +'" class="subactiontab">'+ key.optionC +'</a>';
		if (defTab!=id) {
			xhtml += '<a id="set6_'+ id +'" class="subactiontab">'+ key.optionD +'</a>';
		}
		xhtml += '</span></li>';
	}
	xhtml += '<li id="addtab" class="add">'+ key.createD +'</li>';
	$("#folderow").html(xhtml);
	/*
	$("ul#folderow li").css({backgroundColor:'#'+theme});
	if(theme==='242424'||theme==='069'||theme==='00991b'){
		$("ul#folderow li").css("color","white");
		$("ul#folderow li.add").css({backgroundImage:'url('+general.baseUrl+'/images/add_inv.gif)'});
		$("ul#folderow li.up").css({backgroundImage:'url('+general.baseUrl+'/images/up_inv.gif)'});
	}
	*/
	makeIconsHoverable();
	manageTabClicks();
	manageTabIconClicks();
	addNewTab();
};
// createSpeedlinks(); create xhtml for speedlinks
var createSpeedlinks = function(){
	// .id, .title, .notes, .order, .url, .type (f/s), .folder_id
	var oChilds = $.jspeed.jget.items(currFol);
	var xhtml = '';
	for (var i in oChilds) {
		var id = oChilds[i].id,
		title = oChilds[i].title,
		notes = oChilds[i].notes,
		url = oChilds[i].url,
		css = oChilds[i].type=='f' ? 'folbox' : 'slbox',
		pref1 = oChilds[i].type=='f' ? 'fo_' : 'sl_',
		pref2 = oChilds[i].type=='f' ? 'tf_' : 'ts_',
		fav = oChilds[i].type=='f' ? '' : '<div class="favico"><img src="'+ url +'/favicon.ico" alt="" /></div>',
		notelink = notes==='' ? key.optionF : key.optionI,
		snap = oChilds[i].type=='f' ? '<div class="container"></div>' : '<div class="container"><span class="hidden">'+ url +'</span><img src="http://zombol.websnapr.com/?size=S&url='+ url +'" alt="'+ title +'" title="'+ title +'" /></div>';
		xhtml += '<li class="'+ css +'" id="'+ pref1 + id +'"><div class="titlebar">'+ fav;
		xhtml += '<div class="title" id="'+ pref2 + id +'" style="float:left">'+ title +'</div>';
		xhtml += '<a id="drop'+ id +'" class="action subactiontab"><img src="'+general.baseUrl+'/images/close.gif" class="icon" alt="'+ key.optionD +'" title="'+ key.optionD +'" /></a>';
		xhtml += '<a id="edit'+ id +'" class="action"><img src="'+general.baseUrl+'/images/edit.gif" class="icon" alt="'+ key.optionE +'" title="'+ key.optionE +'" /></a>';
		xhtml += '<span id="ntxt_'+ id +'" class="hidden">'+ notes +'</span>';
		xhtml += '<span id="settings_'+ id +'" class="hidden">';
		xhtml += '<a id="set1_'+ id +'" class="subaction">'+ key.speedLinkG +'</a>';
		xhtml += '<a id="set2_'+ id +'" class="subaction">'+ key.speedLinkH +'</a>';
		xhtml += '<a id="set3_'+ id +'" class="subaction">'+ key.speedLinkI +'</a>';
		xhtml += '<a id="set4_'+ id +'" class="subaction">'+ notelink +'</a>';
		xhtml += '</span></div>'+ snap;
	}
	xhtml += '<li class="slbox"><div class="titlebar"><div class="title2">'+ key.createC +'</div></div>';
	xhtml += '<div class="container"><form id="addsl" method="" action="" onsubmit="return false">';
	xhtml += '<h2>'+ key.createE +':</h2>http://<input type="text" id="sladdurl" name="url" maxlength="60" value="" /><br />';
	xhtml += '<input type="button" id="slsubmit" value="'+ key.createA +'" /></form></div></li>';
	$("#ulSpeedLinks").css({background:'#'+ theme +' url('+general.baseUrl+'/images/themes/'+ theme +'.gif)'}).html(xhtml);
	makeIconsHoverable();
	manageSpeedLinkClicks();
};
// populate tab row and speedlinks area on first load
$(function(){
	createTabs();
	createSpeedlinks();
	initAnonymous();
});
