var fbConnect = {};
var fbEvents = [];
var fbEventsObj = {};
var EventIDString = "";


$(window).load(fbInit);

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}

function fbInit() {
	FB.getLoginStatus(fbStatus);
	FB.Event.subscribe('auth.statusChange', fbStatus);
}

function fbConnected (connected, response) {
    var div;
    if (connected) {
        fbCloseWindow();

        $("#fbloginwrapper").html("<fb:profile-pic class='fbProfilePic' uid='loggedinuser' linked='false'></fb:profile-pic>" +
        "<fb:name class='fbName' uid='loggedinuser' useyou='false'></fb:name> <div class='fbGreyBold'>Welcome back</div>" +
        "");
        FB.XFBML.parse(document.getElementById("fbloginwrapper"));
        fbConnect.user_id = FB.getAuthResponse().uid;
	//dumpProps(response);
	fbConnect.session = response.authResponse;

        if (typeof fbConnect.onLogin == 'function') {
            fbConnect.onLogin();
        }

    } else {
        $("#fbloginwrapper").html("<div class='fbButton' onclick='fbLogin();'></div>");
        FB.XFBML.parse(document.getElementById("fbloginwrapper"));
	fbConnect.session = {};
    }
}

function fbOpenWindow(){
    var header = $("#fbWindowHeader");
    var content = $("#fbWindowContent");
    FB.XFBML.parse();
    $("#fbWindow").css('left',(($(window).width()/2 - $("#fbWindow").width()/2)) + 'px');
    $("#fbWindow").css('top',(($(window).scrollTop() + ($(window).height()/2 - $("#fbWindow").height()))) + 'px');
}

function fbCloseWindow(){
    $("#fbWindow").css('left','-1000px');
}

function fbStatus(response) {
	if (response.authResponse) {
		fbConnected(true,response);
	} else {
		fbConnected(false,null);
	}
}

function fbLogin(){
    FB.login(function(response) {		
        if (response.authResponse) {
            fbConnected(true);
            if (response.scope) {
                fbConnected(true);				
            }
        }
    }, {
        scope:'rsvp_event,publish_stream,offline_access,friends_events'
    });
}

function onFBNotConnected(name,val){

    // alert('onFBNotConnected()');
	
    var profile = $('fb_connect_status');
    profile.innerHTML = '<div class="fb_connect_button" onclick="doLogin();">Connect with Facebook</div>';//'<fb:login-button onlogin="onFBConnected();"></fb:login-button>';
	
    var a = document.getElement('li[title=fb_event_friends]');
	
    //a.addEvent('click', function(){
		
		
    //});
	
	
	
    //$("fb_event_attendees").innerHTML = '<div class="fb_connect_button" onclick="doLogin();">Connect with Facebook</div>';
    FB.XFBML.parse();
}

function fbAddLoginEvent(func) {
    var oldFunc = fbConnect.onLogin;

    fbConnect.onLogin = function() {
        if (oldFunc) {
            oldFunc();
        }
        func();
    }
}

