
// this will hold the filename and fb_filename from ajax request below... these get sent to wall/post and cdn, blah blah
var fb_data = {}; 

function facebookWallPost()
{
  FB.init(
  {
    appId : '151738154881122',
    status : true,
    cookie : true,
    xfbml : true
  });
  
  var product_url = window.location.href;
  if ( product_url.indexOf('?facebook=true') > -1 )
  {
    product_url = product_url.substring(0, product_url.indexOf('?facebook=true'));
  }

  // publish to the stream
  FB.ui(
  {
    method : 'stream.publish',
    display : 'iframe',
    attachment :
    {
      name : 'Family Stickers',
      caption : 'I just created a stick-figure version of my family! Familystickers.com has a huge selection of body types and hairdos. Check out my stick figure design and create your own.',
      href : 'http://www.familystickers.com/facebook_family.html?img=' + fb_data.filename + '&product_url=' + urlencode(product_url),
      media :
      [{
        type : 'image',
        src : 'http://c461654.r54.cf2.rackcdn.com/' + fb_data.fb_filename, // the familybuilder rackspace controller album action uses this path as well
        href : 'http://www.familystickers.com/facebook_family.html?img=' + fb_data.filename + '&product_url=' + urlencode(product_url)
      }]
    },
    action_links :
    [{
      text : 'Design Your Family!',
      href : product_url
    }]
  },
  function(response)
  {
    if ( response && response.post_id )
    {
      $j('#shareYourLifeComplete').show();
      setTimeout(function()
      {
        $j('#shareYourLifeComplete').fadeOut();
      }, 1500);

      // track this with google analytics
      if ( window._gaq )
      {
        window._gaq.push(['_trackEvent', 'familystickers', 'facebook', 'success']);
      }
      facebookAlbum();
    }
    else
    {
      // track this with google analytics
      if ( window._gaq )
      {
        window._gaq.push(['_trackEvent', 'familystickers', 'facebook', 'cancelled']);
      }
    }
  });
}

function facebookAlbum()
{  
  // lets find out our path and family config value
  var info = explode('~', $j('dd.dd-my-family input[type="hidden"]').val(), 2)[1];
  
  $j.ajax(
  {
    url : url + '/familybuilder/facebook/postToWall',
    cache : false,
    type : 'post',
    data :
    {
      family : info,
      fb_data : fb_data
    },
    success : function(data)
    {
      // nothing
    }
  });
}

function facebookInit()
{
  window.fbAsyncInit = function()
  {
    FB.init(
    {
      appId : '151738154881122',
      status : true,
      cookie : true,
      xfbml : true
    });
    
    FB.XFBML.parse();
  };

  // load facebook's BS
  (function() {
    var e = document.createElement('script');
    e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    if ( document.getElementById('fb-root') )
    {
      document.getElementById('fb-root').appendChild(e);
    }
  }());
}

function facebookShare()
{
  facebookInit();

  var pauser;
  
  // share your life
  $j('div.shareYourLife a').click(function()
  {
    // so the user doesn't keep clicking on the damn link
    if ( pauser )
    {
      return false;
    }
    pauser = true;

    // track this with google analytics
    if ( window._gaq )
    {
      window._gaq.push(['_trackEvent', 'familystickers', 'facebook', 'initiated']);
    }

    $j('#shareYourLifeLoader').show();
    $j(window).scroll(function()
    {
      $j('#shareYourLifeLoader, #shareYourLifeComplete').css('top', $j(this).scrollTop() + 200);
    }).scroll();

    // lets find out our path and family config value
    var info = info = explode('~', $j('dd.dd-my-family input[type="hidden"]').val(), 2)[1];
    
    // send the request to save the family to the rack
    $j.ajax(
    {
      url : '/familybuilder/facebook/uploadToTheRack',
      type : 'post',
      cache : false,
      data : { family : info },
      dataType : 'json',
      success : function(data)
      {
        $j('#shareYourLifeLoader').hide();
        pauser = undefined;

        // put this local var into the global var
        fb_data = data;
        
        FB.getLoginStatus(function(response)
        {
          if ( response && response.status == 'connected' )
          {
            fb_data.session = response.session;
            facebookWallPost();
          }
          else
          {
            $j.prettyPhoto.open('/familybuilder/facebook/postToWall?iframe=true&width=350&height=150');
          }
        });
      }
    });

    return false;
  });
  
  // auto click!
  if ( window.location.href.indexOf('?facebook=true') > -1 )
  {
    $j('div.shareYourLife a').click();
  }
}


function saveProductValues()
{
  var data = '';
  $j('.product-custom-option').each(function()
  {
    // we don't want to store this value... it's not needed
    if ( this.value.indexOf('WMIShops_FamilyBuilder_Model_HiddenPriceHandler') == -1 )
    {
      data += this.id + '=' + $j(this).val() + '&';
    }
  });

  $j.cookie('product_info', data.substring(0, data.length - 1),
  {
    expires : 7,
    path : '/'
  });
}
function loadProductValues()
{
  if ( $j('#product_addtocart_form').length == 0 )
  {
    return;
  }

  var data = {};

  for ( var i = 0, info = ($j.cookie('product_info') || '').split('&'); i < info.length; i++ )
  {
    var d = info[i].split('=');
    data[d[0]] = d[1];
  }

  $j('.product-custom-option').each(function()
  {
    if ( data[this.id] !== undefined )
    {
      $j('#' + this.id).val(data[this.id]);
    }
  });
}


function initScrollImg(e)
{
  var img = $j(e);
  if ( !e.tagName )
  {
    img = $j(this);
  }

  var parentHolder = img.parent();

  if ( img.width() <= parentHolder.width() )
  {
    return;
  }

  var x = 0;
  var page_x;
  var is_moving = false;

  function moveImg()
  {
    if ( !is_moving )
    {
      return;
    }

    var left = page_x - parentHolder.offset().left - (parentHolder.width() / 2);

    x += left < 0 ? 1.5 : -1.5;

    if ( x >= 0 )
    {
      x = 0;
    }
    if ( x <= parentHolder.width() - img.width() )
    {
      x = parentHolder.width() - img.width();
    }

    img.css('margin-left', x);

    setTimeout(moveImg, 0);
  }

  parentHolder.mouseover(function()
  {
    is_moving = true;
    moveImg();
  }).mouseout(function()
  {
    is_moving = false;
  }).mousemove(function(e)
  {
    page_x = e.pageX;
  });
}



$j(function()
{
  // larger image, then thumbnail (in the 'my cart' dropdown)
  for ( var i = 0, names = ['famImage', 'famImageThumb']; i < names.length; i++ )
  {
    var img = $j('.' + names[i] + ' img');
    if ( img.length == 0 )
    {
      continue;
    }

    img.each(function()
    {
      if ( this.complete )
      {
        initScrollImg(this);
      }
      else
      {
        $j(this).load(initScrollImg);
      }
    });
  }

  loadProductValues();
  $j('a#toFamilyBuilder').click(saveProductValues);
});
