/* ===========================================================================
 *
 * MI Logger
 * Version 1.0
 * Generates an image with information for NetInsight.
 *
 * ---------------------------------------------------------------------------
 *
 *
 * EXAMPLES OF USE:
 *
 *   // Log this page
 *   jQuery.miLog();
 *
 *   // Bind an event to every <li> element
 *   jQuery("li").bindMIEvent(
 *   {
 *       querystring: "SelectedTab="
 *   }, function() {
 *       // do whatever I need to do in this concrete page
 *       var value1 = "value1";
 *       var value2 = "value2";
 *
 *       return "&newParam1=" + value1 + "&newParam2=" + value2;
 *   }
 *           );
 *
 *   // Bind an event to every element with class=".track_it"
 *   jQuery(".track_it").bindMIEvent({
 *       exitUrl: true
 *   });
 *
 *   // Bind an event to every element with class="split_url"
 *   jQuery(".split_url").bindMIEvent({
 *       exitUrl: true,
 *       sendLocationParams: true
 *   });
 *
 */

/*
 * Needs:
 *      jQuery 1.2.6 or higher
 *     jquery.url.js 1.0 or higher
 *
 */
jQuery(document).ready(function() {

  // Log this page
  jQuery.miLog();

  // Bind an event to every element with class="track_it"  TESCO
  jQuery(".track_it").bindMIEvent({
    exitUrl: true
  });

  // Bind an event to every element with class="split_url"  LLOYDS
  jQuery(".split_url").bindMIEvent({
    exitUrl: true,
    sendLocationParams: true
  });
});


