

function loadingrequest(container){
	$(container).html("<ul><li><p><div class=\"loading\"></div><br /><br /></p></li></ul>");
}
function loadingrequestInside(container){
	$(container).html("<li><p><div class=\"loading\"></div><br /><br /></p></li>");
}
function getMore(offset,location){
	
	var temp="";
	var user = $("#user").val();
var str="off="+offset+"&loc="+location+"&u="+user+"&ppage="+ppage;
		var total = parseInt(offset)+10;
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_more.php",
   data: str,
   loading: loadingrequestInside("#loading"),
   success: function(message){
   	var messa = jQuery.trim(message.toString());
   	if (messa.indexOf("NOMORE") >= 0) {   	
		$("#loading").html("");
   		//$("#refreshcontainer").html("");  		
   		$(".more").html(""); 		
   	}else {
		
	$('#refreshcontainer').append(messa);
			$("#loading").html("");
			$("#rows").val(total);
     	
   	}
   }
 });
  
 return false;
	
}

function getTerms(){
	 $("#toptitle").html("Όροι Χρήσης");
	 $("#backblock").html("<a href=\"javascript:void(0);\" onclick=\"javascript:getDefault();return false;\" class=\"back\">&nbsp;</a>");
	$('#results').load('shortterms.html');
	
}


function getDefault(){
	
		var str="ppage="+ppage;
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_moredefault.php",
   data: str,
   loading: loadingrequest("#results"),
   success: function(message){
   	$("#toptitle").text("Τελευταίες αναρτήσεις");
   	$("#backblock").html("");
	
   	var messa = jQuery.trim(message.toString());
   	$("#results").html(messa);
	 
	 $("#getmore").click(function(event){
   	var c = $("#rows").val();
   	var location = $("#location").val();
     getMore(c,location);
     event.preventDefault();
      });
	    
   
   }
 });
  
	
}
function getRecentComments(){
	
		var str="ppage="+ppage;
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_recent.php",
   data: str,
   loading: loadingrequest("#results"),
   success: function(message){
   	$("#toptitle").text("Τελευταία Σχόλια");
   
   	var messa = jQuery.trim(message.toString());
   	$("#results").html(messa);  
		$("#backblock").html("");	
	$("#backblock").html("<a href=\"javascript:void(0);\" onclick=\"javascript:getDefault();return false;\" class=\"back\">&nbsp;</a>");
	 return false;
   }
 });	
}
function getOnlineUsers(){
	
		var str="ppage="+ppage;
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_onlineusers.php",
   data: str,
   loading: loadingrequest("#onlineusers"),
   success: function(message){      
   	var messa = jQuery.trim(message.toString());
   	$("#onlineusers").html(messa);  
	 return false;
   }
 });	
}


function getTop(){
	
		var str="ppage="+ppage;
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_moredefault.php",
   data: str,
   loading: loadingrequest("#results"),
   success: function(message){
   	$("#toptitle").text("Τελευταίες αναρτήσεις");
   	$("#backblock").html("");
	
   	var messa = jQuery.trim(message.toString());
   	$("#results").html(messa);
	 
	 $("#getmore").click(function(event){
   	var c = $("#rows").val();
   	var location = $("#location").val();
     getMore(c,location);
     event.preventDefault();
      });
	    
   
   }
 });
  
	
}


