/*
 * Analytics support JavaScript that serves as an interim object
 * to Omniture.
 */
var mcgia=function(){
  var pipeline_status=0; // Non-zero when the analytics pipeline executed.
  var marketing_status=0; // Non-zero when the marketing redirect pipeline executed.
  var merchandising_status=0; // Non-zero when the merchandising redirect pipeline executed.
  var analytics_events = new Array();
  var errors = new Array();
  var purchase_products = "";
  var saved_state = {};
  
  this.addPurchaseProduct = function(prod_id,qty,u_price,tax,shipping,discount) {
    var prefix = "";
    
    if( purchase_products !== "" ) {
      prefix = ",";
    }
    
    purchase_products += prefix + ";" + prod_id + ";" + qty + ";" + u_price + ";event3=" + tax + "|event4=" + shipping + "|event5=" + discount;
  };  

  /*
   * sets the campaign (eVar0)
   */  
  this.campaign=function(camp){
    s.campaign=camp;
  };

  this.cartAdd = function(prod_id,qty,bc,promo) {
    this.stateSave();
    this.productlist( ";" + prod_id + ";;;event24=1|event25=" + qty + ";eVar8=" + bc + "|eVar28=" + promo );
    this.distribute(null,{"ev":"scView,scAdd,event1,event24,event25"});   
//    this.stateRestore();
  };

  this.cartOpen = function() {
    this.fireevent("scOpen");
  };
  
  this.cartRemove = function(prod_id,qty) {
    this.productlist(";" + prod_id + ";;;event26=1|event27=" + qty);
  	this.distribute(null,{"ev":"scView,scRemove,event1,event26,event27"});
  };
  
  this.cartView = function(product_list) {
    this.productlist( product_list );
    this.distribute(null,{"ev":"scView,event1"});
  };
  
  this.firedownload = function(link, name)
  {
	  s.tl(link, 'd', name);
  }
  
  /*
   * this.catalog - stores extra information about a particular click on the catalog.
   */
  this.catalog=function(linear,grid,id,type){
    this.setproductcookie(linear,grid);
    
    if ('catalog' != type)
    {
    	this.setproductviewtypecookie(type);
    }
    else
    {
        this.setproductviewtypecookie('Standard'); 	
    }
    
    return this.click(id,'catalog');
  };
  
  this.recomendation=function()
  {
    this.setproductviewtypecookie('Recommendations');
  };

  this.airingnow=function()
  {
    this.setproductviewtypecookie('Airing Now');
  };
  
  /*
   * sets the channel on the provider.
   */
  this.channel=function(ch){
    if (ch == 'Homepage'){
    	s.channel='home';
    	s.prop14='home';
    	s.pageName='home';
    	
        if (typeof lpAddVars == 'function')
        {
        	lpAddVars('page', 'Section', 'home');
        }
    }
    else
    {
    	s.channel=ch;
    }    
  };

  /*
   * clears the product cookie.
   */
  this.clearproductcookie = function() {
    this.eraseCookie("mcgia_product");
  };
    
  this.checkoutStart = function(product_list, shipMethod) {
    this.productlist( product_list );
    this.distribute(null,{"ev":"event1,scCheckout"});
    this.setShippingMethod(shipMethod);
  };
  
  /*
   * adding a checkout function to prevent scCheckout
   * and scView from firing past cart view and cart checkout
   *  
   */
  this.checkoutContinue = function(product_list) {
	  this.productlist(product_list);
	  this.distribute(null,{"ev":"event1"});
  };
  
  /*
   * this.click - creates the analytics cookie.
   */  
  this.click=function(id,type){
    this.createCookie('mcgia',id+'||'+type,30);
    return true;
  };

  /*
   * The following functions are generic cookie handlers.
   * This object should not be dependent on external JavaScript
   * files.
   */
  this.createCookie=function(name,value,days) {
    var expires = "";
    
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      expires = "; expires="+date.toGMTString();
    }
    document.cookie = name+"="+value+expires+"; path=/";
  };

  /*
   * sets customer email
   */
  this.customeremail = function(cemail) {
    s.eVar21 = cemail;
  };
  
  /*
   *  set the coupon
   */
  this.setCoupon = function(coupon) {
	if(s.eVar39 != null && s.eVar39 != "") {
		s.eVar39 += "," + coupon;
	}
	else {
		s.eVar39 = coupon;
	}
  };
  
  this.setUserCoupon = function(coupon) {
		if(s.eVar43 != null && s.eVar43 != "") {
			s.eVar43 += "," + coupon;
		}
		else {
			s.eVar43 = coupon;
		}
	  };

  /*
   * sets the declined MOP
   */
  this.setDeclinedMOP = function(mop) {
	  switch(mop){
	    case 'CREDIT_CARD':
			mop = 'Credit Card';
			break;
		case 'LITLE_BML':
			mop = 'BML';
			break;
		case 'PAYPAL':
			mop = 'PayPal';
			break;
		case 'LITLE_BMLPL':
			mop = 'PA';
			break;
		default:
			mop = mop;
	  }
	  
	  s.eVar35 = mop;
  };
  
  /*
   * sets customer id
   */
  this.customerid = function(cid) {
    s.eVar6 = cid;
  };
  
  /*
   * This sets the shipping method to eVar40
   */
  
   this.setShippingMethod = function(sm) {
     s.eVar40 = sm;
   };
  /*
   * This function is responsible for distributing the configured
   * variables,properties and events into the analytics provider.
   */
  this.distribute=function(id,locations){
    // Do not process null locations.
    if(locations === null) {
      return;
    }
    
    var t;
	var f = new Array();
	
	// Handle properties.
  	if('p' in locations){
  	  t = this.splitlocations(locations.p);
  	  f=f.concat(t);
  	}
  	
  	// Handled variables.
  	if('e' in locations){
  	  t = this.splitlocations(locations.e);
  	  if(t[0]==="eVar0") {
  	    this.campaign(id);
  	  }
      f=f.concat(t);
  	}
  	
  	// Apply the above properties and variables to the analytics provider.
  	for(var x=0;x<f.length;x++){
  	  var i = f[x];
  	  s[f[x]]=id;
  	}
  	
  	// Handle events.
  	if('ev' in locations){
  	  t = this.splitlocations(locations.ev);
  	  
  	  for(var x=0;x<t.length;x++) {
        this.fireevent( t[x] );
  	  }
  	}  
  };

  this.eraseCookie=function(name){
    this.createCookie(name,"",-1);
  };
  
  this.fireerror = function(error) {
	  errors.push(error);
  }
  
  /*
   * Adds an event firing if it doesn't exist.
   */
  this.fireevent = function(event) {
    var current_events = analytics_events;
    var event_to_fire = event;
    var add_event = true;
    
    for( var i = 0; i < current_events.length; i++ ) {
      if( current_events[i] === event_to_fire ) {
        add_event = false;
        break;
      }
    }
    
    if( add_event ) {
      current_events.push( event_to_fire );
      this.events = current_events.join(",");
    }
  };

  /*
   * gets the status
   */
  this.getStatus=function(){
    return pipeline_status;
  };
  
  /*
   * called from any search results page.
   */
  this.search = function() {
    //this.distribute(null,{'ev':'event7'});  Removed due to ARC 15318
	s.channel='estore:search results';
	s.prop14='estore:search results';
	s.pageName='estore:search results';
	
    if (typeof lpAddVars == 'function')
    {
    	lpAddVars('page', 'Section', 'estore:search results');
    }
  };
  
  /*
   * sets hierarchy and a custom variable.
   */
  this.hierarchy=function(h){
  	s.hier1=h;
  	
  	// Also set the product browse path.
  	this.productbrowsepath(h);
  };
  
  /*
   * This function fires a marketing hit.
   */
  this.marketing=function(id,locations){
    this.distribute(id,locations);
  };
  
  /*
   * This function fires a marketing hit.
   */
  this.merchandising=function(id,locations){
    this.distribute(id,locations);
  };
  
  /*
   * Called with the number of search results.
   */
  this.numsearchresults = function(nsr) {
   	s.prop4 = nsr;

    if( nsr <= 0 ) {
      this.fireevent("event28");
    }
    else {
	  this.fireevent("event2");
    }    	
  };
    
  /**
   * sets the pagename on the provider.
   */
  this.pagename=function(pn){
    s.pageName=pn;
    s.eVar41=pn;
  };
  
  this.contenttype=function(ct){
	s.prop14=ct;
	
    if (typeof lpAddVars == 'function')
    {
    	lpAddVars('page', 'Section', ct);
    }
  };

  this.pagetype=function(pt){
  	this.pageType = pt;
  };
  
  this.pagetypeevents=function(events){
    var t = this.splitlocations(events['ev']);
    
    for( var i = 0; i < t.length; i++ ) {
      this.fireevent( t[i] );
    }
  };
  
  /**
   * fires a page view.
   */
  this.pageView=function(pagename){
    s.pageName=pagename;
    this.fireevent("event1");
  };
  
  this.setPaymentMethod = function( pm ) {
  	s.eVar11 = pm;
  };
  
  this.productdetails = function(){
  	this.fireevent("prodView");
  	this.fireevent("event1");
  	this.fireevent("event19");
  };
  this.productdetailsOOS = function(){
  	this.fireevent("prodView");
  	this.fireevent("event1");
  	this.fireevent("event19");
  	this.fireevent("event46");
  };
  
  this.liveViewer = function(){
	  this.pagename('airing now:live');
	  this.channel('airing now');
	  this.fireevent('event1');
	  s.prop14 = 'airing now';
	  
      if (typeof lpAddVars == 'function')
      {
    	lpAddVars('page', 'Section', 'airing now');
      }
  }
  
  this.productbrowsepath = function(path){
    s.eVar14 = path;
  };
  
  this.productfinding=function(type){
    s.eVar23 = type;
  };
  
  this.setCustomShop=function(shopId){
    s.eVar42 = shopId;
  };

  /*
   * this.productlist - sets the product list on the provider.
   */
  this.productlist=function(list){
    s.products = list;
  };
  
  this.product_view_click = function(id,type,vt) {
    this.setproductviewtypecookie(vt);
    this.click(id,type);
  };
  
  /*
   * set the product view type.
   */
  this.productviewtype = function(type){
	  s.eVar23 = type;
	  this.eraseCookie("mcgia_productviewtype");
  };

  this.purchase = function(purchase_products,state,zip,pid,mop,orderid,transactionid) {
    if(typeof(purchase_products) != 'undefined' && purchase_products != ''){
    	this.distribute(null,{"ev":"purchase,event3,event4,event5"});
    	this.productlist( purchase_products );
    	this.state( state );
	    this.zip( zip );
	    this.purchaseID( pid );
	    switch(mop){
		    case 'CREDIT_CARD':
				mop = 'Credit Card';
				break;
			case 'LITLE_BML':
				mop = 'BML';
				break;
			case 'PAYPAL':
				mop = 'PayPal';
				break;
			case 'LITLE_BMLPL':
				mop = 'PA';
				break;
			default:
				mop = mop;
	    }
	    this.setPaymentMethod( mop );
	    this.setOrderID(orderid);
	    this.setTransactionID(transactionid);
    }
  };
  
  this.purchaseID = function( pid ) {
    s.purchaseID = pid;
  };
  
  /*
   * sets the product grid position from the results.
   */
  this.setgridposition = function(gp) {
    s.eVar18 = gp;
  };
  
  /*
   * sets the product linear position from the results.
   */
  this.setlinearposition = function(lp) {
    s.eVar17 = lp;
  };
  
  /*
   * Used to set the status of the marketing pipeline.
   */
  this.setMarketingStatus=function(status){
    marketing_status=status;
  };

  /*
   * Used to set the status of the merchandising pipeline.
   */
  this.setMerchandisingStatus=function(status){
    merchandising_status=status;
  };  
  
  this.setpositioning = function(linear,grid) {
    this.setlinearposition(linear);
    this.setgridposition(grid);
    this.eraseCookie('mcgia_product');
  };
  
  /*
   * sets the product cookie
   */
  this.setproductcookie = function(linear,grid) {
    this.createCookie('mcgia_product',linear+'||'+grid,30);
  };
  
  this.setproductviewtypecookie = function(value) {
  	this.createCookie('mcgia_productviewtype',value,30);
  };
  
  /*
   * Used to get and set the status of the tagging pipeline.
   */
  this.setTaggingStatus=function(status){
    pipeline_status=status;
  };

  /*
   * Splits a comma delimited string into an array.
   */
  this.splitlocations=function(locations){
    if(locations.indexOf(',')==-1){
      return new Array(locations);
    }
    else{
      return locations.split(',');
    }
  };
  
  this.state = function( st ) {
    s.state = st;
  };
  
  /*
   * This function fires a tagging hit.
   */
  this.tagging=function(id,locations){
    this.distribute(id,locations);
  };
   
  this.readCookie=function(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') {
        c = c.substring(1,c.length);
      }
      if (c.indexOf(nameEQ) === 0) {
        return c.substring(nameEQ.length,c.length);
      }
    }
    return null;
  };

  /*
   * this.remove - removes the analytics cookie.
   */
  this.remove=function(){
    this.eraseCookie('mcgia');
  };

  this.searchorigin=function(so){
    s.prop2 = so;
  };

  /*
   * Called when there is a search term to deal with.
   */
  this.searchterm=function(st){
    if( st === null ) {
      s.prop3 = "Not a Search Page";
    }
    else {
      s.prop1=st;
      s.prop3=st;
      s.eVar15=st;
    }
  };
  
  /*
   * Store sort method on Endeca pages.
   * 
   */
   this.addSort=function(sortString){
	   if( sortString === null ) {
		   s.prop18 = "Not a Catalog Page";
	   }
	   else {
		   s.prop18 = sortString;
	   }
   };

  /*
   * restores stored state.
   */
  this.stateRestore = function() {
  
  };
  
  /*
   * saves the state of specific aspects of provider object.
   */
  this.stateSave = function() {
    saved_state = {};
    
	// Remove eVars and props.
	for( var ev = 0; ev < 50; ev++ ) {
		if( ( "eVar" + ev ) in s ) {
			saved_state["eVar"+ev]=s["eVar"+ev];
			delete s["eVar"+ev];
		}
		
		if( ev > 0 ) {
			if( ("prop" + ev) in s ) {
				saved_state["prop"+ev]=s["prop"+ev];
				delete s["prop"+ev];
			}
		}
	}

	if( "products" in s ) { 
		saved_state["products"] = s["products"];
		delete s["products"];
	}

	if( "events" in s ) {
		saved_state["analytics_events"]=analytics_events;
		analytics_events = new Array();
		delete s['events'];
	}
  };
  
  this.writeMacro = function() {
    // add the events fired to the object if there are any.
    if( typeof(analytics_events) != 'undefined' && analytics_events != '' ) {
    	s['events'] = analytics_events;
    }

  	void(s.t());
  };
  this.writeAddCart = function() {
	    // add the events fired to the object if there are any.
	  	s.linkTrackVars='products,events,eVar8,eVar28';
	  	if( typeof(analytics_events) != 'undefined' && analytics_events != '' ) {
	    	s['events'] = analytics_events;
	    	s.events = analytics_events;
	    	s.linkTrackEvents=analytics_events;
	    }
	  	void(s.tl());
	  };
  
  this.cartOrig=function(co) {
	  s.eVar48=co;
  }
	  
  this.url=function(url){
    s.pageURL=url;
  };

  /*
   * this.write - calls the analytics provider write method.
   */
  this.write=function(){
	// always copy s.pageName to s.eVar41
    s.eVar41=s.pageName;
	  
    // always fire event1
    this.fireevent('event1');
    
    var mcidem = this.getParameter('mcidem');
    if (mcidem != '')
    {
    	s.eVar31 = mcidem;
    }
    
    var kwid = this.getParameter('kwid');
    if (kwid != '')
    {
    	this.createCookie('kwid', kwid, 30);
    }
    
    var cm_lm = this.getParameter('cm_lm');
    if (cm_lm != '')
    {
    	s.eVar36 = cm_lm;
    }
    
    // add the events fired to the object if there are any.
    if( this.events != '' ) {
    	s['events'] = this.events;
    }
    
    // Capture all errors displayed to the user
    if (errors != null && errors.length > 0)
    {
    	if (s.pageName != null && typeof(s.pageName) != "undefined")
    	{
    		s.prop17 = s.pageName + " - " + errors.join(", ");
    	}
    	else
    	{
    		s.prop17 = errors.join(", ");
    	}
    }
    
    // Capture the page URL
    s.prop11 = document.location;
    
    var s_code=s.t();if(s_code) {
      document.write(s_code);
    }
    if(this.getStatus()==1){
      this.remove();
    }
  };
  
  this.getParameter=function( name )
  {
	  try
	  {
	    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	    var regexS = "[\\?&]"+name+"=([^&#]*)";
	    var regex = new RegExp( regexS );
	    var results = regex.exec( window.location.href );
	    if( results == null )
	      return "";
	    else
	      return results[1];
	  }
	  catch (e)
	  {
		  return "";
	  }
  }
  
  this.zip = function( zc ) {
    s.zip = zc;
  };
  
  /*
   * set the order id
   */
  this.setOrderID=function(orderid) {
	  s.eVar37=orderid;
  };
  this.setTransactionID=function(transactionid) {
	  s.transactionID=transactionid;
  };
  
  /*
   * Report Credit Card type.
   * Create new s variable for happy sendingness
   */
  this.sendPaymentMethod=function(pm){
	  s = s_gi(s_account);
	  s.linkTrackVars="eVar11";
	  s.eVar11 = pm;
	  s.tl(true,"o","MOP Capture");
  };
  
  /*
   * Reports that a customer has accepted a chat invite
   * from liveperson. This is different from the customer 
   * initiating a chat, because this is when live person pops
   * up and asks the customer if they need help.
   */
  this.chatInviteAccepted=function(){
	  s = s_gi(s_account);
	  s.linkTrackVars="eVar49,prop14,events,channel";
	  s.linkTrackEvents="event1";
	  s.eVar49 = "chat invite";
	  s.prop14="chat";
	  s.channel = "chat";
	  s.events="event1";
	  s.tl(true,"o","chat invite");
  }
};

var mcgia_o=new mcgia();
