// Live
var theApiKey = "36cb864dfbc882cdd5039ad27894fca2";
// Dev
// var theApiKey = "da9c5b94adb06f68fb8e576441ef238b";

$(document).ready(function(){
    $("#dateInput").datepicker({minDate: 0, maxDate: '+1Y',dateFormat: 'dd/mm/yy'});

    $("#haveCarSelect").change(function () {
        if($("#haveCarSelect").val() == "Yes") {
            $(".passengerCount").show();
        } else {
            $(".passengerCount").hide();
        }
    });

    $("#addMeLink").click(function () {
        $("#addMeContainer").show();
        $("#findOthersContainer").hide();
    });

    $("#findOthersLink").click(function () {
        $("#addMeContainer").hide();
        $("#findOthersContainer").show();
    });

    $("#findOthersSubmit").click(function () {
        $("#findOthersForm").submit();

    });

    $("#myTripsLink").click(function () {
        $("#myTripsUid").val(FB.getAuthResponse().userID);
        $("#myTripsForm").submit();
    });

    $("#myMessagesLink").click(function () {
        $("#myMessagesSession").val(FB.getAuthResponse().accessToken);
        $("#myMessagesForm").submit();
    });

    $("#stopOverLink").click(function () {
        $("#stopOverTr").toggle();
        if($("#stopOverLink").html() == "Add Stopover") {
            $("#stopOverLink").html("Remove Stopover");
        } else {
            $("#stopOverLink").html("Add Stopover");
        }
    });

    $('#login').click(function() {        
        FB.login(handleNewUser,{scope:'email'});
      });

      $('#logout').bind('click', function() {
        FB.logout(handleSessionResponse);
      });

      $('#disconnect').bind('click', function() {
        FB.api({method: 'Auth.revokeAuthorization'}, function(response) {
          clearDisplay();
        });
      });

    $("#addMeFormSubmit").click(function () {
     // Validate form     
     FB.getLoginStatus(function(response) {
      if (response.authResponse) {
                addMe();
        } else {
            alert("You need to login prior to adding a trip. Click 'Connect with Facebook' to login. ");
        }
    });
    });

});
function viewReceivedMessagesLink() {
    $("#msgContent").html("<div class=\"red removingLabel\">Loading received messages...</div>");
    $("#msgContent").load("/messages_received.jsp",{accessToken:FB.getAuthResponse().accessToken});
}

function viewSentMessagesLink() {
    $("#msgContent").html("<div class=\"red removingLabel\">Loading sent messages...</div>");
    $("#msgContent").load("/messages_sent.jsp",{accessToken:FB.getAuthResponse().accessToken});
}


function onConnected() {
    //alert('user is connected');
    $(".fbLoggedIn").show();
    $("#headerRight").addClass("bordersTrue");
    $("#loginLink").hide();
    
}


