/******************************************************************************/
/*
    \file       isreallyamazing.js
    \brief      This is the javascript functionality for isreallyamazing.com.
    \version    1.0
*/
/******************************************************************************/

/********** globals ***********************************************************/
var Browser =
{
  detect: function()
  {
    var UA = navigator.userAgent;
    this.isKHTML = /Konqueror|Safari|KHTML/.test(UA);
    this.isGecko = (/Gecko/.test(UA) && !this.isKHTML);
    this.isOpera = /Opera/.test(UA);
    this.isMSIE  = (/MSIE/.test(UA) && !this.isOpera);
    this.isMSIE7 = this.isMSIE && !(/MSIE 6\./.test(UA) && !this.isOpera);
  }
}
var CertificateX = 0;

/********** implementation ****************************************************/
Browser.detect();

/**************************************************************************/
/*
    \function   MainSitePostLoad
    \brief      This function performs the post load processing for the main site.
    \param      None.
    \return     None.
*/
/**************************************************************************/
function MainSitePostLoad()
{
    // Set style on header
    $('header').setStyle({top:'170px',left:'-700px'});
    
    // Set style on logo
    $('logo').setStyle({display:'block'});
    
    // Transition in the header
    new Effect.Move('header',{ x: 700, y: -170 });
    
    // Create bubbles
    CreateBubble('people', 50,  150, { delay:0.2, duration:1.1 });
    CreateBubble('places', 260, 180, { delay:0.5, duration:1.1 });
    CreateBubble('things', 470, 210, { delay:0.8, duration:1.1 });
    
    // Make the bubbles draggable
    ['people-bubble','places-bubble','things-bubble'].each(
        function(b)
        {
            new Draggable(b,{revert:true,handle:b+'-handle'});
        });
    
    // Make footer appear
    if(footerSitesMax > 0)
    {
      RotateMainFooter();
      new Effect.Appear('mainsite-footer');
    
      // Start rotating footer sites (if any)
      setInterval(RotateMainFooter, 3000);
    }
}

/**************************************************************************/
/*
    \function   MainSiteComingSoonPostLoad
    \brief      This function performs the post load processing for the main site.
    \param      None.
    \return     None.
*/
/**************************************************************************/
function MainSiteComingSoonPostLoad()
{
    // Set style on header
    $('header').setStyle({top:'170px',left:'-700px'});
    
    // Set style on logo
    $('logo').setStyle({display:'block'});
    
    // Transition in the header
    new Effect.Move('header',{ x: 700, y: -170 });
    
    // Create bubbles
    CreateBubble('comingsoon', 320, 180, { delay:0.5, duration:1.1 });
    
    // Make the bubbles draggable
    ['comingsoon-bubble'].each(
        function(b)
        {
            new Draggable(b,{revert:true,handle:b+'-handle'});
        });
}

/**************************************************************************/
/*
    \function   CertificateSitePostLoad
    \brief      This function performs the post load processing for the certificate site.
    \param      isAvailable - If the site is available or not, will make the buy now button visible if so.
    \return     None.
*/
/**************************************************************************/
function CertificateSitePostLoad(isAvailable)
{
  CertificateX = GetScreenCenterX()-(349/2);

  // Create bubble
  CreateBubble('certificate', CertificateX, 110, { delay:0.2, duration:1.1 });
  
  // Make the bubbles draggable
  ['certificate-bubble'].each(
      function(b)
      {
          new Draggable(b,{revert:true,handle:b+'-handle'});
      });
  
  // Make footer appear
  new Effect.Appear('certificate-footer');
}

/**************************************************************************/
/*
    \function   OnCertificateSiteResize
    \brief      This function recenters the certificate if the browser is resized.
    \param      None.
    \return     None.
*/
/**************************************************************************/
function OnCertificateSiteResize()
{
    var newX = GetScreenCenterX()-(349/2);
    var oldX = CertificateX;
    var difference = newX - oldX;
    
    // Move the certificate to the new location
    new Effect.MoveBy('certificate-bubble', 0, difference);
    
    // Update global
    CertificateX = newX;
}

