function InitFriendsLiteModule(){
	if(!j$('#friends'))
		return;
	if( typeof FB != 'undefined' && typeof FB.headupLoaded == 'undefined' )
		FB.headupLoaded = true;
	else
		return;
	
    FB.init(settings.facebookApiKey, settings.xd_reciverPath);  // dont touch this line without making sure that the deployment still works
    FB.ensureInit(function() {
        FB.Connect.ifUserConnected(function(uid) {
            FB.Facebook.get_sessionWaitable().waitUntilReady(function(session) {
                try {
                    if (!FB.ApiClient.sessionIsExpired(session)) {
                        // session has not expires yet
                        IfConnected(session.uid, session.session_key);
                    }
                    else {
                        // session has expired
                        IfNotConnected();
                    }
                }
                catch (er) {
                    IfNotConnected();
                }
            });
        },
        function() {
            IfNotConnected();
        });
    });
}

/* Binding */
/*
j$('#fbConnect, #fbConnect_header').live("mousedown",function(){
    OpenWindowConnectToFB();
	sendStat({ event:'tpFacebookConnected' });
	_gaq.push(
		['_setCustomVar', 1, 'customerId', horizon.configid, 2],
		['_setCustomVar', 2, 'URI', horizon.uri, 2],
		['_trackEvent', 'facebook_connected', true]
	);
	return false;
});
*/
function OpenWindowConnectToFB(){
    FB.Connect.requireSession();
}

function fbLogout(){
	j$('#fbConnect_header').unbind('click', fbLogout);
	FB.Connect.logout();
	j$('#friends').removeClass('connected');
	j$('#friends > a.logout').remove();
	//j$('#friends').slideUp('normal', function(){ j$(this).empty().show(); });
	j$('#friends > div.content').empty();
	j$('#friends ul').remove();
	j$('#fbConnect_header').text( 'Facebook Connect' ).attr('title','Check out which of your friends are related to this topic');
}

function IfConnected(uid, session){
	j$('#fbConnect_header').text('connected');
	var loader = j$('<div/>').addClass('loader').css('padding-left',36).html('Loading friends...');
	j$('#friends').addClass('loading').addClass('connected').children('.content').html(loader);

	var api = FB.Facebook.apiClient;
	var fields = ["name"];
	
	var fb_logout_btn = j$('<a/>').text('Logout').addClass('logout btn').bind('click', fbLogout);
	j$('#friends').prepend( fb_logout_btn );
	
	// fetch user name
	api.users_getInfo(uid, fields, function(result){
		if( result )
			j$('#fbConnect_header').text('Hello ' + result[0].name).attr('title','Click to log-out').bind('click', fbLogout).addClass('disconnect');
	});

    if (uid == null){
        //writeStatistic({ type: 'FatalLog', message: 'facebook uid is null' });
        return;
    }

    if (session == null){
        //writeStatistic({ type: 'FatalLog', message: 'facebook session is null' });
        return;
    }
    //writeStatistic({ event: 'facebook_connected' });
    
	getRelatedFriends(uid, session);
}

function IfNotConnected(){
	j$('#friends').removeClass('loading').children('div.content').html( horizon.fb_connect );
	j$('#fbConnect, #fbConnect_header').live("mousedown",function(){
		OpenWindowConnectToFB();
		sendStat({ event:'tpFacebookConnected' });
		_gaq.push(
			['_setCustomVar', 1, 'customerId', horizon.configid, 2],
			['_setCustomVar', 2, 'URI', horizon.uri, 2],
			['_trackEvent', 'facebook_connected', true]
		);
		return false;
	});
}

function getRelatedFriends(uid, session){
	// send request to the server to bring data
    var friendsDataTabName = 'FriendsDataLite';
    var href = settings.RealTimeHandler + "?uri=" + horizon.uri + "&category=" + friendsDataTabName + "&configid=" + (horizon.configid ? horizon.configid : horizon.fullConfigId) + "&facebookSession=" + session + "&facebookid=" + uid;
	
	j$.ajax({
		url: href,
		success: function(data){
			j$('#friends').removeClass('loading').children('div.content').empty();
			var response = j$('<div/>').html( data );
			if( !data ){
				//console.warn('Sorry, no friends related');
				j$('#friends > div.content').append('<p>No related friends were found</p>');
			}
		},
		error: function(request, status, errorThrown){
			j$('#friends').removeClass('loading').children('div.content').empty()
			.append('<p>Something went wrong, <a onclick="getRelatedFriends()">try again</a></p>');
		},
		timeout: 15000
	});
}

function existsInArray(arr, value) {
    for (var i in arr) {
        if (value == arr[i])
            return true;
    }
    return false;
}


