// ==UserScript==
// @name           BigDoor Rewardinator
// @by             @steveho
// ==/UserScript==

if(!bdm_network_bar_loaded) {
(function() {  
   var _network_event_selector = 'bdrn-event-five-sites';
   var _site_event_selector = 'bdrn-event-five-pages';
      
   var BDM = window.BDM = window.BDM || {};
   BDM._is_plugin = 'n';
      
	BDM._loadCss = function(src, media) {
		var link = document.createElement('link');
		link.href = src;
		link.type = "text/css";
		link.rel="stylesheet";
		link.media = media || 'screen';
		document.getElementsByTagName('head')[0].appendChild(link);
	};

   // used for JSONP; stores the global config which was fetched
   BDM._responseGlobal = function(object) {
      BDM.bdrn_global = object;
   };
   
   // used for JSONP; stores the site specific config
   BDM._responseSite = function(object) {
      BDM.bdrn_site = object;
   }

   // to load JS script
	BDM._loadScript = function(src, callback) {
		var script = document.createElement('script');
		script.setAttribute('src', src);
      script.addEventListener('load', function() {
         callback();
      }, false);
      document.getElementsByTagName('head')[0].appendChild(script);
	};
	
	BDM.load_rn = function(pub_id, site_id) {
      /**
       * publisher id is the BDRN publisher id
       * site_id is also the version
      **/
      /**
       * Perform a 'recursive merge' of objects `a` and `b`.
       * This will modify and return `a`. A recursive merge overwrites
       * values in `a` with the corresponding values in `b`,
       * EXCEPT when both values are plain objects.
       * In that case, `merge` is called with the values from `a` and `b`.
       * Thus, nested objects will always be added to or updated,
       * but will never have values removed.
       */
      var merge = function(a, b) {
          for (var key in b) {
              var a_value = a[key];
              var b_value = b[key];
              if (BDM.$.isPlainObject(a_value) && BDM.$.isPlainObject(b_value)) {
                  merge(a_value, b_value);
              }
              else {
                  a[key] = b_value;
              }
          }
          return a;
      };

      var base_url = 'http://static.bigdoor.com/partner/publishers/'
      base_url = base_url + pub_id + '/';

      // gets the site specific config which will store itself in
      // BDM.bdrn_site
      var getSiteConfig = function(pub_id, site_id, callback) {
          return BDM._loadScript(
              base_url + ['release', site_id, 'default.js'].join('/'),
              callback
          );
      };

      // gets the global config which will store itself in BDM.bdrn_global
      var getGlobalConfig = function(pub_id, site_id, callback) { 
          // just an example of where the file could be--this may be
          // changed if the global configuration was not kept here
          return BDM._loadScript(
              base_url + 'release/global.js',
              callback
          );
      };

      // gets the BDM loader
      var getBDMLoad = function(callback) {
          return BDM._loadScript(
              'http://js.bigdoor.com/branches/release/gambit/load.js',
              callback
          );
      };
	   
	   
	   if(window.document.location.protocol != 'http:') return;
	   
	   
      BDM._loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js', function(){ 
         BDM.$ = window.jQuery.noConflict(true);
                     
         // called when one of the config pieces was fetched
         // this will check to see if all the required config pieces
         // are available and then move forward if they are
         var onBdrnConfigResponse = function() {
             if(BDM.bdrn_global && BDM.bdrn_site) {
                 // both site and config files have finished loading
                 getBDMLoad(function() {
                     // have all configs and the load script, so now
                     // we must merge the loaded scripts
                                       
                     BDM._setup(BDM.$);
                     
                     // this part is different than before--here we will
                     // instantiate a Loader with the merged config
                     // and then call the next() fuction to move the
                     // process forward
                     BDM.load = new BDM.Loader({
                         config: merge(BDM.bdrn_global, BDM.bdrn_site),
                         sequence: ['library', 'init'],
                         auto: true
                     }, function() {
                         if(BDM.app.current().auth && !BDM.app.current().auth.is_anonymous()) {
                             BDM._loadQuests(true);
                         }
                     });
                 });
             }
         };
         
         // load the global and site configs and use callbacks to
         // wait for the response
         getGlobalConfig(pub_id, site_id, onBdrnConfigResponse);
         getSiteConfig(pub_id, site_id, onBdrnConfigResponse);     
      });
         	   
	};
	
   BDM._setup = function($) {
      $('body').prepend('<div id="bd-quest-container"></div><div id="bd-nav-container"></div><a id="'+_network_event_selector+'" href="#"></a><a id="'+_site_event_selector+'" href="#"></a>');            
   };

   // Non-Gambit Checkpoint: visit 5 sites in network
   BDM._networkQuestVisit = function() {
      var fb_id = BDM.app.current().sessions.remote.profile.end_user_login();
      if(fb_id) {
         BDM.$.ajax({
            type: 'GET',
            url: 'http://rewards.bigdoor.com/serv/quest.php?t=1&u='+fb_id+'&pl='+BDM._is_plugin+'&l='+encodeURIComponent(window.location.href)+'&ts='+new Date().getTime(),
            success: function(data){
               if(!data) return false;
               var jsonObj = eval('('+data+')');
               if(jsonObj && jsonObj.num_sites >= 5) {
                  BDM.$('#'+_network_event_selector).trigger('click');
               }
            }
         });         
      }
   }
   
   // Non-Gambit Checkpoint: view 5 pages on the same site (site-specific)
   BDM._siteQuestViewPages = function(quest) {
      var quest_id = quest ? quest.id() : 0;
      var fb_id = BDM.app.current().sessions.remote.profile.end_user_login();
      if(fb_id) {
         BDM.$.ajax({
            type: 'GET',
            url: 'http://rewards.bigdoor.com/serv/quest.php?t=2&u='+fb_id+'&pl='+BDM._is_plugin+'&qid='+quest_id+'&l='+encodeURIComponent(window.location.href)+'&ts='+new Date().getTime(),
            success: function(data){
               if(!data) return false;
               var jsonObj = eval('('+data+')');
               if(jsonObj && jsonObj.num_pages >= 5) {
                  BDM.$('#'+_site_event_selector).trigger('click');
               }
            }
         });         
      }      
   }
   
   // track site visit
   BDM._siteVisit = function() {
      var fb_id = BDM.app.current().sessions.remote.profile.end_user_login();
      if(fb_id) {
         BDM.$.ajax({
            type: 'GET',
            url: 'http://rewards.bigdoor.com/serv/quest.php?t=0&u='+fb_id+'&pl='+BDM._is_plugin+'&l='+encodeURIComponent(window.location.href)+'&ts='+new Date().getTime(),
            success: function(data){}
         });         
      }      
   }
      
   // load quests based on friendly_id: global quests and site-specific quests
   BDM._loadQuests = function(force) {      
      if(force || (!force && !BDM._questsAlreadyLoaded)) {
         var _app = BDM.app.current();
         if(_app.auth.is_anonymous()) return;         
         _app.providers.quests.fetch_incomplete(function() {
            if(!force) BDM._questsAlreadyLoaded = true;
            BDM._activateActiveQuest();      
         });
      }
   }
   
   // make sure to activate new quest
   BDM._activateActiveQuest = function() {
      var _app = BDM.app.current();
      if(_app.providers.quests.all().length && (!_app.providers.quests.active() || (_app.providers.quests.active() && _app.providers.quests.all().indexOf(_app.providers.quests.active())==-1))) {
         _app.providers.quests.activate(_app.providers.quests.all()[0]);
      }
      // no more quests - get 'other network sites'
      if(_app.providers.quests.all().length==0) {
         BDM.$.ajax({
            type: 'GET',
            url: 'http://rewards.bigdoor.com/serv/sites.php?h='+window.location.hostname.replace(/www\./i,'')+'&t='+new Date().getTime(),
            success: function(data){
               if(!data) return false;
               var jsonObj = eval('('+data+')');
               if(jsonObj) {
                  _app.otf = {'network_sites': jsonObj};
                  if(jsonObj[0]) { BDM.$('#bdm-network-site-1').attr('href', 'http://'+jsonObj[0]); BDM.$('#bdm-network-site-1').html(jsonObj[0]); }
                  if(jsonObj[1]) { BDM.$('#bdm-network-site-2').attr('href', 'http://'+jsonObj[1]); BDM.$('#bdm-network-site-2').html(jsonObj[1]); }
                  if(jsonObj[2]) { BDM.$('#bdm-network-site-3').attr('href', 'http://'+jsonObj[2]); BDM.$('#bdm-network-site-3').html(jsonObj[2]); }
               }
            }
         });               
      }      
   }
   
   // determine checkpoint types (fb like, share, click event...)
   BDM._getCheckpointType = function(checkpoint) {
      if(!checkpoint || !checkpoint.attributes()) return 0;
      for(var i=0; i<checkpoint.attributes().length; i++) {
         var _fid = checkpoint.attributes()[i].friendly_id();
         var _descr = checkpoint.attributes()[i].description();
         if(checkpoint.page() && _fid == 'bdm-checkpoint-event') return 1;
         else if(_fid == 'bdm-event-facebook-like') return 2; 
         else if(_fid == 'bdm-checkpoint-quiz') return 3;
         else if(_fid == 'bdm-event-user-wish-added') return 4;
         else if(_descr.indexOf(_network_event_selector) > 0) return 5;
         else if(_descr.indexOf(_site_event_selector) > 0) return 6;
      }
      return 0;
   }   
   
   // is reward item an Amazon Gift Card? need different redemption form
   BDM._isAmazonGiftCard = function(reward) {
      return true; // all rewards are gift card; meaning BDRB only works with gift card for now
      return (reward && reward.title().indexOf('Amazon')>=0 && reward.cost()%30 == 0) ? true : false;
   }
   
   // get last wishlist item (added last)
   BDM._get_last_wishlist_item = function(id) {
      if(!BDM.app.current().sessions.remote.read('wishlist')) return null;
      var ids = BDM.app.current().sessions.remote.read('wishlist').split(',');
      id = ids[ids.length-1];
      for(var i=0; i<BDM.app.current().providers.products.all().length; i++) {
         if(BDM.app.current().providers.products.all()[i].id() == id) {
            return BDM.app.current().providers.products.all()[i];
         }
      }
      return null;
   }
   
   // get local date format e.g. 'Jan 10, 2012'
   BDM._get_date_string = function(d, short) {
      var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
      try {
         return (short ? months[d.getMonth()].substr(0,3) : months[d.getMonth()])+' '+d.getDate()+', '+d.getFullYear();
      } catch(e){}      
   }
   
})();
var bdm_network_bar_loaded = true;
}