function getbyLocation(location){
	$("#location").val(location);
	$("#user").val("");
var str="loc="+location+"&ppage="+ppage;
		
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_morebyother.php",
   data: str,
   loading: loadingrequest("#results"),
   success: function(message){
   	var messa = jQuery.trim(message.toString());
	$("#backblock").html("<a href=\"javascript:void(0);\" onclick=\"javascript:getDefault();return false;\" class=\"back\">&nbsp;</a>");
   	$("#results").html(messa);	
	$("#toptitle").html("Αναρτήσεις στο σημείο: <span class=\"white\">"+location+"</span>");
	 $("#getmore").click(function(event){
   	var c = $("#rows").val();
   	var location = $("#location").val();
     getMore(c,location);
     event.preventDefault();
      });
	    return false;
   
   }
 });
  
 return false;
}
function getbyUser(user,username){
	$("#user").val(user);	
	$("#location").val("");	
var str="u="+user+"&ppage="+ppage;		
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_morebyother.php",
   data: str,
   loading: loadingrequest("#results"),
   success: function(message){
   	var messa = jQuery.trim(message.toString());
   	$("#results").html(messa);
	 $("#toptitle").html("Αναρτήσεις απο τον χρήστη: <span class=\"white\"> "+username+"</span>");
	 $("#backblock").html("<a href=\"javascript:void(0);\" onclick=\"javascript:getDefault();return false;\" class=\"back\">&nbsp;</a>");
	 $("#getmore").click(function(event){
   	var c = $("#rows").val();
   	var location = "";
     getMore(c,location);
     event.preventDefault();
      });
	  
   
   }
 });
  
 return false;
}

function doComment(commentID){
	if (commentID != "") {
	
	var str="p="+commentID+"&ppage="+ppage;		
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_loadcomment.php",
   data: str,
   loading: loadingrequest("#"+commentID),
   success: function(message){
   	var messa = jQuery.trim(message.toString());
	
	$('#'+commentID).html(messa).show(); 
	  
   }
 });
  
 return false;
	
	}
	
}
function closeComment(commentID){
	if (commentID != "") {
		$("#" + commentID).html("");
		$("#" + commentID).hide();
	}
	
}
function submitComment(commentID){
	if(commentID!=""){
		
	if($("#"+commentID+"_comment").val()!="" && $("#"+commentID+"_locationItem").val()!=""){
		
	var str="i="+commentID+"&ppage="+ppage+"&c="+$("#"+commentID+"_comment").val()+"&l="+$("#"+commentID+"_locationItem").val()+"&u="+$("#"+commentID+"_user").val();		
 // Code goes here 
 $.ajax({
   type: "POST",
   url: "_z_comment.php",
   data: str,  
   success: function(message){
   //	var messa = jQuery.trim(message.toString());
	//alert('commentID'+commentID);
	switch(message){
		case "ERROR":
		alert("Συγνώμη αλλά προέκυψε ένα πρόβλημα, προσπαθείστε πάλι φορτώνοντας τη σελίδα απο την αρχή");
		 return false;
		break;
		case "BANNED":
		alert("Συγνώμη αλλά δεν μπορείτε να αφήσετε σχόλιο, προσπαθείστε πάλι φορτώνοντας τη σελίδα απο την αρχή");
		 return false;
		break;		
		case "NOTLEGGEDIN":
		alert("Συγνώμη αλλά δεν είσαι συνδεμένος!! Συνδέσου πρώτα και μετά άφησε το σχολιό σου");
		 return false;
		break;
		case "DUPLICATE":
		alert("ΖΑΒΟΛΙΑ!!! Αυτό μας το ξανάπες! Πές μας κάτι φρέσκο!");
		 return false;
		break;
		
		
		default:
	$('#'+commentID+"_show").prepend(message); 
	 $("#"+commentID+"_comment").val("");
	 return false;
	 break;  
   }
   }
 });
  
 return false;
		
	}		
		
	}
 return false;	
}

/*******************FACEBOOK****************************/

var debugging = true; // or true
if (typeof console == "undefined") {var console = {	log: function(){}};
}else {if (!debugging || typeof console.log == "undefined")console.log = function(){};}

  var canPostWithoutAsking = false;
  var facebookuserid="";
  var userData = "";
  var fbphoto="";
  function initFB() {
	  // initialize the library with the API key
	  FB.init({ 
		apiKey: 'aaf7d47327c56683d6a501097f33e38c',
		channelUrl: "http://www.onthego.gr/home"
		});

	  // fetch the status on load
	  FB.getLoginStatus(handleLoginResponse);
  
  }
 function ensureLoginFB() {
	// re-initialize the library with the API key -- this synchs with facebook again
	FB.init({ 
		apiKey: 'aaf7d47327c56683d6a501097f33e38c',
		channelUrl: "http://www.onthego.gr/home"
		});
	// fetch the status on load
	FB.getLoginStatus(promptLoginIfNotLoggedIn);  
  }
  // prompt login if user is not logged in
  function promptLoginIfNotLoggedIn(response){
      // if we dont have a session, return false
      if (!response.session) {
          loginFBWithoutUserid();
		  	//console.log("just called loginFBWithoutUserid");
      }
      else {
	  	collectText("ok");
		//	console.log("just called collectText(ok)");
          return true;
      }
  }
