(function(){

  var getUrlVars = function(url_tail) {
    var pairs = url_tail.split('&');
    var out = {};

    $.each(pairs, function(){
      var pair = this.split('=');
      out[pair[0]] = pair[1];
    });
    return out;
  };

  var emptyHash = function(relavant_keys) {
    var empty = function(key){ return relavant_keys[key] == ''; }; 

    return (
      empty('CAMPAIGN_NAME') && 
      empty('SCENARIO_NAME') && 
      empty('SCENARIO_STEP') && 
      empty('ASSET_KEY') &&
      empty('promocode')
    );
  };

  var writeCookies = function(hash){
    $.each(hash, function(key, val){
      $.cookie(key, val, {path: '/'});
    });
  };

  var recordTags = function() {
    var relavant_keys = null;
    var query_params  = null;
    var hashed_params = null;

    // set cookies if user comes in with relevant query params
    if (window.location.href.indexOf('?') + 1 > 0) {
      // Set cookie if user comes in with it and their query params correspond to keys we care about
      query_params  = window.location.href.slice(window.location.href.indexOf('?') + 1);
      hashed_params = getUrlVars(query_params);
      relavant_keys = {
        'CAMPAIGN_NAME' : (hashed_params['CAMPAIGN_NAME'] || '') ,
        'SCENARIO_NAME' : (hashed_params['SCENARIO_NAME'] || '') , 
        'SCENARIO_STEP' : (hashed_params['SCENARIO_STEP'] || '') , 
        'ASSET_KEY'     : (hashed_params['ASSET_KEY'] || '') ,
        'promocode'     : (hashed_params['WT.mc_id'] || '') // note this line
      }; 
      if(!emptyHash(relavant_keys)) {
        writeCookies(relavant_keys);
      }
    }
  };

  var assetLookup = function() {
    var key = $.cookie('ion_download_href') || $.url.attr('path').replace(/\/$/, '');  // either filename or url, with railing slash removed

    var lookupTable = {
      'Yankee_Group_Data_Center_Whitepaper.pdf'          : {id: '1-500763371', name: 'Q210GBL_GM_AD_YankeeWP_GBL'},
      'http://idcdocserv.com/942'                        : {id: '1-500763391', name: 'Q210GBL_GM_AD_IDCWPNNIH_GBL'},
      'Securing_the_Physical_Virtual_Cloud_Continuum.pdf': {id: '1-500763381', name: 'Q210GBL_GM_AD_NemertesWP_GBL'},
      '/us/en'                                           : {id: '1-500763407', name: 'Q210GBL_GM_AD_LearnMoreHPNNIH_GBL'},
      '/us/en/new_network/datacenter.html'               : {id: '1-500741161', name: 'Q210GBL_GM_AD_LearnMoreOvNNIH_GBL'},
      '/us/en/next_gen/simplify.html'                    : {id: '1-500763427', name: 'Q210GBL_GM_AD_LearnMoreSimpNNIH_GBL'},
      '/us/en/new_network/security.html'                 : {id: '1-500763417', name: 'Q210GBL_AD_LearnMoreSecNNIH_GBL'},
      '/us/en/new_network/automate.html'                 : {id: '1-500763447', name: 'Q210GBL_GM_AD_LearnMoreAut_GBL'},
      '/us/en/new_network/services.html'                 : {id: '1-500763437', name: 'Q210GBL_GM_AD_LearnMoreServ_GBL'}
    };

    return lookupTable[key] || {id: '', name: ''};
  };

  var getValue = function(key) {
    var value = null;
    var asset = assetLookup();

    value = $.cookie(key);
    switch(key) {
      case 'CAMPAIGN_NAME':  // the asset name from the lookup table
        value = asset.name;
        break;
      case 'PROGRAM_ID':    // campaign_name + '_' + WT.mc_id
        value = $.cookie('CAMPAIGN_NAME') + "_" + $.cookie('promocode');
        break;
      case 'promocode':      // asset_id from lookup table
        value = asset.id;
        break;
    }

    return value || '';
  };

  var loadSideBarLeadGen = function(){
    if($('.side_bar_lead_gen')) {                               // if the side bar lead gen is on the page
      $.each(['CAMPAIGN_NAME', 'PROGRAM_ID', 'promocode'],     // then gather the values for these hidden fields 
          function(index, value){
            $("#" + value).val(getValue(value));
          }
      ); 
    }
  };

  var loadIonLeadgen = function(){
    // pull tags from cookies- may have been set this time, may have been set previously
    var outQueryParams = 
      '?CAMPAIGN_NAME=' + getValue('CAMPAIGN_NAME') + 
      '&PROGRAM_ID='    + getValue("PROGRAM_ID")    + 
      '&promocode='     + getValue("promocode");

    if($('#leadgen').length != 0) {
      $('#leadgen').jqm({
        ajax: '/us/en/lead_gen.html',
        trigger: 'a.lead_gen',
        onLoad: function(hash) {
          hash.w
            .append(
              //"<iframe style='width: 600px; height: 540px;' align='top' frameborder='0' id='iFrameForm' scroll='auto' src='http://junipernetworks.postclickmarketing.com/test-eng-constellation-short" + outQueryParams + "'></iframe>")
              "<iframe style='width: 600px; height: 555px;' align='top' frameborder='0' id='iFrameForm' scroll='auto' src='http://junipernetworks.postclickmarketing.com/engconstellation-short" + outQueryParams + "'></iframe>")
            .show();

					file_name = $.cookie('ion_download_filename');
					$.cookie('ion_download_filename', null, {path: '/'});
					$('#ion_download_filename').text(file_name || "Juniper Networks");
					
					if($(window).height() < 800) {
						$("#leadgen").css({
							position: 'absolute',
							top: ($(window).scrollTop() + 20)+'px'
						});
					}
        }
      });
    }
  };

  $(window).load(function(){
    recordTags();
    loadIonLeadgen();
    loadSideBarLeadGen();
  });

})();
