var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};

var ceilidh;
var running;
var FBAPI;
var FBUser = {};

document.observe("dom:loaded", function() {
	//apply smartness to text field
	$("txt-keywords").observe("focus", function(event) { prefill_field_control(this, "focus"); });
	$("txt-keywords").observe("blur", function(event) { prefill_field_control(this, "blur"); });
	
	// Add new friends' email field 
	if($$('#invite').length>0) {
		p = document.createElement('p'); p.id = 'add-friends'; p.innerHTML = 'Add more';
		var friendCount = 3;
		$$('#invite #friends')[0].insert(p);
		$('add-friends').observe('click',function(ev){
			friendCount++;
			label = document.createElement('label');
			span = document.createElement('span'); span.innerHTML = 'Friend '+friendCount+': ';
			input = document.createElement('input'); input.type='text'; input.name='friend_'+friendCount;
			label.appendChild(span);
			label.appendChild(input);
			$$('#invite #friends p#add-friends')[0].insert({before:label});
		});
	}
	
	// External tracking
	$$('#content a').each(function(el){
		if(el.href.hostname != location.host && el.href != '#') {
			el.observe('click',function(ev) {
				e = (ev.srcElement) ? ev.srcElement : this;
			    while (e.tagName != "A") { e = e.parentNode; }
			    lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname;
			    if (e.search && e.pathname.indexOf(e.search) == -1) lnk += e.search;
			    lnk = "/external/" + e.hostname + lnk;
			    if (typeof(pageTracker) == "object") pageTracker._trackPageview(lnk);
			});
		}
	});

	var fb_hash = hashID.toString().replace('#','%23');
	$('facebook').writeAttribute($('facebook').readAttribute("href") + fb_hash);

});

function checkCookie(){
	if(Cookie.get('visited')==null) {
		Cookie.set('visited','1',365);
		return 'false';
	} else {
		return 'true';
	}
}

function navigateToId(couple) {
	window.location = '#'+couple;
	return false;
}

function prefill_field_control(field, action) {
	val = field.value;
	if (action == "focus" && val == field.readAttribute("title")) {
		field.clear();
	} else if (action == "blur" && val == "") {
		field.value = field.readAttribute("title");
	}
}

function facebookConnect(){
	FB_RequireFeatures(["Api"], function(){	
		FBAPI = FB.Facebook.apiClient;
		FB.Connect.requireSession(function(exception){
			FBUser.uid = FBAPI.get_session().uid;
			running = 0;
			/* Fetch user's galleries and images */
			running++;
			FBAPI.fql_query('SELECT aid,name FROM album WHERE owner='+FBUser.uid,function(response){
				running--;
				FBUser.galleries = response;
				if(FBUser.galleries.length>=1) {
					for(i=0;i<FBUser.galleries.length;i++){
						running++;
						FBAPI.fql_query('SELECT src, src_big, src_small, link, caption, "'+i+'" FROM photo WHERE aid IN (SELECT aid FROM album WHERE aid = '+FBUser.galleries[i].aid+' AND owner='+FBUser.uid+')',function(response){
							running--;
							FBUser.galleries[response[0].anon].photos = response;
							if(running<=0) {
								ceilidh.sendJSON(FBUser);
							}
						});
					}
				} else {
					FBUser.err = 'No galleries could be found.';
					ceilidh.sendJSON(FBUser);
				}
			});
		});
	});
	return FBUser;
}

function navigateToURL(anchor){
	window.location.hash = anchor;
	return false;
}

function facebookUserImages(gallery){
	var images;
	FBAPI.fql_query('SELECT src, src_big, src_small, link, caption FROM photo WHERE aid IN (SELECT aid FROM album WHERE aid = '+gallery+')',function(response){
		images = response;
	});
	return images;
}

Event.observe(window, 'load', function() {
	FB.init("621e68b2ae952b67ac6076cacbbd986e", "/ceilidh/xd_receiver.htm");
	ceilidh = $('infinite-ceilidh-cust');
});