/* File displays the following:-
 *
 * 1. ShareASale tracking
 * 2. PMG tracking
 * 3. Commission Junction tracking
 * 4. Linkshare pixel tracking
 * 5. Bing AdCenter tracking
 * 6. Google adwords rev pixel tracking
 * 7. Webgains tracking
 *
 * ShareAshare details :-
 *
 * For each Order that has AssociatedStore matching ShareAshare produce an img
 * tag.  
 *
 * Linkshare details :-
 *
 * For each Order that has AssociatedStore matching linkshare produce an img
 * tag.  
 *
 * The image tag contains
 * BeforeTax Amount for the Order
 * a '|' delimited list of skus       of the LineItems
 * a '|' delimited list of Quantities of the LineItems
 * a '|' delimited list of Prices     of the LineItems
 *
 * */

jQuery.fn.affiliateThankYou = function() {
  var merchAffiliate = function() {};

  merchAffiliate.initialize = function() {
    this.callAffiliate();
  },

  merchAffiliate.callAffiliate = function() {
      
    var shareASaleId;
    if (jQuery("#shareASaleId").attr("value")) {
      shareASaleId = jQuery("#shareASaleId").val();
    }

    var cjId;
    var cjActionId;
    if (jQuery("#cjId").attr("value")) {
      cjId = jQuery("#cjId").val();
    }
    if (jQuery("#cjActionId").attr("value")) {
      cjActionId = jQuery("#cjActionId").val();
    }

    var pmgId; 
    if(jQuery("#pmgId").attr("value")){
      pmgId=jQuery("#pmgId").val();
    }

    var linkShareID;
    if(jQuery("#linkShareId").attr("value")){
      linkShareID=jQuery("#linkShareId").val();
    }

    var google_conversion_id;
    if(jQuery("#googleAdwordsId").attr("value")){
      google_conversion_id= jQuery("#googleAdwordsId").val();
    }

    var webgainsId; 
    if(jQuery("#webgainsId").attr("value")){
      webgainsId= jQuery("#webgainsId").val();
    }

    var adCenterId; 
    if(jQuery("#adCenterId").attr("value")){
      webgainsId= jQuery("#adCenterId").val();
    }

    var orders = amznAnalytics.getList("multiOrderPurchase");
    if(orders && orders.length > 0) {
      for(var i = 0; i < orders.length ; i++) {
        var orderID = orders[i].orderId;
        var currency = "USD";
        if(amznAnalytics.getElement("language") == "en_GB") {
            currency = "GBP";
        }
        var totalRevenue = orders[i].orderPrice;
        var totalRevenueWithoutPromoAmount = parseFloat(totalRevenue);
        var totalPromoAmount = 0;
        /* Promotions except free shipping promotions */
        var promotions = amznAnalytics.getList("promotions");
        if ( promotions ) {
          for ( var index=0 ; index < promotions.length ; index ++ ) {
            var promoCode = promotions[index]['code'].toString() ;
            if (promoCode && ! promoCode.match(/shipping/i) && promotions[index]['amount'] > 0 ) {
              totalRevenueWithoutPromoAmount -= promotions[index]['amount'];
              totalPromoAmount += promotions[index]['amount'];
            }
          }
          totalRevenueWithoutPromoAmount = totalRevenueWithoutPromoAmount.toFixed(2);
          totalPromoAmount = totalPromoAmount.toFixed(2);
        }
        var skuList = [];
        var qtyList = [];
        var priceList = [];
        for(var i2 = 0; i2 < orders[i].itemList.length; i2 ++) {
          skuList.push(orders[i].itemList[i2].SKU);
          qtyList.push(orders[i].itemList[i2].quantity);
          priceList.push(orders[i].itemList[i2].revenue);
        }

        // Share a sale
        if(shareASaleId){
          var scsstring ="<img src=\"https://shareasale.com/sale.cfm?amount=" + totalRevenue + "&tracking=" + orderID + "&transtype=sale&merchantID=" + shareASaleId + "\" width=\"1\" height=\"1\">"; 
          jQuery('body').append(jQuery(scsstring)); 
        }

        // Commission Junction
        if(cjId) {
          var cjstring = "<img src=\"https://www.emjcd.com/u?AMOUNT=" + totalRevenue + "&CID=" +cjId+ "&OID=" + orderID + "&TYPE="+cjActionId+"&CURRENCY=" + currency + "&METHOD=IMG\" height=\"1\" width=\"1\">";
          jQuery('body').append(jQuery(cjstring));
        }

        // PMG
        if(pmgId){
          jQuery('body').append(jQuery('<iframe frameborder="0" height="1" width="1" scrolling="no" src="https://dys.pmg2.me/track/?STORE='+pmgId+'&CURRENCY='+ currency + '&OID=' + orderID +'&SUBTOTAL='+totalRevenue+'"></iframe>' ));
        }

        // Linkshare
        if(linkShareID){
          var discountString = "";
          var discountAmount = "";
          var qtyDiscountString = "";
          if(promotions && promotions.length > 0) {
            discountString = "|Discount";
            discountAmount = "|" + totalPromoAmount;
            qtyDiscountString = "|0";
          }
          jQuery('body').append(jQuery('<img src="https://track.linksynergy.com/ep?mid=' + linkShareID + '&ord=' + orderID  + '&skulist=' + skuList.join("|") + discountString + '&qlist=' + qtyList.join("|") + qtyDiscountString + '&amtlist=' + priceList.join("|") + discountAmount + '"' + ' width="1" height="1">'));
        }

        // Adcenter
        if(adCenterId) {
          if (!window.mstag) 
            mstag = {loadTag : function(){},time : (new Date()).getTime()};
          jQuery('body').append("<sc" + "ript id=\"mstag_tops\" type=\"text/javascript\" src=\"//flex.atdmt.com/mstag/site/" + adCenterId + "/mstag.js\"></script>");
          mstag.loadTag("conversion", {cp:"5050",dedup:"1"});
          jQuery('body').append("<iframe src=\"//flex.atdmt.com/mstag/tag/" + adCenterId + "/conversion.html?cp=5050&dedup=1\" frameborder=\"0\" scrolling=\"no\" width=\"1\" height=\"1\" style=\"visibility:hidden;display:none\"> </iframe>");
        }

        // Webgains
        if(webgainsId) {
          var wgLang = amznAnalytics.getElement("language");
          var wgsLang = "javascript-client";
          var wgVersion="1.1";
          var wgProgramID=5694;
          var wgOrderReference=orderID;
          var wgOrderValue=totalRevenue;
          var wgEventID=webgainsId;
          var wgSubDomain="track";
          var wgComment="";
          var wgCheckSum = "";
          if(location.protocol.toLowerCase() == "https:") wgProtocol="https";
          else wgProtocol="http";

          wgUri = wgProtocol + "://" + wgSubDomain + ".webgains.com/transaction.html" + "?wgver=" + wgVersion + "&wgprotocol=" + wgProtocol + "&wgsubdomain=" + wgSubDomain + "&wglang=" + wgLang + "&wgprogramid=" + wgProgramID + "&wgeventid=" + wgEventID + "&wgvalue=" + wgOrderValue + "&wgchecksum=" + wgCheckSum + "&wgorderreference="  + wgOrderReference + "&wgcomment=" + escape(wgComment) + "&ref=" + escape(document.referrer);
          jQuery('body').append('<sc'+'ript language="JavaScript"  type="text/javascript" src="'+wgUri+'"></sc'+'ript>');
          jQuery('body').append("<img src=\"https://track.webgains.com/transaction.html?wgprogramid=5694&wgvalue=" + totalRevenue + "&wgeventid=" + webgainsId + "&wgorderreference=" + orderID+ "\" alt=\"\" width=\"1\" height=\"1\" />");
        }

        // Google Adwords
        if(googleAdwordsId) {
          var google_conversion_language = amznAnalytics.getElement("language");
          var google_conversion_format = "3";
          var google_conversion_color = "ffffff";
          var google_conversion_label = "Purchase";
          var google_conversion_value = totalRevenue;
          jQuery('body').append(jQuery('<script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js" />')); 
        }
      }
    }


  }
  merchAffiliate.initialize();
};
//invoke popovers on page load
jQuery(window).load(function(){
  jQuery(document).affiliateThankYou();
});


