/////////////////////////////////////////////
// FB callback functions - move to main.js
/////////////////////////////////////////////
// Global Variables
var facebook_status_result_set = Array();
var facebook_pagination_items_per_page = 3;
var facebook_pagination_total_pages = 0;
var facebook_pagination_total_items = 0;
var facebook_current_select_page = 1;
var logged_out_html = ""; // This is to cache the logged out state HTML for on logout
var logged_in_user_id = null;
var logged_in_user_session_key = null;
var fb_username1="default";
var fqdnvalue1="";
if($.cookie("ftkn")!="" && $.cookie("ftkn")!=null){
      
      $.ajax({url:"https://graph.facebook.com/me?access_token="+$.cookie("ftkn"), success: function(userdetails) {$.cookie("floggedinuser",userdetails.id,{expires: 1200, path: '/', domain: 'mydaily.com'});
}, dataType:"jsonp", error: function(response, status, error){alert(response);}});	
}




function is_not_connected_callback() { /* No need to do anything at the moment */ }
function is_connected_callback() {
    
    //logged_in_user_id = FB.Connect.get_loggedInUser();

    logged_in_user_id=$.cookie("floggedinuser");
   
    FB.Facebook.apiClient.get_sessionWaitable().waitUntilReady(
    function(session) {    	
            logged_in_user_session_key = session.session_key;            

	
	var detailsurl='https://graph.facebook.com/'+logged_in_user_id;
   
	$.ajax({url:detailsurl, success: function(userdetails) {fb_username1=userdetails.name;startupfunction(fb_username1);	}, dataType:"jsonp", error: function(response, status, error){alert(response);}});	
    });


	//setTimeout("load_facebook_widget_ui()", 500);


}
function startupfunction(username1){

	fb_username1=username1;
	setTimeout("load_facebook_widget_ui()", 1000);
}
function logout_callback() {build_logout_state(true);return false; /* They clicked log out, so we should rebuild the not logged in UI */}

function onconnect_callback() {
    is_connected_callback();

    FB.Connect.forceSessionRefresh(function() {
            is_connected_callback();
            $("#facebook #facebookpreview").show();
    });
} //Called after the run the FB Connect authorization
function stream_get_callback(status_objects) { // Called when status stream loads
    if (!status_objects) {
		$('.friends').html('<li class="loading-dialog"><b>Unable to load status updates.</b><small>Please try again later.</small></li>');
        return false;
    }
    
    $("#status_viewer_container .friends").html('');
	
    //TODO: Probably want to cache these
    for(status_type in status_objects) {
		
        if (status_type == 'data') {
            // Setup pagination and store data...
            facebook_status_result_set = Array(); // To prevent reloading the same events..
            for (i in status_objects[status_type]) {
				if(status_objects[status_type][i].message != undefined){
					if(facebook_status_result_set.length < 15)
					facebook_status_result_set.push(status_objects[status_type][i]);
				}
               
            }
            facebook_pagination_total_items = facebook_status_result_set.length;
			
            facebook_pagination_total_pages =  Math.ceil(facebook_pagination_total_items / facebook_pagination_items_per_page);
			
            // Build out pagination links...
            pagination_html ='<li class="previous">&nbsp;<a href="#" rel="previous">&laquo; Previous</a></li>'
            for (var p_num = 1; p_num <= facebook_pagination_total_pages; p_num++) {
					pagination_html += '<li id="p_' + p_num + '" class="pages"><a href="#" rel="' + p_num  +'">' + p_num + '</a></li>';
				
			}
            pagination_html +='<li class="next"><a href="#" rel="next">Next &raquo;</a></li>';
            $('#status_viewer_container .pagination-links').html('<ul>' + pagination_html + '</ul>');
            $('#status_viewer_container .pagination-links li a').click(function(){facebook_widget_display_page($(this).attr('rel'));});
            facebook_widget_display_page("1");

            break; //Only want to do facebook posts for now
        }
    }
}

////////////////////////////////////
// Facebook UI functions
///////////////////////////////////
function build_logout_state(re_populate) {
    if (re_populate){ //such as when logging out
        $("#facebookpreview").html(logged_out_html);
	$(".flyouts #facebookpreview .closebtn_flyover").hover(function(){$(this).addClass("hoverstate");},function(){$(this).removeClass("hoverstate");});
        $("#toolbar-item-container  li#toolbar_facebook .toolbar-item-title").css("color","#333333");
        $(".flyouts #facebookpreview .closebtn_flyover").click(function(){ $(this).parent().hide();$("#toolbar-item-container li.toolbar-item").find(".toolbar-item-title").css("color", "#333");});
        $("#facebookpreview").hide();
        clickcount=0;
$.cookie("floggedinuser","",{expires: -1, path: '/', domain: 'mydaily.com'});
$.cookie("ftkn","",{expires: -1, path: '/', domain: 'mydaily.com'});
$.cookie("fmlf","",{expires: -1, path: '/', domain: 'mydaily.com'});
          
        }
    // add click handlers
}

