
var MaxFB=function(){
/*
 * Ejemplo de instancia de MaxFB:
 *
 * MaxFB.init("es_ES");
 * MaxFB.makeButton("coche"(sitio de renderizado clase de la capa),"mFinCarrera",41331,"es_ES")
 */
    // ha de ir añadido esto:<script src="http://connect.facebook.net/{#FACEBOOK_LOCALE#}/all.js"></script>
    var permisos= {scope:'email, user_birthday,user_about_me,offline_access,publish_stream'};
    var intervalos;//variable usada para intervalos de tiempo para la precarga de los js
    var loaded=false;//variable usada para saber si ya ha cargado
    var basicAction='window.location.href ="/pages/welcome/cover/social_login.php"';
    var AbsoluteUrlToChannelFile  = "http://local.maxdriving.com/static/img/facebook/ChannelFile.htm";
    var load1 = function(locale){
/*      if(!locale){locale="es_ES"} ESTO PERTENECE AL ANTIGUO SISTEMA DE CARGA
      if($("[src$='http://connect.facebook.net/"+locale+"/all.js']").length==0){
      //if($("[src$='http://static.ak.facebook.com/js/api_lib/FacebookApi.debug.js']").length==0){
          var fileref=document.createElement('script');
          fileref.setAttribute("type","text/javascript");
          fileref.setAttribute("src", "http://connect.facebook.net/"+locale+"/all.js");
          //fileref.setAttribute("src", "http://static.ak.facebook.com/js/api_lib/FacebookApi.debug.js");
          document.getElementsByTagName("head")[0].appendChild(fileref);
      }

      if($("#fb-root").length==0){
          var fileref2=document.createElement('div');
          fileref2.setAttribute("id","fb-root");
          document.getElementsByTagName("body").item(0).appendChild(fileref2);
      }
      if($("#fb-root").length==1 && $("[src$='http://connect.facebook.net/"+locale+"/all.js']").length==1){
          return true
      }else return false;*/
    }

    var load2= function(){
        if(typeof(FB)!="undefined"){
	    FB.init({appId: '136721603057940',
		status: true,
		cookie: true,
		xfbml: true,
		oauth: true,
		channelUrl: AbsoluteUrlToChannelFile});
            clearInterval(intervalos);
            loaded=true;
            return true;
        }
        else{return false;}
    };

    var init=function(locale){
        MaxFB.load2();
            /*$("document").ready(function(){
                if(load1(locale)) {
                intervalos = setInterval("MaxFB.load2()",1000);
            }
        })*/


    }
    var isConnected= function(){
        FB.getLoginStatus(function(response) {
          if (response.status=="connected") {
              return true;
          } else {
              return false;
          }
        });

    }

    var sync= function(){

    }


    var fb_login=function(topage){
        if(!loaded) return false;
        
	if(!topage) topage= basicAction;
	FB.login(function(response) {
	    if (response.authResponse) {
	      var token  = response.authResponse.accessToken
		eval(topage);
	    } else {
		$("#facebook_status_dialog.ui-dialog-content").dialog("close");
		//console.log('User cancelled login or did not fully authorize.');
	    }
	}, permisos);

    }
    var fb_login2=function(fb_url){
	if(!loaded) return false;
	FB.login(function(response) {
	    if (response.authResponse) {
	      var token  = response.authResponse.accessToken
	    FB.api('/me', function(response) {
	      loading.close();
	      window.location.href = fb_url+token;
	    });
	    } else {
	    //console.log('User cancelled login or did not fully authorize.');
	    }
	}, permisos);
    }
    var publish= function(action,uid,type,flash){

        if(!loaded) return false;
	if (type === undefined){type = null;}
	FB.login(function(response) {
          $(".fc-button-inner").css("background-position","left -26px");
          if($(".facebookstatus").length>0){$(".facebookstatus").html(FB_SENDING+"<br/><center><img src='/static/img/icon/loading.gif' style='margin-top:5px;' /></center>")}

          var oldonclick=$(".fc-button-inner").attr("onClick");
          var oldonclick2=$(".fc-button-inner").attr("onClick");

          $(".fc-button-inner").attr("onClick","return false;");
          $(".share-facebook").attr("onClick","return false;");

          if (response.authResponse) {
              $.ajax({
                type:"post",
                url:"/pages/socialnetworks/ajax.php",
                data:{action:action,op:"facebook",id:uid,type:type},
                success:function(a){
                    var datos =jQuery.parseJSON(a);


                    FB.api('/me/feed', 'post', datos, function(response) {
                        //console.log(response);

                      if (!response || response.error) {
                            $(".fc-button-inner").css("background-position","left -52px");

                            $(".fc-button-inner").attr("onClick",oldonclick);

                            $(".share-facebook").attr("onClick",oldonclick2);
                            if($(".facebookstatus").length>0){$(".facebookstatus").html(FB_SENTFAIL);}else{
                                if(response.error.message.indexOf("(#200)")!=-1){
                                    MaxFB.login();
                                }

                                alert("FaceBook Error: "+response.error.message);
                                  if(flash==1){
                                    window.location.reload();
                                  }
                            }
                      } else {

                        $(".fc-button-inner").css("background-position","left 0px");
                        $(".fc-button-inner").attr("onClick","return false;");
                        $(".share-facebook").attr("onClick","return false;");
                        if($(".facebookstatus").length>0){$(".facebookstatus").html(FB_SENT)}
                        if($(".ui-dialog-content:visible").dialog("isOpen") && action=="mShowCar"){
                            //$(".ui-dialog-content:visible").dialog("close");
                        }
                        if(flash==1){window.location.reload();}//cuando viene del flash de personalizar coche
                        if(flash==2){eval(basicAction)}//cuando viene de un login recien echo y hay que checkear el status de ese usuario.

                      }
                    });

                }
              });
          } else {
            MaxFB.login("(MaxFB.publish('"+action+"',"+uid+",2))");
	    $("#facebook_status_dialog").dialog("close");
          }
        });
    }
    var makeButton = function(render_id,action,id,locale){
        if(!locale){locale="es_ES"}
        var toRender="<div class='fc-button-inner' onClick=\"MaxFB.publish('"+action+"',"+id+");\" style='cursor:pointer;width:129px;height:26px;background-image:url(/static/img/lang/"+locale+"/sharefb.png);background-position:left -52px;'> </div>";

        if($("."+render_id).attr("class")==render_id){
            $("."+render_id).html(toRender);
        }
        return $(".fc-button-inner").attr("class")=="fc-button-inner";
    }
    var shareWithFriends= function(){
	FB.login(function(response) {
	  if (response.authResponse) {
		//console.log("User is connected to the application.");
		var token  = response.authResponse.accessToken;
		function SortByName(x,y) {
		      return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name) ? 1 : -1 ));
		}
		FB.api('/me',function(response){
		    $("#preview_invitation_show_header").html(response.name);
		});
		$.ajax({
		  type: "POST",
		  url: "/pages/socialnetworks/invitations.php",
		  data: ({
		    op: "facebook",
		    action: "filter_friends",
		    token: token
		    }),
		  beforeSend:function(){
		      loading.open();
		  } ,
		  success: function(data) {
		      loading.close()
		    //_friend_data = data.sort(sortByName);
		    if (data == ''){
			alert(FB_NO_FRIENDS);
		    }else{
		    var json_data = $.parseJSON(data);
		    //console.log(json_data);
		    $.each(json_data, function(friend_id) {
			var friend=json_data[friend_id];
			$("#friends_selector_listfriends").append("<div onclick='addFriend(this);' class='jfmfs-friend fbhov' id='" + friend.id  +"'><img class='friend-picture' src='https://graph.facebook.com/" + friend.id + "/picture' /><div class='friend-name'>" + friend.name + "</div></div>");
		    });
		    $("#dialog_friendsselector").fadeTo("slow",1.0); 
		    }
		  }
		});
		   //_friend_data = response.data.sort(sortByName);
		    
	  } else {
	    //console.log('User cancelled login or did not fully authorize.');
	  }
	}, permisos);
    }
    var sendfeeds = function (selectedFriends,msg,userRef){
	// Falta por definir el action
	var action = 'invitefriend';
	var id = Math.floor(Math.random()*1000000001);
	for (i=0;i<selectedFriends.length;i++)
	{
	    FB.api('/'+selectedFriends[i]+'/feed', 'post', 
	    { 
		message: msg,
		name:'¡ Tienes una invitación de MaxDriving !', 
		// -- Old Link 
		//link: 'http://www.maxdriving.com/pages/welcome/facebook?a='+action+'&i='+id+'&u='+userRef, 
		link: 'http://www.maxdriving.com/es/pages/welcome/registration_step2_inputdata/?car=2&carcolor=car_2_red.png&i='+id+'&fbref='+userRef, 
		caption: 'Maxdriving', 
		picture: 'http://www.maxdriving.com/static/img/facebook/fb_share_icon.jpg',
		description: '¿ Quieres unirte a mí en MaxDriving ? Podrás tener tus pilotos y coches, tunear y entrenar para competir conmigo por la fama.' 
	    }, 
	    function(response) {
		  if (!response || response.error) {
		    //alert('Error occurred');
		  } else {
		    //alert('Post ID: ' + response.id);
		  }
	    });
	    $.ajax({
                type:"post",
                url:"/pages/socialnetworks/invitations.php",
                data:{
			op:"facebook",
			action: "add_invitations",
			fbid_to:selectedFriends[i]
		    },
                success:function(){
		    // Invitaciones guardadas correctamente
		    $("#dlg_invitation_sent").dialog('open');
		    loading.close();
		},
		beforeSend:function(){
		    loading.open();
		} 
	    });
	    // send method is for sending private message to one user
	    
	}
    }
    var sendmsg = function (selectedFriend,userRef){
	var id = Math.floor(Math.random()*1000000001);
	FB.ui({
	    to: selectedFriend,
	    method: 'send',
	    name: '¡ Tienes una invitación de MaxDriving !',
	    description: '¿ Quieres unirte a mí en MaxDriving ? Podrás tener tus pilotos y coches, tunear y entrenar para competir conmigo por la fama.',
	    link: 'http://www.maxdriving.com/es/pages/welcome/registration_step2_inputdata/?car=2&carcolor=car_2_red.png&i='+id+'&fbref='+userRef, 
	    picture: 'http://www.maxdriving.com/static/img/facebook/fb_share_icon.jpg' 
	}, 
	function(response) {
	    if (!response || response.error) {
	    }
	});
    }
    var shareCar = function(ref,type){
	if (type === undefined){type = null;}
                    //z-index colrobox must be 850;
                    $("#facebook_status_dialog").dialog({
                            autoOpen: false,
                            dialogCLass: 'info',
                            draggable: false,
                            resizable: false,
                            title:"Facebook",
                            bgiframe: true,
                            modal: true,
                            width:125,
                            height:125,
                            zindex: 2000,
                            open:function(){
                                 MaxFB.publish('mShowCar',ref,type);
                            },
                            buttons: {

                            }
                    });
                    $("#facebook_status_dialog").dialog("open");
    }

    return {
        publish:publish,
        sync:sync,
        init:init,
        load2:load2,
        login:fb_login,
	login2:fb_login2,
        makeButton:makeButton,
        share:shareWithFriends,
	sendfeeds:sendfeeds,
	sendmsg:sendmsg,
        shareCar:shareCar
    }
}();