function doLoginAndGet(localuserid){
	
	loginFB(localuserid);
	if( FB.getLoginStatus(handleLoginResponse)){
		//value = requestUserData(localuserid);
		//console.log("getuserdata = "+value);
	
		//return "fbconnected=ok";
	}else{
		//console.log("user not logged in");
	}
}


function loginFBWithoutUserid(){
	console.log("started loginFBWithoutUserid");
		FB.login(function(response) {
		if (response.session) {
			if (response.perms){
				// user is logged in and granted some permissions.
				// perms is a comma separated list of granted permissions
				//console.log(response.perms == 'publish_stream');
				if(response.perms == 'publish_stream')
				{
					canPostWithoutAsking = true;
					//console.log("canPostWithoutAsking - true");
				}
			}else{
			// user is logged in, but did not grant any permissions
			//console.log("logged in did not grant any permissions");
			}  
       	collectText("ok");
		//console.log("just called collectText(ok)");
				
		}else{
			collectText("NOTok");
			//console.log("just called collectText(NOTok)");
		// user is not logged in
		}
	}, {perms:'publish_stream'});	
	
}




  function loginFB(localuserid) {
	FB.login(function(response) {
		if (response.session) {
			if (response.perms){
				// user is logged in and granted some permissions.
				// perms is a comma separated list of granted permissions
				//console.log(response.perms == 'publish_stream');
				if(response.perms == 'publish_stream')
				{
					canPostWithoutAsking = true;
				}
			}else{
			// user is logged in, but did not grant any permissions
			}
		
    //update local face id
    facebookuserid = FB.getSession().uid;	
	
    if (localuserid != "" && facebookuserid != ""){
        var str = "userid=" + localuserid + "&facebookid=" + facebookuserid+"&ppage="+ppage;
        $.ajax({
            type: "POST",
            url: "_z_updateuser.php",
            data: str,
            loading: "",
            success: function(message){
                var messa = jQuery.trim(message.toString());
                if (messa != "OK") {
                   // console.log("did not update local user id");
                }
                
            }
        });
       	collectText("ok");         
     
	 
		//console.log("collectLikes, result:"+readUserLikesPage());
		
    }
				
		}else{
		// user is not logged in
			collectText("NOTok");
		}
	}, {perms:'publish_stream'});
	
 
	
	
	
  }
  	  
  
  // handle a session response from any of the auth related calls
  function handleLoginResponse(response) {
	// if we dont have a session, return false
	if (!response.session) {
	  return false;
	}
	
	//console.log("user logged in & authorized");
	return true;
  }
  
  
  function requestUserData(localuserid) {
  		var photo = "";
			var fbname ="";
			var fbid="";
	
		// if we have a session, query for the user's profile picture and name
		FB.api(
		  {
			method: 'fql.query',
			query: 'SELECT name, pic_square FROM profile WHERE id=' + FB.getSession().uid
		  },
		  function(response) {
		  	if (response[0] != "undefined") {
				userData = "pic=" + response[0].pic_square + "&name=" + response[0].name;
				photo = response[0].pic_square;
				fbname = response[0].name;
				fbid = FB.getSession().uid;
				facebookuserid=fbid;
			}
	if (photo != "") {
		collectPhoto(photo);
			var str = "userid="+localuserid+"&facebookid=" + fbid + "&photo=" + photo+ "&fullname=" + fbname+"&ppage="+ppage;
			$.ajax({
				type: "POST",
				url: "_z_updatefbuser.php",
				data: str,
				loading: "",
				success: function(message){
					var messa = jQuery.trim(message.toString());
					if (messa != "OK") {
						//console.log("did not update local user id");
					}
					
					fbphoto = photo;
						
				}
			});
		}
	
			
			//console.log("userData="+userData);
		  }
		);
		if (fbid != "") {
			//requestUserLikesPage(117215025004062);
		}
		
		
  }
  
 
  
  function readUserData() {
	return userData;
  }
		
	
  
  
  function postOnMyWall(post_message) 
  {
	if(canPostWithoutAsking)
	{
		FB.api('/me/feed', 'post', { message: post_message }, function(response) {
		if (!response || response.error) {
			alert('Error occured');
		} else {
			//console.log(response);
		}
		});
	}
	else
	{
		FB.ui({
		 method: 'stream.publish',
		 message: post_message,
		 action_links: [
		   { text: 'From On The Go', href: 'http://www.onthego.gr' }
		 ],
		 user_prompt_message: 'User promt msg'
		},
		function(response) {
		 if (response && response.post_id) {
		 //  console.log('Post was published.');
		 } else {
		  // console.log('Post was not published.');
		 }
		});  
	}
  }
  
  function postOnSpecificWall(post_message, target_user) 
  {
	//console.log('post on wall attempt');
	//console.log(target_user);
	//console.log('post_message:' + post_message);
	if(canPostWithoutAsking)
	{
		FB.api('/'+target_user+'/feed', 'post', { message: post_message }, function(response) {		
		if (!response || response.error) {
			//console.log('posting error');
		} else {
			//console.log(response);
		}
		});
	}
	else
	{
		FB.ui({
		 method: 'stream.publish',
		 message: post_message,
		 target_id: target_user,
		 action_links: [
		   { text: 'From On The Go', href: 'http://www.onthego.gr' }
		 ],
		 user_prompt_message: post_message
		},
		function(response) {
		 if (response && response.post_id) {
		  // console.log('Post was published.');
		 } else {
		   //console.log('Post was not published.');
		 }
		});  
	}
  }