;
(function($) {
  /*
   * Write an image in the current page with information for the MI tracker.
   */
  $.miLog = function(options) {

    // Default settings
    var miSettings = {
      variables: ["MI_TAG_CS", "MI_TAG_APP"],
      textToAppend: new Array(),
      tagImages: ["/images/mi/pagetag.gif?", "/images/sync/app.jpeg"]
    };

    // Merge settings and options, modifying settings
    if (options != undefined) {
      $.extend(miSettings, options);
    }

    // Merge variables
    var source = new String();
    for (var i = 0; i < miSettings.variables.length; i++)
    {
      var variable = new String(miSettings.variables[i]);
      var value = new String();
      if (new String(window[variable]) != 'undefined') {
        value = window[variable];
        source += value;
      }
    }

    // Append strings in the textToAppend field
    for (i = 0; i < miSettings.textToAppend.length; i++) {
      source += "&";
      source += miSettings.textToAppend[i];
    }

    // Prepend the browser info
    source = jQuery.basicBrowserInfo() + source;

    var encodedSource = source.replace(/\?/g, encodeURIComponent("?")).replace(/\|/g, encodeURIComponent("|"));

    for (i in miSettings.tagImages) {

      var newImageURL = prefixURIWithBaseRef(miSettings.tagImages[i]);

      if (newImageURL.indexOf("?") != -1) {
        newImageURL += encodedSource;
      }

      $.ajax({
        url: newImageURL,
        type: 'GET'
      });
    }
  };

  /*
   * Attach an event to an element.
   *
   * exec_function:   Function that will be executed before any other thing.
   *                  This function might return a string that will be append to the request
   *
   * Options:
   * ( Possible type values (events): blur, focus, load, resize, scroll,
   *   unload, beforeunload, click, dblclick,  mousedown, mouseup, mousemove, mouseover,
   *   mouseout, mouseenter, mouseleave, change, select,  submit, keydown, keypress, keyup, error )
   * type: string
   * querystring: string the eventString that we want to append to the image tag
   * eventKey: param name
   * exitUrl: This url is going to any other site and we need to track it!
   * sendLocationParams: look for params in the "document.location" to append them to the mi string and
   *                      send it to the new location.
   *                      If the (sendLocationParams == true) look for the params in the paramNames map,
   *                      appending its default value if the param isn't in the URL.
   *
   * paramNames: the name of the params in the "document.location url" that we want to append to the
   *              mi string.
   * targetURL: To generate the string event
   */
  $.fn.bindMIEvent = function(options, custom_func) {

    var eventSettings = {
      eventKey : "ev=",
      type: "click",
      querystring: "triggeredEventFrom=",
      exitUrl: false,
      sendLocationParams:  false,
      paramNames: {
        'cardtype':    'Airmiles%20Duo',
        'affiliateid': 'Airmiles1500',
        'WT.mc_id':    'Air07125'
      },
      targetURL: 'https://secure.lloydstsb.com/credit_card/application.asp'
    };


    if (options != undefined) {
      $.extend(eventSettings, options);
    }

    var exec_function = custom_func;

    return $(this).each(function() {
      $(this).bind(eventSettings.type, eventSettings, function(event) {
        var strToAppend;
        var customStringToAppend = new String();

        if (exec_function != undefined) {
          customStringToAppend = exec_function();
        }

        if (eventSettings.exitUrl) {
          strToAppend = eventSettings.eventKey + "exit_";

          if (eventSettings.sendLocationParams) {
            event.preventDefault();

            var url = document.location.toString();
            //var url = "http://www.airmiles.co.uk/collect/partner.do?partner=Lloyds+TSB+Airmiles+Duo&affiliateid=Airmiles1500&WT.mc_id=Air0802H_CMO&from=collectlist";
            $.url.setUrl(url);

            var strURL = eventSettings.targetURL;
            if ((options.targetURL == undefined) &&
                ($(this).attr('href') != undefined) && ($(this).attr('href') != ''))
              strURL = $(this).attr('href');

            if (strURL.indexOf('?') == -1)
              strURL = strURL.concat('?');

            for (var key in eventSettings.paramNames) {
              var value = $.url.param(key);
              if (value == undefined)
                value = eventSettings.paramNames[key];
              strURL = strURL.concat(key + '=' + value + '&');
            }

            $.remoteWindow(strURL, 800, 600, 'yes', 'yes', '');

            strToAppend += $.encodeMIParam(strURL);
          } else {
            if ($(this).attr('href') != undefined && ($(this).attr('href') != '')) {
              strToAppend += $.encodeMIParam($(this).attr('href'));
            } else {
              strToAppend += "#";
            }
          }
        } else {
          strToAppend = eventSettings.eventKey + $.encodeMIParam(event.data.querystring.toString());
          strToAppend += $(this).attr('id');
        }


        // Append customized params to log
        strToAppend += customStringToAppend;

        $.miLog({
          textToAppend: new Array(strToAppend)
        });
      });
    });
  };

  /*
   * Gets the browser information needed
   */
  $.basicBrowserInfo = function() {
    var browser = navigator.appCodeName;
    var b_version = navigator.appVersion;
    var version = parseFloat(b_version);

    var toWrite = new String();
    toWrite += "lc=" + $.encodeMIParam(document.location.toString());
    toWrite += "&rf=" + $.encodeMIParam(document.referrer.toString());
    toWrite += "&rs=" + screen.height + "X" + screen.width;
    toWrite += "&cd=" + screen.colorDepth;

    var language = navigator.language;
    if (navigator.appName != 'Netscape')
      language = navigator.browserlanguage;
    toWrite += "&ln=" + language;

    var dateInfo = new Date();
    toWrite += "&tz=" + dateInfo.getTimezoneOffset();

    toWrite += "&jv=" + navigator.javaEnabled();
    toWrite += "&ts=" + dateInfo.getTime();

    return toWrite;
  };

  /*
   * Replace &, =, ? and | with the encoded character
   */
  $.encodeMIParam = function(string) {
    return string.replace(/\?/g, encodeURIComponent("?")).replace(/\&/g, encodeURIComponent("&")).replace(/\=/g, encodeURIComponent("=")).replace(/\|/g, encodeURIComponent("|"));
  };

  /*
   * POP-UP WINDOWS
   */
  $.remoteWindow = function(URL, width, height, scroll, resize, name) {
    // set window size
    var agent = navigator.userAgent.toLowerCase();
    var dimensions = 'width=' + width + ',height=' + height;
    var winProperties = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll + ',resizable=' + resize;

    //location of popup
    // winProperties += ",top=0,left=0,";
    winProperties += ",top=" + ((screen.height - height) / 2) + ",left=" + ((screen.width - width) / 2) + ",";
    var remote = window.open(URL, name, winProperties + ',' + dimensions);

    //	create opener reference if browser doesn't do it
    if (remote.opener == null) {
      remote.opener = self;
    }

    //	bring remote to top if supported
    if (agent.indexOf("msie 3") == -1) {
      remote.focus();
    }
  };
})(jQuery);