/**************************************************************************/
/*
    \function   CreateBubble
    \brief      This function creates a bubble effect for a div.
    \param      id - The div id to apply the effect to.
    \param      x - The x-offset in pixels.
    \param      y - The y-offset in pixels.
    \return     None.
*/
/**************************************************************************/
function CreateBubble(id,x,y)
{
    // Set the style
    $(id+'-bubble').setStyle({left:x+'px',top:y+'px'});
    
    // Create a new effect for the div
    new Effect.Scale(id+'-bubble',100,
                    Object.extend(
                    {
                        beforeStart:function(effect)
                        {
                            $(effect.element).style.display = 'block';
                            $(effect.element).setOpacity(0);
                            $$('#'+id+'-bubble p').each(function(p)
                                                        {
                                                            p.hide()
                                                        });
                        },
                        afterUpdate:function(effect)
                        {
                            $(effect.element).setOpacity(effect.position);
                        },
                        scaleFrom:0,
                        scaleFromCenter:true,
                        afterFinish:function(effect)
                        {
                            $$('#'+id+'-bubble p').each(function(p)
                                                        {
                                                            new Effect.Appear(p,{duration:0.4});
                                                        });
                        }
                    },
                    arguments[3] || {}));        
}

/**************************************************************************/
/*
    \function   GetScreenCenterY
    \brief      This function calculates the y coordinate for the screen center.
    \param      None.
    \return     y coordinate of screen center.
*/
/**************************************************************************/
function GetScreenCenterY()
{
  return( GetScrollOffset() + (GetInnerHeight() / 2) );
}

/**************************************************************************/
/*
    \function   GetScreenCenterX
    \brief      This function calculates the x coordinate for the screen center.
    \param      None.
    \return     x coordinate of screen center.
*/
/**************************************************************************/
function GetScreenCenterX()
{
  return( document.body.clientWidth / 2 );  
}

/**************************************************************************/
/*
    \function   GetInnerHeight
    \brief      This function calculates the inner height of the page space.
    \param      None.
    \return     inner height.
*/
/**************************************************************************/
function GetInnerHeight()
{
  var y = 0;  
  if (self.innerHeight) // all except Explorer  
  {
    y = self.innerHeight;  
  }
  else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
  {
    y = document.documentElement.clientHeight;
  }
  else if (document.body) // other Explorers
  {
    y = document.body.clientHeight;
  }

  return(y);
}

