// JavaScript Document
/* Global JavaScript File for gc */

var debugging = false; // or true
if (typeof console == "undefined") var console = { log: function() {} }; 
else if (!debugging || typeof console.log == "undefined") console.log = function() {};

//fix so tags will show after hitting back button - tags still broken in chrome
history.navigationMode = 'compatible';

//Global variables;
var gc_vars = new Object();
gc_vars.checkstatus=false;


// execute when the HTML file's (document object model: DOM) has loaded
$(document).ready(function() {

  	//reset vars
	gc_reset_vars();
	
	//init toolbar menus
	gc_init_menus();
	
	//enable rel="facebox" links
	//$('a[rel*=facebox]').facebox();
	//$.facebox.settings.opacity = 0.5; 
	
	//enable tipsy tooltips
	$('.tipsy').tipsy({fade: true, gravity: 'n'});
	
	//init global ui elements
	gc_init_ui();
	
	//check for new notifications 
	//setTimeout("gc_session_check(true)",2000); 
	gc_session_check(true)
	
	//init facebook
	//gc_init_facebook();
	
	console.log('check status is', gc_vars.checkstatus);
});


//TODO: remove all calls to this function in views
function addthis_toolbar()
{
	return true;	
}


//reset vars so dynmaic content can be refreshed
function gc_reset_vars() {
  gc_vars.messages_loaded=false;
  gc_vars.friendrequests_loaded=false;
  gc_vars.notifications_loaded=false;
  gc_vars.message_count_loaded=false;
}


//keeps session alive if page left open and check for new notifications
function gc_session_check(firstload) {
	
	var remoteURL = '/api/ping/' + firstload + '/' + Math.random()*9999999;
	
	$.ajax({  
		type: "POST", 
		dataType: 'json',
		url: remoteURL,  
		data: "",  
		success: function(data){ 
			gc_vars.checkstatus = data['check'];
			
			if(gc_vars.checkstatus==true)
			{
				//reset vars so dynamic content can be refreshed
				gc_reset_vars();
				
				//update new message / friend counters
				gc_update_counters(data['counters']);
				
				//parse any messages retured from server
				gc_parse_servermessages(data);	
			}
		}, 
	});
	
	setTimeout("gc_session_check(false)",120000); //re-check every 2 min 
}



//update new message / friend counters
function gc_update_counters(counters)
{
	console.log("in gc update counters", counters);
	
	//new message counter
	if(counters['num_msg'] != undefined)
	{
		unread_msgs = counters['num_msg'];
		if(unread_msgs > 0)
		{
			if(unread_msgs>99) unread_msgs='99+';
			$('#msg_num_indicator').html(unread_msgs);
			$('#msg_num_outer').show();
		}
	}
	
	//friend request counter
	if(counters['num_requests'] != undefined)
	{
		requests = counters['num_requests'];
		if(requests > 0)
		{
			if(requests>99) requests='99+';
			$('#friend_requests_indicator').html(requests);
			$('#friend_requests_outer').show();
		}
	}
	
	
	//new notifications counter
	if(counters['num_notifications'] != undefined)
	{
		unread_notifications = counters['num_notifications'];
		if(unread_notifications > 0)
		{
			if(unread_notifications>99) unread_notifications='99+';
			$('#notifications_num_indicator').html(unread_notifications);
			$('#notifications_num_outer').show();
		}
	}
	
	
}


//handle any server messages
function gc_parse_servermessages(data)
{
	//console.log("in gc serverdata parse",data['time']);
	
}


