// Call from end of page.
// Customizable values

//global variables - these values are used in the id of the container div.
var utProductPrefix = "P_";
var utCategoryPrefix = "C_";
var utRetailerPrefix = "R_";
var utAdPositionPrefix = "S_";
var utEcommPrefix = "E_";
var utVariableDelimiter = "-ut";
var utSpaceDelimiter = "_";
var utAdClassName = "ad"; //the name of class of the html element that should contain our ads.
var tsaSiteID = 313;
var tsaWaypointID = 1006;

/ 1: onload add-event scripting, for all browsers

if(typeof window.attachEvent != 'undefined')
{
   //.. win/ie
   window.attachEvent('onload', ut_ad_init);
}
else if(typeof window.addEventListener != 'undefined')
{
   //.. gecko, safari, konqueror and standard
   window.addEventListener('load', ut_ad_init, false);
}
else if(typeof document.addEventListener != 'undefined')
{
   //.. opera 7
   document.addEventListener('load', ut_ad_init, false);
}
//** remove this condition to degrade older browsers
else
{
   //.. mac/ie5 and anything else that gets this far
   //if there's an existing onload function
   if(typeof window.onload == 'function')
   {
      //store it
      var ut_existing = onload;
      //add new onload handler
      window.onload = function()
      {
         //call existing onload function
         ut_existing();
         //call adsense_init onload function
         ut_ad_init();
      };
    }
    else
    {
      //setup onload function
      window.onload = ut_ad_init;
    }
}

// 2: Add the initialization code to track ad clicks.

function ut_ad_init () {
   //deal with ads in iframes
   if (document.all){  //ie specific iframe handling
      var ut_el = document.getElementsByTagName("iframe");
      for(var i = 0; i < ut_el.length; i++) {
         ut_el[i].onfocus = ut_ad_click;
      }//end for loop
   }//end if document.all
   else{   //call the mozilla/firefox code
      window.addEventListener('beforeunload', ut_doPageExit, false);
      window.addEventListener('mousemove', ut_getMouse, true);
   }
   
   //deal with ads in plain links - should work with all browsers
   var ut_anchors = document.getElementsByTagName("a");
   for(var i = 0; i < ut_anchors.length; i++) {
      ut_anchors[i].onclick = ut_ad_click;
   }//end loop through anchor tags on page

}//end ad_init function

