/*global YAHOO, SKYPE, SWFObject, container, makeContainerDiv, document, console, pageTracker, aCustomInclient*/
/*jslint bitwise: true, browser: true, eqeqeq: true, immed: true, newcap: true, nomen: true, onevar: true, plusplus: true, white: true, widget: true, undef: true, indent: 2*/

if (typeof SKYPE.inclient === "undefined") {
  SKYPE.namespace("inclient");
}

SKYPE.inclient.Acquisition = (function () {
  
  var the_referrer  = document.referrer.toLowerCase(),
  the_url           = location.pathname.toLowerCase(),
  the_param         = (decodeURIComponent(location.search)).toLowerCase(),
  
  getCMTagValues = function (a_param) {
    
    var a_temp,
    segment     = { channel: "", source: "", group: "", detail: ""};
    
    if (a_param.indexOf("cm_mmc=") === -1) {
      return false; //if no cm_mmc, drops off
    }
    
    /* get the cm_mmc part */
    a_temp = a_param.match(/cm_mmc=([^&]*)/)[1];
    
    /* breaks into 4 */
    a_temp = a_temp.split("-_-");
    
    if (a_temp.length === 4) {
      segment.channel = a_temp[0];
      segment.source  = a_temp[1];
      segment.group   = a_temp[2];
      segment.detail  = a_temp[3];

      return segment;
    }
    else {
      return false;
    }
  },
  
  isSegmentValid = function (segment) {
    return ((typeof segment.channel !== "undefined") && (typeof segment.source !== "undefined") &&
            (typeof segment.group !== "undefined") && (typeof segment.detail !== "undefined"));
  },
  
  isInClientValid = function (acquisition_channel, partner_site, group, detailed_source) {
    return ((typeof acquisition_channel !== "undefined") && acquisition_channel.match(/^[A-Z-_|\.0-9]+$/i) &&
            (typeof partner_site !== "undefined") && partner_site.match(/^[A-Z-_|\.0-9]+$/i) &&
            (typeof group !== "undefined") && group.match(/^[A-Z-_|\.0-9]+$/i) &&
            (typeof detailed_source !== "undefined"));
  },

  writeTrackingFlash = function (trackingFlashUrl, acquisition_channel, partner_site, group, detailed_source) {
    var so = new SWFObject(trackingFlashUrl, "trackFls", "3", "3", 9, "#FFFFFF");
    so.addParam("wmode", "transparent");
    so.addParam("allowScriptAccess", "always");
    
    so.addVariable("acquisition_channel", acquisition_channel);
    so.addVariable("partner_site", partner_site);
    so.addVariable("group", group);
    if (typeof detailed_source !== "undefined") {
      so.addVariable("detailed_source", detailed_source);
    }
    
    so.write(makeContainerDiv("inclientreportingFlashDiv"));
  },
  
  makeContainerDiv = function (divId) {
    var container = document.createElement("DIV");
    container.id = divId;
    YAHOO.util.Dom.setStyle(container, "position", "absolute");
    YAHOO.util.Dom.setStyle(container, "width", "3px");
    YAHOO.util.Dom.setStyle(container, "height", "3px");
    YAHOO.util.Dom.setStyle(container, "font", "1px monospace");
    YAHOO.util.Dom.setStyle(container, "top", "0px");
    YAHOO.util.Dom.setStyle(container, "left", "0px");
    document.body.appendChild(container);
    return container;
  },
  
  /**********************
   *  Reporting Methods */
  inClientReport = function (acquisition_channel, partner_site, group, detailed_source) {

    if (!isInClientValid(acquisition_channel, partner_site, group, detailed_source)) {
      return false;
    }

    var MODE = "production",
    trackingFlashUrl = (MODE === "production") ? "http://www.skype.com/apps/inclient/tracker.swf" :
      "http://www.skype.com/apps/inclient/tracker-pretrack.swf";
    if (MODE === "production") {
      writeTrackingFlash(trackingFlashUrl, acquisition_channel, partner_site, group, detailed_source);
    }
    else {
      if ((typeof console !== "undefined") && (typeof console.log !== "undefined")) {
        console.log("Inclient.report: ", arguments);
      }
      writeTrackingFlash(trackingFlashUrl, acquisition_channel, partner_site, group, detailed_source);
    }
    return true;
  },

  /*************
   * Inclient Channels  
   *************/

  /* All the channels bellow are invoked in pre-defined way, 
   * so all are required to have same interfacing rules:
   * - inclient... = function (a_referrer, a_url, a_param) {
   * - return false, when no channel found.
   * - return { channel: "", source: "", group: "", detail: ""}, when channel found.
   */
  
  inclientNatural = function (a_referrer, a_url, a_param) {

    //Excluding the stuff coming in with marketing tags
    if ((typeof a_referrer === "undefined") || a_referrer === "" ||
	(a_param.indexOf("cm_mmc=") !== -1) || (a_param.indexOf("source=") !== -1)) {
      return false;
    }

    var segment = { channel: "", source: "", group: "", detail: ""},

    s_engines   = {/*Order matters, because it stops eval when match*/
      "google-suggest": /google\..*(\?q=|&q=)([^&]+).*source=suggest.*/,
      "google":         /google\..*(\?q=|&q=)([^&]+).*/,
      "yahoo":          /yahoo\.co.*(\?p=|&p=)([^&]+).*/,
      "bing":           /bing\..*(\?q=|&q=)([^&]+).*/,
      "msn":            /msn\..*(\?q=|&q=)([^&]+).*/,
      "msn.live":       /^http:\/\/search\.live\.com.*(\?q=|&q=)([^&]+).*/,
      "yandex":         /yandex\.ru\/.*([\?|&]text=)([^&]+).*/,
      "baidu":          /baidu\.com\/.*([\?|&]wd=)([^&]+).*/,
      "naver":          /naver\.com\/.*([\?|&]query=)([^&]+).*/,
      "ayna":           /ayna\.com\/.*(\?q=|&q=)([^&]+).*/,
      "wala":           /search\.walla\.co\.il\/.*(\?q=|&q=)([^&]+).*/
    },

    the_params  = {
      "google":         /q=([^&]*)/,
      "google-suggest": /q=([^&]*)/,
      "yahoo":          /p=([^&]*)/,
      "bing":           /q=([^&]*)/,
      "msn":            /q=([^&]*)/,
      "msn.live":       /q=([^&]*)/,
      "yandex":         /text=([^&]*)/,
      "baidu":          /wd=([^&]*)/,
      "naver":          /query=([^&]*)/,
      "ayna":           /q=([^&]*)/,
      "wala":           /q=([^&]*)/
    },
    
    tkey, tkey2;

    //figure out which engine
    for (tkey in s_engines) {
      if (a_referrer.match(s_engines[tkey])) {
        segment.channel = "natural-search";
        segment.source = tkey;
        break;
      }
    }

    if (segment.channel === "") {
      return false; //no inclient neither cookie, drops off
    }

    //figure out the local
    segment.group = a_referrer.replace("http://", "").split("/")[0];

    //figure out the search keyword
    for (tkey2 in the_params) {
      if (tkey2 === segment.source) {
        segment.detail = a_referrer.match(the_params[tkey2])[1];
        break;
      }
    }
    return segment;
  },
  
  inclientTagger = function (a_referrer, a_url, a_param) {
    
    var tags = [
      "cm_mmc=paids|",
      "cm_mmc=aff",
      "cm_mmc=banem|cnn", 
      "cm_mmc=banla|",
      "cm_mmc=banna|", 
      "cm_mmc=banap|", 
      "cm_mmc=viral|",
      "cm_mmc=socialm"
    ],
    idx = 0;
    
    for (idx in tags) {
      if (a_param.indexOf(tags[idx]) !== -1) {
        return getCMTagValues(a_param);
      }
    }
    return false; //none matched, so drops off
  },

  /* To be used, to directly report values 
   * variables to be used:
   * var aCustomInclient = { channel: "", source: "", group: "", detail: ""};
   */
  inclientCustom = function (a_referrer, a_url, a_param) {
    if (typeof aCustomInclient !== "undefined") {
      return aCustomInclient;
    }
  },

  getAllSegmentMethods = function () {
    return [inclientNatural, inclientTagger, inclientCustom];
  };

  YAHOO.util.Event.onDOMReady(function () {
    SKYPE.inclient.Acquisition.segment(the_referrer, the_url, the_param);
  });

  return {

    //SKYPE.inclient.Acquisition.segment();
    segment: function (a_referrer, a_url, a_param) {

      var f_referrer = (a_referrer || the_referrer).toLowerCase(),
      f_url          = (a_url || the_url).toLowerCase(),
      f_param        = (decodeURIComponent(a_param || the_param)).toLowerCase(),
      all_segment    = getAllSegmentMethods(),
      segment        = null,
      sucess         = false, 
      i;

      for (i = 0; i < all_segment.length; i = i + 1) {
        segment = all_segment[i](f_referrer, f_url, f_param);
        if (segment && isSegmentValid(segment) && segment.channel !== "") {
          sucess = inClientReport(segment.channel, segment.source, segment.group, segment.detail);
          break;
        }
      }

      return ((sucess) ? "channel:" + segment.channel + ";source:" + segment.source +
              ";group:" + segment.group + ";detail:" + segment.detail : false);
    }
  };
}());