function fbStory(EventID,EventName,status,offset){

    fbCloseWindow();
    //alert($("showings").value);
    var s = EventID;
    var msg = (status == "attending")? "I'm going! Who's in?": "I want to go! Who's in?";
    var prompt = (status == "attending")? "Tell friends you're going!": "Tell friends you want to go!";

    var dte = new Date(fbEventsObj[s].start_time * 1000);
    dte = DateAdd('h',dte,offset);
	
    var dte_end = new Date(fbEventsObj[s].end_time * 1000);
    dte_end = DateAdd('h',dte_end,offset);

    var date_start = FormatDate(dte,'hh:nn am/pm');
    var date_end = FormatDate(dte_end,'hh:nn am/pm');
	
    var date = FormatDate(dte,'dddd, mmmm dd');
    date += " "+date_start;
    if(date_start != date_end) date += " - " + date_end;
    var venue = fbEventsObj[s].venue.street +" " + fbEventsObj[s].venue.city + ", " + fbEventsObj[s].venue.state;
    var pic = fbEventsObj[s].pic_small;
    var loc = fbEventsObj[s].location;
    FB.ui(
    {
        method: 'stream.publish',
        message:msg,
        attachment: {
            name:EventName,
            caption: '',
            description: (
                ''
                ),
            href: 'http://www.facebook.com/event.php?eid=' + s,
            'properties': {
                'Date':date,
                'Venue':venue,
                'Location':loc
            }
			
        },
		

        'media': [{
            'type': 'image',
            'src':pic,
            'href': 'http://www.facebook.com/event.php?eid=' + s
        }],
		
        user_message_prompt:prompt
    },
    function(response) {
        //alert(dump(response));
        if (response && response.post_id) {
            //alert('Post was published.');
            sendFBData('rsvp_event',s,status,EventName,offset);
			
        } else {
            sendFBData('rsvp_event',s,status,EventName,offset);
        }
		
    }
    );
    FB.XFBML.parse();
}

function fbCancelRSVP(s,EventName,offset){
    sendFBData('rsvp_event',s,"declined",EventName,offset);
}

