// Globals for Note Popup

var pt_xmlhttpreq;
var pt_lid;
var pt_ft;
var pt_title;
var pt_widgetName;
var pt_noteId=null;

function isFacebookUser()
{
    var theCookies = document.cookie.split(/[; ]+/);
 
    for (var i = 0 ; i < theCookies.length; i++) {
        var aName = theCookies[i].substring(0,theCookies[i].indexOf('='));
        if (aName == "UserName") {
	    var aValue = theCookies[i].substring(theCookies[i].indexOf('=')+1);
	    if ((aValue.length > 13) && (aValue.substring(0,13) == "FacebookUser_")) {
	            return true;
	    }
        }
    }
    return false;
}

// User opted in for Facebook email notification
function onEmailOptIn()
{
    // Set global flag so we won't pop-up this dialog again
    g_FacebookEmailPermission=true;

    // Hide the dialog
    fbconnect_optin_hidediv();

    // Now, finally, pop up the requested widget
    displayWidgetPopupNow(nwp_lid, nwp_ft, nwp_title, nwp_refId, nwp_widget);
}

// Notebook widget parameters
var nwp_lid=null;
var nwp_ft=null;
var nwp_title=null;
var nwp_refId=null;
var nwp_widget=null;

function displayNotePopup(lid, ft, title, refId)
{
    if (ft == 10)
    {
	// Neighborhoods and larger objects cannot have I Was Here notes
	showSuggestionBox(refId);
	return true;
    }
    return displayWidgetPopup(lid, ft, title, refId, "NoteWidget", true);
}

function displayEditNotePopup(nid, lid, ft)
{
    pt_noteId = nid;
    return displayWidgetPopup(lid, ft, "Edit Note", 0, "NoteWidget", true);
}

function displayLocatePopup(lid, ft, title, refId)
{
    if (ft == 10)
    {
	// Neighborhoods and larger objects cannot have I'm Looking For notes
	showSuggestionBox(refId);
	return true;
    }
    return displayWidgetPopup(lid, ft, title, refId, "LocateWidget" , true);
}

function displayDiscussPopup(lid, ft, title, refId)
{
    // Tell the discuss widget the current lid
    initDiscuss(lid);
    return displayWidgetPopup(lid, ft, title, refId, "DiscussWidget" , false);
}

function displayInvitePopup(lid, ft, title, refId)
{
    return displayWidgetPopup(lid, ft, title, refId, "InviteWidget", false);
}

// Determine whether the current user is enabled to receive replies. That means that
// he must be a ZA user or a FB user who opted in for emails. If he is a FB user
// who has not opted in, give him a chance to do so.
function displayWidgetPopup(lid, ft, title, refId, widgetName, requiresOptIn)
{
    // Get rid of the bubble
      closePopup();

    // Display the popup div to opt-in only for current Facebook users who have not opted-in
    // who are trying to post a note type which requires opt-in
    if (isFacebookUser() && requiresOptIn)
	{
	    nwp_lid=lid;
	    nwp_ft=ft;
	    nwp_title=title;
	    nwp_refId=refId;
	    nwp_widget=widgetName;
	    // If the current FB Connect user has NOT granted ZoomAtlas permission to email him, pop up the div with the permission window
	    FB.Facebook.apiClient.users_hasAppPermission('email', 
		function(result)
		{
		// The result is 0 for users who have not yet opted in, and 1 for those who have 
		if (result==0) 
		    { 
			fbconnect_optin_showdiv(); 
		    } 
		else
		    {
			// User HAS opted in...pop up the note widget immediately
			displayWidgetPopupNow(lid, ft, title, refId, widgetName);
		    }
		} );
	    
	    return true;
	}
    else
	{
            var userid = YAHOO.util.Cookie.get("UserId");
            if (!userid)
		{
		askToRegister();
		return true;
		}
	    else
		{
		return displayWidgetPopupNow(lid, ft, title, refId, widgetName);
		}
	}
}

