/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
	
	

	var _actions = [];
	var site = 'noenergytax';
	var current_action = -1;
  var timerId = 0;
  var canvas = false;
  
	$(document).ready( function()
	{
		if( env.user == undefined )
		{
			env.user = false;
		}

		getLeaderboard();
		
    if ( ! canvas ) {
		  logAction( "pageload" );
		  loadActions();
    }
    
		loadBlog();

		
		$('#resources-container').jScrollPane({ scrollbarWidth: 37 });
		
		
		// set up our lightbox links
		$('a.lightbox').each( function() {
		  $('a#' + this.id).fancybox({
		    frameWidth: 560,
		    frameHeight: 340,
		    hideOnContentClick: false
		  });
    });
    
	});

	function logAction( args )
	{
		
		$.post( env.local + 'actions.php',
				{
					action: 'log',
					action_id: getCurrentActionId(),
					args: args
				} );
	}

	function getCurrentActionId()
	{
		if( _actions[current_action] )
		{
			return _actions[current_action].id;
		}

		return -1;
	}

	function formatTimePart( raw )
	{
		var raw_string = "" + raw;

		switch( raw_string.length )
		{
			case 1: return '0' + raw_string;
			case 2: return raw_string;
		}

		return '00';
	}

	function longFormatTimePart( value, part )
	{
		var result = value + " " + part;
		
		if( value == 1 )
		{
			return result + " " ;
		}

		return result + "s ";
	}

	function updateCountdown()
	{
		var date = new Date();
		var now = Math.floor( date.getTime() / 1000 );
		var seconds_left = env.nextUpdate - now;

		if( seconds_left > 0 )
		{

			var days = Math.floor( seconds_left / ( 60 * 60 * 24 ) );
			var hours = Math.floor( ( seconds_left / ( 60 * 60 ) ) % 24 );
			var minutes = Math.floor( ( seconds_left / 60 ) % 60 );
			var seconds = seconds_left % 60;

			var countdown_text = "New Actions in ";

			if( days > 0 )
			{
				countdown_text += longFormatTimePart( days, "day" );
			}

			//countdown_text += formatTimePart( hours ) + " hours ";
			//countdown_text += formatTimePart( minutes ) + ":";
			//countdown_text += formatTimePart( seconds );

			countdown_text += longFormatTimePart( hours, "hour" );
			countdown_text += longFormatTimePart( minutes, "minute" );
			countdown_text += longFormatTimePart( seconds, "second" );

			countdown_text += " (" + env.nextUpdateString + ")";

			$('#countdown').text( countdown_text );
			setTimeout( updateCountdown, 1000 );
		}
		else
		{
			$('#countdown').text( " New Actions are here - check them out now!" );
		}
	}

	function loadBlog()
	{
		var pagesize = 8;
		
		// fetch stories
		//$.post( local + 'actions.php', { action: 'fetch_blog'}, loadBlogCarousel );
		$.getJSON(  env.lb  + "blog?site=" + site + "&count=" + pagesize + "&callback=?", loadBlogCarousel );
	}

	function loadBlogCarousel( response )
	{
		$('#blog_carousel').empty();

		var items = eval( response );
		
		for( var i in items )
		{
			var item = items[i];
			var html = "<li>";
			html += "<a href='iframe.php?blog=1&href=" + item.link + "'>";
			html += "<h3>" + item.title + "</h3>";
			html += "</a>";
			html += "<div class='item'>";
			html += "<span class='date'>" + item.pubDate + "</span>";
			
			// replace link with image
			//var content = item.description.replace(/read more/, "<img src='styles/images/readmore.gif' />");
			html += "<p>" + item.description + "</p>";
			html += "<a class='readmore' href='iframe.php?blog=1&href=" + item.link + "'><img src='styles/images/readmore.png' /></a>";
			
			html += "</div>";
			html += "</li>";

			$('#blog_carousel').append( html );
		}

    $('#resources-container').jScrollPane({ scrollbarWidth: 37 });
    
		// make carousel
//		$('#blog_carousel').jcarousel({
//										vertical: false,
//										scroll: 2,
//										size: items.length,
//										buttonPrevHTML: "<div id='prev' class='scroll left'></div>",
//										buttonNextHTML: "<div id='next' class='scroll right'></div>"
//									});
	}

	function loadActions()
	{
		//$.getJSON(  lb  + "remote?site=" + site + "&action=fetch_list&callback=?", loadActionCarousel );

		$.post( env.local + 'actions.php', { action: 'fetch_list'}, loadActionCarousel );
	}

	function loadActionCarousel( response )
	{
		var json = eval( '(' + response + ')' );
		
		// unpack json
		_actions = json.actions;
		
		// set up carousel contents
		$('#action_carousel').empty();

		for( var i in _actions )
		{
			var action = _actions[i];

			// assemble html
			var html =  "<li class='action' onclick='selectAction(" + i + ", true)'>";
			html += "<span class='" + action.category + " png'>  </span>";
			html += "<h3 class='" + action.category + "'>" + action.title + "</h3>";
			html += "<p>" + action.label + "</p>";

			// only show points if there are points to be had
			if( action.tpoints > 0 )
			{
				html += "<div class='tpoints'>" + action.tpoints + "<br /><span class='points'>points</span></div>";
			}

			html += "</li>";
			
			$('#action_carousel').append( html );
		}
	
	   
	  if ( _actions.length > 3 ) {
	   $('#action_carousel').jScrollPane({ scrollbarWidth: 37, scrollbarOnLeft: true } );
		}
		// decorate
//		$('#action_carousel').jcarousel({
//										vertical: true,
//										scroll: 2,
//										//size: _actions.length,
//										buttonPrevHTML: "<div id='prev' class='scroll up'></div>",
//										buttonNextHTML: "<div id='next' class='scroll down'></div>"
//									});

		// prime the selection
		if( current_action == -1 )
		{
			selectInitialAction();
		}

		$('#action_carousel').css('visibility', 'visible');

		// remove progress spinner
		$('#action_carousel_container').removeClass( 'loading' );

		// update the forthcoming actions banner:
		env.nextUpdate = json.nextUpdate;
		env.nextUpdateString = json.nextUpdateString;
		
		updateCountdown();
	}

	function getIndexForActionId( action_id )
	{
		// translate global action id to local index:
		for( var i in _actions )
		{
			if( _actions[i].id == action_id ) return i;
		}
		
		return 0;
	}

	function selectInitialAction()
	{
		var action = 0;

		// check to see if we were passed an action id in the GET
		if( env.user && env.user.ps )
		{
			current_action = getIndexForActionId( env.user.ps );
			selectActionCarouselItem( current_action );
			markActionComplete();
		}
		else
		{
			selectAction( action, false );
		}
	}

	function selectActionCarouselItem( index )
	{
		$('#action_carousel li').removeClass( 'selected');
		$('#action_carousel li:eq(' + index + ')').addClass( 'selected');
	}

	function selectAction( i, animated )
	{
	  // clear out bg image
    $('.content').css('background', "none");

		if( current_action != i )
		{
			current_action = i;

			// update carousel
			selectActionCarouselItem( i );

			if( animated )
			{
				// update presentation
				$('#presentation div.content').animate( { left: 2000 },
														500,
														function(){ finishUpdate(i) } );

				// log
				logAction( 'select' );
			}
			else
			{
				updateContent( i );
			}
		}
	}

	function updateContent( i )
	{
		// set the html:
		var html = ''; //"<h3>" + _actions[i].title + "</h3>";
    
		// insert main content and commit
		html += _actions[i].content;
		$('#presentation div.content').html( html );
	  //$('#presentation div.content')[0].innerHTML = html;
	  //document.getElementById('action-content').innerHTML = html;
	  //FB.XFBML.Host.parseDomTree();
	}

	function addLink( href, src, text, iframe )
	{

    $('.content').css('background', "transparent url('" + src + "') no-repeat top left");

		var action = _actions[current_action];
		var new_href;

		if( iframe )
		{
			new_href = env.local + 'iframe.php?href=' + href
								 + '&action_id=' + action.id
								 + '&user_id=' + env.user.fb_uid;
		}
		else
		{
			new_href = href;
		}
    
    var cclass = 'add-link';
    if ( action.category == 'comment' ) {
      cclass = 'comment-text';
    }
    
		$('.content').html( "<p class='" + cclass + "'>" +  text + "</p><a id='ref' class='ref_go'>Click here to " + action.title + "<br /><span class='points'>and score " + action.tpoints + " points</span></a>" );

		$('#ref').bind( 'click', function(){ followScoreableLink( new_href, iframe ) } );
	}

	function followScoreableLink( href, iframe )
	{
		if( iframe )
		{
			// target will take current window
			window.location = href;
		}
		else
		{
			// target doesn't like iframes, so open it in new window
			// and show score immediately
			markActionComplete();
			window.open( href );
		}
	}

	function finishUpdate( i )
	{
		updateContent( i );
		$('#presentation div.content').animate( { left: 0 }, 500 );
	}

	/* action specific */

	function getLeaderboard()
	{
	  
	  var link = 'actions.php';
	  if ( canvas ) {
	    var parts = window.location.href.split('?');
	    link = 'actions.php?' + parts[1];
    }
    
    
		$.post( env.local +  link ,
			{
				action: 'fetch_leaderboard'
			},
			displayLeaderboard );
	}

	function processLeaders( leaders, count_from, additional )
	{
	  if ( additional ) {
	    var html = "<div class='leader_set additional'>";
    } else {
		  var html = "<div class='leader_set'>";
    }
    
		for( var i in leaders )
		{
			var leader = leaders[i];

      var cclass = 'profline';
      
			// distinguish current user
			if( leader.id == env.user.fb_uid )
			{
			  cclass += ' current_user';
			}

      
      html += "<div class='" + cclass + "'>";
      
			var rank = parseInt( i ) + parseInt( count_from );
			html += "<span class='rank'>" + rank + "</span>";
			// calculate margin
      var margin = 40;
      var len = rank.toString().length;
      if ( len > 2 ) {
        margin = 40 + ( (len-2) * 20 );
      }

			html += "<img style='left: " + margin + "px;' src='" + leader.profile_pic + "' />";
			html += "<p><a href='http://facebook.com/profile.php?id=" + leader.id + "'>" + leader.name + "</a><br />" + leader.score + "</p>";
			html += "</div>";
		}

		html += "</div>";

		return html;
	}

	function displayLeaderboard( response )
	{
		var json = eval( '(' + response + ')' );
		$('#leaderboard-content').empty();
		$('#leaderboard-content').append( processLeaders( json.top, 1, false ) );

    $('#leaderboard-content').append( "<img id='seperator' src='styles/images/leaderboard-arrow.png' />" );
    
		if( env.user )
		{
			if( json.rank == 0 )
			{
				json.rank = 1;
			}
			
			$('#leaderboard-content').append( processLeaders( json.adjacent, json.rank, true ) );
		}
		else
		{
		  var onemore = parseInt(json.total_users) + 1;

      if ( canvas ) {
		    var join = "<div class='leader_set additional'><div class='profline current_user join'><span class='rank'>" + onemore + "</span><a href='http://www.facebook.com/tos.php?api_key=313be5919b7ee513c2b83f450c46f913&requirelogin=1&return_session=true&next=http://apps.facebook.com/noenergytax/' >Join us</a></div></div>";
      } else {
		    var join = "<div class='leader_set additional'><div class='profline current_user join'><span class='rank'>" + onemore + "</span><a href='#' onclick='FB.Connect.requireSession(); return false;' ><img id='fb_login_image' src='http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_long.gif' alt='Connect'/></a></div></div>";
			}
			$('#leaderboard-content').append( join );
		}

		// additional info
		//var additional = "<div id='additional'>";
		$('#additional').empty();
		var additional = "Total members: <span class='blue'>" + json.total_users + "</span> | ";
		additional += "Total points scored: <span class='white'>" + json.total_points + "</span> | ";
		additional += "Newest member: <span class='blue'>" + json.newest_user + "</span>";
		//additional += "</div>";

		$('#additional').append( additional );
	}

	function showInviteForm()
	{
		// fetch the users friend list
		$.post( env.local + 'actions.php',
			{
				action: 'fetch_invites'
			},
			displayInviteForm );
	}
	
	function showRequestForm() {
	  //document.getElementById('action-content').
	  var html = '<fb:serverfbml style="width: 640px;"><script type="text/fbml"><fb:fbml><fb:request-form action="http://noenergytax.com/index.php?action=' + getCurrentActionId() + '" method="POST" invite="true" type="No Energy Tax" content="<fb:name uid=\'' + FB.Connect.get_loggedInUser() + '\' /> is a member of NoEnergyTax.com and would like to share that experience with you. To register, simply click on the Register button below.&lt;fb:req-choice url=&quot;http://noenergytax.com&quot; label=&quot;Register&quot; /&gt;"><fb:multi-friend-selector cols=5 showborder="false" actiontext="Invite your Facebook Friends to use No Energy Tax" /> </fb:request-form></fb:fbml></script></fb:serverfbml>';
	  
	  // you might think you can use jquery to insert this. you would be wrong.
	  document.getElementById('action-content').innerHTML = html;
	  $('#action-content').css('background', 'url(styles/images/ajax-loader.gif) center center no-repeat');
	  
	  // you might think it's silly to set a timeout for 0 ms. you would be right.
	  // however if you want the form to actually render, you would be wise to care
	  // less about being right.
    setTimeout( 'FB.XFBML.Host.parseDomTree();', 0 );

  }
  

	function displayInviteForm( response )
	{
	  var response = eval( '(' + response + ')' );
		var friends = response.friends;
		var invites = response.invites;
		
		var message = $('p.status').html();

		var stripped_message = message.replace( /(<([^>]+)>)/ig, "" );
		//$('#inviter').html( "<h3>Invite Friends to Join the Game Against Energy Tax</h3><div class='fb'><p class='status'>" + stripped_message + "</p></div>" );

    $('#friends').empty();
    
    $('#friends').append( "<div id='yourphoto'><fb:profile-pic uid=loggedinuser facebook-logo=false size=small width=75 height=75></fb:profile-pic></div>" );
    $('#friends').append( "<span><a id='ref' class='ref_go'>Click here to Invite Friends<br /><span class='points'>and score 10 points</span></a></span>" );
    
    $('#friends').append( "<a id='checkall'>Select all</a><input type='text' id='search' name='serach' value='Search Friends' />" );
    
    $('#friends').append( "<p id='invite-limit'>You can invite up to " + invites + " of your friends</p>" );
    
    $('input#search').bind('focus', function() {
      $('input#search').val('');  
      $('input#search').css('color', 'black');
      $('input#search').css('font-style', 'normal');
    });
    
    
    $('input#search').keyup(function(e) {
      
      var search = function() {
        if (timerId) {
          clearTimeout(timerId);
        }
        timerId = 0;
        
        val = $('input#search').val().toLowerCase();

        
        var names = $('div#friends div.profline p');

        // search, wooo! looking for matching content of div.profline p
        names.each( function() {
          if ( val != '' && ! this.innerHTML.toLowerCase().match( val ) ) {
            this.parentNode.style.display = 'none';
          } else {
            this.parentNode.style.display = 'block';
          }    
        });        
      }
      
      if ( e.keyCode == 13 ) {
        search();
      } else {
        timerId = setTimeout(search, 1000);
      }
    });
    
    $('#inviter a#checkall').bind('click', function() {
      checkAllPrettyCheckboxes(this, $('#inviter'));
    });
    
		for( var i in friends )
		{
			var friend = friends[i];
			var html = "<div class='profline'>";
			html += "<label for='invite_" + friend.uid + "'>Invite</label> <input type='checkbox' id='invite_" + friend.uid + "' value='" + friend.uid + "' />"
			html += "<img src='" + friend.pic_square + "' />";
			html += "<p>" + friend.name + "</p>"
			html += "</div>";
			$('#friends').append(  html );
		}


    
		//$('#inviter').append( "</div><button>Invite</button>" );
		//$('#inviter button').bind('click', function(){ sendInviteRequest( message ) } );
		$('#inviter a#ref').bind('click', function() { sendInviteRequest(message); } );
		
		$('input[type=checkbox]').prettyCheckboxes({ checkboxWidth: 25, checkboxHeight: 24 });
    FB.XFBML.Host.parseDomTree(); 


	}
	
	function showConnectAction() {
	  var content = $('#leaderboard-content').html();
	  
	  // add it to the div
	  $('#connect-action').append( '<div id="leaderboard">' + content + '</div>' );
	  
  }
  

	function sendInviteRequest( message )
	{
		// collect uids
		var invitees = [];
		
		$('#inviter input').each(	function()
									{
										if( $(this).attr('checked') )
										{
											invitees.push( $(this).val() )
										}
									});

		if( invitees.length > 0 )
		{
			// phone home
			$.post( env.local + 'actions.php',
				{
					action: 'send_invites',
					action_id: getCurrentActionId(),
					invites: invitees.join(','),
					message: message
				},
				completedAction );
		}
	}

	function reloadAction()
	{
		// defeat the reload test
		var action = current_action;
		current_action = -1;
		selectAction( action, true );
	}

	function showScore( json, is_persistent )
	{
		// show the feedback screen
		//$('#presentation .content').slideUp( 500 );
		
		var html = "<div id='thanks'>";
		html += "<span id='message'>";
		
		if ( json.delta > 0 ) {
		  html += "You just scored " + json.delta + " points";
    } else {
      html += "Your score on the No Energy Tax Leaderboard is " + json.score + " points";
    }
    
    html += "</span>";

    html += "<img src='styles/images/score-dots.png' id='dot1' /><div id='leaderboard'>";
         
    if ( typeof( json.next ) != 'undefined' ) {
      html += "<div class='leader_set additional'>";
      html += "<div class='profline'>";
    
      var nrank = parseInt(json.rank) - 1;
      var margin = 40;
      var len = nrank.toString().length;
      if ( len > 2 ) {
        margin = 40 + ( (len-2) * 20 );
      }


      html += "<span class='rank'>" + nrank + "</span>";
      html += "<img src='" + json.next.profile_pic + "' style='left: " + margin + "px;' />";
  		html += "<p><a href='http://facebook.com/profile.php?id=" + json.next.id + "'>" + json.next.name + "</a><br />" + json.next.score + "</p>";
  		html += "</div></div>";
    } else {
      var margin = 40;
    }

    html += "<div class='leader_set additional'>";
    html += "<div class='profline current_user'>";
    html += "<span class='rank'>" + json.rank + "</span>";
		html += "<img src='" + json.profile_pic + "' style='left: " + margin + "px;' />";    
		html += "<p><a href='http://facebook.com/profile.php?id=" + json.id + "'>" + json.name + "</a><br />" + json.score + "</p>";
		html += "</div></div>";

    html += "</div>";
    html += "<img src='styles/images/score-dots.png' id='dot2' />";

    if ( typeof( json.next ) != 'undefined' ) {
      var diff = json.next.score - json.score;
      html += "<div id='text'>Only " + diff + " more points to pass " + json.next.name + " on the Leaderboard</div>";
    }
    
		if( is_persistent )
		{
			html += "<a id='back' onclick='reloadAction()'></a>";
		}

		if( json.delta > 0 )
		{
			html += "<p id='announce-text'>Score 10 more points by announcing on Facebook</p><a id='announce' onclick='announceScore(" + json.delta + ")'></a>";
		}

  
		html += "</div>";


    $('#action-content').html( html );
		//$('#presentation .content').html( html );
		//$('#presentation .content').slideDown( 500 );

		// increment the counter
		bumpCtr( json.delta );
	}

	function announceScore( delta )
	{
	  /* FIXME */
	  var inline_message = "I just scored " + delta + " points to spread the word about a dangerous energy tax. Get involved before it's too late.";
		//var inline_message = "I just scored " + delta + " points on No Energy Tax. Check it out! http://noenergytax.com";
		setStatusInline( inline_message );
	}

	function bumpCtr( delta )
	{
		if( delta-- > 0 ) // decrements after comparison
		{
			incrementCtr();
			setTimeout( function(){ bumpCtr( delta ) }, 1000 );
		}
	}

	function completedAction( response )
	{
		// get the info about the action
		if( response )
		{
			var action = _actions[current_action];

			// show the score change
			showScore( eval( '(' + response + ')' ), action.is_persistent );

			// reload the leaderboard
			getLeaderboard();

			// hide the action, if it isn't persistent
			if( action.is_persistent == 0 )
			{
				loadActions();
			}
			
			
		}
	}

	function displayTweeter()
	{
		var message = $('#tweeter').text();

		// do we have twitter auth?
		if( env.user.twitter )
		{
			// yay
			$('#tweeter').html( "authorized" );
		}
		else
		{
			// boo. ask for auth
			$.getJSON(  env.lb + "oauthlink?site=" + site + "&ps=" + current_action + "&callback=?", showTwitterOauth );
		}
	}

	function showTwitterOauth( response )
	{
		var json = eval( response );
		
		$('#tweeter').html( "<a href='" + json.url + "'>Enable your twitter account</a>" );

	}

	/* video tracking */

	var ytplayer;

	function onYouTubePlayerReady(playerId)
	{
		ytplayer = document.getElementById("myytplayer");
		ytplayer.addEventListener("onStateChange", "handleVideoStateChange");
	}

	function markActionComplete()
	{
		var action = _actions[current_action];
		
		$.post( env.local + 'actions.php',
				{
					action: 'mark_action',
					action_id: action.id, // the action id is global; current_action is local
				  invites: invites // if we got a response from fb, include the number of invites
				},
				completedAction );

		logAction( "completedAction" );
	}

	function handleVideoStateChange( state )
	{
		//	onStateChange
		//  This event is fired whenever the player's state changes.
		//	Possible values are
		//	unstarted (-1),
		//	ended (0),
		//	playing (1),
		//	paused (2),
		//	buffering (3),
		//	video cued (5).
		//	When the SWF is first loaded it will broadcast an unstarted (-1) event.
		//	When the video is cued and ready to play it will broadcast a video cued event (5).

		// we only care about ended (0) rn:
		if( state == 0 )
		{
			markActionComplete();
		}
	}

	function watchVideo( hash )
	{
		// add something for the video to replace:
		$('.content').html( "<div id='ytapiplayer'></div>" );

		// use swfobject to embed the video
		var params = { allowScriptAccess: "always",
					   wmode: "opaque" };
		var atts = { id: "myytplayer" };
		swfobject.embedSWF( "http://www.youtube.com/v/" + hash + "&enablejsapi=1&playerapiid=ytplayer",
							"ytapiplayer",
							"560", "340", "8",
							null, null, params, atts);

		// the swf will call onYouTubePlayerReady when it's loaded
		// don't try to do anything with it here; it loads async
	}

	function submitMail() {
	  // lightbox duplicates our form
	  var name = document.email[1].name.value;
	  var email = document.email[1].email.value;
	  var subject = document.email[1].subject.value;
	  var comments = document.email[1].comments.value;
	  	  
	  if ( name == '' || email == '' || subject == '' || comments == '' ) {
	    $('#fancy_div').prepend('<b>Please fill out all fields</b>');
	     return;
    }
	  $.post( env.local + 'sendmail.php', { 
	       name: name,
	       email: email,
	       subject: subject,
	       comments: comments
	      }, function( response ) {
	         $('#fancy_div').empty();
	         $('#fancy_div').append("<h3>Thank you for your comments</h3>"); 

	      });
	      
	      return false;

  }
