var list = "";
var showAll = false;

$(function() {
		initAddable();
});

$(function() {
	// add remove link
	$("ul#quicklinks > li > .removeLink").click(function(){
		removeLink(this);
	});

	// create sortable list of custom quick links
	$("#quicklinks").sortable({
		//cancel: '.qldisabled',
		opacity: 0.7,
		update: function() {
			var order = $(this).sortable("toArray");
			updateLinkList(order,this);
		}
	});
});

function initAddable()
{
	// make addable links 'clickable'
	$('#addablelinks > li').not('.newLetter').click(function() {
		tempCookie = $.cookie("quicklinks");
		if( tempCookie != "" )
			tempCookie = tempCookie + "|||";
		if( (tempCookie != null) && (tempCookie.indexOf("|||" + this.id + "|||") > 0 || tempCookie.indexOf(this.id + "|||") == 0) )
		{
			alert("That link already exists in your custom Quick Links");
			return;
		}
		else
		{
			//self.scrollTo(0,0);
			$('<li id="' + this.id + '"><div class="linkbox">' + this.innerHTML + '</div><div class="removeLink" onClick="removeLink(this);">Remove</div></li>').hide().appendTo("#quicklinks").fadeIn(1000);
			// find position of new link and scroll to it if needed
			newPosition = findPos(document.getElementById(this.id));
			newPosition = newPosition[1] - 100;
			if( document.getElementById(this.id).offsetTop > window.screen.availHeight )
				self.scrollTo(0,newPosition);
			// remove "preview" link
			$('#quicklinks li .previewLink').remove();
		}
		// update list to set cookie
		updateLinkList( $('#quicklinks').sortable('toArray') );
	});
	// make "preview" link clickable
	$('#addablelinks > li > .previewLink > a').click(function() {
		window.open(this,'','width=950,height=600');
		return false;
	});
	// set Back to Top links clickable
	$('.backToTop').click(function() {
		self.scrollTo(0,0);
	});
	// set letter links clickable
	$('.alphaNavLink').click(function() {
		letterClicked = this.id;
		// find position of desired section and scroll to it
		position = findPos(document.getElementById("nav" + letterClicked));
		scrollTo(0,position[1]-20);
		return false;
	});
}

// we set the cookie here any time the list is changed
function updateLinkList(order)
{
	list = "";
	var item;
	for( item in order )
	{
		list = list + order[item] + "|||";
	}
	list = list.substring(0,list.length-3);
	setCookie("quicklinks",list);
	updateQuickLinks();
	updateDB(list);
}

function clearCustomLinks()
{
	// set and empty cookie
	setCookie("quicklinks","");
	// remove IP from database by sending empty list
	updateDB("");
	// reload the page
	setTimeout("document.location.reload()",500);
}

// run when removing a link from custom list
function removeLink(link)
{
	// find the parent of the 'remove' link (i.e., the div of the link to remove) - 'link' var is the 'remove' link object itself, we must go one step up...
	link = $(link).parent().get(0);
	// fade the link div out
	$(link).fadeOut(1000,function() {
		$(link).remove();
		// update sortable list
		$("ul#quicklinks").sortable('refresh');
		//update cookie
		updateLinkList($("#quicklinks").sortable("toArray"),$("#quicklinks"));
	});
}

// set the cookie - used function so we could more easily set expiration, null, etc.
function setCookie(name, value)
{
	if( value == "" )
		value = null;
	var expireDate = new Date("December 31, 2020 00:00:00");
	var cookieExpire = expireDate.toGMTString();
	var options = { expires: expireDate, path: '/' };
	$.cookie(name, value, options);
}

// request list of A to Z links and display on page
function showAllLinks()
{
	if(!showAll)
	{
		showAll = true;
		// get all links from ?r=all and replace #addablelinks with response
		$("#loadingDiv").ajaxStart(function() {
			$("#addablelinks").hide();
			$(this).show();
		});
		$("#addablelinks").load("editql.php?r=all");
		$("#loadingDiv").ajaxStop(function() {
			$(this).hide();
			$("#addablelinks").show();
			disableNavLinks();
		});
		// change link so we can get back to "common" links
		document.getElementById('optionLink').innerHTML = "Show Common Links";
	}
	else
	{
		showAll = false;
		// get common links
		$("#addablelinks").load("editql.php?r=common");
		// change link
		document.getElementById('optionLink').innerHTML = "Show All";
	}
	// re-run .click init
	setTimeout("initAddable()",500);
}

// find the position of any element in the DOM
function findPos(obj)
{
	if(!obj)
		return false;

	var curleft = curtop = 0;
	if( obj.offsetParent )
	{
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while( obj = obj.offsetParent );
		
		return [curleft, curtop];
	}
}

// check all letter sections by looping through ABC nav links, disabling links that have no corresponding section to scroll to
function disableNavLinks()
{
	$('.alphaNavLink').each(function() {
		if( !findPos(document.getElementById("nav" + this.id)) )
			$(this).after(this.id).remove();
	});
}

// update the database with users ip address and link selections - for reporting purposes...
function updateDB(list)
{
	$.get("editql.php", { s: list, a: Math.random() });//, function(data) { alert("Response: " + data); });
}