// We should find a better way to make this map for the future, but I am putting it directly in here for now. 

var dash_seen = Cookie.get('DASH_SEEN');

 var dashboard_el = {
  "FOUNDATION FINDER" : [
    "Dashboard -  Foundation",
    "Main"
  ],
  "MY SKIN CONSULTATION" : [
    "Dashboard -  Skin Consultation",
    "Main"
  ],
  "MY CONSULTANT" : [
    "Dashboard -  My Consultant",
    "Main"
  ],
  "MY HOW TO" : [
    "Dashboard -  How to Engine",
    "Main"
  ],
  "LIVE CHAT EMAIL" : [
    "Dashboard -  Live Chat",
    "Email Consultant Form"
  ],
  "MY PAST PURCHASES" : [
    "Dashboard -  Past Purchases",
    "Main"
  ],
  "MY NEWS" : [
    "Dashboard -  News",
    "Main"
  ],
  "ASK AN EXPERT PRE CHAT" : [
    "Dashboard -  Live Chat",
    "Pre Chat Form"
  ],
  "A MESSAGE FROM CLINIQUE" : [
    "Dashboard -  Main",
    "Main"
  ],
  "ASK AN EXPERT" : [
    "Dashboard -  Live Chat",
    "Main"
  ],
  "NEED HELP?" : [
    "Dashboard - Help",
    "Main"
  ]
}; 

var cm2data;
    

// Endeca
// Helper functions for CoreMetrics
// Called when we first start processing a response from the server.
// Can/should be used to init data for this page view.
var endeca_tags={};

var ecatCmBeginProcessing = function() {

   endeca_tags['pcount'] = 0;
   endeca_tags['ccount']=0;
   endeca_tags['term']='';
   endeca_tags['filter_list']=  ''; 
   endeca_tags['current_page']=0;
   endeca_tags['page_count']=0;
}

// Set current search term for CM.
// "sterm" is the search term (string).
var ecatCmSetSearchTerm = function(sterm) {
       //console.log("TERM ",sterm);
   endeca_tags['term'] = sterm;
 
}

// Add another filter name to the CM list of filters.
// Will be called once for each filter used in the request.
// "fname" is the value of the filter.
var ecatCmAddFilter = function(dim,fname) {
      //console.log("Filter list ",fname,dim);
      //console.log("Existing Filters ", endeca_tags['filter_list']);
   var sf = {
      "Skin Type" : "Typ",
      "Skin Tone" : "Ton"
  };
  if (typeof sf[dim] != "undefined"){
    dim = sf[dim];
       //console.log("SF ran",dim);
  }else{
    var filter_words = dim.split(' ');
         //console.log("filter words ", filter_words); 
       if (filter_words.size() > 1){
            dim = filter_words[0].substr(0,3);
            for (i=1; i<=filter_words.size() - 1;i++){
              dim = dim + filter_words[i].substr(0,1);
            } 
       }else{
          dim = dim.substr(0,3);
       }
  } 
   if (fname){
      if (endeca_tags['filter_list'].length > 1 ){
        endeca_tags['filter_list'] = endeca_tags['filter_list'] +' > '+ dim + ':'+ fname;
       }else{
       endeca_tags['filter_list'] = dim + ':' +fname;
       }
   } 
}

// Called when we know how many results we have.
// Indicates total number of products and content items found.
var ecatCmResultCount = function(countProducts,countContent) {
   endeca_tags['pcount'] = countProducts;
   endeca_tags['ccount'] = countContent;
  console.log("ccount ", countContent);
  console.log("pcount ", countProducts);
}

// Called to indicate which page we're on and how many total pages.
var ecatCmPageNumber = function(currentPage,totalPages) {
   endeca_tags['current_page']=currentPage;
   endeca_tags['page_count']=totalPages;

}