function facebook_widget_display_page(page){
    if (page == 'previous')
        page = facebook_current_selected_page - 1;

    else if (page == 'next')
        page = facebook_current_selected_page + 1;
    
    else {
    	page = parseInt(page)
    	
    	}
facebook_current_selected_page = page
    // Hide/show paging links

    if (page <= 1) {$('#status_viewer_container .pagination-links li.previous a').hide();}
    else {$('#status_viewer_container .pagination-links li.previous a').show();}

    if (page >= facebook_pagination_total_pages) {$('#status_viewer_container .pagination-links li.next a').hide();}
    else {$('#status_viewer_container .pagination-links li.next a').show();}

    rendered_items = ''
    this_pages_items = []
    start = (page - 1) * facebook_pagination_items_per_page
    end = page * facebook_pagination_items_per_page
    items_to_display = facebook_status_result_set.slice(start, end)
	
    for (var x = 0; x < items_to_display.length; x++)    {
	
	  	rendered_items += render_status_html(items_to_display[x]);        
		
	}
    $('ul.friends').html(rendered_items);
    $(".pagination-links li.pages").removeClass("active")
    $("#p_" + page).addClass("active")
		htmlcontent="";
		/*for(var i=0;i<data.data.length;i++){
			if(data.data[i].message==undefined){
				data.data[i].message="";
			}
			else{
			htmlcontent+="<li style='clear:both'><a href='http://www.facebook.com/profile.php?id="+data.data[i].from.id+"'><img src='http://graph.facebook.com/"+data.data[i].from.id+"/picture'/></a>"+data.data[i].from.name+" - "+data.data[i].message+"</li>";
			$("ul.friends").html(htmlcontent);
			}
		} */
}

function load_facebook_widget_ui() {

	
	//<fb:name uid="loggedinuser" useyou="true"></fb:name>
        html = '';
        html += '<span class="closebtn_flyover">Close</span><div id="facebook_profile_info">';
                html += '    <div id="facebook_widget_header"><div id="facebook_widget_header_welcome">Welcome, '+ fb_username1 +'</div><div id="facebook_widget_header_logout"><a href="#" id="facebook_logout_link">Logout</a></div></div>';
                html += '    <div id="profile_image_container">';
        //'<span class="profile_pic"><img src="http://graph.facebook.com/'+logged_in_user_id+'/picture" alt="''"/></span>'     <span class="profile_pic"><img src="http://graph.facebook.com/'+logged_in_user_id+'/picture"/></span>        
		html += '<span class="profile_pic"><img src="http://graph.facebook.com/'+logged_in_user_id+'/picture"/></span>';//'<fb:profile-pic uid="'+logged_in_user_id+'" size="normal" facebook-logo="true"></fb:profile-pic>';
        html += '    </div>';
        html += '    <div class="links">';
        html += '        <a target="_blank" href="http://www.new.facebook.com/profile.php?id=' + logged_in_user_id + '">Profile &raquo;</a>'; //TODO: Get User ID non-FBML
        html += '        <a target="_blank" href="http://www.facebook.com/friends.php">Friends  &raquo;</a>';
        html += '        <a target="_blank" href="http://www.facebook.com/networks/">Networks  &raquo;</a>';
        html += '    </div>';
        html += '</div>';
        html += '<div id="status_viewer_container">';
        html += '    <div id="status_viewer_container_header"><div id="status_viewer_container_header_title">Your Friends\' Updates</div><div id="status_viewer_container_refresh_container"><a href="#" id="facebook_refresh_link">Refresh</a></div></div>';
        html += fb_render_loading_status(); //'    <ul class="friends">Loading Your Friends\' Updates... </ul>'
        html += '   <div class="pagination-links"></div>';
        html += '</div>';

        $('#facebookpreview').html(html);
        //FB.XFBML.Host.parseDomElement($("#facebookpreview")[0]); // Initial parse for profile image, etc

        // Add click handlers
        $('#facebook_logout_link').click(function(){
            //FB.Connect.logout();
            logout_callback();
        });
        // Add click handlers
        $('#facebook_refresh_link').click(function(){
                $("#status_viewer_container .friends").html(fb_render_loading_status());
            fetch_status_feed();
          return false;
         });
        fetch_status_feed();
        $(".flyouts #facebookpreview .closebtn_flyover").hover(function(){$(this).addClass("hoverstate");},function(){$(this).removeClass("hoverstate");});
        $(".flyouts #facebookpreview .closebtn_flyover").click(function(){ $(this).parent().hide();$("#toolbar-item-container li.toolbar-item").find(".toolbar-item-title").css("color", "#333");});
        

}

