/*
 * Triple asia 2.0 Facebook application
 * Version: 1.0
 * Requires: jQuery v1.4.2+
 * Requires: Google map api v3
 */

  
  
;(function($) {
  
  
  
  
  $.fn.ta20fbapp = function(){
    
  }
  
  $.ta20fbapp = function (){
    
  }
  
  
  $.ta20fbapp.friendList = new Array();
  $.ta20fbapp.pagination = new Object();
  
  $.ta20fbapp.map = new Object();
  
      
  $.ta20fbapp.setStatus = function (status, text){
    text = typeof(text) != 'undefined' ? text : '';
    if(status == 'load'){
      $("#ta20fbapp_status").css('display', 'inline-block');
      $("#ta20fbapp_status_txt").css('display', 'inline-block');
      $("#ta20fbapp_status_txt").html("");
    }

    if(status == 'finish'){
      $("#ta20fbapp_status").css('display', 'none');
    }

    if(status == 'close'){
      $("#ta20fbapp_status").css('display', 'none');
    }

    if(status == 'close_and_settext'){
      $("#ta20fbapp_status").css('display', 'none');
      $("#ta20fbapp_status_txt").html(text);
    }

    if(status == 'settext'){
      $("#ta20fbapp_status_txt").css('display', 'inline-block');
      $("#ta20fbapp_status_txt").html(text);
    }
  }
  
  
  
  
  $.ta20fbapp.ta20fbapp_prev = function(){
    this.pagination.currentpage = this.pagination.currentpage-1;
    if(this.pagination.currentpage < 1){
      this.pagination.currentpage = 1;
    }else{
      this.ta20fbapp_show(this.pagination.currentpage);
    }
    return false;
  }
  
  $.ta20fbapp.ta20fbapp_next = function (){
    this.pagination.currentpage = this.pagination.currentpage+1;
    if(this.pagination.currentpage > Math.ceil(this.friendList.length/4)){
      this.pagination.currentpage = Math.ceil(this.friendList.length/4);
    }else{
      this.ta20fbapp_show(this.pagination.currentpage);
    }
    return false;
  }
  
  
  $.ta20fbapp.ta20fbapp_show = function (page){
    $("#ta20fbapp_friend_list_0,#ta20fbapp_friend_list_1,#ta20fbapp_friend_list_2,#ta20fbapp_friend_list_3").html("");
    var friend_box = "";
    for(var i = (page-1)*4; i < page*4; i++){
      if(i >= this.friendList.length){
        break;
      }
      $("#ta20fbapp_friend_list_"+(i%4)).html(
        '<a href="#Triple Asia" onclick="$.ta20fbapp.showMapByUserId('+ this.friendList[i].id +')"><fb:profile-pic uid="'+ this.friendList[i].id +'" size="square" width="54" linked="false" /></a>'
      );
    }
    FB.XFBML.parse();
  }
  
  
  
  
  
  
  $.ta20fbapp.showCheckinPlace = function (id){
    FB.init({
      appId  : '233309066736443',
      status : true,
      cookie : true,
      xfbml  : true
    });
    
    this.setStatus('load');
    FB.api('/'+id, function(response) {
      $.ta20fbapp.setStatus('finish');
//alert(response.category);
      var path = '/social-apps/facebook/ta20fbapp/images/';
      var catergory = response.category;
      catergory = catergory.replace(' ','_');
      catergory = catergory.replace('/','_');
      catergory = catergory.toLowerCase();
      catergory = path+'checkin/'+catergory+'.jpg';

      $("#gogogomap_showplace").show();
      $("#gogogomap_place").attr('src', catergory);
      $("#gogogomap_place").attr('width', '105');
      $("#gogogomap_place").attr('height', '75');

      spotlightText = response.name+"<br />"+response.checkins+" check-ins";
      spotlightText = typeof(response.likes) != 'undefined' ? spotlightText+" · "+response.likes+" likes" : spotlightText;

      $("#gogogomap_placename").html(spotlightText);
      //$("#gogogomap_readmore").attr('href', response.link);       //comment for change readmore
      //$("#gogogomap_readmore").attr('target', '_page');
    });
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  $.ta20fbapp.clearCurrentMarker = function (){
    if (this.pagination.markersArray) {
      for (i in this.pagination.markersArray) {
        this.pagination.markersArray[i].setMap(null);
      }
      this.pagination.markersArray.length = 0;
    }
  }
  
  $.ta20fbapp.markCheckinToMap = function (checkin){
    //if duplicate return false
    for(i in this.pagination.markersArray){
      if(this.pagination.markersArray[i].getPosition().equals(new google.maps.LatLng(checkin.place.location.latitude, checkin.place.location.longitude)) == true){
        return false;
      }
    }

    var image = '/social-apps/facebook/ta20fbapp/images/marker_icon.png';
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(checkin.place.location.latitude, checkin.place.location.longitude),
      map: this.map,
      title:checkin.place.name,
      icon: image
    });
    marker.place_id = checkin.place.id;
    google.maps.event.addListener(marker, 'click', function() {
      $.ta20fbapp.showCheckinPlace(this.place_id);
    });
    return this.pagination.markersArray.push(marker);
  }
  
  $.ta20fbapp.showMapByAllFriend = function(){
    this.setStatus('load');

    var u0 = $('#ta20fbapp_friend_list_0 .fb_profile_pic_rendered').attr("uid");
    var u1 = $('#ta20fbapp_friend_list_1 .fb_profile_pic_rendered').attr("uid");
    var u2 = $('#ta20fbapp_friend_list_2 .fb_profile_pic_rendered').attr("uid");
    var u3 = $('#ta20fbapp_friend_list_3 .fb_profile_pic_rendered').attr("uid");


    $.getJSON('/social-apps/facebook/ta20fbapp/api.php/api?q=targetfriend_checkins&uid='+u0+','+u1+','+u2+','+u3, function(json){
      $.ta20fbapp.setStatus('finish');

      $.ta20fbapp.clearCurrentMarker();

      if(json.data.length == 0){
        $.ta20fbapp.setStatus('settext', 'Check in not aviable.');
      }

      for(i in json.data){
        $.ta20fbapp.markCheckinToMap(json.data[i]);
        if(json.data.indexOf(json.data[i]) == 0){
          $.ta20fbapp.map.panTo(new google.maps.LatLng(
            json.data[i].place.location.latitude,
            json.data[i].place.location.longitude)
            );
          $.ta20fbapp.showCheckinPlace(json.data[i].place.id);
        }
      }

    });
  }
  
  $.ta20fbapp.showMapByUserId = function (uid){
    this.setStatus('load');

    $.getJSON('/social-apps/facebook/ta20fbapp/api.php/api?q=checkin_user&uid='+uid, function(json){
      $.ta20fbapp.setStatus('finish');
      $.ta20fbapp.clearCurrentMarker();

      if(json.data.length == 0){
        $.ta20fbapp.setStatus('settext', 'Check in not aviable.');
      }

      for(i in json.data){
        $.ta20fbapp.markCheckinToMap(json.data[i]);
        if(json.data.indexOf(json.data[i]) == 0){
          $.ta20fbapp.map.panTo(new google.maps.LatLng(
            json.data[i].place.location.latitude,
            json.data[i].place.location.longitude)
            );
          $.ta20fbapp.showCheckinPlace(json.data[i].place.id);
        }
      }

    });

  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  $.ta20fbapp.init = function(){
    this.pagination.currentpage = 1;
    this.pagination.markersArray = new Array();
  }
  
  $.ta20fbapp.initmap = function(){
    //this.firstCenter = new google.maps.LatLng(13.793981935484, 100.6279);
    this.firstCenter = new google.maps.LatLng(25, 0);
    this.map = new google.maps.Map(document.getElementById("ta20fbapp_map_canvas"), {
      zoom: 1,
      center: this.firstCenter,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    $('#ta20fbapp_map_canvas').css('height','390px');
    $('#ta20fbapp_map_canvas').css('border','1px solid #99B3CC');
  }
  
  
  
  $.ta20fbapp.firstinit = function(){
    
    $("#ta20fbapp_content").load("/social-apps/facebook/ta20fbapp/api.php/api/getMapConsol", function(){
      
      $.ta20fbapp.initmap();
      
      $.ta20fbapp.showMapByUserId('me');
      
      $.getJSON('/social-apps/facebook/ta20fbapp/api.php/api?q=sum_country&uid=me', function(json){
        $("#friend_have_been_cities").html(", your friends have been to "+json.count+" cities what's this");
      });
      
      $.getJSON('/social-apps/facebook/ta20fbapp/api.php/api?q=checkin_friends', function(json){
        $('#ta20fbapp_loadfriend_status').hide();
        $.ta20fbapp.friendList = json.data;
        $.ta20fbapp.ta20fbapp_show($.ta20fbapp.pagination.currentpage);
      });
      
    });
    
  }
  
  
  $.ta20fbapp.updateSessionAndStart = function(uid, sig, access_token, session_key){
    jQuery.ajax({ 
      async:true, 
      type: "POST", 
      url: ("/social-apps/facebook/ta20fbapp/api.php/api/setSession"),
      dataType : 'json',
      data: {
        uid : uid,
        sig : sig,
        access_token: access_token,
        session_key: session_key
      },
      success : function(data){
          $.ta20fbapp.firstinit();
      },
      error : function(XMLHttpRequest, textStatus, errorThrown) {
          //alert("XMLHttpRequest error");
      }
    });
  }
  
  
  
  
  
  
  
  $(document).ready(function() {
		$.ta20fbapp.init();
    
    FB.init({
      appId  : '233309066736443',
      status : true,
      cookie : true,
      xfbml  : true
    });
    
    FB.getLoginStatus(function(response) {
      if (response.status == "connected") {
        //$("#ta20fbapp_login_button").html('<a id="ta20fbapp_logout_button_logout" href="#Triple Asia" title="Disconnect">Sign out</a>');
        $("#ta20fbapp_login_button").html('');
        
        $.ta20fbapp.updateSessionAndStart(
          response.session.uid,
          response.session.sig,
          response.session.access_token,
          response.session.session_key
        );
        
      }else{
        $("#ta20fbapp_login_button").html('<a id="ta20fbapp_login_button_login" href="#Triple Asia" title="Sign in with Facebook">Sign in with Facebook</a>');
      }
    });
    
    
    
    
    
    $("#ta20fbapp_login_button_login").live("click", function(){
      FB.init({
        appId  : '233309066736443',
        status : true,
        cookie : true,
        xfbml  : true
      });
    
      FB.getLoginStatus(function(response) {
        if (response.status != "connected") {
          FB.login(function(response) {
            if (response.session) {
              $.ta20fbapp.updateSessionAndStart(
                response.session.uid,
                response.session.sig,
                response.session.access_token,
                response.session.session_key
              );
              //$("#ta20fbapp_login_button").html('<a id="ta20fbapp_logout_button_logout" href="#Triple Asia" title="Disconnect">Sign out</a>');
              $("#ta20fbapp_login_button").html('');
            } else {
              alert("หากไม่กดรับจะมีข้อมูลไม่เพียงพอต่อการช่วยเลือกโรงแรมที่เหมาะกับคุณ.");
            }
          }, {perms:'email,read_stream,read_friendlists,user_birthday,user_relationships,user_relationship_details,user_hometown,user_location,user_likes,user_interests,user_education_history,user_checkins,user_status,friends_birthday,friends_relationships,friends_relationship_details,friends_hometown,friends_location,friends_likes,friends_interests,friends_education_history,friends_work_history,friends_checkins,friends_status'});
        }
      });
      
      return false;
    });
    
    
    $("#ta20fbapp_logout_button_logout").live("click", function(){
      FB.init({
        appId  : '233309066736443',
        status : true,
        cookie : true,
        xfbml  : true
      });
      
      FB.logout(function(response) {
          window.location.reload();
      });
    });
    
    
	});
  
  
})(jQuery);





