 // add js for facebook

 var PAGE_ID = '95369608614';//'124533620911415';//
 var APP_ID = '129119840449508';//'131249020225082';//
 var PAGE_USER = null;
 var PAGE_INFO = null;
 var IS_PUBLISH_STREAM = false;
	$(document).ready(function(){
	
		  (function() {
			
			if (channel.indexOf("m-") > -1){
				return false;
			};
	        var e = document.createElement('script');
	        e.type = 'text/javascript';
	        e.src = document.location.protocol +
	          '//connect.facebook.net/en_US/all.js';
	        e.async = true;
	       
	        document.getElementById('fb-root').appendChild(e);
	      }());
	
	});
	    
	window.fbAsyncInit = function() {
	 
		FB.init({appId: APP_ID, status: true, cookie: true, xfbml: true});
	
		if (channel == 'social'){
			FB.Event.subscribe('auth.statusChange', function(response) {
				// do something with response
				// if logged in, show friends and check if userisfan to hide message
				if (response.session){
					GetAsMuch();
					// also refresh parselikebox
					setTimeout(ParseLikeBox,1000);
				}
			});
			// if already a fan, hide fan message
			GetLoginStatus(GetAsMuch,false);
			DisplayPosts();
		}
		if (channel == 'default'){
		
			setTimeout(ParseHomeLikeBox,1000);
		}
	
	};
    function doPostComment() {
        if (!IS_PUBLISH_STREAM){
            RequestExtendedPerms(PublishToMyStream);
        }else{
            PublishToMyStream();
        }
        // since that is the fastest way to read and set permissions, there is no other way to try to publish without it

    }
	 function ParseHomeLikeBox(){
	        var markup = '<fb:fan profile_id="'+ PAGE_ID +'" stream="false" header="false"  width="200" height="420" connections="12" logobar="0" css="http://australia.msteched.com/p/TEAU10/ui/css_fb.css?v=25"></fb:fan>';
	        $("#fbLike").html(markup);
	        FB.XFBML.parse(document.getElementById('fbLike'));
			
	   }

   function ParseLikeBox(){
        var markup = '<fb:fan profile_id="'+ PAGE_ID +'" stream="false" header="false" width="500px" connections="0" css="http://australia.msteched.com/p/TEAU10/ui/css_fb.css?v=25"></fb:fan>';
        $("#fbLike").html(markup);
        FB.XFBML.parse(document.getElementById('fbLike'));
   }
   
    function GetLoginStatus(fn,bConnect){

        FB.getLoginStatus(function(response){
         
            if (response.status != "unknown"){
                // if no permission, silently keep message until later
                
                if (typeof(fn) == "function"){
                
                    fn();
                }
                
            }else{
                if (bConnect){
                    // attempt to login
                    RequestExtendedPerms(fn);
                }
            }
        }
        );
    }
   
    function fnHideFanMessage(){
        $("#fbfan").hide();
    }
        
      function RequestExtendedPerms(fn){
		        
		FB.ui(
			{
				method: 'auth.login',
				perms: 'publish_stream,read_stream',
                display: 'popup'
			},
			function(response) {
            
				if(response.session){
					// if response has perms, save perms for later use // TODO: save in a cookie
                    if (response.perms.indexOf("auto_publish_recent_activity") > -1){
                        IS_PUBLISH_STREAM = true;
                    }
					if (typeof(fn) == "function"){
						fn();
					}
				}
			} 
		); // end fb.ui

	}
      function PublishToMyStream() {
          FB.ui(
            {
                method: 'stream.publish',
                message: document.getElementById("txtcomment").value,
                attachment: {
                    name: 'Tech.Ed Australia',
                    caption: 'The offical site of Tech.Ed Australia',
                    description: (
                  "At Microsoft, we're motivated and inspired every day by how our customers use our software to find creative solutions to business problems, develop breakthrough ideas, and stay connected to what's most important to them."
                ),
                    href: 'http://australia.msteched.com/'
                },
                action_links: [
                { text: 'Tech.Ed Australia Page', href: 'http://www.facebook.com/pages/TechEd-Australia/95369608614' }
              ],
                user_prompt_message: 'Share Tech.Ed Australia link with friends'
            }, function (response) {
                // now publish to page quietly, note if i do not get perms to go this far, i dont need to go any further
               // get the session again
              
               //UserIsFan(PublishToStream);
                PublishToStream();
            }

        );
      }
     
       function UserIsFan(fn){
	    FB.api(
		    {
			    method: 'pages.isFan',
			    uid: FB.getSession().uid,
			    page_id: PAGE_ID 
		    },
		    function(response) {
                
			   
				    if (typeof(fn) == "function"){
                        fn(response);
                    }
			    
		    }
	    );
	}  	
   	function PublishToStream(){
   	    FB.api(
            {
                method: 'stream.publish',
                message: document.getElementById("txtcomment").value,
                action_links: [
                  { text: 'Tech.Ed Australia', href: 'http://australia.msteched.com' }
                ],
                target_id: PAGE_ID,
               
            }, function (response) {
                if (response) {
                    if (response.error_code){
                        if (response.error_msg) alert(response.error_msg + " (are you a fan of our page?)");
                        //if (response.error_code == "200") user not a fan 
                    }else{
                   
                        // refresh list of teched posts
                       AddPost(response);
                    }
                }
                // TODO: catch null, could not post to wall
            }

        );

	}
    
    function AddPost(pid){
       
        if (PAGE_USER){
       
            FB.api(
                {
                    method: 'fql.query',
                    query: 'select message,actor_id,created_time from stream WHERE  post_id = "'+ pid +'" LIMIT 1'
                  },
                  function(response) {
                        // add post element
                        
                        if (response){
                            var o =  {actor_id: response[0].actor_id, created_time: response[0].created_time, message: response[0].message}; 
                            elementHTML(o,null,false);
                        }
                  }

            );
        }else{
            
            var query = FB.Data.query( "select message,actor_id,created_time from stream WHERE  post_id = '{0}' LIMIT 1 ",pid);
            // logged in user
          
            var user = FB.Data.query("select  uid,name, pic_square from user where uid ='{0}'",FB.getSession().uid);
            FB.Data.waitOn([query, user], function() {
           
               PAGE_USER = {name: user.value[0].name, pic_square: user.value[0].pic_square, uid: user.value[0].uid};
              
               var o = {actor_id: query.value[0].actor_id, created_time: query.value[0].created_time, message: query.value[0].message};
               
               elementHTML(o,null,false);
            
            });
        }
    }
    var  str = (
				'<li>{0}<a href="{1}">{2}</a> {3}' +
				'<span class="sptime">{4}</span>' +
				'</li>');
    var imgStr = '<img src="{0}" class="fbuser" />';

    function elementHTML(o,ouser,isreverse){
        // replace with objects
       
        var user = (ouser) ? ouser : PAGE_USER;
        var html = '';
        var fbwall = $("#fbwall");
              

        // if page is actor, use page values
        if (PAGE_ID == o.actor_id){
            html = str.replace("{0}","").replace("{1}",PAGE_INFO.url).replace("{2}",PAGE_INFO.name);
        }else{
            html = str.replace("{0}",imgStr.replace("{0}",user.pic_square));
            html = html.replace("{1}","http://www.facebook.com/profile.php?id="+user.uid).replace("{2}",user.name);
        }
        // process row.created_time
		
        html = html.replace("{3}",o.message).replace("{4}",fixTime(o.created_time));
        
        if (isreverse)
			fbwall.append(html);
        else 
			fbwall.prepend(html);
        

    }

      function DisplayPosts(){

      // query page details first
     
        var query = FB.Data.query( "select message,actor_id,created_time from stream WHERE  source_id = '{0}' LIMIT 5 ",PAGE_ID);
        var page = FB.Data.query("select name,pic_square,page_url from page where page_id = '{0}'",PAGE_ID);
        var users = FB.Data.query("select  uid,name, pic_square from user where uid in (select actor_id from {0})",query);
        
        FB.Data.waitOn([page, query, users], function() {
           var usernames = {};
           
           PAGE_INFO = {url: page.value[0].page_url,name: page.value[0].name};
           
           var session = FB.getSession();
           FB.Array.forEach(users.value, function(row) {
             usernames[row.uid] = {name: row.name, pic_square: row.pic_square,uid: row.uid};
            

             // if by any chance u find currently logged in user, save details
             if (session)
                if (session.uid == row.uid)
                    PAGE_USER = {name: row.name,pic_square: row.pic_square,uid: row.uid};
           });

          
           var html = '';
           $("#fbwall").html("");

           FB.Array.forEach(query.value, function(row) {
                 var o = {actor_id: row.actor_id, created_time: row.created_time, message: row.message};
				 
                 elementHTML(o,usernames[row.actor_id],true);
                 
            });
            // i would like to parse this a bit later
            setTimeout(ParseLikeBox,1000);
             
        });
       

      }
      function GetAsMuch(){
        
        var isfan = FB.Data.query( "SELECT uid FROM page_fan where uid='{0}' and page_id='{1}' LIMIT 1",FB.getSession().uid,PAGE_ID);
        
        var FriendsFans = FB.Data.query("SELECT uid,name,pic_square  FROM user  WHERE uid IN (SELECT uid FROM page_fan WHERE page_id='"+ PAGE_ID +"' AND uid IN (SELECT uid2 FROM friend WHERE uid1='"+ FB.getSession().uid +"')) ");
        

        FB.Data.waitOn([isfan,FriendsFans], function() {
        
            var isFan = (isfan.value[0]) ? true : false;
            
            if (isFan){
                fnHideFanMessage();
            }
            
            var markup = ('<a href="{0}" title="{1}"><img src="{2}" /></a>');
            var fbFriends = $("#fbfriends");
            fbFriends.html("<h4>Friends who also like our page</h4>");
            var html = '';

            var fbshow = false;
            FB.Array.forEach(FriendsFans.value, function(row) {
               
                html = markup.replace("{0}","http://www.facebook.com/profile.php?id="+row.uid).replace("{1}",row.name).replace("{2}",row.pic_square);
                fbFriends.append(html);
                fbshow = true;
            });
            if(fbshow) fbFriends.show();
        });
      }

      
       
      function fixTime(time) {
        // php timestamp is different than js stamp!
        time *= 1000;

        var date = new Date(time);

        var alldate = date.toLocaleDateString();
        alldate = alldate.substring(0, alldate.length - 5);
        var hours = date.getHours();
        var am = "am";
        if (hours > 12) { hours -= 12; am = "pm"; }

        return alldate +" at "+ hours + ":" + date.getMinutes() + am;

    }