/**************************************************************************/
/*
    \function   GetScrollOffset
    \brief      This function calculates the scroll offset of the page space.
    \param      None.
    \return     scroll offset.
*/
/**************************************************************************/
function GetScrollOffset()
{
  var y = 0;
  
  if (self.pageYOffset) // all except Explorer
  {
    y = self.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict  
  {
    y = document.documentElement.scrollTop;
  }
  else if (document.body) // all other Explorers
  {
    y = document.body.scrollTop;
  }
  
  return(y);
}

/**************************************************************************/
/*
    \function   CheckNameAvailability
    \brief      This function checks to see if the name is available.
    \param      The name to check.
    \return     async content fill.
*/
/**************************************************************************/
function CheckNameAvailability(name)
{
  new Ajax.Updater('testnameresult', '/include/checkname.php?name=' + name, {asynchronous:true});
}

/**************************************************************************/
/*
    \function   PlaceOrder
    \brief      This function begins the Facebook order flow.
    \param      The name to purchase. The FB ID of the user purchasing.
    \param      If this is a gift purchase or not.
    \return     none.
*/
/**************************************************************************/
function PlaceOrder(name,wasGift)
{
  // Send data needed for order.
  var nameToOrder = name.toLowerCase();
  var order_info = { "name":nameToOrder.replace(/([^0-9A-Za-z])/g,"") };
                   
  // calling the API ...
  var obj = {
        method: 'pay',
        order_info: order_info,
        purchase_type: 'item',
        credits_purchase: false
  };

  if(wasGift)
  {
    FB.ui(obj, PlaceGiftOrderCallback);
  }
  else
  {
    FB.ui(obj, PlaceOrderCallback);
  }
}

/**************************************************************************/
/*
    \function   PlaceOrderCallback
    \brief      Callback function for facebook API order processing.
    \param      Data sent by Facebook after the order is complete.
    \return     none.
*/
/**************************************************************************/
function PlaceOrderCallback(data)
{
  if (data['order_id'])
  {
    // Post to the user's wall
    top.location.href='http://www.facebook.com/dialog/feed?app_id=' + appId + '&link=http://apps.facebook.com/isreallyamazing/&picture=http://www.isreallyamazing.com/images/thumbsup.gif&name=IsReallyAmazing.com!&caption=Amazing%20people,%20places,%20and%20things!&description=I%20just%20made%20something%20really%20amazing!%20Check%20out%20' + $('testname').value + '.isreallyamazing.com!%20Make%20something%20or%20someone%20really%20amazing%20today!&redirect_uri=http://' + $('testname').value + '.isreallyamazing.com/?fromfb%26purchased';
  }
}

/**************************************************************************/
/*
    \function   PlaceGiftOrderCallback
    \brief      Callback function for facebook API order processing.
    \param      Data sent by Facebook after the order is complete.
    \return     none.
*/
/**************************************************************************/
function PlaceGiftOrderCallback(data)
{
  if (data['order_id'])
  {
    // Post to the user's wall
    top.location.href='http://www.facebook.com/dialog/send?app_id=' + appId + '&to=' + giftFriendId + '&link=http://apps.facebook.com/isreallyamazing/&picture=http://www.isreallyamazing.com/images/thumbsup.gif&name=IsReallyAmazing.com!&caption=' + $('testname').value + '.isreallyamazing.com&description=You%20have%20just%20been%20certified%20as%20really%20amazing!%20Check%20out%20' + $('testname').value + '.isreallyamazing.com!&redirect_uri=http://' + $('testname').value + '.isreallyamazing.com/?fromfb%26purchased%26gift';
  }
}

/**************************************************************************/
/*
    \function   OnCertificatePurchase
    \brief      Function called when first navigating to a purchased site after sale.
    \param      The site name.
    \return     none.
*/
/**************************************************************************/
function OnCertificatePurchase(name)
{
  /*
  var answer = confirm("You have successfully purchased " + name + ".IsReallyAmazing.com!\n\nWas this a gift for someone?")
  if (answer)
  {
    window.location.href='http://www.facebook.com/dialog/send?app_id=' + appId + '&link=http://apps.facebook.com/isreallyamazing/&picture=http://www.isreallyamazing.com/images/thumbsup.gif&name=IsReallyAmazing.com!&caption=' + name + '.isreallyamazing.com&description=You%20have%20just%20been%20certified%20as%20really%20amazing!%20Check%20out%20' + name + '.isreallyamazing.com!&redirect_uri=http://' + name + '.isreallyamazing.com/';
  }
  */
}

/**************************************************************************/
/*
    \function   RotateMainFooter
    \brief      Function to rotate the content in the main site's footer.
    \param      none.
    \return     none.
*/
/**************************************************************************/
function RotateMainFooter()
{
  $('mainsite-footer-content').innerHTML = footerSites[footerSitesIndex];
  footerSitesIndex++;
  if(footerSitesIndex >= footerSitesMax) { footerSitesIndex = 0; }
}

/**************************************************************************/
/*
    \function   ClearPendingRequests
    \brief      Function to clear any FB app requests from this app.
    \param      none.
    \return     none.
*/
/**************************************************************************/
function ClearPendingRequests()
{
  FB.api("/me/apprequests/",
    function(response)
    {
      var ids = [];
      for (var i=0, l=response.data.length; i<l; i++)
      {
        FB.api("/" + response.data[i].id, "DELETE", null);
      }
    }
  );
}
