function Nestle(){
  
  // id gry pobrane z flashvara (to się może zmienić)
  var gameId;
  // w kodzie kilka razy pojawia się url do strony z aplikacją, więc został wrzucony do zmiennej
  
  var longName;
      
  this.getScore = getScore;    

  
 function stream_callback (post_id, exception) {
  if (post_id) {
	document.getElementById("game").publishComplete();
  }
} 
  
  function getScore(gameId, gameScore, publ){
    // obiekt, który przyjmuje facebook-owa funkcja 'streamPublish' 
  var gameData = {
      "name": "",
      "href": siteUrl,
      "description": "",
      "media":[{
        "type": "image",
        "src": "http://www.lody.nestle.pl/",
        "href": siteUrl
      }]
    }  
	    // każda z gier ma inny tytuł
    switch(gameId)
    {
      case 1:
      gameData.name = "kitkat";
      longName = "Kit Kat - Lodowieża";
      break;
      case 2:
      gameData.name = "manhattan";
      longName = "Manhattan - Gdzie to było? Co to było? Kolonijne wspomnienia";
      break;
      case 3:
      gameData.name = "cortina";
      longName = "Cortina Ślizzzzg!";
      break;
      case 4:
      gameData.name = "lacremeria";
      longName = "La Cremeria - Zagraj w ulubione smaki";
      break;
      case 5:
      gameData.name = "nesquik";
      longName = "Nesquik - Ułóż to jeszcze raz!";
      break;
      case 6:
      gameData.name = "princessa";
      longName = "Princessa - Jakim dzieckiem jesteś?";
      break;
    };  
	
	gameData.href+="#/dla-ciebie/"+gameData.name; 
//jezeli ta funkcja ma publikowac to publ = 1
if(publ == 1){
  //jeżeli wynik nie jest liczbą, tylko tekstem - np "symulant"
	if(typeof gameScore != 'number'){
				$.ajax({
		type: "GET",
		url: "_xml/"+gameData.name+"/results.xml",
		dataType: "xml",
		success: function(xml) {
		
			$("result", xml).each(function(){
				var type = $(this).attr('type');
				
				if(type==gameScore){
					gameData.caption = "Gra: "+longName+", wynik: ";
					gameData.caption+= $(this).children("title").text();
					gameData.description+=$(this).children("copy").text();					
					gameData.media[0].src += $(this).children("image").text();
				}
			});
			gameData.name = 'Jakim dzieckiem jesteś?';
			FB.Connect.streamPublish('', gameData, null, null, 'Podziel się wrażeniami...', stream_callback); 
			
			
		}
	});

	
	}
	    // jeżeli wynik jest liczbą
    else 
	{
	var loc = location.href;
	
			$.ajax({
		type: "GET",
		url: "_xml/"+gameData.name+"/results.xml",
		dataType: "xml",
		success: function(xml) {
		
			$("result", xml).each(function(){
				var start = parseInt($(this).attr('start'));
				var end = parseInt($(this).attr('end'));
				if( start <= gameScore && gameScore <= end){
					gameData.caption = "Gra: "+longName+", wynik: "+ gameScore+" punktów: ";
					gameData.caption+= $(this).children("title").text();
					gameData.description+=$(this).children("copy").text();					
					gameData.media[0].src += $(this).children("image").text();
				}
			});
			gameData.name = 'Jakim dzieckiem jesteś?';
			 var actionLink = [{ "text": "Zagraj", "href": loc}];
			FB.Connect.streamPublish('', gameData, actionLink, null, 'Podziel się wrażeniami...', stream_callback); 
			
			
		}
	});
		
		
	}
}


    
    return gameData;   
  }
}


  


function send(){
   FB.Facebook.apiClient.fql_query( "SELECT pic_square, first_name, last_name FROM user WHERE uid =" + FB.Facebook.apiClient.get_session().uid, function (result) 
   {
	  document.getElementById("game").connectComplete(FB.Facebook.apiClient.get_session().uid, result[0].pic_square, result[0].first_name, result[0].last_name);
   });
   
}
//loguje usera i wysyla do flasha jego id i avatar
function connect(){

      FB.ensureInit(function()
		{ 
		  FB.Connect.get_status().waitUntilReady(function(status) 
		  {
			if (status == FB.ConnectState.connected) 
			{    
				send();       
			} 
			else 
			{ 			
				FB.Connect.requireSession(function()
				{
					send();
				});
			}
		  });                                  
       }   
    );
}