/*
The ut_ad_click function looks for an html element that is 'surrounding' the ad that has a class equal to the 
*/
function ut_ad_click(e){
   var e = (e) ? e : ((window.event) ? window.event: null);
   if(e){//if there was an event
   
   //this will hold the reference to the html element that was the target of the click(or event)
   var ut_targ = (e.target) ? e.target : e.srcElement;
   
   //create variable placeholders
   var ut_product;
   var ut_category;
   var ut_retailer;
   var ut_position;
   var ut_ecomm;
   
   var ut_adElement; //placeholder for the HTML element that holds the actual ad (an iframe or a tag)
   var ut_productDivFound = false;
   var ut_curr = ut_targ;
   
   //start looking at the dom tree
   while(ut_productDivFound != true){//loop through the event caller's parent nodes till you hit a container with the correct class. try to get the ad itself along the way
      if(!(ut_adElement) && (ut_curr.tagName == "A" || ut_curr.tagName == "IFRAME" || ut_curr.tagName == "a" || ut_curr.tagName == "iframe")){//if ut_adElement is not already set, and this is an a tag or iframe
         ut_adElement = ut_curr;//set the ut_adElement to this one
      }

                if(typeof ut_curr.getAttribute != 'undefined') { 
         if(ut_curr.getAttribute("class") == utAdClassName || ut_curr.getAttribute("className") == utAdClassName){//if this div's class attribute is 'ad'
            ut_productDivFound = true;
            break;
         }
         else if(ut_curr.parentNode){
            ut_curr = ut_curr.parentNode; //go up to the next level in the DOM tree\\
         }
         else {
            break;
         }
                } else {
                     break;
                }
   }//end while
   
   if(ut_adElement.src){//the ad is in an iframe
      if(ut_adElement.src.indexOf('googlesyndication.com') > -1){ ut_retailer="adsense";}
//      else if(ut_adElement.src.indexOf('rcm.amazon.com') > -1){ ut_retailer="amazon";}
//      else if(ut_adElement.src.indexOf('shopping.com') > -1){ ut_retailer="shopping";}
      else {return;}
   }
   else if(ut_adElement.href){//the ad is in an 'a' tag
      if(ut_adElement.href.indexOf('shopping.com') > -1){ ut_retailer="shopping";}
      else if(ut_adElement.href.indexOf('googlesyndication.com') > -1){ ut_retailer="adsense";}
//      else if(ut_adElement.href.indexOf('dealtime.com') > -1){ ut_retailer="shopping";}
//      else if(ut_adElement.href.indexOf('qksrv.net') > -1){ ut_retailer="ebay";}
//      else if(ut_adElement.href.indexOf('bizrate.com') > -1){ ut_retailer="bizrate";}
//      else if(ut_adElement.href.indexOf('amazon.com') > -1){ ut_retailer="amazon";}
      else {return;}
   }
   else{return;}
   
   if(ut_productDivFound == true){//if we have found the productDiv
      
      var urchinTrackerString; //will hold the ultimate virtual url that is passed to the urchinTracker() call
      
      //parse out our variables
      var ut_adDivId;
      if(ut_curr.getAttribute("id")){//browser supports getAttribute() method
         ut_adDivId = ut_curr.getAttribute("id");
      }
      else if(ut_curr.id != null){//browser does not support getAttribute Method
         ut_adDivId = ut_curr.id;
      }
      
      //split up the variables
      var ut_varArray = ut_adDivId.split(utVariableDelimiter);
      
      for(i=0; i < ut_varArray.length; i++){//loop through the variables in the array
         //get the next variable
         var ut_tempVar = "" + ut_varArray[i];
         //test to see which variable this is
         if(ut_tempVar.indexOf(utProductPrefix) != -1){//this is the product variable
            //extract and set the product variable
            ut_product = ut_tempVar.substring(ut_tempVar.indexOf(utProductPrefix) + utProductPrefix.length);
         }
         else if(ut_tempVar.indexOf(utCategoryPrefix) != -1){//this is the category variable
            //extract and set the category variable
            ut_category = ut_tempVar.substring(ut_tempVar.indexOf(utCategoryPrefix) + utCategoryPrefix.length);
         }
         else if(ut_tempVar.indexOf(utRetailerPrefix) != -1){//this is the retailer variable
            //extract and set the retailer variable
            ut_retailer = ut_tempVar.substring(ut_tempVar.indexOf(utRetailerPrefix) + utRetailerPrefix.length);
         }
         else if(ut_tempVar.indexOf(utAdPositionPrefix) != -1){//this is the ad position variable
            //extract and set the position variable
            ut_position = ut_tempVar.substring(ut_tempVar.indexOf(utAdPositionPrefix) + utAdPositionPrefix.length);
         }
         else if(ut_tempVar.indexOf(utEcommPrefix) != -1){//this is the ecomm variable
            //extract and set the ecomm variable
            ut_ecomm = ut_tempVar.substring(ut_tempVar.indexOf(utEcommPrefix) + utEcommPrefix.length);
         }
         
      }//end loop through the variables in the array

   }//end if product div was found
   else{//product div was not found
      //TODO: handle this case
   }
   if(ut_retailer){
      //call the urchinAdTracker with the variables
      urchinAdTracker(ut_retailer, ut_product, ut_position, ut_ecomm);
        tsaAdTracker(false, tsaSiteID, tsaWaypointID, ut_retailer);
   }
      
   }//end if - there was an event
}//end ut_ad_click function

