//<![CDATA[ 

// Avoids breaking browsers with logs.
if( typeof console == "undefined" ) var console = {};
if( typeof console.log == "undefined" ) console.log = function(){};

var path = window.location.pathname;
var sections = path.split("/");
if( path.indexOf( "/arkiv/" ) > -1 && window.location.hash == "" ) {
	if( sections.length > 2 ) {
		hash = sections.pop();
		if( hash != "" )
			window.location.href =  sections.join("/") + "/#" + hash;
	}
}

function user_connected() {
	if( $.isFunction( this["fb_user_connected"] ) )
		this["fb_user_connected"]();
}

function user_disconnected() {
	if( $.isFunction( this["fb_user_disconnected"] ) )
		this["fb_user_disconnected"]();
}

function check_permissions( cb , permissions ) {
	if( !permissions ) 
		permissions = "publish_stream";
	FB.Connect.requireSession( function() {
		FB.Facebook.apiClient.users_hasAppPermission( permissions , function( result ) {
			if( !result ) {
				FB.Connect.showPermissionDialog(permissions, cb);
			} else {
				cb(true);
			}
		} );
	} );
}

var dialog = null;
function popup( is_fbml , title , type , options , width , height ) {
	check_permissions( function( permitted ) {
		if( permitted ) {
			options["is_fbml"] = is_fbml;
			$.get( "/fbml/" + type , options , function( fbml ) {
				if( dialog ) {
					dialog.close(false);
				}
				if( is_fbml )
					dialog = new FB.UI.FBMLPopupDialog( title , fbml );
				else
					dialog = new FB.UI.PopupDialog( title , $(fbml)[0] );
				if( width )
					dialog.setContentWidth( width );
				if( height )
					dialog.setContentHeight( height );
				dialog.add_closing( function() { dialog = null } );
				dialog.show();
			} );
		}
	} );
}

function show_invite_friends( name , url ) {
	popup( "Bjud in vänner" , "invite_friends" , { url: url , name: name } , 760, 540 );
}

var hash;
function hashListener() {
	if( hash != window.location.hash ) {
		hash = window.location.hash;
		var id = hash.split("#").join("");
		$(".event-image a[href$='"+id+"']:first").click();
	}
}

function hideCollectArea() {
	$(".user-collect-points").remove();
	$(".photos .collect-points:hidden").show( "blind", "fast" );
}

function addCollectListeners() {
	var fbText = "Lägg till ett personligt meddelande...";
	$(".share-link form textarea").focus( function() {
		if( $(this).val() == fbText )
			$(this).val( "" );
	} );
	
	$(".share-link form textarea").blur( function() {
		if( $(this).val() == "" )
			$(this).val( fbText );
	} );
	
	$(".user-collect-points .close").click( function() {
		hideCollectArea();
	} );
	$( ".user-collect-points .tail" ).css( "left", 138 * .5 );
}

function update_gallery( elem ) {	
	var direction = "down";
	if( $(".pagination a").index( $( elem ) ) - $(".pagination a").index( $(".pagination a.active")[ 0 ] ) > 0 )
		direction = "up";
	$(elem).siblings().removeClass( "active" );
	$(elem).addClass( "active" );
	activeGalleryPage = $(".pagination a").index( $(elem) );
	update_gallery_nav();

	$.get( "/titta/" + $(elem).attr("href") , function(data) {
		$("#gallery").height( $("#gallery").height() );
		var newGrid;
		if( direction == "up" ) {
			$("#gallery").children().animate( { marginTop: -$("#gallery").height() + "px" }, "medium", null, function() { $(this).remove() } );
			newGrid = $( data ).appendTo( "#gallery" );
		} else {
			newGrid = $( data ).prependTo( "#gallery" );
			newGrid.css( "marginTop", -newGrid.height() );
			newGrid.animate( { marginTop: 0 + "px" }, "medium", null, function() { $(this).siblings().remove() } );
		}
		if( newGrid.height() != $("#gallery") )
			$("#gallery").animate( { height: newGrid.height() + "px" }, "medium" );
	} );
}