//Utillity functions
function fetch_status_feed() {
	/*$.ajax({
		url : "/ajax.jsp?module=facebook_status_get&statusFetchSize=" + facebook_fetch_limit + "&fbSessionKey=" + encodeURIComponent(logged_in_user_session_key) + "&fbUserId=" + logged_in_user_id,
		success : function(resp) {stream_get_callback(resp);},
		contentType: "application/json; charset=utf-8",
		dataType:"json"		
	});*/
	var ac_tkn=readCookie('ftkn');
        
	$.ajax({
	url:'https://graph.facebook.com/me/home?access_token='+ac_tkn,
	success: function(data) {  
		stream_get_callback(data);
	},
	dataType:"jsonp",
	error: function(response, status, error){alert(response);}
	});
	
	//FB.Facebook.apiClient.stream_get(null, null, null, facebook_fetch_limit, null, stream_get_callback); // Fetch Stream stream_get_callback handles payload
}
function fb_render_loading_status() {
    html = '';
    html += '    <ul class="friends"><li class="loading-dialog"><b>Checking For Updates...</b><small>This may take a few seconds.</small><span class="loading-spinner">&nbsp;</span></li></ul>';
    return html;
}
function render_status_html(status) {
	
   if(status.message==null || status.message==undefined){
	   status_message="";
	   fstatus_id="";
	  
   }
   else{
	  
	   status_message=status.message;
	   fstatus_id=status.from.name;
	   if (status_message.length > 85)
        status_message = status_message.substr(0, 82) + '...';
	
		html = '';
		html += '<li class="friend">';
		html += '   <div class="friend-image">';
		html += '           <a href="http://www.facebook.com/profile.php?id=' + status.from.id + '" class="FB_Link" target="_blank"><img class="FB_profile_pic fb_profile_pic_rendered" style="" title="' + status.from.name + '" alt="' + status.from.name + '" src="http://graph.facebook.com/'+status.from.id+'/picture"/></a>';
		//html += '           <fb:profile-pic uid="' + status.uid + '" size="square" facebook-logo="true"></fb:profile-pic>';
		html += '   </div>';
		html += '   <div class="friend-info list">';
		//html += '       <strong><fb:name uid="' + status.uid + '" useyou="true" linked="true"></fb:name></strong>';
		html += '       <strong><a href="http://www.facebook.com/profile.php?id=' + status.from.id + '" class="FB_Link" target="_blank">' + status.from.name +  '</a></strong>';
		html += '       <div class="status"><p>' +  status_message + '</p> <a href="http://www.facebook.com/n/?profile.php&v=feed&story_fbid=' + status.id + '&id=' + status.from.id + '" target="_blank" class="facebook_status_read_more">more &raquo;</a></div>';
		html += '   </div>';
		html += '</li>';
		return html;
   }


        
    
}