// It is finally time to display the appropriate widget popup
function displayWidgetPopupNow(lid, ft, title, refId, widgetName)
{
    pt_lid = lid;
    pt_ft = ft;
    pt_title = title;
    pt_refId = refId;
    pt_widgetName = widgetName;
    pt_xmlhttpreq = false;

    // First get rid of the bubble
    closePopup();

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        pt_xmlhttpreq = new XMLHttpRequest();
    	if (pt_xmlhttpreq.overrideMimeType) {
    	    pt_xmlhttpreq.overrideMimeType('text/html');
    	}
    } else if (window.ActiveXObject) { // IE
        try {
    	    pt_xmlhttpreq = new ActiveXObject("Msxml2.XMLHTTP");
    	} catch (e) {
    	    try {
    	        pt_xmlhttpreq = new ActiveXObject("Microsoft.XMLHTTP");
    	    } catch (e) {}
    	}
    }

    if (!pt_xmlhttpreq) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    pt_xmlhttpreq.onreadystatechange = noteBarPopupCallback;

    var url="";

    if (widgetName == "NoteWidget") {
        url="http://www.zoomatlas.com/notebar/ConnectWidget.php?prfx=pnw";
    } else if (widgetName == "LocateWidget") {
        url="http://www.zoomatlas.com/notebar/LocateWidget.php?prfx=plw";
    } else {
        url="http://www.zoomatlas.com/notebar/"+widgetName+".html";
    }

    pt_xmlhttpreq.open('GET', url, true);
    pt_xmlhttpreq.send(null);
    return true;
}

function noteBarPopupCallback()
{
     if (pt_xmlhttpreq.readyState == 4) {
        if (pt_xmlhttpreq.status == 200) {
          var response = pt_xmlhttpreq.responseText;

          msgBoxPanel =  new YAHOO.widget.Panel("popupNote" + pt_lid,
            {
                width:"320px",
                visible:true,
                draggable:true,
                close:true,
                constraintoviewport:true,
                x:400,
                y:200
            }
          );
          msgBoxPanel.setHeader(pt_title);
          msgBoxPanel.setBody(response);
          msgBoxPanel.render(document.body);

	  if (pt_widgetName == "NoteWidget") {
            initNoteBar(pt_lid, pt_ft, "pnw");
            if (pt_noteId != null) {
              // This is a note edit
              initializeNoteEdit(pt_noteId);
              pt_noteId = null;
            }
	  } else if (pt_widgetName == "LocateWidget") {
            initLocateWidget(pt_lid, pt_ft, "plw");
	  }

          return false;
       }
   }
}

function initializeNoteEdit(noteId)
{
    pt_xmlhttpreq = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        pt_xmlhttpreq = new XMLHttpRequest();
    	if (pt_xmlhttpreq.overrideMimeType) {
    	    pt_xmlhttpreq.overrideMimeType('text/html');
    	}
    } else if (window.ActiveXObject) { // IE
        try {
    	    pt_xmlhttpreq = new ActiveXObject("Msxml2.XMLHTTP");
    	} catch (e) {
    	    try {
    	        pt_xmlhttpreq = new ActiveXObject("Microsoft.XMLHTTP");
    	    } catch (e) {}
    	}
    }

    if (!pt_xmlhttpreq) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    pt_xmlhttpreq.onreadystatechange = getNoteInfoCallback;

    url="http://www.zoomatlas.com/notebar/GetNoteInfo.php?nid=" + noteId;
    pt_xmlhttpreq.open('GET', url, true);
    pt_xmlhttpreq.send(null);
    return true;
}

function getNoteInfoCallback()
{
    if (pt_xmlhttpreq.readyState == 4) {
        if (pt_xmlhttpreq.status == 200) {
            var response = pt_xmlhttpreq.responseText;
            var data = json_parse(response);
            if (data.result == "error") {
                alert("getNoteInfoCallback got error from server");
            } else if (data.result == "ok") {
                alert("getNoteInfoCallback got ok from server");
            } else {
                alert("getNoteInfoCallback got unknown result from server");
            }
       } else {
           alert("getNoteInfoCallback: problem with request, status = " + pt_xmlhttpreq.status);
       }
   }
}