function update_gallery_nav() {
	var prev = $(".pagination .previous");
	var next = $(".pagination .next");
	var active = $(".pagination .active");
	if( active.prev() == prev ) {
		prev.addClass( "inactive" );
	} else {
		prev.removeClass( "inactive" );
	}
	
	prev.attr( "href", active.prev().attr( "href" ) );
	next.attr( "href", active.next().attr( "href" ) );
		
	if( active.next().next() != next )
		next.removeClass( "inactive" );
	else
		next.addClass( "inactive" );
}


$(function() {
	
	FB.init( '3e6c59b79cce71db3798ba0b5b4f523e' , '/xd_receiver.htm' , { 
		"ifUserConnected": user_connected, 
		"ifUserNotConnected": user_disconnected,  
		"doNotUseCachedConnectState": true,
		"forceBrowserPopupForLogin": true
	} );
	
	$(".tree-close").next().hide();
	$(".tree-open").next().show();
	
	$(".accordion dt").live("click", function() {
		$(this).toggleClass( "tree-open" );
		if( $(this).hasClass( "tree-open" ) )
			$(this).next().show("blind", "fast");
		else 
			$(this).next().hide("blind", "fast");
	});
	
	if( $(".event-page").size() > 0 ) {
		$(".event-image a").click( function() {
			var ul = $(this).parent().parent();
			$(".event-page .event-selected").removeClass( "active" );
			ul.prev( ".event-selected" ).addClass( "active" );
			
			window.location.hash = $(this).attr("href").split("/arkiv/").join("");
			hash = window.location.hash;
			$(".event-page .event-selected:visible").not( ".active" ).hide("blind", {}, "fast", function() {
				$(this).children().remove();
			} );
			$.get( $(this).attr("href") , function(data) {
				ul.prev( ".event-selected" ).children().hide( "blind", {}, "fast", function() {
						$(this).children().remove();
				} );
				ul.prev( ".event-selected" ).append( data ).attr( "id", hash.split("#").join("") );
				if( !ul.parent().prev().hasClass( "tree-open" ) ) ul.parent().prev().click(); 
				ul.prev( ".event-selected" ).show( "blind", "fast" );
				
			} );
			return false;
		} );
		
		$(".fb-comments").live( "click", function() {
			if( !$(this).hasClass( "tree-open" ) ) {
				$( ".fb-container", $(this).next() ).empty();
			} else {
				$( ".fb-container", $(this).next() ).append( '<fb:comments numposts="20" width="340" xid="' + $(this).next().attr("id").split("_").pop() + '" css="http://telenorjobbamobilt.s3.amazonaws.com/comments-small.css?v=1256212820"></fb:comments>' );
				FB.XFBML.Host.parseDomElement( $(this).next()[0] );
			}
			return false;
		} );
		
		$(".accordion dt").click( function() {
			if( $(this).hasClass( "tree-open" ) ) {
				$(".event-selected", $(this).next() ).hide( "blind", {}, "fast", function() {
					$(this).empty();
				} );
			}
		} );
		
		var hashInterval = setInterval( "hashListener();", 500 );
	}
		
	$(".gallery .pagination a").click( function() {
		if( $(this).hasClass( "active" ) || $(this).hasClass( "inactive" ) ) return false;
		if( $(this).hasClass( "prev" ) || $(this).hasClass( "next" ) ) {
			update_gallery( $(".pagination a:not(.prev):not(.next)[href='" + $(this).attr("href") + "']:first") );
		} else {
			update_gallery( this );
		}
		return false;
	} );
	
	
	$("a.logout").click( function() {
		FB.Connect.logout(function(){
			window.location.reload(true);
		});
		return false;
	} );
	
	$("li.visit-user-page").click( function() {
		window.location.href = $(".logged-in-as").attr( "href" );
	} );
	
	$("li.select-photo").click( function() {
		popup( true , "Välj en av dina bilder" , "select_photos", {}, 676, 540 );
	} );
	
	$("li.upload-photo").click( function() {
		popup( false , "Ladda upp en bild" , "upload", {}, 450, 230 );
	} );
		
	$('.upload').live( "submit", function() {
	    if( !$('input:checkbox', this).is(':checked') ) {
	        alert('För att delta i tävlingen måste du godkänna villkoren.');
	        return false;
	    }
		if( $(this).hasClass( "sent" ) ) return;
		$(this).addClass( "sent" );
	} );
	
	$('.happenings .tree-close:gt(5)').hide( 0 );
	
	$('.happenings .show-more').click( function() {
		if( $('.happenings .tree-close:hidden:lt(5)').show("blind", "fast").size() < 5 ) {
			$(this).hide();
		}
	} );
	
	$('.send-to-friend input:text').focus( function() {
		$(this).removeClass( "invalid" );
		if( $(this).attr( "name" ) == "name" && $(this).val() == "Ditt namn" )
			$(this).val( "" );
		if( $(this).attr( "name" ) == "email" && $(this).val() == "Din kollegas e-post" )
			$(this).val( "" );
		$(this).addClass( "active" );
	} );
	
	$('.send-to-friend input:text').blur( function() {
		if( $(this).attr( "name" ) == "name" && $(this).val() == "" )
			$(this).val( "Ditt namn" );
		if( $(this).attr( "name" ) == "email" && $(this).val() == "" )
			$(this).val( "Din kollegas e-post" );
		$(this).removeClass( "active" );
	} );
	
	$('.send-to-friend').live( "submit", function() {
		$('.email', this ).removeClass( "valid" );
		$('.name', this ).removeClass( "valid" );

		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		if( emailReg.test( $(".email", this ).val() ) ) {
		 	$(".email", this ).addClass( "valid" );
		} else 
			$(".name", this ).addClass( "invalid" );
			
		if( $(".name", this ).val().length > 2 && $(".name", this ).val() != "Ditt namn" )
		 	$(".name", this ).addClass( "valid" );
		else 
			$('.name', this ).addClass( "invalid" );
		
		if( $('.send-to-friend input:text').size() != $('.send-to-friend input.valid').size() )
			return false;
	} );
	
	$(".user-collect-points .share-link form").live( "submit", function() {
		var str = "";
		if( $("textarea", this ).val() != "Lägg till ett personligt meddelande..." )
			str = $("textarea", this).val();
		return false;
	} );
	
	$(".user-entries .collect-points").live( "click", function() {
		
		hideCollectArea();
		
		var img = $(this).prev();
		var rowLength = 6;
		var href = $( "a:first", img ).attr( "href" ).split("/titta/").join("");
		var holder =$( this ).parent().parent();
		var index = holder.children().index( $( this ).parent() );
		var row = Math.floor( index  / rowLength ) + 1;
		var column = index % rowLength;
		var startIndex = ( ( row - 1 ) * rowLength ) - 1;
		
		var gt = ":gt(" + startIndex + ")";
		if( startIndex < 0 ) gt  = "";
		$(".photos" + gt + ":lt("+rowLength+") .collect-points").hide( "blind", "fast" );
		
		$.get( "/user/points/" + href, function(data) {
			var pos = row * rowLength - 1;
			var pointHolder;
			if( pos > $(".photos").size() - 1 )	pointHolder = holder.append( $(data) ); 
			else pointHolder = holder.children().eq( pos ).after( $(data) ); 
			addCollectListeners();
			
			var tailPos = ( column * 160 ) + ( 138 * .5 ); 
			$( ".user-collect-points .tail" ).css( "left", tailPos );

			$(".share-link form").submit( function() {
				var m = "";
				var img = $(".preview img").attr( "src" );
				var href = $(".preview a").attr( "href" );
				var caption = $(".preview .caption").html();
				var xid = $(".share-link form").attr( "id" );
				if( $(".share-link form").children("textarea:first").val() != "Lägg till ett personligt meddelande..." )
					m = $(".share-link form").children("textarea:first").val()
				var actionLinks = [{ "text": "Jag jobbar härifrån idag", "href": href }];
				var attachment = {'media':[ {'type': 'image', 'src': img, 'href': href } ], 'caption': caption, "comments_xid": xid, "href": href, "name": "Jag jobbar härifrån idag", "properties": [{"text":href.split("http://").join("") ,"href":href}] };
				FB.Connect.streamPublish( m, attachment, actionLinks, null, null, null, true );
				return false;
			} );
			
			FB.XFBML.Host.parseDomElement( holder[0] );
		} );
	} );
	
	$(".user-page .remove-entries").live( "click", function() {
		$(".user-entries .collect-points").css( "display", "none" );
		$(".user-entries .remove-entry").css( "display", "block" );
		$(this).css( "display", "none" );
	} );
	
	$(".user-entries .remove-entry").click( function() {
		if( !$(this).hasClass("confirm") ) {
			$(this).addClass("confirm");
			$(this).children(".confirm").css( "display", "inline" );
			$(this).children(".info").css( "display", "none" );
		} else {
			var btn = $(this);
			$.post( "/photo/", {_method: "delete", id: $(this).attr( "id").split("_").pop() }, function() {
				btn.closest( "li.user-photo" ).hide( "blind", "fast" );
			} ); 
		}
	} );
	
	$(".user-page .remove").click( function() {
		if( $(this).children(".confirm:hidden").size() > 0 )
			$(this).children().toggle();
		else {
			$.post( "/user/", {_method: "delete" }, function() {
				alert( "Du är inte längre en deltagare i tävlingen.");
				FB.Connect.logout(function(){
					window.location.pathname = "/";
				});
				return;
			} );
		}
		return;
	} );
	
	// Tracking stuff...
	$(".share li a").click(function(){
		var md = $(this).attr("href").match( /http:\/\/([^\/]+)\//i );
		addParam(3831,md[1]);
		createConversion('2f52eef2-6631-4071-b27c-e85814cb553c', 'SEK', '0');
	});
	$(".share form").submit( function() {
		addParam(3831,"email");
		createConversion('2f52eef2-6631-4071-b27c-e85814cb553c', 'SEK', '0');
	} );
	
	// Updates the comments every X seconds
	var attempts = 0;
	var queue = [];
	var queueInterval;
	var removeLast = true;
	var total = $("ul.all-comments li:not(.more)").size();
	
	$(".comments .menu li:eq(0)").click( function() {
		stopQueue();
		$(this).addClass( "active" ).siblings().removeClass( "active" );
		$(".comments .sources div.content-holder:eq(0)").show().next().hide();
	} );
	$(".comments .menu li:eq(1)").click( function() {
		startQueue();
		$(this).addClass( "active" ).siblings().removeClass( "active" );
		$(".comments .sources div.content-holder:eq(1)").show().prev().hide();
	} );
	$(".left-column ul.all-comments li:not(.more)").each(function(i){
		if( i < ( total - 5 ) ) {
			$(this).hide();
			queue.push( $(this) );
		}
	} );
	
	$("ul.all-comments li.more").click( function() {
		// Fetch the older ones than currently visible
		var last_id = $("ul.all-comments li:not(.more):last").attr("id");
		if( !last_id ) return null;
		var xhr = $.get( "/posts" , { before_id: last_id.split("_")[1] } , function( data ) {
			console.log( xhr.status , status , data );
			if( xhr.status == 200 ) {
				// Append the posts into ul.all-comments (not adding to the queue)
				$( "ul.all-comments li.more" ).before( $(data) );
			} else {
				// If there's no posts we hide the more button
				// TODO This should be earlier preferably
				$("ul.all-comments li.more").hide();
			}
			// Stop the removal of posts
			removeLast = false;
		} );
	} );
	
	function popQueue() {
		var post = queue.pop();
		if( post ) {
			if( removeLast ) {
				$("ul.all-comments li:not(.more):last").hide( "blind", "fast" , function() {
					$(this).remove();
				});
			}
			post.show( "blind", "fast" );
		}
		if( ++attempts > 5 ) {
			updateQueue();
			attempts = 0;
		}
	}

	function getSinceId() {
		// First in queue, or first visible if the queue is empty
		var latest_id = $(queue[0] || $("ul.all-comments li:not(.more):first")).attr("id");
		if( !latest_id )
			return null;
		return latest_id.split("_")[1];
	}
	
	function updateQueue() {
		var xhr = $.get( "/posts" , { since_id: getSinceId() } , function( data ) {
			if( xhr.status == 200 ) {
				// Update the queue with the elements in data
				$( data ).filter("li").each(function(){
					var li = $(this).hide();
					$( "ul.all-comments li.more" ).before( li );
					queue.unshift( li );
				})
			}
		} );
	}
	
	function startQueue() {
		clearInterval( queueInterval );
		queueInterval = setInterval( popQueue , 5000 );
	}
	function stopQueue() {
		clearInterval( queueInterval );
	}
	
	addCollectListeners();
	update_gallery_nav();
});

function hideCollectArea() {
	$(".user-collect-points").remove();
	$(".photos .collect-points:hidden").show( "blind", "fast" );
}

function addCollectListeners() {
	var fbText = "Lägg till ett personligt meddelande...";
	$(".share-link form textarea").focus( function() {
		if( $(this).val() == fbText )
			$(this).val( "" );
	} );
	
	$(".share-link form textarea").blur( function() {
		if( $(this).val() == "" )
			$(this).val( fbText );
	} );
	
	$(".user-collect-points .close").click( function() {
		hideCollectArea();
	} );
	$( ".user-collect-points .tail" ).css( "left", 138 * .5 );
}

function update_gallery( elem ) {	
	var direction = "down";
	if( $(".pagination a:not(.prev):not(.next)").index( $( elem ) ) - $(".pagination a:not(.prev):not(.next)").index( $(".pagination a.active")[ 0 ] ) > 0 )
		direction = "up";
	$(elem).siblings().removeClass( "active" );
	$(elem).addClass( "active" );
	activeGalleryPage = $(".pagination a:not(.prev):not(.next)").index( $(elem) );
	update_gallery_nav();

	$.get( "/titta/" + $(elem).attr("href") , function(data) {
		$("#gallery").height( $("#gallery").height() );
		var newGrid;
		if( direction == "up" ) {
			$("#gallery").children().animate( { marginTop: -$("#gallery").height() + "px" }, "medium", null, function() { $(this).remove() } );
			newGrid = $( data ).appendTo( "#gallery" );
		} else {
			newGrid = $( data ).prependTo( "#gallery" );
			newGrid.css( "marginTop", -newGrid.height() );
			newGrid.animate( { marginTop: 0 + "px" }, "medium", null, function() { $(this).siblings().remove() } );
		}
		if( newGrid.height() != $("#gallery") )
			$("#gallery").animate( { height: newGrid.height() + "px" }, "medium" );
	} );
}

function update_gallery_nav() {
	var prev = $(".pagination .prev");
	var next = $(".pagination .next");
	var active = $(".pagination .active:first");
	var index = $(".pagination a:not(.prev):not(.next)").index( active[ 0 ] );
	
	if( active.prev().hasClass( "prev" ) ) prev.addClass( "inactive" );
	else prev.removeClass( "inactive" );
	if( active.next(":first").hasClass( "next" ) ) next.addClass( "inactive" );
	else next.removeClass( "inactive" );
	prev.attr( "href", active.prev().attr( "href" ) );
	next.attr( "href", active.next().attr( "href" ) );
	
	var count = 9;
	var pagination = $(".pagination a:not(.prev):not(.next)");
	var l = pagination.size();
	if( l > count ) {
		if( index >= Math.floor( count*.5 ) ) {
			startCount = index - Math.floor(count*.5);
			pagination.hide().filter(":gt("+startCount+"):lt(8)").show();
		} else {
			pagination.hide().filter(":lt(8)").show();
		}
	}
}