// Called when we're done processing results.
// Can/should be used to send the actual page view tag
// using the data provided by the above calls.
var ecatCmFinishProcessing = function() {
  var page_count = endeca_tags['current_page'] || '1';
  var PAGE_ID = 'Search Results ' + page_count;
  //if (page_count < 1 && endeca_tags['ccount'] == 0){
   //   PAGE_ID = PAGE_ID + " BestSellers";
  //}
  if (endeca_tags['filter_list'].length > 0){
      PAGE_ID = 'Search Results Filtered ' + page_count;
  }
  var CATID = '2200';
  var KEYWORDS = endeca_tags['term'];

   if (endeca_tags['ccount'] > 0 && endeca_tags['pcount'] == 0){
           KEYWORDS = '*' + KEYWORDS;
   }

  var RESULTS = endeca_tags['ccount'] + endeca_tags['pcount'] || '0';
  
  cmCreatePageviewTag(PAGE_ID, KEYWORDS,CATID,RESULTS,endeca_tags['filter_list']);
   

}

var ecatCmContentClick  = function() {
  cmCreatePageElementTag("CONTENT", "SEARCH DROPDOWN");
}
var ecatCmProductClick = function() {
 cmCreatePageElementTag("PRODUCTS", "SEARCH DROPDOWN");
} 
var ecatCmSeeAll = function() {
  cmCreatePageElementTag("SEE ALL","SEARCH DROPDOWN");
}

// end Endeca


    //SHOP5 Tags      
    document.observe('cart:modify', function (obj) {
         if (typeof obj.memo.result.cm_tags != "undefined"){
             eval (obj.memo.result.cm_tags);
         }
    });


    // Works with and Similar products

    document.observe('recommendWidget:loaded',function(evt){
            var ww_el = $('works_well_wrapper').select('dd');
            var sim_el = $('similar_wrapper').select('dd.add a');
             
             cm2data = GlobalCatProdData.data._object.product.all;
         //console.log(cm2data[2].url);
    });



    // Dashboard Element tags
    document.observe('accordion:onBeforeExpand',function(evt){
       var proto_element = $(evt.element() ) ;
        //console.log("Opened ",proto_element.down("a").innerHTML);
          var a = proto_element.down("a").innerHTML;
          var el_tag = dashboard_el[a];  
         
       if (typeof(el_tag) != "undefined"){
          if ( a.match("CLINIQUE") ){
                 //console.log("main open");
               //if ( ( dash_seen ==null ) && (location.pathname == "/") ){
             if ( ( dash_seen ==null ) && ( (location.pathname == "/") || (location.pathname =="/index.tmpl") || (location.pathname=="/setcountry/index.tmpl")) ){
                   //skip
                  }else{
                     cmCreatePageviewTag("My Clinique Dashboard", null, "5000", null);
                      //cmCreatePageElementTag("Main","Dashboard -  Main");
                  }
           }
             if ( (el_tag[1].length > 3) ){
                if ( ( dash_seen ==null ) && ( (location.pathname == "/") || (location.pathname =="/index.tmpl") || (location.pathname=="setcountry/index.tmpl")) ){
                    
                    //skip
                  }else{
                     cmCreatePageElementTag(el_tag[1],el_tag[0]);
                  }
              }
            // console.log(el_tag[1]);
       }
             // console.log(dashboard_el[a]);
            dash_seen = Cookie.get('DASH_SEEN'); 
    });

//Jeremy's search function
var findFirstTextNode = function(ele) {
    var textAccum = '';

	if (ele.hasChildNodes()) {
		for (var i=0, len=ele.childNodes.length; i<len; i++) {
			if (ele.childNodes[i].nodeType === 3) { // test for

				textAccum = textAccum + ele.childNodes[i].nodeValue;
			} else if (ele.childNodes[i].nodeType === 1) { //

				return findFirstTextNode(ele.childNodes[i]);
			}
		}
	}
     return textAccum;
};

