/*
 * @description - 	handles all JS for site : login modal, error handling, and the FB Connect code
 * 					addEvent - overcomes a number of problems with MooTools 1.2.3 and IE with DOM Ready
 * 
 * @!ftw - keeping it DRY though
 * 
 * @ JS dependency
 * 		MooTools 1.2.3
 * 		Smoothbox 
 * 		FB Feature Provider for Connect
 * 		VSPink Navigation
 * 
 * @ DOM context dependency - all pages need <body onload="javascript:ie7Ready();">
 * 
 * @ variable context dependency - these variables must be present in the JS context from the including page
 * 		login_failed - bool
 * 		FBAPIK - string
 * 		logged_in - bool
 */ 


/**
* @author Toby Miller <tmiller@tobymiller.com>
* @copyright Copyright (C) 2005, Toby Miller
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*
* add an event to an element
*
* @param object dom element to add event to
* @param string w3c-standard event name being handled
* @param object w3c-standard event object or simulated function
* @param boolean [optional] whether to truly process the onload event or not (default = false)
* @return void
*/
function addEvent(element, eventName, eventObject) {
	
	if (element.addEventListener)
	{
		// this is a w3c-compliant browser, just wrap existing functions
		element.addEventListener(eventName, eventObject, false);
	}
	else if (element.attachEvent)
	{
		// collect optional parameters
		var processOnload = (arguments.length == 4) ? arguments[3] : false;

		if ((element == window) && (eventName == 'load') && (!processOnload))
		{
			// store this event, we'll do it in order with the other onloads
			_onloads.push(eventObject);
		}
		else
		{
			// add the new event
			element.attachEvent('on' + eventName, eventObject);
		}
	}
	return(true);
}
_onloads = [];
addEvent(window, 'load', function(){for(var i = 0; i < _onloads.length; i++){_onloads[i]();}}, true);




function focus_modal_login() {
	if ($("TB_ajaxContent").getElement("input") != null) {
		$("TB_ajaxContent").getElement("input").focus();
	}
}

function process_login_form(form_name) {
	recordAnalytics( { 'ga' : { 'tag' : '/event/global_login/sign_in/go' } } );
}

//trigger the GUL overlay if login failed
function hande_login_errors() { 
	if (login_failed) {

		//grab the link for the button
		var button = $('login_button');

	    if (button != null) {
	    	if (button.href != null) {
	    		
	    		var caption = button.title || button.name || "";
	    	    var rel = button.rel || false;
	    		
	    		TB_show(caption, button.href, rel);
	    		
	    	    // set modal 
	    	    focus_modal_login.delay(500);
	    	}
	    }
	    
	    // track login failures
	    recordAnalytics( { 'ga' : { 'tag' : '/event/global_login/sign_in/fail' } } );
	}
}


function spawn_global_login() {
	
	//grab the link for the button
	var button = $('login_button');

    if (button != null) {
    	if (button.href != null) {
    		
    		var caption = button.title || button.name || "";
    	    var rel = button.rel || false;
    		
    		TB_show(caption, button.href, rel);
    		
    	    // set modal 
    	    focus_modal_login.delay(500);
    	}
    }
    
}


// handles re-subscription of event triggering 
function show_global_login(event) {
	
    var event = new Event(event);
    // stop default behaviour
    event.preventDefault();
    // remove click border
    this.blur();
    // get caption: either title or name attribute
    var caption = this.title || this.name || "";
    // get rel attribute for image groups
    var group = this.rel || false;
    // display the box for the elements href
    TB_show(caption, this.href, group);
    this.onclick = show_global_login;
    
    // set modal 
    focus_modal_login.delay(500);

    // track login attempts 
    recordAnalytics( { 'ga' : { 'tag' : '/event/global_login/sign_in' } } );
    
    return false;
}

function subscribe_global_user_login() {
	
	$("login_button").onclick = show_global_login;
	
	if ($("other_login_button")) {
		$("other_login_button").onclick = show_global_login;
	}
}


//Variables for FB Connect user 
var uid; 
var first_name;
var last_name;
var clicked = false;

function FB_Connect_load() {
	
	FB_RequireFeatures(["Connect"], function () {
		
		// pre-emptive load
	});
	
}


