// Linked to offsite.

var EPStore = {
  // server is just a meta tag for the server this file is used on
  server: '6invegas.com',
  _initialized: null,

  init: function () {
    this.set_ep_site_links({adv: 'a', mid: 'm', imid: 'i'}, {adv: 'V101'});
    this._initialized = true; 
  },
    
  // elapsed time until expires, in minutes
  set_cookie: function (name, value, elapsed) {
    var expires = "";
    if (elapsed) { 
      var date = new Date();
      date.setTime(date.getTime()+(elapsed*60*1000));
      expires = "; expires="+date.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expires + "; path=/";
  },

  // An associative array containing parameter values keyed by name
  parameters: (function () {
    var loc = window.location.toString();
    var qI = loc.indexOf('?');
    var kvs = qI > 0 ? loc.substring(qI + 1).split('&') : [];
    var params = {};

    for (var i = 0; i < kvs.length; i++) {
      var pos = kvs[i].indexOf('=');
      if (pos > 0) {
        var key = kvs[i].substring(0,pos);
        var val = kvs[i].substring(pos+1);
        params[key] = val;
      }
    }

    return params;
  })(),

  /*
   name optional - if provided return the value of named cookie or null,
   otherwise return hash of all cookies
  */
  read_cookies: function (name) {
    var cookies = document.cookie.split(/; */);
    var cookie_hash = {};

    for(var i=0;i < cookies.length;i++) {
      var cookie = cookies[i];
      var c_pair = cookie.match(/^(\w+)=(.*)/);

      // IE doesn't always include the = when there is no value
      if (! c_pair) {
        c_pair = cookie.match(/^(\w+)/);
        if (! c_pair) { continue; }
      }

      // if we get here and c_pair doesn't have at least two elements then we have failed to usefully parse this cookie
      if (c_pair.length < 2) { continue; }

        // If the cookies value is false here it is undefined, set it to an empty string, which is generally more useful (urls etc)
        var val = c_pair[2] ? c_pair[2] : '';
        if (name) {
          if (c_pair[1] == name) { return val; }
        }
        else { cookie_hash[c_pair[1]] = val; }
      }

      if (name) { return null; }
      else { return cookie_hash; }
    },

    erase_cookie: function (name) {
      this.createCookie(name,"",-1);
    },

    extract_elements: function (keys, source) {
      var hash = {};
      source = source || {};
      keys = keys || [];

      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var value = source[key];

        if (value !== undefined) { 
          hash[key] = value; 
        }
      }
      return hash;
    },

    set_ep_site_links: function (param_map, defaults) {
      $("a.ep_site_link").each(function (j, link) {
        var url = link.href;
        var param_names = [];
        var ep_params = {};

        // load parameter names from keys of param_map
        for (name in param_map) {
          param_names[param_names.length] = name;
        }

        ep_params = EPStore.extract_elements(param_names, EPStore.parameters);

        url += url.match('\\?') ? '&' : '?';
            
        // If there wasn't cookie info in the parameters
        //    Load from cookies.

        var empty = true;

        for (k in ep_params) {
          empty = false;
          break;
        }

        if (empty) {
          console.info("looking to cookies");
          var cookie_names = [];
          var cookies = EPStore.read_cookies();

          // retrieve cookie names from param map
          for (param_name in param_map) {
            var cookie_value = cookies[param_map[param_name]];
            if (cookie_value !== undefined) {
              ep_params[param_name] = cookie_value;
            }
          }                
        }

        for (var i = 0; i < param_names.length; i++) {
          // each is either a string or null
          var key = param_names[i];
          var c = ep_params[key]; 
          var val = c !== undefined ? c : (defaults[key] || '');
          url +=  key + "=" + val + "&";
        }
        link.href = url;
      });
    }
};

$(function(){
    EPStore.init();
});