/*function launch_facebook_connect_popup() {
	// Launch Custom Signin Popup
    var fb_win_width = 600;
    var fb_win_height = 400;
    var fb_win_left = (screen.width - fb_win_width) / 2;
    var fb_win_top = (screen.height - fb_win_height) / 2;
    var end_point_url = encodeURIComponent(facebook_login_endpoint_url);
    var next_url = encodeURIComponent('http://www.facebook.com/connect/prompt_permissions.php?api_key=' + facebook_api_key + '&v=1.0&extern=2&next=' + end_point_url + '&dialog_id=0_0.19030929174175237&ext_perm=read_stream,offline_access');
    var cancel_url = encodeURIComponent(window.location);

    var fb_popup = window.open("http://www.facebook.com/login.php?api_key=" + facebook_api_key + "&v=1.0&popup&skipcookie&next=" + next_url + "&cancel_url=" + cancel_url, "FacebookLoginWindow", "menubar=no,width=" + fb_win_width + ",height=" + fb_win_height + ",toolbar=no,top=" + fb_win_top + ",left=" + fb_win_left);
    fb_popup.focus();
    return false;
}*/
function launch_facebook_connect_popup(currurl) {
	// Launch Custom Signin Popup
    var fb_win_width = 600;
    var fb_win_height = 400;
    var fb_win_left = (screen.width - fb_win_width) / 2;
    var fb_win_top = (screen.height - fb_win_height) / 2;
	var facebook_token_url="";
	var test="";
	
	fqdnvalue1=currurl;
    var end_point_url = encodeURIComponent(facebook_login_endpoint_url);
    //var next_url = encodeURIComponent('http://www.facebook.com/connect/prompt_permissions.php?api_key=' + facebook_api_key + '&v=1.0&extern=2&next=' + end_point_url + '&dialog_id=0_0.19030929174175237&ext_perm=read_stream,offline_access');
	var next_url = encodeURIComponent('https://graph.facebook.com/oauth/authorize?client_id=150014941679926&redirect_uri=http://'+fqdnvalue1+'/&type=user_agent&next=' + end_point_url);

	//	var next_url = encodeURIComponent('https://graph.facebook.com/oauth/authorize?client_id=122567974457605&redirect_uri='+window.opener.location.href+'&type=user_agent&next=' + end_point_url);
    var cancel_url = encodeURIComponent(window.location);
	
    //var fb_popup = window.open("http://www.facebook.com/login.php?api_key=" + facebook_api_key + "&v=1.0&popup&skipcookie&next=" + next_url + "&cancel_url=" + cancel_url, "FacebookLoginWindow", "menubar=no,width=" + fb_win_width + ",height=" + fb_win_height + ",toolbar=no,top=" + fb_win_top + ",left=" + fb_win_left);
   var fb_popup = window.open('https://graph.facebook.com/oauth/authorize?client_id=150014941679926&next=http://'+fqdnvalue1+'/&redirect_uri=http://www.mydaily.com/facebook_endpoint/&type=user_agent&cancel_url=' + cancel_url, "FacebookLoginWindow", "menubar=no,width=" + fb_win_width + ",height=" + fb_win_height + ",toolbar=no,top=" + fb_win_top + ",left=" + fb_win_left);

	//var fb_popup = window.open('https://graph.facebook.com/oauth/authorize?client_id=122567974457605&next=http://'+fqdnvalue1+'/&redirect_uri=http://'+fqdnvalue1+'/facebook_endpoint.html&type=user_agent&cancel_url=' + cancel_url, "FacebookLoginWindow", "menubar=no,width=" + fb_win_width + ",height=" + fb_win_height + ",toolbar=no,top=" + fb_win_top + ",left=" + fb_win_left);
	
	/*var name="access_token";
  	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  	var regexS = "[\\#&]"+name+"=([^&#]*)";
  	var regex = new RegExp( regexS );
  	var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		//alert(results[1]);
*/


	fb_popup.focus();
	
    return false;
}

function readCookie(name) {

	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function getdetails(){

		var ac_tkn=readCookie('ftkn');

		
}

// End Facebook Connect JS


function gmailSignOut(b, a) {
    //showTab("gmailpreview", "sTbLdng");
    //omcl(b, "gml_signout");
    //load("supertab", "gmailpreview", "gmail", "reset_gml=true&tab=gmail", 1, null, null, 1);
    //$("b.gmail.mlCnt").empty();
    //return false
    var d = new Date();
	$.cookie("gtkn","",{expires: -1, path: '/', domain: 'mydaily.com'});
$.cookie("gmlf","",{expires: -1, path: '/', domain: 'mydaily.com'});
        var scurrurl=window.location.href;
       var sscurrurl=scurrurl.split("#");
       window.location.href=sscurrurl[0];
}
function ymailSignOut(a) {

//showTab("ymailpreview", "sTbLdng");
  //  omcl(a, "yml_signout");
    //load("supertab", "ymailpreview", "ymail", "reset_yml=true&tab=ymail", 1, null, null, 1);
    //$("b.ymail.mlCnt").empty();
    //return false
   // alert("clear Cookies?");
    var d = new Date();
	$.cookie("ytkn","",{expires: -1, path: '/', domain: 'mydaily.com'});
        $.cookie("ymlf","",{expires: -1, path: '/', domain: 'mydaily.com'});

       var scurrurl=window.location.href;
       var sscurrurl=scurrurl.split("#");
       window.location.href=sscurrurl[0];

}

function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/";}
function popup_init() {
		//FB_RequireFeatures(["Connect", "XFBML", "Api"], function() { 
		//	FB.init(window.opener.facebook_api_key, "/xd_receiver.htm", {});
		//	window.opener.onconnect_callback();
			test="success";
			var name="access_token";
			name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			var regexS = "[\\#&]"+name+"=([^&#]*)";
			var regex = new RegExp( regexS );
			var results = regex.exec( window.location.href );
			  if( results == null )
				return "";
			  else{
				createCookie("ftkn",results[1],1);
				createCookie("fmlf","1",1);
			  }
			  
$.ajax({ url: "http://remote.mydaily.com/", datatype:"jsonp" });
			  if (window.opener.progressWindow)
					
			 {
				window.opener.progressWindow.close();
			  }
window.opener.location = window.opener.location.href;
			//window.opener.location=window.opener.location.href;

			window.close();
			
		//});
}