function popUpWindow(url, width, height, resizable, scrollbars) {
	
	if (arguments.length == 1) {
		width = 335;
		height = 370;
		resizable = "yes";
		scrollbars = "yes";
	} else if (arguments.length == 3) {
		resizable = "no";
		scrollbars = "no";
	} else if (arguments.length == 4) {
		scrollbars = "no";
	}

	var win = window.open(url, "PopUp", "width=" + width + ",height=" + height + ",resizable=" + resizable + ",scrollbars=" + scrollbars + ",menubar=no,toolbar=no,left=20,top=20");
}


// query users who are already logged into facebook
function FB_Subscribe() {
	FB_RequireFeatures(["XFBML"], function() {
      FB.Facebook.init(FBAPIK, "/facebook_connect/xd_receiver_ssl.htm");
	  FB.Facebook.get_sessionState().waitUntilReady(function(session) {
			  	uid = FB.Facebook.apiClient.get_session().uid;
			  	var apiClient = FB.Facebook.apiClient;
				var query='SELECT first_name, last_name FROM user WHERE uid=' + apiClient.get_session().uid;
				apiClient.fql_query(query,function(result, ex) {
					first_name = result[0]['first_name'];
					last_name = result[0]['last_name'];
					uid = apiClient.get_session().uid;
					
					document.fb_overlay_login.fb_first_name.value = first_name;
					document.fb_overlay_login.fb_last_name.value = last_name;
					document.fb_overlay_login.fb_uid.value = uid;
					
					if(clicked == true) {
						document.fb_overlay_login.submit();
					}
				});
		      	
		 });        
    });
}

function FB_QueryInfo(tag) {

	uid = FB.Facebook.apiClient.get_session().uid;
  	var apiClient = FB.Facebook.apiClient;
	var query = 'SELECT first_name, last_name FROM user WHERE uid=' + apiClient.get_session().uid;
	apiClient.fql_query(query,function(result, ex) {
		first_name = result[0]['first_name'];
		last_name = result[0]['last_name'];
		uid = apiClient.get_session().uid;
		
		document.fb_overlay_login.fb_first_name.value = first_name;
		document.fb_overlay_login.fb_last_name.value = last_name;
		document.fb_overlay_login.fb_uid.value = uid;
		
		recordAnalytics({ 'ga': { 'tag' : tag } });
		
		document.fb_overlay_login.submit();
	});
	
}

function facebook_click(tag) {
	
	// determine receiver location for FB Connect to handle normal and SSL pages
	var receiver_location = (("https:" == document.location.protocol) ? "/facebook_connect/xd_receiver_ssl.htm" : "/facebook_connect/xd_receiver.htm");
	
	// http:\/\/developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.requireSession
	FB_RequireFeatures(["Connect"], function() {
		
		// init FB Connect, handle dynamic logout of users
		FB.Facebook.init( FBAPIK, receiver_location, { "doNotUseCachedConnectState" : true } );
		
		FB.Connect.requireSession(
			function() {
				FB_QueryInfo(tag);
				
				
			}, 
			function() {
				// cancel
			}, 
			true
		);
	});
	return false;
}


function rf_temp_iframe(url) {
	var iframe=document.createElement('iframe');
	iframe.src=url;
	iframe.width=0;
	iframe.height=0;
	document.getElementsByTagName('body')[0].appendChild(iframe);
}


function rf_temp_img(url) {
	var iframe=document.createElement('img');
	iframe.src=url;
	iframe.width=1;
	iframe.height=1;
	document.getElementsByTagName('body')[0].appendChild(iframe);
}


// over come limitation from MooTools
function init() {
	
	// TODO: delete this - depend on Mootools not init
	// subscribe the navigation
	if(typeof subscribe_nav == 'function') {
		//subscribe_nav();
	}
	
	// we need smoothbox even if the user is logged in...
	// init the smoothbox overlay control 
	
	if(typeof TB_init == 'function') {
		// TB_init();
	}
	
	if (!logged_in) {
		
		// subscribe the special click
		subscribe_global_user_login();		 

		// init the handling of login errors to show the login control on load
		hande_login_errors();
			
		// get FB Connect loaded
		FB_Connect_load();
		
	}
	
}

//prevent duplicate call of init function
function ie7Ready() {
  	// if (Browser.Engine.trident) init();
}

//prevent duplicate call of init function
window.addEvent('domready', function () {
	// if(!Browser.Engine.trident) init();
});

addEvent(window, 'load', init);