// handle menus with dynamic content 
function gc_menu_content(dropdown)
{
	//console.log('loading content',dropdown);
	menu = dropdown.attr('id');
	
	//Messages menu content
	if(menu=='messages-dd')
	{
	  //console.log('messages drop down menu show');
	    
	  if(gc_vars.messages_loaded==false)
	  {
		  //console.log('Doing messages ajax load ', gc_vars);
		
		  $('#messages-dd-content').html('<div class="spinner_bar">&nbsp;</div>Loading...Please wait');
		  $('#messages-dd-content').load('/messages/getrecent/' +  Math.random()*9999999, function() {
										gc_vars.messages_loaded=true;
									});
	  }
	}
	
	//Friend requests menu content
	if(menu=='friends-dd')
	{
	  //console.log('friends drop down menu show');
	    
	  if(gc_vars.friendrequests_loaded==false)
	  {
		  //console.log('Doing friend requests ajax load ', gc_vars);
		
		  $('#friends-dd-content').html('<div class="spinner_bar">&nbsp;</div>Loading...Please wait');
		  $('#friends-dd-content').load('/friends/getrecent/' +  Math.random()*9999999, function() {
										gc_vars.friendrequests_loaded=true;
									});
	  }
	}
	
	
	//Notifications menu content
	if(menu=='notifications-dd')
	{
	  //console.log('messages drop down menu show');
	    
	  if(gc_vars.notifications_loaded==false)
	  {
		  //console.log('Doing messages ajax load ', gc_vars);
		
		  $('#notifications-dd-content').html('<div class="spinner_bar">&nbsp;</div>Loading...Please wait');
		  $('#notifications-dd-content').load('/notifications/getrecent/' +  Math.random()*9999999, function() {
										gc_vars.notifications_loaded=true;
									});
	  }
	}
	
}




//setup menu handlers
function gc_init_menus() {
	
	/* for keeping track of what's "open" */
	var activeClass = 'dropdown-active', showingDropdown, showingMenu, showingParent;

	/* hides the current menu */
	var hideMenu = function() {
		if(showingDropdown) {
		  showingDropdown.removeClass(activeClass);
		  showingMenu.hide();
		}
	};
	
	/* recurse through dropdown menus */
	$('.dropdown').each(function() {
		/* track elements: menu, parent */
		var dropdown = $(this);
		//var menu = dropdown.next('div.dropdown-menu'), parent = dropdown.parent();
		
		var menu = dropdown.next('div.dropdown-menu'), parent = dropdown.parent();
		
		/* function that shows THIS menu */
		var showMenu = function() {
		  hideMenu();
		  showingDropdown = dropdown.addClass('dropdown-active');
		  showingMenu = menu.show();
		  showingParent = parent;
		};
		
		/* function to show menu when clicked */
		dropdown.bind('click',function(e) {
		  if(e) e.stopPropagation();
		  if(e) e.preventDefault();
		  showMenu(); 
		  gc_menu_content(dropdown);
		});
		
		/* function to show menu when someone tabs to the box */
		dropdown.bind('focus',function() {
			 showMenu();
			 
		});
	});
	
	/* hide when clicked outside */
	$(document.body).bind('click',function(e) {
		if(showingParent) {
		  var parentElement = showingParent[0];
		  if(!$.contains(parentElement,e.target) || !parentElement == e.target) {
			hideMenu();
		  }
		}
	});
	
}



//global gc ui setup
function gc_init_ui()
{
	
	//from messages.js - turn into a more generic row-click class or global message.js include file
	//use live as we will load message-rows from ajax
	
	//highligh  on hover
	$(".highlight").hover(
	  function () {
		 $(this).addClass("highlight-on");
	  }, 
	  function () {
		 $(this).removeClass("highlight-on");
	  }
	);
	
	//highligh messages on 
	$('.message-row').live('mouseover mouseout click', function(event) {
	  if (event.type == 'mouseover') {
		// do something on mouseover
		$(this).removeClass("highlight-on2");
		 	$(this).addClass("highlight-on");
	  } else if ( event.type == 'mouseout') {
			// do something on mouseout
			$(this).removeClass("highlight-on");
		 	if ($(this).hasClass("msgunread") )
		 	{
				$(this).addClass("highlight-on2");
		 	}
	  } else {
			var $target = $(event.target);
		   	if( $target.is('input[type="checkbox"]') ) {
			    return;
		   	} else {
		  		rowlink = $(this).find(".readmsgdiv a").attr('href') ;
				if(rowlink != undefined)
				{
					location.href = $(this).find(".readmsgdiv a").attr('href') ;
				}
			}
	  }
	  
	});
}




//load facebook script
function gc_init_facebook()
{
	var e = document.createElement('script');
	e.type = 'text/javascript';
	e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	//'http://static.ak.fbcdn.net/connect/en_US/core.debug.js';
	e.async = true;
	document.getElementById('fb-root').appendChild(e);		
}