function debug(){
	//console.log("called debug");
}

function postMe(post_message,localuserid){
	if(post_message!=""){
	var message = jQuery.trim(post_message.toString());
	var result = false;
	//result = ensureLoginFB();
	
		
		postOnSpecificWall(message, '117215025004062');
		//console.log("finished posting on fb");
	
		requestUserData(localuserid);
	   	//collectLikes();
	
	/*if( FB.getLoginStatus(handleLoginResponse)){
		postOnSpecificWall(message,'120227974654485');
		console.log("getuserdata = "+value);
	}else{
		console.log("user not logged in");
		
		//loginFB(localuserid);
		//postMe(post_message,localuserid)
	}*/
		
	}	
	//return false;
}

/* User Likes Page Functions & Properties */
	var userLikesPage = false;
	function requestUserLikesPage(page_id) {
		// if we have a session, query for the user's connection with the page
		if (facebookuserid != "") {
			FB.api({
				method: 'fql.query',
				query: 'SELECT target_id FROM connection WHERE source_id = ' + FB.getSession().uid + ' AND target_id = ' + page_id
			}, function(response){
				target_id = response[0];
				userLikesPage = false;
				if (target_id != '' && target_id != undefined && target_id != null) {
					userLikesPage = true;
				}
				//console.log("collectLikes 2, result:"+userLikesPage);
			});
		}
	}
  
	function readUserLikesPage() {
		return userLikesPage;
	}



function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}

function collectText(string) {
var text = string;
getFlashMovie("myContent").sendTextToFlash(text);
}

function collectPhoto(string) {
var text = string;
getFlashMovie("myContent").sendPhotoToFlash(text);
}
function collectLikes() {
var text = "";
	if(readUserLikesPage()){
		text="yes";
	}else{
		text="no";
	}
	
getFlashMovie("myContent").sendLikesToFlash(text);
//console.log("collectLikes, result:"+text);
}