function urchinAdTracker(ut_retailer, ut_product, ut_position, ut_ecomm){
   var utString = "/ads"+ escape(window.location.pathname) +  "/"; //build the base url -- Change this as you see fit
   
   //check to make sure that the variables are set
   if(ut_retailer != null && ut_retailer != "undefined" && ut_retailer != ""){//if retailer is set, add it 
      utString += "" + ut_retailer + "/";
   }
   if(ut_product != null && ut_product != "undefined" && ut_product != ""){//if product is set, add it 
      utString += "" + ut_product + "/";
   }
   if(ut_position != null && ut_position != "undefined" && ut_position != ""){//if position is set, add it 
      utString += "" + ut_position + "/";
   }
   if(ut_ecomm != null && ut_ecomm != "undefined" && ut_ecomm != ""){//if position is set, add it 
      //call the ecomm method
      urchinEcommTracker(ut_ecomm, ut_product, ut_retailer);
   }
   //call urchinTracker
   urchinTracker("" + utString);
}

function tsaAdTracker(aSecureFlag, aSiteID, aWaypointID, aProductID)
{
    if (aSiteID && aWaypointID) {
        var url = 'http';
        if (aSecureFlag) utl += 's';
        url += '://thesearchagency.net/tsawaypoint.php?siteid='+aSiteID+'&wayid='+aWaypointID;

        if (aProductID) {
            url += ('&prodid='+aProductID);
        }
        var head = document.getElementsByTagName('head').item(0);
        var js = document.createElement('script');
        js.setAttribute('language', 'javascript');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', url);
        head.appendChild(js);
    }
}


// ecommerce values 
**********************************************/
function urchinEcommTracker(ut_ecomm, ut_product, ut_retailer){
   //get current time, make it the unique id
   var dateObj = new Date();
   var transid = dateObj.getTime();
   var ecomm_val = (ut_ecomm/100);

var ecommString = "<form style=\"display:none\" name=\"utmform\">\n<textarea id=\"utmtrans\">\n" +
"UTM:T|" + transid + "||"+ ecomm_val +"|||||\n" +
"UTM:I|" + transid + "||" + ut_product + "|" +  ut_retailer + "|" + ecomm_val + "|1\n" +
"</textarea></form>"
   
   //get a reference to the <body> element
   var contDiv = document.getElementById("topad");
   var newdiv = document.createElement('div');
   newdiv.innerHTML = ecommString;
   //alert(newdiv.innerHTML);
   contDiv.appendChild(newdiv);
   __utmSetTrans();
}

// 3: Mozilla/Firefox Iframe Handling

var ut_px;
var ut_py;

function ut_getMouse(e) {
   ut_px=e.pageX;
   ut_py=e.clientY;
}

function ut_findY(obj) {
   var y = 0;
   while (obj) {
      y += obj.offsetTop;
      obj = obj.offsetParent;
   }
   return(y);
}

function ut_findX(obj) {
   var x = 0;
   while (obj) {
      x += obj.offsetLeft;
      obj = obj.offsetParent;
   }
   return(x);
}

function ut_doPageExit(e) {
   //process iframes
   //ad = document.frames;
   ut_ad = document.getElementsByTagName("iframe");
   for (i=0; i<ut_ad.length; i++) {
      var ut_currentAd = ut_ad[i];
      var ut_adLeft = ut_findX(ut_currentAd);
      var ut_adTop = ut_findY(ut_currentAd);
      var ut_inFrameX = ((ut_px > (parseInt(ut_adLeft) - 10)) && (ut_px < (parseInt(ut_adLeft) + parseInt(ut_currentAd.width) + 15)));
      var ut_inFrameY = ((ut_py > (parseInt(ut_adTop) - 10)) && (ut_py < (parseInt(ut_adTop) + parseInt(ut_currentAd.height) + 10)));
      
      if (ut_inFrameY && ut_inFrameX) {
         if(ut_currentAd.src.indexOf('googlesyndication.com') > -1){urchinAdTracker('adsense',"","");}
         else if(ut_currentAd.src.indexOf('rcm.amazon.com') > -1){urchinAdTracker("amazon","","");}
         else if(ut_currentAd.src.indexOf('overture.com') > -1){urchinAdTracker("yahoo","","");}
         //**********add new advertisers here********** (if they are iframes in mozilla)
         /* cut/paste example code:
         else if(ad[i].src.indexOf('advertisername.com') > -1){urchinAdTracker("advertisername');}
         */
         else{
            urchinAdTracker("unknown","","");
         }
         
      }
   }
   
}//end doPageExit function

