var obj = this;
$('document').ready(function(){
	$('.facebook').each(function(){
		obj.tool_selector = $(this);
		obj.interaction = obj.tool_selector.find('input[name=fb_interaction]').val();
		obj.at = $(this).find('input[name=fb_tool_at]').val();
		obj.fb_app_host = $(this).find('input[name=fb_app_host]').val();
		//gets user info, profile pic, username, id
		$.ajax({
			url: 'https://graph.facebook.com/me/?access_token='+obj.at+'&fields=id,name,link,locale',
			type: 'get',
			dataType: 'jsonp',
			success: function(response){
				obj.user_id = response.id;
				obj.link = response.link;
				obj.locale = response.locale;
				obj.name = response.name;	
			}
		});
		$(obj.tool_selector).append('<div id="fb_loader"><img src="/images/fb_loader.gif" width="30" style="margin: 30px 0px 30px 45%"></div>');
		switch(obj.interaction){
		case 'status':
			var graph_url = 'https://graph.facebook.com/me/feed?access_token='+obj.at;
			//gets user status
			$.ajax({
				url: graph_url,
				type: 'get',
				dataType: 'jsonp',
				success: function(response){
					var status = response.data;
					var amount = parseInt($(obj.tool_selector).children('input[name=status_amount]').val());
					$(obj.tool_selector).append($('<ul></ul>').attr({'class':'status_list_container'}).hide());
					$('.status_list_container').append($('<li></li>').attr({'id':'user_status_info'}));
					$('#user_status_info').append('<div id="user_image"><img src="https://graph.facebook.com/'+obj.user_id+'/picture" /></div>');
					$('#user_status_info').append('<div id="user_name"><a href="'+obj.link+'">'+obj.name+'</a><br>Facebook Status</div>');
					amount <= status.length ? amount : amount = status.length;
					for (var i = 0; i < amount; i++){
						$('.status_list_container').append($('<li></li>').attr({'id':status[i].id})
								.append('<div id="status">'+status[i].message+'</div>')
								.append('<div id="other_info"></div>'));
						if(status[i].picture && typeof status[i].caption == 'undefined'){
							$('#'+status[i].id).children('#status').append('<br><img src="'+status[i].picture+'"></a>');

						}
						if(status[i].caption && status[i].picture){
							$('#'+status[i].id).children('#status').append('<br><a href="'+status[i].caption+'"><img src="'+status[i].picture+'"></a>');
						}
						if (status[i].application){
							$('#'+status[i].id).children('#other_info').append('<div class="via_fb_app"><img src="https://graph.facebook.com/'+status[i].application.id+'/picture">Via: '+status[i].application.name+'</div>');
						}
						var time_value = status[i].updated_time.replace(/[-T:+]/g,',').split(',');
						var updated_time = new Date(time_value[0], time_value[1], time_value[2], time_value[3], time_value[4], time_value[5]);
						$('#'+status[i].id).children('#other_info').append('<div class="updated_time">'+dateFormat(updated_time, 'ddd mmm d"th", "at" H:MM')+'</div>');
						 
						if($(obj.tool_selector).children('input[name=status_permissions]').val() == 'true'){
							$('#'+status[i].id).children('#other_info').append('<div class="fb_like_button">Like!</div><div class="fb_comment">Comment</div>');
						}

					}
					$('#fb_loader').remove();
					$('.status_list_container').fadeIn(1500);
				}
			});
			break;

		case 'notes':
			var graph_url = 'https://graph.facebook.com/me/notes?access_token='+obj.at;
			//gets user notes
			$.ajax({
				url: graph_url,
				type: 'get',
				dataType: 'jsonp',
				success: function(response){
					var note = response.data;
					var amount = parseInt($(obj.tool_selector).children('input[name=notes_amount]').val());
					amount <= note.length ? amount : amount = note.length;
					$(obj.tool_selector).append($('<ul></ul>').attr({'class':'notes_list_container'}).hide());
					for (var i = 0; i < amount; i++){
						var time_value = note[i].updated_time.replace(/[-T:+]/g,',').split(',');
						var updated_time = new Date(time_value[0], time_value[1], time_value[2], time_value[3], time_value[4], time_value[5]);
						$('.notes_list_container').append($('<li></li>').attr({'id':note[i].id})
								.append('<div class="note_title"><a href="http://www.facebook.com/note.php?note_id='+note[i].id+'">'+note[i].subject+'</a></div>')
								.append('<div id="user_name">From: <a href="'+obj.link+'">'+obj.name+'</a> '+dateFormat(updated_time, 'ddd mmm d"th", "at" H:MM')+'</div>')
								.append($('<div></div>').attr({'id':'status'}))
								.append('<div id="other_info"></div>'));
						var text = Encoder.htmlDecode(note[i].message);
						if (text.length >= 400){
							$('#'+note[i].id).children('#status').html(text.substr(0,400)+' ...');
							$('#'+note[i].id).children('#status').append('<a href="http://www.facebook.com/note.php?note_id='+note[i].id+'">Read full note from Facebook.</a>');
						}
						if($(obj.tool_selector).children('input[name=notes_permissions]').val() == 'true'){
							$('#'+note[i].id).children('#other_info').append('<div class="fb_like_button">Like!</div><div class="fb_comment">Comment</div>');
						}
					}
					$('#fb_loader').remove();
					$('.notes_list_container').fadeIn(1500);
				}
			});
			break;

		case 'events':
			if ($(obj.tool_selector).children('input[name=show_particular_event]').val() == 'true'){
				var event_id = $(obj.tool_selector).children('input[name=particular_event]').val();
				var graph_url = 'https://graph.facebook.com/'+event_id+'?access_token='+obj.at;
				//gets event_id info
				$.ajax({
					url: graph_url,
					type: 'get',
					dataType: 'jsonp',
					success: function(event){
						$(obj.tool_selector).append($('<ul></ul>').attr({'class':'events_list_container'}).hide());
						if(event.privacy == 'SECRET')
							$(obj.tool_selector).find('.events_list_container').append('<div>This event is SECRET and can not be displayed.</div>');
						else{
							$(obj.tool_selector).find('.events_list_container').append($('<li></li>').attr('id',event.id)
									.append($('<div></div>').attr({'id':'particular_event_photo_description'}))
							);
							$(obj.tool_selector).find('#particular_event_photo_description')
							.append('<div class="particular_event_photo"><img src="https://graph.facebook.com/'+event.id+'/picture?type=normal"></div>')
							.append('<div class="particular_event_description">'+event.name+'</div>');
							$(obj.tool_selector).find('.events_list_container li').append('<div id="particular_event_info"></div>');
							if (typeof event.venue != 'undefined' && typeof event.venue.street != 'undefined' && typeof event.venue.state != 'undefined' && typeof event.venue.city != 'undefined' && typeof event.venue.country)
								var address = urlencode(event.venue.street+' '+event.venue.state+' '+event.venue.city+' '+event.venue.country);
							else
								var adress = '';
								var time_value = event.start_time.replace(/[-T:+]/g,',').split(',');
								var start_time = new Date(time_value[0], time_value[1]-1, time_value[2], time_value[3], time_value[4], time_value[5]);
								time_value = event.end_time.replace(/[-T:+]/g,',').split(',');
								var end_time = new Date(time_value[0], time_value[1], time_value[2], time_value[3], time_value[4], time_value[5]);
							$(obj.tool_selector).find('#particular_event_info')
							.append('<div class="info_holder"><h3 class="event_controls">Confirm Attendance</h3></div>')
							.append('<div class="info_holder"><h3>Host:</h3>'+event.owner.name+'</div>')
							.append('<div class="info_holder"><h3>Date and Time:</h3>From '+dateFormat(start_time, 'ddd mmm d"th", "at" H:MM')+' to '+dateFormat(end_time, 'ddd mmm d"th", "at" H:MM')+'</div>')
							.append('<div class="info_holder"><h3>Place:</h3>'+event.location+'</div>');
							if (typeof event.venue != 'undefined' && typeof event.venue.street != 'undefined' && typeof event.venue.state != 'undefined' && typeof event.venue.city != 'undefined' && typeof event.venue.country)
								$(obj.tool_selector).find('#particular_event_info').append('<div class="info_holder"><h3>Address:</h3><a href="http://maps.google.com/maps?q='+address+'">'+event.venue.street+'<br>'+event.venue.state+'<br>'+event.venue.city+'<br>'+event.venue.country+'</a></div>');
							$(obj.tool_selector).find('#particular_event_info')
							.append('<div class="info_holder"><h3>How to get there:</h3><a href="http://maps.google.com/maps?daddr='+urlencode(event.location)+'&saddr='+address+'">From here</a></div>')
							.append('<div class="info_holder"><h3>Information:</h3>'+event.description+'</div>');
							$('#fb_loader').remove();
							$('.events_list_container').fadeIn(1500);
						}
					}
				});
			}

			else{
				//gets user events
				var graph_url = 'https://graph.facebook.com/me/events?access_token='+obj.at;
				$.ajax({
					url: graph_url,
					type: 'get',
					dataType: 'jsonp',
					success: function(response){
						var event = response.data;
						var amount = parseInt($(obj.tool_selector).children('input[name=events_amount]').val());
						var show_past_events = $(obj.tool_selector).children('input[name=show_past_events]').val();
						amount <= event.length ? amount : amount = event.length;
						$(obj.tool_selector).append($('<ul></ul>').attr({'class':'events_list_container'}).hide());
						if (show_past_events == 'false'){
							var is_past_event = 0;
							for (var i=0; i < amount; i++){
								var start_time = event[i].start_time.replace(/[-T:+]/g,',').split(',');
								var end_time = event[i].end_time.replace(/[-T:+]/g,',').split(',');
								start_time = new Date(end_time[0], end_time[1]-1, end_time[2], end_time[3], end_time[4], end_time[5]);
								end_time = new Date(end_time[0], end_time[1]-1, end_time[2], end_time[3], end_time[4], end_time[5]);
								is_past_event = end_time.getTime() - new Date().getTime() < 0;
								if(!is_past_event){
									$('.events_list_container').append($('<li></li>').attr({'id':event[i].id})
											.append('<div class="event_photo"><img src="https://graph.facebook.com/'+event[i].id+'/picture"></div>'));
									$('#'+event[i].id).append($('<div></div>').addClass('event_info')
											.append('<div class="event_name">'+event[i].name+'</div>')
											.append('<div class="event_location">'+event[i].location+'</div>')
											.append('<div class="event_date">From '+dateFormat(start_time, 'ddd mmm d"th", "at" H:MM')+' to '+dateFormat(end_time, 'ddd mmm d"th", "at" H:MM')+'</div>')
											.append('<div class="event_controls">Confirm attendance</div>'));

								}
							}
						}
						else{
							for (var i=0; i < amount; i++){
								var start_time = event[i].start_time.replace(/[-T:+]/g,',').split(',');
								var end_time = event[i].end_time.replace(/[-T:+]/g,',').split(',');
								start_time = new Date(end_time[0], end_time[1]-1, end_time[2], end_time[3], end_time[4], end_time[5]);
								end_time = new Date(end_time[0], end_time[1]-1, end_time[2], end_time[3], end_time[4], end_time[5]);
								$('.events_list_container').append($('<li></li>').attr({'id':event[i].id})
										.append('<div class="event_photo"><img src="https://graph.facebook.com/'+event[i].id+'/picture"></div>'));
								$('#'+event[i].id).append($('<div></div>').addClass('event_info')
										.append('<div class="event_name">'+event[i].name+'</div>')
										.append('<div class="event_location">'+event[i].location+'</div>')
										.append('<div class="event_date">From '+dateFormat(start_time, 'ddd mmm d"th", "at" H:MM')+' to '+dateFormat(end_time, 'ddd mmm d"th", "at" H:MM')+'</div>')
										.append('<div class="event_controls">Confirm attendance</div>'));
							}
						}
						$('#fb_loader').remove();
						$('.events_list_container').fadeIn(1500);
					}
				});
			}
			break;

		case 'like':
			var url = document.URL;
			var show_faces = tool_selector.find('input[name=show_faces]').val();
			var font = tool_selector.find('input[name=like_button_font]').val();
			var layout = tool_selector.find('input[name=like_button_type]').val();
			var app_id = tool_selector.find('input[name=fb_tool_app_id]').val();
			$('#fb_loader').remove();
			$('body').append('<div id="fb-root"></div>');
			obj.tool_selector.css('margin','5px');
			window.fbAsyncInit = function() {
				FB.init({appId: app_id, cookie: true, xfbml: true});
			};
			(function() {
				var e = document.createElement('script');
				e.async = true;
				e.src = document.location.protocol +
				'//connect.facebook.net/en_US/all.js';
				document.getElementById('fb-root').appendChild(e);
			}());
			tool_selector.append('<fb:like href="'+url+'" width="300" layout="'+layout+'" show_faces="'+show_faces+'" font="'+font+'"></fb:like>');
			break;
		}
	});

	$('.fb_like_button, .fb_comment, .event_controls').live('click', function(){
		var element_id = $(this).parents('li').attr('id');
		var page = window.location.href;
		var interaction_action = $(this).attr('class');
		var interaction = $(this).parents('ul').attr('class').replace(/_list_container/, '');
		var document_end = $(document).height();
		var screen_size = $(window).height();
		var top_of_screen = $(window).scrollTop();
		var dialog_interface_height = $('#dialog_interface').height() + $('#dialog_controls').height() + screen_size - (($('#dialog_interface').height() + $('#dialog_controls').height()));

		$('#comment_fb_status').remove();
		$('#page').append($('<div></div>').addClass('slideup').append($('<div></div>').attr('id','comment_fb_status')));

		switch(interaction_action){
		case 'fb_like_button':
			interaction_action = 'like';
			var url = 'https://'+obj.fb_app_host+'/index.php/facebook/app?';
			var params = 'interaction_action='+interaction_action+'&id='+element_id+'&page='+urlencode(page)+'&interaction='+interaction;
			window.location = url+params;
			break;
		case 'fb_comment':
			interaction_action = 'comment';
			$('#comment_fb_status').append($('<div></div>').attr('id', 'shadow_box')
					.append($('<div></div>').attr('id', 'wrapper')
							.append($('<span></span>').attr('id','close_dialog').html('x'))
							.append($('<span></span>').attr('id','small_facebook_img'))
							.append($('<span></span>').attr('id','dialog_title').html('Publish in Facebook'))
					)
					.append($('<div></div>').attr('id','dialog_interface')
							.append($('<span></span>').attr('id','interface_name').html('Write a comment.'))
							.append($('<span></span>').attr('id','interface_instructions').html('Write something about this '+interaction+'.'))
							.append($('<textarea></textarea>').attr({'id':'user_input', 'name':'user_input'}))
					)
					.append($('<div></div>').attr('id','dialog_controls')
							.append($('<span></span>').attr('id','publish_btn').html('Publish'))
							.append($('<span></span>').attr('id','cancel_btn').html('Cancel')))
			);
			/**************************************/
			window.location = '#comment_fb_status';
			$(window).scrollTop(top_of_screen);
			$('#shadow_box').css('height', screen_size);
			$('#dialog_interface').css('height',dialog_interface_height-120);
			$('#comment_fb_status').css({'margin-top': -(document_end - top_of_screen)});
			/**************************************/
			break;
		case 'event_controls':
			interaction_action = 'event';
			$('#comment_fb_status').append($('<div></div>').attr('id', 'shadow_box')
					.append($('<div></div>').attr('id', 'wrapper')
							.append($('<span></span>').attr('id','close_dialog').html('x'))
							.append($('<span></span>').attr('id','small_facebook_img'))
							.append($('<span></span>').attr('id','dialog_title').html('Publish in Facebook'))
					)
					.append($('<div></div>').attr('id','dialog_interface')
							.append($('<span></span>').attr('id','interface_name').html('Will you attend to this event?'))
							.append($('<span></span>').attr('id','will_attend').html('I will'))
							.append($('<span></span>').attr('id','may_attend').html('Maybe'))
							.append($('<span></span>').attr('id','wont_attend').html('I wont'))
					)
					.append($('<div></div>').attr('id','dialog_controls')
							.append($('<span></span>').attr('id','cancel_btn').html('Cancel')))
			);
			/**************************************/
			window.location = '#comment_fb_status';
			$(window).scrollTop(top_of_screen);
			$('#shadow_box').css('height', screen_size);
			$('#dialog_interface').css('height',dialog_interface_height-120);
			$('#comment_fb_status').css({'margin-top': -(document_end - top_of_screen)});
			/**************************************/
			break;
		}
		$('#close_dialog, #cancel_btn').live('mouseup', function(e){
			$('#comment_fb_status').css('margin-top','0');
			setTimeout("$('#comment_fb_status').remove()", 600);
		});
		$('#publish_btn, #will_attend, #may_attend, #wont_attend').live('mouseup', function(e){
			var message = urlencode($('#user_input').val());
			if($(this).attr('id') !== 'publish_btn'){
				message = $(this).attr('id');
			}
			var url = 'https://'+obj.fb_app_host+'/index.php/facebook/app?';
			var params = 'interaction_action='+interaction_action+'&id='+element_id+'&page='+urlencode(page)+'&interaction='+interaction+'&fbmessage='+message;
			window.location = url+params;
		});
	});
});