var cmSearchElements = function(evt){
 
   if (evt != "undefined"){
     cmEvent = evt.target;
     attrs = evt.target.attributes; // what attribtes do you check?
      cmText = findFirstTextNode(cmEvent);
         //    console.log("TEXT ",cmText);



    for (var cmInc=0, l=cm_elData.length; cmInc<l; cmInc++){
               //Loop on attr and check values where they match
             if (cmText == cm_elData[cmInc].text){
//                 console.log("MATCH text ",cmText);
                 return cm_elData[cmInc].tag;
              }
        

       for (var attrInc=0, len=attrs.length; attrInc<len; attrInc++) {
         if (typeof attrs[attrInc].nodeName != "undefined" && typeof attrs[attrInc].nodeValue != "undefined"){
                //     console.log(attrs[attrInc].nodeName);

             if (attrs[attrInc].nodeName  == "href" && attrs[attrInc].nodeValue.match(cm_elData[cmInc].src) && cm_elData[cmInc].src != "undefined" ){
//                 console.log("MATCH href VALUE ",attrs[attrInc].nodeValue);
                 if ( attrs[attrInc].nodeValue == "#"){
                   return "undefined";
                 }

                 return cm_elData[cmInc].tag;
             }
             if (attrs[attrInc].nodeName == "alt" && cm_elData[cmInc].alt == attrs[attrInc].nodeValue){ 
//                 console.log("Alt is ",attrs[attrInc].nodeValue);
                 return cm_elData[cmInc].alt;

             }
             if (attrs[attrInc].nodeName == "src" && cm_elData[cmInc].src == attrs[attrInc].nodeValue && cm_elData[cmInc].src != "undefined"){
//                 console.log("src MATCH is ",attrs[attrInc].nodeValue);
                 return cm_elData[cmInc].tag;
             }
              if (attrs[attrInc].nodeName == "src" && attrs[attrInc].nodeValue.match(cm_elData[cmInc].src) && cm_elData[cmInc].src != "undefined" ){
       //          console.log("src MATCH2 is ",cm_elData[cmInc].src,attrs[attrInc].nodeValue);
       //          return cm_elData[cmInc].tag;
             }

             if (attrs[attrInc].nodeName == "value" && cm_elData[cmInc].text == attrs[attrInc].nodeValue){
//                 console.log("MATCH Value is ",attrs[attrInc].nodeValue);
                  return cm_elData[cmInc].tag;
 
             }

//           console.log("got some value ",attrs[attrInc].nodeValue, " Data ",  cm_elData[cmInc].src);



         }
       }
    }
  }
};




var cmEvent = '';  

cm_elData = [
  {"src" : "liveperson",
   "tag" : [
      "Dashboard -  Live Chat",
      "Pre Chat Form"
    ]
  },
  {
    "id_or_parent" : "db-my-purchases-content",
    "src" : "/templates/user/account/purchases.tmpl",
    "tag" : [
      "Dashboard -  Past Purchases",
      "View All Results"
    ]
  },
  {
    "src" : "/templates/user/account/orders.tmpl",
    "class" : "db-my-orders-container",
    "tag" : [
      "Dashboard -  News",
      "Order Details"
    ]
  },
  {
    "id_or_parent" : "special_offers",
    "src" : "/landing/freeship.tmpl",
    "tag" : [
      "Dashboard -  News",
      "Offer Details"
    ]
  }
];


document.observe("dom:loaded", function() {

  Event.observe(document.body, 'click', function(event) {
  // First element from event source with 'container' among its CSS classes
if (typeof event != "undefined"){
 cmEvent = event.target;
 cmAttrs = event.target.attributes; // what attribtes do you check?

    try {
       firstDiv = cmEvent.up('.def_sidebar'); // if defined then we are in the dashboard; 
       if (typeof firstDiv != "undefined"){
    //      console.log(" target ",cmEvent," attributes ", cmAttrs, "First Div ",firstDiv  );
          var tagData = cmSearchElements(event); 

//         console.log("TAG DATA " ,tagData);
         if (typeof tagData != "undefined"){ 
           cmCreatePageElementTag(tagData[1],tagData[0]);
         }
       }
    }
    catch(err)
     {
       console.log(err);
     }

}

});

});


 

 














 
 
