var ReturnFlash = "";
var ReturnValue = "";
var Incall = 0;
var SessID = '';
var aPerms = new Array();

/* These are the entry points for Flash to come in */
function FBLogin(FlashID) {
  ReturnFlash = FlashID;
/*  FB.login(ReturnStatus, {perms:'publish_stream,offline_access'}); */
  FB.login(ReturnStatus);
}
function FBLogout(FlashID) {
  ReturnFlash = FlashID;
  FB.logout(ReturnStatus);
}
/* These is the receiver for the Facebook login return */
function ReturnStatus(response) {
  if ( response.session ) {
    if ( response.perms ) {
      aPerms = response.perms.split(",");
    } else {
      aPerms = new Array();
    }
    MakeCall("fblogin", "session="+JSON.stringify(response.session)+"&sid="+SessID+"&rand=" + Math.random());
    if (close_on_complete) {
      window.close();
    } else {
      setTimeout("UpdateDisplay()", 200);
    }
  } else if (response.status == 'connected') {
    FB.getLoginStatus(ReturnStatus2, true);
  } else {
    MakeCall("whoami", "sid="+SessID+"&rand=" + Math.random());
    if (close_on_complete) {
      window.close();
    } else {
      setTimeout("UpdateDisplay()", 200);
    }
  }
}

function ReturnStatus2(response) {
  if ( response.session ) {
    if ( response.perms ) {
      aPerms = response.perms.split(",");
    } else {
      aPerms = new Array();
    }
    MakeCall("fblogin", "session="+JSON.stringify(response.session)+"&sid="+SessID+"&rand=" + Math.random());
  } else {
    MakeCall("whoami", "sid="+SessID+"&rand=" + Math.random());
  }
  if (close_on_complete) {
    window.close();
  } else {
    setTimeout("UpdateDisplay()", 200);
  }
}


function FBPostAchievment(FlashID, ach_name, ach_points, ach_ref) {
  var caption = '{*actor*} has just scored the ' + ach_name + ' achievement for ' + ach_points + ' points!';
  var description = "Don't get left behind, Join the Voyage today!";
  if ( ach_ref ) {
    var picture = 'http://www.narnia.com/images/achieve/' + ach_ref + '.png';
  } else {
    var picture = 'http://www.narnia.com/images/fb_promo.jpg';
  }
  FBPostItem(FlashID, caption, description, picture);
}
function FBPostMessage(FlashID) {
  var caption = 'Travel on the Dawn Treader';
  var description = "Don't get left behind, Join the Voyage today!";
  var picture = 'http://www.narnia.com/images/fb_promo.jpg';
  FBPostItem(FlashID, caption, description, picture);
}

function FBPostItem(FlashID, caption, description, picture) {
  var link = 'http://www.narnia.com/';
  var name = 'Narnia - Voyage of the Dawn Treader';

  FB.ui(
    {
      method: 'stream.publish',
      display: 'popup',
      message: "Narnia - Voyage of the Dawn Treader",
      attachment: {
        name: name,
        caption: caption,
        description: description,
        href: link ,
        media: [{
          type: 'image',
          src: picture,
          href: link
        }]
      },
      action_links: [
        { text: 'Join the adventure', href: link }
      ]
    },
    function(response) {
      if (!response) {
        var myReply = "ERROR";
      } else if (response.error) {
        var myReply = "ERROR";
      } else if (response.post_id) {
        var myReply = response.post_id;
        MakeCall("fbpost", "postID=" + myReply + "&sid="+SessID+"&rand=" + Math.random());
      } else {
        var myReply = "";
      }
      if (FlashID) {
        obj = getFlashMovie(FlashID);
        if (obj) {
          if (obj.JSComplete) {
            obj.JSComplete(myReply);
            return;
          }
        }
      }
    }
  );

}

function TwitterPostMessage(UserRef) {
    MyWin = window.open("http://twitter.com/home?status=Come travel with me on the Dawn Treader: " + base_url + "us/" + UserRef + "", 'NarniaTwitter', "width=800,height=400,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1");
    if (MyWin) {
      MyWin.focus();
    }
    MakeCall("tweeted", "sid="+SessID+"&rand=" + Math.random());
}

function TwitterPostAchievment(UserRef, ach_name, ach_points) {
    MyWin = window.open("http://twitter.com/home?status=I have just got the " + ach_name + " achievement for " + ach_points + " points! Join the Voyage today! " + base_url + "us/" + UserRef + "", 'NarniaTwitter', "width=800,height=400,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1");
    if (MyWin) {
      MyWin.focus();
    }
    MakeCall("tweeted", "sid="+SessID+"&rand=" + Math.random());
}