function addMe() {
    if($("#fromSelect").val() == $("#toSelect").val()) {
            showErrorDialog("Departure point same as destination.  Where do you need a lift to? The pub? :-)");
        } else {
            var from = $("#fromSelect").val();
            var to = $("#toSelect").val();
            var via = "";
            
            //if($("#stopOverTr").is(":visible")) {
             if($("#stopOverLink").html()== "Remove Stopover") {               
               via = $("#stopOverSelect").val();
            }
            var travelDate = $("#dateInput").val();
            //alert($("#dateInput").val());
            var haveCar = $("#haveCarSelect").val();
            var passengerCount = $("#passengerCountSelect").val();
            var comment = $("#commentTextarea").val();
            var location = $("#locationHidden").val();
            var id = $("#idHidden").val();
            //$("emptyContainer").load("/savemessage",{'uid' : FB.getAuthResponse().uid , 'from' : from, 'to': to,'date': travelDate,'passengerCount':passengerCount,'comment': comment  });
            $("#addMeContent").hide();
            $("#addMeResponse").show();
            //$("#addMeResponse").load("/savemessage",{'uid' : 1 , 'from' : from, 'to': to,'date': travelDate,'haveCar':haveCar,'passengerCount':passengerCount,'comment': comment  });
            var caption = "Looking for a lift";
            //from = "Shepherds Bush";
            //to = "Tescos, Hammersmith";
            var description = "Looking for a lift from "+from+" to "+to+" on "+travelDate+".";
            var userMsg = "Can anyone give me a lift?";
            if (haveCar == "Yes") {
                userMsg = "Is anyone looking for a lift?"
                caption = "Room for extra passengers";
                description = "Room for "+passengerCount+ " extra passengers going from "+from+" to "+to+" on "+travelDate+".";
            }
            var attachment = {'media':[{'type':'image','src':'http://www.liftsurfer.com/images/logo.gif','href':'http://www.liftsurfer.com/'}],"name":caption,"href":"http://www.liftsurfer.com","caption":description};
            //FB.Connect.streamPublish(userMsg,attachment);
            FB.ui(
  {
    method: 'stream.publish',
    attachment: {'media':[{'type':'image','src':'http://www.liftsurfer.com/images/logo.gif','href':'http://www.liftsurfer.com/'}],"name":caption,"href":"http://www.liftsurfer.com","caption":description}    
  },
  function(response) {
    if (response && response.post_id) {
      //alert('Post was published.');
    } else {
      //alert('Post was not published.');
    }
  }
);





            $("#addMeResponse").load("/savemessage",{'uid' : FB.getAuthResponse().userID,"accessToken":FB.getAuthResponse().accessToken , 'from' : from, 'to': to,'via': via,'date': travelDate,'haveCar':haveCar,'passengerCount':passengerCount,'comment': comment, 'location':location, 'id':id});


        }
}
function showErrorDialog(message) {
            //alert("Departure point same destination.  Where do you need a lift to? The pub? :-)");
            $("#dialogContent").html(message);
            $("#dialog").dialog({
			bgiframe: true,
			modal: true,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
        $("#dialog").dialog("open");
}
function showMsgDialog(uidTo, pic, name) {
    //var api = FB.Facebook.apiClient;
    if (FB.getAuthResponse() == null) {
         alert("You need to login before contacting other users. Click 'Connect with Facebook' to login. ");
     } else {
        //FB.Connect.showPermissionDialog("publish_stream", function(x){addMe();});
        showMsgDialog2(uidTo,pic,name);
     }
}

function showMsgDialog2(uidTo, pic, name) {
    $("#msgTextarea").val("");
    $("#msgStatus").hide();
    $("#msgTable").show();
    $("#msgToUid").val(uidTo);
    $("#msgPic").attr("src", pic);
    $("#msgToName").html(name);
    $("#msgDialog").dialog({
            bgiframe: true,
            modal: true,            
            width: 600
    });
    $('#msgDialog').dialog('option', 'buttons', {
                'Send': function() {
                        $("#msgStatus").html('Sending message...');
                        $("#msgTable").hide();
                        $("#msgStatus").show();
                        $('#msgDialog').dialog('option', 'buttons', {  });
                        
                        var uidTo = $("#msgToUid").val();
                        var msg = $("#msgTextarea").val();                        
                        $("#msgStatus").load("/saveusermessage",{'uidTo' : uidTo, 'accessToken':FB.getAuthResponse().accessToken,'msg':msg});
                        $('#msgDialog').dialog('option', 'buttons', {"Ok": function() {$(this).dialog("close");}});
                },
                'Cancel': function() {
                        $(this).dialog('close');
                }
            });
    $("#msgDialog").dialog("open");
}
function removeMessage(msgId) {
    if (confirm("Remove message. Please confirm?")) {
        $("#m"+msgId).html("<div class=\"red removingLabel\">Removing...</div>");
        var url = "/removeusermessage";
        jQuery.ajax({
        url:url,
        //data:{to:nicknameTo,from:nicknameFrom,subject:theSubject, message:msg },
        data:{'msgId':msgId},
        dataType:"html",
        success:function(data){
              $("#m"+msgId).hide();
              //alert(data);
        },
        error:function(xhr,err,e){alert( "An error occured whilst attempting to remove trip"  );}
        });
    }
}

function removeTrip(tripId) {
    if (confirm("Removing trip. Please confirm?")) {
        $("#m"+tripId).html("<div class=\"red removingLabel\">Removing...</div>");
        var url = "/removemessage";
        jQuery.ajax({
        url:url,
        //data:{to:nicknameTo,from:nicknameFrom,subject:theSubject, message:msg },
        data:{msgId:tripId},
        dataType:"html",
        success:function(data){
              $("#m"+tripId).hide();
              //alert(data);
        },
        error:function(xhr,err,e){alert( "An error occured whilst attempting to remove trip"  );}
        });
    }    
}

function editTrip(tripId) {
    $("#f"+tripId).submit();
}

function ismaxlength(obj,mlength){
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}

function openTravelGuide(country, city) {
    //var url = "http://www.offbeatguides.com/destination/Byron_Bay:Australia/"
    
    var url = "/travelguide?location="+country+"&city="+city;
    //var api = FB.Facebook.apiClient;
    if (FB.getAuthResponse() != null) {
        url = url + "&uid="+FB.getAuthResponse().userID;
    }
    window.location = url;
}
function openHostelFinder(country, city)
{var url = "http://reservations.bookhostels.com/lifttowoopwoop.com/";
            if (country == "southafrica") {
                country = "south+africa";
            }
            if (country == "newzealand") {
                country = "new+zealand";
            }
	if (city == "Anywhere") {            
            url = "http://reservations.bookhostels.com/lifttowoopwoop.com/countrylist.php?ChosenCountry="+country;
        } else {
            url = "http://reservations.bookhostels.com/lifttowoopwoop.com/findabed.php?ChosenCountry="+country+"&ChosenCity="+city;
        }
        if (country == "europe") {
            url = "http://reservations.bookhostels.com/lifttowoopwoop.com/";
        }
        if (country == "help") {
            url = "http://www.reservations.bookhostels.com/lifttowoopwoop.com/supportcentre.php";
        }
        newwindow=window.open(url,'name','height=500,width=720,resizable=1,scrollbars=1,location=1');
	if (window.focus) {newwindow.focus()}
}

// no user, clear display
      function clearDisplay() {
        $('#user-info').hide('fast');
      }
      function handleNewUser(response) {
          // TODO: Do the following
          //var api = FB.Facebook.apiClient;
          //FB.Connect.showPermissionDialog("email");
          
          $.getJSON("/login",{'uid' : FB.getAuthResponse().userID , 'accessToken' : FB.getAuthResponse().accessToken },function(data){
              alert(data);
          });
          handleSessionResponse(response);
      }
      // handle a session response from any of the auth related calls
      function handleSessionResponse(response) {
      
       // if we dont have a session, just hide the user info        
        if (!response.authResponse) {          
          $("#loading").hide();
          $("#login").show();
          clearDisplay();
          
          return;
        }
       
        // if we have a session, query for the user's profile picture and name
        //onConnected();
        FB.api(
          {
            method: 'fql.query',
            query: 'SELECT name, pic_square FROM profile WHERE id=' + FB.getAuthResponse().userID
          },
          function(response) {
            var user = response[0];
            
            $('#imageContainer').html('<img src="' + user.pic_square + '" style="height:37px">').show('fast');
            $('#user-name').html(user.name).show('fast');
            onConnected();
          }
        );
      }