function urlencode (str) {
	str = (str + '').toString();
	// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
	// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
	replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
	timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
	timezoneClip = /[^-+\dA-Z]/g,
	pad = function (val, len) {
		val = String(val);
		len = len || 2;
		while (val.length < len) val = "0" + val;
		return val;
	};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
				d = date[_ + "Date"](),
				D = date[_ + "Day"](),
				m = date[_ + "Month"](),
				y = date[_ + "FullYear"](),
				H = date[_ + "Hours"](),
				M = date[_ + "Minutes"](),
				s = date[_ + "Seconds"](),
				L = date[_ + "Milliseconds"](),
				o = utc ? 0 : date.getTimezoneOffset(),
						flags = {
						d:    d,
						dd:   pad(d),
						ddd:  dF.i18n.dayNames[D],
						dddd: dF.i18n.dayNames[D + 7],
						m:    m + 1,
						mm:   pad(m + 1),
						mmm:  dF.i18n.monthNames[m],
						mmmm: dF.i18n.monthNames[m + 12],
						yy:   String(y).slice(2),
						yyyy: y,
						h:    H % 12 || 12,
						hh:   pad(H % 12 || 12),
						H:    H,
						HH:   pad(H),
						M:    M,
						MM:   pad(M),
						s:    s,
						ss:   pad(s),
						l:    pad(L, 3),
						L:    pad(L > 99 ? Math.round(L / 10) : L),
						t:    H < 12 ? "a"  : "p",
								tt:   H < 12 ? "am" : "pm",
										T:    H < 12 ? "A"  : "P",
												TT:   H < 12 ? "AM" : "PM",
														Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
																o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
																S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
				};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

//Some common format strings
dateFormat.masks = {
		"default":      "ddd mmm dd yyyy HH:MM:ss",
		shortDate:      "m/d/yy",
		mediumDate:     "mmm d, yyyy",
		longDate:       "mmmm d, yyyy",
		fullDate:       "dddd, mmmm d, yyyy",
		shortTime:      "h:MM TT",
		mediumTime:     "h:MM:ss TT",
		longTime:       "h:MM:ss TT Z",
		isoDate:        "yyyy-mm-dd",
		isoTime:        "HH:MM:ss",
		isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
		isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

//Internationalization strings
dateFormat.i18n = {
		dayNames: [
		           "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		           "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
		           ],
		           monthNames: [
		                        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		                        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
		                        ]
};

//For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