/* Updates the display or retrusn to flahs if called */
function UpdateDisplay() {
  if (ReturnFlash) {
     obj = getFlashMovie(ReturnFlash)
     if (! (obj && obj.JSComplete)) {
       ReturnFlash = "";
     }
  }
  if (ReturnFlash) {
    try {
      if (ReturnValue) {
        obj.JSComplete($(ReturnValue).xml(1));
      } else {
        obj.JSComplete("");
      }
    } catch (e) {
    }
  } else if (typeof setDisplay == 'function') {
    setDisplay();
  }
}
function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  obj = (isIE) ? window[movieName] : document[movieName]
  return obj;
}


function MakeCall(callid, postvars) {
  if (Incall == 0) {
    Incall = 1;
    ReturnValue = "";
    $.ajax({
      async: false,
      dataType: "xml",
      type: "POST",
      url: base_url + 'php/' + callid,
      data: postvars,
      timeout: 10000,
      success: function(responseBody, textStatus, XMLHttpRequest) {
            if (textStatus == "success") {
                    ProcessCookies(XMLHttpRequest);
                    ReturnValue = responseBody;
                    Incall = 0;
            } else {
//                    alert("Failed to contact server");
                    ReturnValue = XMLError(callid, 9, 'Unexpected response from server - please try again');
                    Incall = 0;
            }
         },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
//          alert("Error in response:\n" + textStatus + "\n" + XMLHttpRequest.responseText);
          ReturnValue = XMLError(callid, 9, 'Error in response from server - please try again');
          Incall = 0;
         }
    });
  }
}

function XMLError(callid, errNo, errMsg) {
  var txt='<' + callid + '><error id="' + errNo + '">' + errMsg + '</error></' + callid + '>';
  if (window.DOMParser) {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(txt,"text/xml");
  } else {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(txt);
  }
  return xmlDoc;
}

function ProcessCookies(request) {
   var cookies = request.getResponseHeader("set-cookie");
   if (cookies) {
     cookie_arr = cookies.split("\n");
     for(i=0; i<cookie_arr.length; i++) {
/*       alert("SET COOKIE\n" + document.cookie + "=" + cookie_arr[i]); */
       document.cookie = cookie_arr[i];
     }
   }
}

// Handle the flash resize
jQuery(document).ready(function(){
  jQuery(window).bind("resize", resizeWindow);
  resizeWindow();
  window.setTimeout('resizeWindow()', 1000);

  jQuery("#login").bind("click", function() {
    FBLogin();
  });
  $("#logout").bind("click", function() {
    FBLogout();
  });

});

function resizeWindow( e ) {
  var h = jQuery(window).height();
  h -= 130;
  if (h < 600) h = 600;
/*  if (h > 840) h = 840;  */
  jQuery("#narniaMain").height(h);

  if (jQuery.browser.safari) {
      var w = jQuery("body").width();
  } else {
      var w = jQuery(window).width();
  }
    if (w < 990) w = 990;
/*  if (w > 1600) w = 1600; */
  jQuery("#narniaMain").width(w);
}

jQuery.fn.xml=function(all){var s="";if(this.length) (((typeof all!="undefined")&&all)?this:jQuery(this[0]).contents()).each(function(){s+=window.ActiveXObject?this.xml:(new XMLSerializer()).serializeToString(this);});return s;};

function RedirectTo( url, lNew ) {
  var MyTop = '';
  if ( top ) {
    try {
      if ( top.location ) {
        MyTop = top.location.href;
      }
    } catch (err) {
      MyTop = 'Permission Denied';
    }
  } else {
    MyTop = window.location.href;
  }

  if (MyTop != window.location.href) {
    if (locale == 'us' && island == 'goldwater') {
      url = 'http://www.cartoonnetwork.com/redirects/third/index_exclude.html?' + url;
      lNew = true;
    }
  }

  if ( lNew ) {
    MyWin = window.open(url, '', '');
    if (MyWin) {
      MyWin.focus();
    }
  } else if ( top ) {
    top.location.href = url;
  } else {
    window.location.href = url ;
  }
}  // RedirectTo

function FrameOwner() {
  var MyTop = '';
  try {
    if ( top ) {
      if ( top.location ) {
        MyTop = top.location.href;
      }
    }
  } catch (err) {
    MyTop = 'Permission Denied';
  }

  var MyWindow = '';
  if ( window ) {
    if ( window.location ) {
      MyWindow = window.location.href;
    }
  }

  if ( MyTop != MyWindow ) {
    retval = MyTop;
  } else {
    retval = '';
  }
  alert('Frame Owner ' + retval);
  return retval;
}  // FrameOwner

