// barebones functions needed to make the inline scripts work
// cookie functions copied from http://www.quirksmode.org/js/cookies.html
var mexpress = {
  showCharactersRemaining: function(element){
    $('#character_counter').text(maxCommentLength-$(element).val().length+' characters remaining');
  },

  RECAPTCHA_PUBLIC_KEY: '6LdkggUAAAAAAIf2RNeYMCOMN8ckZFN5ckR2KQGD',

  setupUserStatus: function() {
    var cookie = readCookie('userInfo');
    if(cookie) {
      var cookieArray = unescape(cookie).split("|");

      var userId           = unescape(cookieArray[0]);
      var username         = unescape(cookieArray[1]);
      var userImageUrl     = unescape(cookieArray[2]);
      var userBadgeClasses = unescape(cookieArray[3]);

      var sessionElem = $('#session');

      sessionElem.html($('#session_logged_in_template').html()).
                  addClass('user-loggedin').
                  removeClass('user-loggedout');

      var userProfileLink = sessionElem.find('a.user-profile-link');
      userProfileLink.attr('href', "/users/" + userId).html(username);

      var imageProfileLinks = sessionElem.find('div.badge-wrapper a');
      imageProfileLinks.attr('href', "/users/" + userId)

      sessionElem.find('img.user-avatar-image').attr('src', userImageUrl);
      sessionElem.find('a.user-badge-overlay').addClass(userBadgeClasses);
    }
  }
};

function createCookie(name,value,days) {
  var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	if (document.cookie !== undefined) {
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') { c = c.substring(1,c.length); }
			if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


var MMX = MMX || {};

MMX.DealTracker = {
  _requestcount: 0,
  _queues: {},
  _base_lon_server: 'ads.localoffernetwork.com',
  
  track_page_views: function(feed, ids) {
    //console.log("tracking page views for '%s', ids: %o", feed, ids);
    switch(feed) {
      case "lon_voucher_pro": 
        this._call_lon(ids, null);
        break;
      case "local_offer_network": 
        this._call_lon(ids, null);
        break;
      case "find_me_specials":
        this._call_fms(ids, null);
    }
  },
  
  track_impressions: function(feed, ids) {
    //console.log("tracking impressions for '%s', ids: %o", feed, ids);
    switch(feed) {
      case "lon_voucher_pro": 
        this._call_lon(null, ids);
        break;
      case "local_offer_network": 
        this._call_lon(null, ids);
        break;
      case "find_me_specials":
        this._call_fms(null, ids);
    }
  },

  queue_tracked_impressions: function(feed, ids) {
    //console.log("queueing impressions for '%s', ids: %o", feed, ids);
    if (this._queues[feed] == null) this._queues[feed] = [];
    this._queues[feed] = this._queues[feed].concat(ids);
  },

  send_queued: function() {
    //console.log("sending queued impressions");
    for (var feed in this._queues) {
      this.track_impressions(feed, this._queues[feed]);
      this._queues[feed] = [];
    }
  },

  _call_fms: function(page_views, impressions) {
    if (!page_views && !impressions) { return; }
    
    var tracking_payload = {
      'affiliate_code': 'metromix'
    };
    if (page_views) {
      tracking_payload['page_views'] = page_views;
    }
    if (impressions) {
      tracking_payload['impressions'] = impressions;
    }
    //console.log("calling track_fms_views; payload=%o", tracking_payload);
    // global FMS function
    try {
      //track_fms_views(tracking_payload);
      this.track_fms_views(tracking_payload);
    } catch(err) {
      //console.error("FMS tracking failed");
    }
  },
  
  _call_lon: function(page_views, impressions) {
    if (!page_views && !impressions) { return; }
    var tracking_payload = {
    };
    if (page_views) {
      tracking_payload['page_views'] = page_views;
    }
    if (impressions) {
      tracking_payload['impressions'] = impressions;
    }
    //console.log("calling track_lon_views...");
    this.track_lon_views(tracking_payload);
  },

  track_fms_views: function(args) {
    try {
      var _gb_analytics_url = null;
      if (typeof(_gb_base_server_analytics_url) !="undefined"){
          _gb_analytics_url = _gb_base_server_analytics_url + '/analytics/record?';
      } else {
          _gb_analytics_url = 'http://www.findmespecials.com/analytics/record?';
      }
      for (arg in args) {
          values = args[arg];
          if(values && (values.constructor!=Array || values.length>0)){
              _gb_analytics_url = _gb_analytics_url + arg + '=' + escape(values) + '&';
          }
      }
      if (typeof(rails_environment) !="undefined"){
           _gb_analytics_url = _gb_analytics_url + 'env=' + rails_environment;
      }
      //_gb_analytics_url= _gb_analytics_url + '\" />';
      //console.debug("fms url is %s", _gb_analytics_url)
      //var img = new Element('img', { src: _gb_analytics_url });
      var img = $('<img src="'+_gb_analytics_url+ '&requestcount=' + this._requestcount + '" />');
      this._requestcount++;
    } catch(err) {
      //console.error("exception in fms tracking code: %o", err);
    }
  },

  
  track_lon_views: function(args) {
    try {
      
      //var _lon_analytics_url = '<script type="text/javascript" src="http://'+this._base_lon_server+'/mmx/record?';
      var _lon_analytics_url = 'http://'+this._base_lon_server+'/mmx/record?';
      for (arg in args) {
          values = args[arg];
          if(values && (values.constructor!=Array || values.length>0)){
              _lon_analytics_url= _lon_analytics_url + arg + '=' + escape(values) + '&';
          }
      }
      if (typeof(rails_environment) !="undefined"){
        _lon_analytics_url = _lon_analytics_url + 'env=' + rails_environment;
      }
      // Instead of document.write, we are going to just create the element in js

      //var img = new Element('img', { src: _lon_analytics_url });
      var img = $('<img src="'+_lon_analytics_url+ '&requestcount=' + this._requestcount + '" />');
      this._requestcount++;
    } catch(err) {
      //console.error("Caught error in track_lon_views: %o", err);
    }
  },

  setBaseLONServer: function(base) {
    //console.debug("setting base lon server: %s", base)
    this._base_lon_server = base;
  },

  setBaseFMSServer: function(base) {
    // FMS uses a global variable
    _gb_base_server_analytics_url = base;
  }
  
};

