var cookieName = 'myqueue';
var myqueue = '';
var cookieDays = 365;

/* 	calculate text length within an element */
$.fn.textWidth = function() {
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>'
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

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

function readCookie(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,'',-1);
}

function myQueueAdd(item) {
	myqueue = readCookie(cookieName);
	if (myqueue == null) {
		createCookie(cookieName, '-'+item, cookieDays);
	} else {
		if (myqueue.indexOf('-'+item) == -1) {
			createCookie(cookieName, myqueue + '-' + item, cookieDays);	
		}
	}
}

function myQueueRemove(item) {
	myqueue = readCookie(cookieName);
	if (myqueue != null) {
		ar = myqueue.split('-');
		ar = $.map(ar, function(itm,indx) {
			if (itm != '' && itm != item) {
				return itm;
			}
		});
		createCookie(cookieName, '-'+ar.join('-'), cookieDays);				
	}
}

function updateMyQueueLink() {
	myqueue = readCookie(cookieName);
	newlink = '';
	if (myqueue != null) {
		/* my queue link */
		newlink = '/queue/' + myqueue.substring(1) + '/';
		$.each($('a.myqueue'), function() {
			$(this).attr('href', newlink);
		});
	}
	return newlink;
}

$(document).ready(function() {

	/* 	fold lists with more than min items into multicolumns */		
	minItems = 3; // bigger than this, try to fold the list
	minColItemCnt = 6; // smaller than this, use less columns

	s = $('.textlisting li').size();
	if (s > minItems) {
	
		mwidth = $('#main').innerWidth();
		lwidth = 0;
		nwidth = 0;
		rmargin = 20;

	/* 	find the widest text width within the list */		
		$.each($('.textlisting li'), function() {
			nwidth = $(this).textWidth();	
			if (nwidth > lwidth) {
				lwidth = nwidth;
			}	
		});
		

	/* 	max number of list columns that will fit in #main */
		cols = Math.floor(mwidth / (lwidth+rmargin));

	/* 	recalc to avoid short cols:
		try to have minColItemCnt items per column
		or fallback to 2 cols		
	*/
		fcols = 0;		
		if (cols > 2) {

			for (i=0;i<cols-1;i++) {		
				if (s / (cols-i) < minColItemCnt) {			
				} else {
					fcols = cols-i;
					break;
				}
			}
		}	

		if (fcols == 0) { fcols = 2;}
		
	/* 	if fewer columns, given them some space */
		if (fcols != cols || fcols == 2) {
			rmargin = Math.floor(mwidth / fcols - lwidth);
			if (rmargin > 120) { rmargin = 120;}
		}

	/*	split list */
		$('.textlisting').easyListSplitter({colNumber: fcols, direction: 'vertical'});

	/*	make list float and give it a nice column width */		
		$('.textlisting').css({
			width: lwidth+rmargin+'px',
			float: 'left'
		});		
	}

	/* custom search input list*/
	$('.inputlisting').easyListSplitter({colNumber: 3, direction: 'vertical'});

	/*	make folded lists visible */			
	$('.textlisting, .inputlisting').css({
		display: 'none',
		visibility: 'visible'
	}).fadeIn('fast');

	/* empty / load my queue */
	if ($('body.emptyqueue').size() > 0) {
		eraseCookie(cookieName);
		updateMyQueueLink();		
	} else {
		myqueue = readCookie(cookieName);
		updateMyQueueLink();
	}
	
	/* add to queue links */
	$('a[href^=\/queue\/add\/]').click(function(e) {
		e.preventDefault();
		$('#tooltip').stop(true).css('display','none');		
		title = $(this).attr('href').substring(11);
		myQueueAdd(title);
		updateMyQueueLink();	
		p = $(this).offset();
		t = Math.max(Math.floor(p.top)-35,0)+'px';
		l = Math.max(Math.floor(p.left)-30,0)+'px';

		$('#tooltip').mouseenter(function() {
			$(this).stop(true);
		});

		$('#tooltip').mouseleave(function() {
			$(this).fadeTo(1500,1.0).slideUp();
		});
				
		$('#tooltip').css({left: l, top: t}).slideDown().fadeTo(1500,1.0).slideUp();
	});

	/* remove from queue links */
	$('a[href^=\/queue\/remove\/]').click(function(e) {
		e.preventDefault();
		l = $(e.target).closest('li');
		title = $(this).attr('href').substring(14);
		myQueueRemove(title);
		newpage = updateMyQueueLink();
		if (newpage != '') {
			window.location.href = newpage;	
		}	
	});

	
	/* view by code drop-down menu  */
	$('#viewjump').click(function(e) {
		e.preventDefault();
		u = $('#codejump').val();
		window.location.href = '/locations/'+u+'/';
	});
	
	/* detail pages slideshow */
	if ($('#deet a').size() > 0) {
		cnt = 0;
		ovimg = '';
		$('body').append('<div class="overlay" id="overlay"><div id="images"><div class="items"></div></div><div class="navp"><span class="close">done</span><br /><span class="prev">&lt; prev</span> | <span class="next">next &gt;</span></div></div>');		
		$.each($('#deet a'), function(idx) {
			$(this).overlay({
				target: '#overlay',
				mask: { 
					maskId: 'mask',
					color: '#000000',
					opacity: 0.95
					},	
				onBeforeLoad: function() {
					$('#images').css('visibility','hidden');
				},
				onLoad: function() {
					$('#images').data('scrollable').seekTo(idx,0);
					$('#images').css('visibility','visible');
				}
			});
			ovimg += '<div><img src="'+$(this).attr('href')+'" border="0" /></div>';
			cnt++;
		});
		if (ovimg != '') {
			$('#images .items').html(ovimg);
			$("#images").scrollable({speed: 0});		
		}
	}	
	
	/* custom search form submission */	
	$('#csearch').submit(function(e) {
		e.preventDefault();
		f = $(this).serializeArray();
		u = '';
		r = '';
		$.each(f, function(ind, obj) {	
			if (obj.value != '') {
				if (obj.name != 'room') {
					u += '-'+ obj.value;
				} else {
					r = obj.value;
				}
			}	
		})
		if (u !='') {
			u = u.substring(1)+'/';
		}
		if (r!='') {
			window.location.href = '/locations/room/'+r+'/search/'+u;			
		} else {
			window.location.href = '/locations/search/'+u;
		}	
	});	
});


