var SHREK = SHREK || {},
  flashvars = {},
  attributes = {},
  resizeTimeoutId = null,
  params = {
    "allowScriptAccess": "always"
  };

function createGoogleAnalyticsTracker(trackerName, trackingCode, trackerIndex) {
  try {
    window[trackerName] = _gat._getTracker(trackingCode);
    window[trackerName]._trackPageview();
    
    $("#swfApplication")[0].createGoogleAnalyticsTrackerCallback(trackerIndex);
  } catch(err){

  }
}

function loginWithFacebook(countryCode) {
  FB.login(function(response) {
    if (response.session) {
      FB.api('/me', function (response) {
        var connectParams = "&userFacebookId=" + response.id + "&countryCode=" + countryCode;
        var connectStr = "php/action.php?action=shellfbLogin" + connectParams;
        $.get(connectStr, function (ogreResponse) {    
          $("#swfApplication")[0].loginWithFacebookCallback(response.id, response.name, ogreResponse);
        });
      });
    } else {
      //alert("Error: Could not login with Facebook");
    }
  }, { perms:'publish_stream' });
}

function logoutOfFacebook() {
  FB.logout();
}

function postScoreToFacebook(postMsg, attachmentTitle, attachmentMsg, attachmentImgURL, actionText, actionURL) {
  var post = {
    method: 'stream.publish',
    message: postMsg,
    
    action_links: [{
      text: actionText,
      href: actionURL
    }],
    
    attachment: {
      name: attachmentTitle,
      href: actionURL,
      caption: attachmentMsg,
      media: [{
        type: 'image',
        src: attachmentImgURL,
        href: actionURL
      }]
    }
  };
  
  FB.api(post, function (response) {
    if (!response || response.error) {
      //alert('Error: Could not post to Facebook');
    } 
  });
}

function resizeWindow() {
  var offset = $(window).height() - 800;
  if (offset > 0) {
    $("#ogres, #witches").css("top", offset);
    $("#footer").css("margin-top", (offset + 170  ) + "px");
  } else {
    $("#footer").css("margin-top", 170);
    $("#ogres, #witches").css("top", 1);
  }
  resizeTimeoutId = null;
}

$(window).resize(function() {
  if (resizeTimeoutId) {
    clearTimeout(resizeTimeoutId);
  }
  resizeTimeoutId = setTimeout(resizeWindow, 50);
});

// Set up Facebook app ID (sometimes called API key). Hard-coded key for localhost / dev / QA deployment,
// but use the specified key in XML for the production instance.
function setFacebookAppId(live_key) {
  if ( document.location.href.match(/http\:\/\/localhost\/~peter\/shrek/) ) {
    // Pete's localhost development
    SHREK.APP_ID = '8bb94bc8a0c13f25a63580dfd75f945b';

  } else if ( document.location.href.match(/http\:\/\/dev\.shrekinternational\.com/) ) {
    // dev Facebook app
    SHREK.APP_ID = 'be39ebeda0b045677dc7ab25bb2dec1e';

  } else if ( document.location.href.match(/http\:\/\/qa\.shrekinternational\.com/) ) {
    // QA Facebook app
    SHREK.APP_ID = '3e0331cb893c7d5eaf17c581c73dcea9';

  } else {
    // live Facebook app
    SHREK.APP_ID = live_key;
  }
}

$(function () {

  $.get("xml/mainCopy.xml", function (response) {
    
    setFacebookAppId( $(response).find("FACEBOOK APP_ID").text() );
    
    var headerImage = $(response).find("HEADER_IMAGE_URL").text();
    $("#shrekLogoLocal").attr("src", headerImage).css("visibility", "visible");
    
    var header3dImage = $(response).find("HEADER_IMAGE_3D_URL").text();
    $("#header").css("background", 'url("' + header3dImage + '") no-repeat scroll 0 133px transparent');
    
    $("#headerLink")
      .attr("href", $(response).find("HEADER_LINK").text())
      .append("<div id='releaseDate'>" + $(response).find("RELEASE_DATE").text() + "</div>");
     
    $(response).find("FOOTER LINK").each(function (i, n) {
      var text = $(n).find("TEXT").text();
      var href = $(n).find("HREF").text();
      
      var spacer = (i > 0) ? "<span>|</span> " : "";
      var link = $(spacer + "<a target='_new' href='" + href + "' alt='footerLink'>" + text + "</a>");
      $("#footerInner").append(link);
    });
    
    $("#distributedBy").html($(response).find("DISTRIBUTED_BY").text());
    $("#footerInner").append("<div id='copyright'>" + $(response).find("FOOTER COPYRIGHT").text() + "</div>");

    var usePPCWrapper = $(response).find("PPC ENABLED").text();
    if (usePPCWrapper.toLowerCase() == "true") {
      var flashvars = {
        app_id : $(response).find("PPC APP_ID").text(),
        lang : $(response).find("PPC LANG").text().toLowerCase()
      };
      swfobject.embedSWF("gamewrapper.swf", "swfApplication", "540", "400", "10.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
    } else {
      // otherwise just use the swf from the local environment
      swfobject.embedSWF("preloader.swf", "swfApplication", "540", "400", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    resizeWindow();
    
    if ($.browser.msie && $.browser.version == 8) {
      // force IE8 to respect the top margin on the footer element
      setTimeout(function () {
        $("#footer").clone().prependTo("#footer").remove();
      }, 10);
    }
    
    // Defer FB.init() until after the XML has been read and the page has loaded.
    FB.init({
      appId: SHREK.APP_ID, 
      status: true, 
      cookie: true, 
      xfbml: true
    });
    
  }, "xml");
});