function fbShowAddEvent(EventID,EventName,status,offset){

    var sHTML = "";
    var sExtra = (status == "maybe")? "Do you want to go to " : "Are you going to ";

    $("#fbWindowHeader").html('Add Event to Facebook');
    sHTML += '<div class="textarea"><h3>'+sExtra+EventName.replace(/'/g,"\\'")+'?</h3>';
    sHTML += '<p>Click \'Yes\' to add '+EventName.replace(/'/g,"\\'")+' to your Facebook profile.</p>';
    sHTML +='</div></div><div class="toolbar"><button class="submit" onclick="fbStory('+EventID+',\''+EventName.replace(/'/g,"\\'")+'\',\''+status+'\','+offset+')">Yes</button><button class="cancel" onclick="fbCloseWindow()">No</button></div>';
	
    $("#fbWindowContent").html(sHTML);
    fbOpenWindow();
}

function DateAdd(ItemType, DateToWorkOn, ValueToBeAdded)
{
    switch (ItemType)
    {
        //date portion         
        case 'd': //add days
            DateToWorkOn.setDate(DateToWorkOn.getDate() + ValueToBeAdded)
            break;
        case 'm': //add months
            DateToWorkOn.setMonth(DateToWorkOn.getMonth() + ValueToBeAdded)
            break;
        case 'y': //add years
            DateToWorkOn.setYear(DateToWorkOn.getFullYear() + ValueToBeAdded)
            break;
        //time portion         
        case 'h': //add days
            DateToWorkOn.setHours(DateToWorkOn.getHours() + ValueToBeAdded)
            break;
        case 'n': //add minutes
            DateToWorkOn.setMinutes(DateToWorkOn.getMinutes() + ValueToBeAdded)
            break;
        case 's': //add seconds
            DateToWorkOn.setSeconds(DateToWorkOn.getSeconds() + ValueToBeAdded)
            break;
    }
    return DateToWorkOn;
}


function FormatDate(sDateTime,sFormat){
    // a global month names array
    var gsMonthNames = new Array(
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
        );

    // a global day names array
    var gsDayNames = new Array(
        'Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
        );
    var d = sDateTime;//new Date(sDateTime *1000);
    sFormat = sFormat.toLowerCase();
    var nDate = sFormat.replace(/(yyyy|yy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|gh|gn|gs|a\/p|am\/pm)/gi,
        function($1)
        {
            switch ($1.toLowerCase())
            {
                case 'yyyy':
                    return d.getFullYear();
                case 'yy':
                    return String(d.getFullYear()).substr(2,4);
                case 'mmmm':
                    return gsMonthNames[d.getMonth()];
                case 'mmm':
                    return gsMonthNames[d.getMonth()].substr(0, 3);
                case 'mm':
                    return (d.getMonth() + 1);
                case 'dddd':
                    return gsDayNames[d.getDay()];
                case 'ddd':
                    return gsDayNames[d.getDay()].substr(0, 3);
                case 'dd':
                    return d.getDate();
                case 'hh':
                    return ((h = d.getHours() % 12) ? h : 12);
                case 'gh':
                    return d.getHours();
                case 'nn':
                    return d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
                case 'gn':
                    return d.getMinutes();
                case 'ss':
                    return d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
                case 'gs':
                    return d.getSeconds();
                case 'a/p':
                    return d.getHours() < 12 ? 'a' : 'p';
                case 'am/pm':
                    return d.getHours() < 12 ? 'AM' : 'PM';
            }
        })
	
    return nDate;
}


/***********************************************
Login Event Functions

***********************************************/

function getFBEventStatus(EventID,EventName,dateOffset){

    $('#fbRSVPShare').html('<a href="javascript:fbShowAddEvent('+EventID+',\''+EventName+'\',\'attending\','+dateOffset+');" id="link_rsvp">I\'m going!</a><a href="javascript:fbShowAddEvent('+EventID+',\''+EventName+'\',\'maybe\','+dateOffset+');" id="link_rsvp">Maybe</a>');
	
}
function getFBEventAttendees(EventIDStr){

    var acc_token = "";
//dumpProps(fbConnect);
	if (fbConnect.session.access_token) {
		acc_token = fbConnect.session.access_token;
	} 

    fbEvents = new Array();
    fbEventsObj = {};
    $("#fbAttendees").html("");
    $("#fbFriends").html("");
    //var eidArr = EventIDStr.split(",");
var eidArr = [];	
eidArr[0] = EventIDStr;
    var sqlWhere = "";
    var a = "";
    for(var i =0;i<eidArr.length;i++){
        if(i == 0) a= eidArr[i];
        sqlWhere +=  eidArr[i] + ",";
	
    }
    sqlWhere = sqlWhere.substring(0,sqlWhere.length -1);
    EventIDString = sqlWhere;
//    var query = FB.Data.query('SELECT uid, eid, rsvp_status FROM event_member WHERE eid IN({0})',
//        sqlWhere);
		
    var rsvpArray = new Array();
    var rsvpArrayFriends = new Array();

//    var queryEvent = FB.Data.query('SELECT name,eid,start_time,end_time,pic_small,description,host,location,venue FROM event WHERE eid IN({0})',
//        sqlWhere);
	
    var uid =0;
    FB.getLoginStatus(function(response) {
        if (response.authResponse) {
            uid = FB.getAuthResponse().uid;
        }
    });

//alert(uid);

    var eventArr ={};
	
    var iCount = 0;
    var iCount1 = 0;
 
 
    if(uid === 0){
        var qr= {
            "users":"SELECT uid, eid, rsvp_status FROM event_member WHERE eid IN("+sqlWhere+")",
            "events":"SELECT name,eid,start_time,end_time,pic_small,description,host,location,venue FROM event WHERE eid IN("+sqlWhere+")"
        };
	
        FB.api({
            method: 'fql.multiquery',
            queries:qr,
            access_token:acc_token
        }, function(result) {
	  
            if(result.length > 0){
                FB.Array.forEach(result[0].fql_result_set, function(rows) {
	  
                    var eid = '"' + rows.eid + '"';
                    fbEvents.push(rows);
                    fbEventsObj[rows.eid]=rows;
			
                });
                if(result[1].fql_result_set.length < 1){
                    $("#fbAttendees").html("<strong>Be the first of you friends to say you're going to this event!</strong>");
                    $("#fbFriends").html("<strong>Be the first to say you're going to this event!</strong>");
                }
                FB.Array.forEach(result[1].fql_result_set, function(rows) {
	  
                    if(iCount1 == result[1].fql_result_set.length &&  rsvpArray.length < 1)
                    {
                        $("#fbAttendees").html("<strong>Be the first to say you're going to this event!</strong>");
                    }
	  
                    if(rows.rsvp_status == "attending" || rows.rsvp_status == "unsure"){

                        var eid = rows.eid;
                        var status = rows.rsvp_status;
				
                        if(status=="attending") status="Going";
                        if(status=="unsure") status="Maybe";
				
				
				
                        FB.api('/' + rows.uid, function(response) {
					
                            if(rsvpArray.indexOf(response.id) > -1){
                            //var div = "status_" + response.id;
                            //$(div).innerHTML = $(div).innerHTML + status;
                            }else{
				if (rsvpArray.length < 20) {
                                var name = response.first_name;
                                $("#fbAttendees").html($("#fbAttendees").html() + '<div class="attendee" id="fb_'+response.id+'">'+
                                '<a class="fb_link" href="' + response.link + '"><img src="https://graph.facebook.com/'+response.id+'/picture" alt="'+
                                name+'" title="'+name+'" /></a>' +
                                '<a class="fb_name" href="'+response.link+'">'+name+'<span id="status_'+response.id+'">' + status + '</span></div>');
				}
                                rsvpArray.push(response.id);
                            }
                        });
                    }

                    iCount1++;
			
                });
            }
	  

        });
    }
    else{
	
	
	
        var qr= {
            "users":"SELECT uid, eid, rsvp_status FROM event_member WHERE eid IN("+sqlWhere+")",
            "events":"SELECT name,eid,start_time,end_time,pic_small,description,host,location,venue FROM event WHERE eid IN("+sqlWhere+")"
        };
	
        FB.api({
            method: 'fql.multiquery',
            queries:qr,
            access_token:acc_token
        }, function(result) {
	  
            if(result.length > 0){
                FB.Array.forEach(result[0].fql_result_set, function(rows) {
	  
                    var eid = '"' + rows.eid + '"';
                    fbEvents.push(rows);
                    fbEventsObj[rows.eid]=rows;
			
                });
                if(result[1].fql_result_set.length < 1){
                    $("#fbFriends").html("<strong>Be the first of you friends to say you're going to this event!</strong>");
                    $("#fbAddendees").html("<strong>Be the first to say you're going to this event!!!</strong>");
                }
                FB.Array.forEach(result[1].fql_result_set, function(rows) {

                    var isFriend = false;
                    if(rows.rsvp_status == "attending" || rows.rsvp_status == "unsure"){
                        FB.api(
                        {
                            method: 'friends.areFriends',
                            uids1:FB.getAuthResponse().uid,
                            uids2:rows.uid
                        },
                        function(response) {
                            if(response[0].are_friends == true || response[0].are_friends  == "true") isFriend = true;
                        }
                        );
                        var eid = rows.eid;
                        var status = rows.rsvp_status;
				
                        if(status=="attending") status="Going";
                        if(status=="unsure") status="Maybe";
				
                        FB.api('/' + rows.uid, function(response) {
					
                            if(rsvpArray.indexOf(response.id) > -1){
                            }else{

					
                                var name = response.first_name;
                                if(response.id == uid) {
				//	alert("got here");
                                    name = "You";
                                    var sText = "";
                                    if(rows.rsvp_status == "attending") sText = '<span class="status">You are going</span>';
                                    else if(rows.rsvp_status == "unsure") sText = '<span class="status">You want to go</span>';
                                    if(sText != "") $('#fbRSVPShare').html(sText + '<a class="cancel" href="#" onclick="fbCancelRSVP(\''+rows.eid+'\',\''+fbEventsObj[rows.eid].name+'\','+fbConnect.hOffset+'); return false;">Cancel</a> ');
                                }
				if (rsvpArray.length < 20) {
                                $("#fbAttendees").html($("#fbAttendees").html() +  '<div class="attendee" id="fb_'+response.id+'">'+
                                '<a class="fb_link" href="' + response.link + '"><img src="https://graph.facebook.com/'+response.id+'/picture" alt="'+
                                name+'" title="'+name+'" /></a>' +
                                '<a class="fb_name" href="'+response.link+'">'+name+'<span id="status_'+response.id+'">' + status + '</span></div>');
						
                                if(isFriend == true) {
                                    rsvpArrayFriends.push(response.id);
                                    $("#fbFriends").html($("#fbFriends").html() + '<div class="attendee" id="fb_'+response.id+'">'+
                                    '<a class="fb_link" href="' + response.link + '"><img src="https://graph.facebook.com/'+response.id+'/picture" alt="'+
                                    name+'" title="'+name+'" /></a>' +
                                    '<a class="fb_name" href="'+response.link+'">'+name+'<span id="status_'+response.id+'">' + status + '</span></div>');
                                }
				}
                                if(iCount == result[1].fql_result_set.length-1  &&  rsvpArrayFriends.length < 1)
                                {
                                    $("#fbFriends").html("<strong>Be the first of you friends to say you're going to this event!</strong>");
                                }
                                rsvpArray.push(response.id);
                            }
                        });
                    }
                    iCount++;
	 

                });
	//	alert($("#fbAttendees").html());
            }
	 

        });
  
    }



}


function sendFBData(type,EventID,status,EventName,offset){
	if (!offset) {
		offset = 0;
	}
    switch (type) {
        case 'rsvp_event':
            FB.api('/'+EventID+'/' + status,'post',function(response){
                callbackRsvpFBEvent(response,EventID,status,type,EventName,offset);
            //window.location.reload();
            });
            break;
    }
}

// Callback

function callbackRsvpFBEvent(result,EventID,status,type,EventName,offset){
    fbCloseWindow();
    $("#bAttendees").html("");
    $("#bFriends").html("");
    getFBEventAttendees(fbConnect.EventIDStr);
    var sText = '<span class="status">You are going</span>';
    if(status == "maybe") sText = '<span class="status">You want to go</span>';
    if(status != "declined") $('#bRSVPShare').html(sText + '<a class="cancel" href="#" onclick="fbCancelRSVP(\''+EventID+'\',\''+EventName+'\','+offset+'); return false;">Cancel</a> ');
		
    if(status == "declined") $('fbRSVPShare').html('<a href="javascript:fbShowAddEvent('+EventID+',\''+EventName+'\',\'attending\','+offset+');" id="link_rsvp">I\'m going!</a><a href="javascript:displayFBConnectAddEvent('+EventID+',\''+EventName+'\',\'maybe\','+offset+');" id="link_rsvp">I want to go</a>');
}


function fbWallHTML(div) {

	$.ajax({
		url: "http://graph.facebook.com/JeffersonTheater/feed",
		dataType: "jsonp",
		success: function (data, textStatus, jqXHR) { fbWallHTML2(div, data); }
		
	});


}

function fbWallHTML2(div, data) {
	data = data.data;

	html = "";
	for (i = 0; i < data.length; i++) {
		if (data[i].message) {
			html += "<div class=\"fbPost\">";
			html += "<table><tr><td class=\"fbProfilePicTD\">";
			html += "<div class=\"fbProfilePic\">";
			if (data[i].from) {
				html += "<img src=\"http://graph.facebook.com/" + data[i].from.id + "/picture\" />";
			}
			html += "</div>";
			html += "</td><td>";
			html += "<div class=\"fbMessage\">";
			if (data[i].from) {
				html += "<span class=\"fbFromName\">" + data[i].from.name +"</span><br/>";
			}
			html += data[i].message + "</div>";
			html += "</td></tr></table>";
			html += "</div>";
		}
	}

	$("#" + div).html(html);

}