function invite(gameId){
    var name = nestle.getScore(gameId, "", 0).name;
	window.open( "inviteform.aspx?name="+name, "myWindow", "status = 1, height = 800, width = 800, resizable = 0" );
	document.getElementById("game").inviteComplete();
	
}
var nestle = new Nestle(); 

//loguje usera przy publikacji wyniku + wykonuje publikacje
function publish(gameid, result){
 FB.ensureInit(function()
		{ 
		  FB.Connect.get_status().waitUntilReady(function(status) 
		  {
			if (status == FB.ConnectState.connected) 
			{    
				nestle.getScore(gameid, result, 1);
			} 
			else 
			{ 			
				FB.Connect.requireSession(function()
				{
					nestle.getScore(gameid, result, 1);
				});
			}
		  });                                  
       }   
    );
}
var test = new Array();
var res = new Array();
var resstring;
var i;

/*function getNick(j){
	var position = test.length - j;
	//console.log(position);
		  FB.Facebook.apiClient.fql_query("SELECT first_name FROM user WHERE uid = '"+test[position]+"'", function (result) 
		   {
			   res[position] = result[0].first_name;   
					if(j>1){
							i--;
							getNick(i);
						}
					else{
							//console.log(res);
							resstring =res.join(",");
							//console.log(resstring);
							document.getElementById("game").deliverNicksComplete(resstring);
							return true;
						}
		   });
}  */


 function deliverNicks(arr){
		 var x = arr.join(",");
		 FB.Facebook.apiClient.fql_query("SELECT first_name, pic_square FROM user WHERE uid IN ("+x+")", function (result) 
		   {
		       var returnme="";
		       for(var i=0; i<result.length; i++){    
                 returnme+=result[i].first_name+"*"+result[i].pic_square;
                 if(i!=result.length-1) returnme+="@";
               }          			   
           document.getElementById("game").deliverNicksComplete(returnme);
		   return true;
		   });
	 }
	 

function moveMe() {
                var locH = (typeof window.innerHeight == 'number') ? window.innerHeight : document.documentElement.clientHeight; 
                $('body').height(locH);
                locH = $('body').height(); //checkin the 
                
                var locW = (typeof window.innerWidth == 'number') ? window.innerWidth : document.documentElement.clientWidth; 
                $('body').width(locW);
                locW = $('body').width();                            
                
                var W = locW/2 - ($('#likeIt').width()/2)-250;     
                var H = locH/2 - ($('#likeIt').height()/2)+280; 
                
                $('#likeIt').css({'top': H, 'left': W});
 }
 
function capitalise(str) {
                //check that str is a string
                if(typeof str != String)
                {
                               return str;
                }
                //extract the first letter of str
                var letter = str.substr(0,1);
                //return letter capitalised concatonated with
                //str minus it's first letter
                return letter.toUpperCase() + str.substr(1);
 }
 
 var domain = window.location.hostname;
 var domaintab = domain.split(".");
 if(domaintab[0] != "www") domain = "www."+domain;
 
 //uruchamiane dla stron nieproduktowych, czyszczenie buttona like it!
 function hideLikeButton() {
     document.title = "Lody Nestle";
                $('#likeIt').remove();
 }
 
 function likeJS(name) { // function for FB 'like it!' button           
                name = capitalise(name);
                //document.title = name +' :: Lody Nestle';            
                $('meta:first').attr('content',name);      
               var rand = new Date().getTime();
                var src;

                //var domain = window.location.hostname;

                $('#likeIt').remove();
                //var name = document.getElementById('game').getBrand(); 
                
                $('form').append('<iframe id="likeIt" class="'+name+'" src="http://www.facebook.com/plugins/like.php?href=http%253A%252F%252F'+domain+'%252Fdefault.aspx%253Fproduct%253D'+name+'%2523%252Foferta%252F'+name+'%252F1&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=tahoma&amp;colorscheme=light&amp;height=35&amp;tstamp='+rand+'" scrolling="no" frameborder="0" style="position: absolute; overflow:hidden; width: 460px; height:80px;" allowTransparency="false"></iframe>');
                moveMe();        
                //console.log(name);                   
} 


$(document).ready(function() {
                //var name = 'maxibon';
                
                $(window).resize(function() {                  
                               moveMe();
                });
                //$('meta:first').attr('content',name);                                  
                if(!window.location.hash.length && window.location.search.length){
                var name = window.location.search.split("product=");
                window.location = window.location+"#/oferta/"+name[1]+"/1";
                }
                
});