// FriendsCarousel - Is called from a script tag returned from the xhr call.
function FriendsCarousel(galId, json){
	FB.headupfriends = json || FB.headupfriends;
	
	galId = '#friends';
	if( !j$(galId).length || !FB.headupfriends )
		return false;
		
	json = FB.headupfriends;
	FB.headupfriends = false;
	
    var items_size = json.length,
		oFilmStrip = j$('<ul/>').attr('class', 'fbFriends'),
		oItem,
		exists = [];
	
	/*
	if( items_size > 1 )
		j$(galId).append('<h2 class="title">Related Friends</h2>');
		
	*/
	oFilmStrip.appendTo(galId).show();
	
    for (var key in json){
        if (!existsInArray(exists, json[key].link))
            preLoadThumb(json[key], key);
        else {
            if (--items_size == 0)
                buildNow();
        }

        exists[key] = json[key].link;
    }

    function preLoadThumb(item, index){
        var aimg = j$(new Image());

        aimg[0].onload = function(){
            this.onload = null;
            var thumbcontainer = j$('<a/>').html(aimg);
            thumbcontainer.attr('href', item.link);

            oItem = j$('<li/>').html(thumbcontainer).hide();
            oItem.appendTo(oFilmStrip);
			oItem.show('normal');
			/*
            if (--items_size == 0)
                buildNow();
			*/
        }

        aimg[0].onerror = function(){ };
        var caption = item.name;// + ", " + wordToUpper(item.tooltip) + ' ' + name;
        aimg.attr({ 'src': item.image, 'title': caption, 'alt': item.name })
    }

    function buildNow(){
        oFilmStrip.appendTo(innerGallery);
    }
}

function wordToUpper(s) {
    return s.toLowerCase().replace( /\b[a-z]/g, function(a){ return a.toUpperCase(); } );
}


/* jCarouselLite - v1.0.1 
--------------------------------*/
(function($) {
    $.fn.jCarouselLite = function(o) {
        o = $.extend({
            btnPrev: null,
            btnNext: null,
            btnGo: null,
            mouseWheel: false,
            auto: null,

            speed: 200,
            easing: null,

            vertical: false,
            circular: false,
            visible: 3,
            start: 0,
            scroll: 1,

            beforeStart: null,
            afterEnd: null
        }, o || {});

        return this.each(function() {                           // Returns the element collection. Chainable.
            var running = false, animCss = o.vertical ? "top" : "left", sizeCss = o.vertical ? "height" : "width";
            var div = $(this), divHolder = div.parent(".ad-gallery"), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

            if (o.circular) {
                ul.prepend(tLi.slice(tl - v - 1 + 1).clone())
              .append(tLi.slice(0, v).clone());
                o.start += v;
            }

            var li = $("li", ul), itemLength = li.size(), curr = o.start;
            div.css("visibility", "visible");


            //li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
            ul.css({ margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1" });
            div.css({ overflow: "hidden", position: "relative", "z-index": "2", left: "0px" });

            var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
            var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
            var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

            //li.css({width: li.width(), height: li.height()});
            ul.css(sizeCss, ulSize + "px").css(animCss, -(curr * liSize));

            div.css(sizeCss, divSize + "px");                     // Width of the DIV. length of visible images

            if (o.btnPrev && o.btnNext && tLi > 6) {
                divHolder.addClass("hasArrows");
                div.siblings(o.btnPrev).click(function() {
                    return go(curr - o.scroll);
                }).siblings(o.btnNext).click(function() {
                    return go(curr + o.scroll);
                });
            }

            if (o.btnGo)
                $.each(o.btnGo, function(i, val) {
                    $(val).click(function() {
                        return go(o.circular ? o.visible + i : i);
                    });
                });

            if (o.mouseWheel && div.mousewheel)
                div.mousewheel(function(e, d) {
                    return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll);
                });

            if (o.auto)
                setInterval(function() {
                    go(curr + o.scroll);
                }, o.auto + o.speed);

            function vis() {
                return li.slice(curr).slice(0, v);
            };

            function go(to) {
                if (!running) {

                    if (o.beforeStart)
                        o.beforeStart.call(this, vis());

                    if (o.circular) {            // If circular we are in first or last, then goto the other end
                        if (to <= o.start - v - 1) {           // If first, then goto last
                            ul.css(animCss, -((itemLength - (v * 2)) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                            curr = to == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll;
                        } else if (to >= itemLength - v + 1) { // If last, then goto first
                            ul.css(animCss, -((v) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                            curr = to == itemLength - v + 1 ? v + 1 : v + o.scroll;
                        } else curr = to;
                    } else {                    // If non-circular and to points to first or last, we just return.
                        if (to < 0 || to > itemLength - v) return;
                        else curr = to;
                    }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                    running = true;

                    ul.animate(
                    animCss == "left" ? { left: -(curr * liSize)} : { top: -(curr * liSize) }, o.speed, o.easing,
                    function() {
                        if (o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                    // Disable buttons when the carousel reaches the last/first, and enable when not
                    if (!o.circular) {
                        $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                        $((curr - o.scroll < 0 && o.btnPrev)
                        ||
                       (curr + o.scroll > itemLength - v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                    }

                }
                return false;
            };
        });
    };

    function css(el, prop) {
        return parseInt($.css(el[0], prop)) || 0;
    };
    function width(el) {
        return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
    };
    function height(el) {
        return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
    };

})(hjquery);
