var myDest="";

document.onload= new function () {
_gaUtil = new gaUtils('mla.com.au'); // change to www.mla.com.au in production

// Uncomment the following line to turn on debug messages
//_gaUtil.SetDebug(true);

}


// Preserve the earliers Silhouette functions so that link tracking doesn't require substantial rework
function ni_LoadUrl(url, title, trigger)
{  
  // not title and trigger are no longer used in GA
  //TODO check whether window.title is settable
  var oldTitle = document.title;
  document.title = title;
  _gaUtil.TrackLink(url,false);
  document.title = oldTitle;
}


// no user servicable parts below this line
///// gaUtils object
// (c) 2009 Panalysis Pty Ltd all rights reserved www.panalysis.com
// licensed to Meat & Livestock Australia
// for alterations and support regarding this script please contact support@panalysis.com
// Version 1 - 15-12-2009


// Start GAUtils object
function gaUtils(d)
{
  // private property declarations
  var bDomain ="";
  var bDebug = false;
  var bTrackExternalDomains = false;
  var bTrackLinkID = false;
  var dTypes = new Array(".pdf",".doc",".docx",".xls",".xlsx",".exe",".zip",".rtf",".jpg",".png",".gif",".tiff",".tif",".mp3",".wav",".swf",".mpg");
  var bHasFormInteraction = 0;
  var bIsMember = 0;
  
  if(d != "")
    bDomain = d;
  
  // Public method declarations
  
  // SetBaseDomain (string domain) - sets the base domain from which to identify external links
  this.SetBaseDomain = _gaSetBaseDomain;
  
  // SetDebug(bool) - turn on alerts when sending data to Google Analytics
  this.SetDebug = _gaSetDebug;
  
  // TrackLink(string path, bool opens in same window ) - tracks the click on the link and records this as a page in Google Analytics
  this.TrackLink = _gaTrackThis; 
  
  // AddDownloadType(string ext) - adds a new document to the list of downloads to track.
  this.AddDownloadType = _gaAddDownloadType;
  
  // TrackLogin(string status) - tracks the login attempts of the user
  this.TrackLogin = _gaTrackLoginStatus;
  
  // initialisation
  var cDomain = document.location.hostname.toLowerCase();
  // split the domain into its component parts
  var dp = cDomain.split(".");
  if(bDomain == "")
  {
    if(dp[dp.length-1].length==2 && dp.length>=3)
      bDomain = dp[dp.length-3] + "." + dp[dp.length-2] + "." + dp[dp.length-1]; // set to the current domain including country code
    else if(dp[dp.length-1].length>=3)
      bDomain = dp[dp.length-2] + "." + dp[dp.length-1]; // assume .com, .info, etc
  }
  
  if(document.location.hash.indexOf('debug')>=0)
    _gaSetDebug(true);
    
  var bannerParams = new Array('ac');
  
  // set up link tracking
  _gaInitLinks();
  
  // is the user a member?
  _gaTestMember();
  
  // check whether the click is from a tagged link
  _gaCheckBannerClick(bannerParams);
  
  // check any form commencements
  _gaTrackFormStart();
  
  // check any login events
  if(typeof(_galoginStatus) != "undefined")
    _gaTrackLoginStatus(_galoginStatus);
  
  // if the variable _gauserseg exists set a visitor level custom variable
  if(typeof(_gavisitorseg) != "undefined")
    _gaSetCustomSegment(_gavisitorseg);
  
  // _gaSetDebug(bool) - turns on or off debug mode
  function _gaSetDebug(val)
  {
    bDebug = val;
  }
  
  // _gaSetBaseDomain(string domain) - sets the base domain from which to determine whether a link is external or not
  function _gaSetBaseDomain(val)
  {
    bDomain = val;
    _gaInitLinks();
  }
  
  // _gaTrim - trims leading and trailing whitespace
  function _gATrim(val){ return val.replace(/^\s+|\s+$/g, '') ; }
  
  // _gaInitLinks - scan the DOM and associate an onclick handler for each link based on its content
  function _gaInitLinks()
  {
    var mL = document.getElementsByTagName("a");
    var myRegexp = /^http[s]?:\/\/(.*)/;
    for(var i=0;i<mL.length;i++)
    {
      var myRef = mL[i].href.toLowerCase();
      if(myRef == undefined)
        continue;
        
      var myMatch = myRegexp.exec(myRef);
      var lchar = myRef.substring(myRef.length-1);
      if((lchar=="#" && mL[i].onclick != "") || (myMatch != undefined && myMatch.length>1 && bDomain != undefined && myRef.indexOf(bDomain) < 0))
      {
        _gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); });
      }
      else
      {
        for(x=0;x<dTypes.length;x++)
        {
          if(myRef.indexOf(dTypes[x])>-1 && self.pageTracker)
          {
            if(mL[i].target != "")
              _gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); });
            else
              _gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,true); return false;});
              
            _gaAddEvent(mL[i],"mouseup",function (e) { _gaCheckRightClick(e,this); });
          }
        }
      }
    }
  }

  // _gaTrackThis(string path,bool has target attribute) - records clicks on pdf and other links. 
  // If the target is the same window, then dwell for 1/2 second before redirecting user.
  function _gaTrackThis(t,r)
  {
    myDest = t;
    var myMatch = myDest.match(/^http[s]?:\/\/(.*)/);
    if(myMatch && myDest.indexOf(bDomain) < 0)
    {
      t = "/outbound/" + myMatch[1];
    }
    else
      t = t.replace(/http[s]?:\/\/[^\/]*/,"");
  
    if(self.pageTracker)
    {
      if(bDebug==true)
        alert(t);
      pageTracker._trackPageview(t);
    }
    
    
    if(r==true)
    {
      setTimeout("document.location.href=myDest;",500); // delay for 1/2 second
      return false;
    }
    else
      return true;
  }

  // _gaCheckRightClick(event,object) - tests for the right mouseclick event
  function _gaCheckRightClick(e,o)
  {
    var button;
    // determine which button was clicked.
    if (e.which == null)
      /* IE case */
      button= (e.button < 2) ? "LEFT" : ((e.button == 4) ? "MIDDLE" : "RIGHT");
    else
      /* All others */
      button= (e.which < 2) ? "LEFT" : ((e.which == 2) ? "MIDDLE" : "RIGHT");
    
    // tracking the right mouse click isn't accurate as we can't reliably get whether the link was clicked. 
    if(button=="RIGHT")
    {
      _gaTrackThis(o.href,false);
    }
  }
  
  // _gaTrackFormStart() - records the start of a form when the user has entered a value into any text field
  function _gaTrackFormStart()
  {
    if(document.forms.length>0)
    {
      for(i=0; i<document.forms.length;i++)
      {
        var f = document.forms[i];
        var tf=0;
        // if the form has an action in the specified list of forms to track then add it
        
        if(typeof(_gaformlist) != "undefined")
        {
          for(var a=0; a<_gaformlist.length; a++)
          {
            try
            {
              if(_gaformlist[a].toLowerCase()==f.action.toLowerCase())
                tf=1;
              else if(_gaformlist[a].toLowerCase()==f.name.toLowerCase())
                tf=1;
              else if(_gaformlist[a].toLowerCase()==f.id.toLowerCase())
                tf=1;
            }
            catch (err) {}
          }
        }
        if(f.className=="formtrack" || tf==1)
        {
          flist = f.elements;
          for(var l=0; l<flist.length; l++)
          {
            var fEl = flist[l];
            try
            {
              if(fEl.type.toLowerCase()=="text" || fEl.type.toLowerCase()=="textarea")
              {
                _gaAddEvent(fEl,"keypress",function() { _gaTestInput(this);});
              }
            }
            catch(err) {}
          }
        }
      }
    }
  }
  
  // _gaTestInput(formElement) - tracks the keypress on the form to determine whether the form was started or not
  function _gaTestInput(fID)
  {
    if(fID.value  != undefined && fID.value.length>0 && bHasFormInteraction==0)
    {
      var d ="?";
      var u = document.location.pathname;
      if(document.location.search !="")
      {
        u += document.location.search;
        d="&";
      }
      
      if(typeof(urchinTracker) !="undefined")
      {
        if(bDebug==true)
          alert("Urchin: " + u + d + "formstarted=1");
        urchinTracker(u + d + "formstarted=1");
      }
      
      if(typeof(pageTracker)  !="undefined")
      {
        if(bDebug==true)
          alert("pageTracker: " + u + d + "formstarted=1");
        pageTracker._trackPageview(u + d + "formstarted=1");
      }
      bHasFormInteraction=1;
    }
  }
  
  // _gaTrackLoginAttempt(status) - tracks the login actions of the user
  // status expected values:
  //  Success - user has successfully logged in
  //  Error - user has not logged in and has received an error
  //  PasswordReset - user has requested a password reset
  
  function _gaTrackLoginStatus(s)
  {
    var cn = '_galgc';
    var lgc = _gaGetCookie(cn);
    var isLoggedIn = 0;
    var numErrors = 0;
    var isPasswordReset = 0;
    
    if(lgc != "")
    {
      if(lgc.substring(0,1)=="1")
        isLoggedIn="1";
      if(lgc.substring(1,2)=="1")
        isPasswordReset = "1";
      numErrors = parseInt(lgc.substring(2));
    }
    
    switch(s.toUpperCase())
    {
      case "SUCCESS":
        isLoggedIn="1";
        break;
      case "ERROR":
        isLoggedIn = 0;
        numErrors ++;
        break;
      case "PASSWORDRESET":
        isPasswordReset = "1";
        break;
    }
    
    lgc = "" + isLoggedIn + isPasswordReset + numErrors;
    _gaSetCookie(cn,lgc,0,"");
    
    // record events
    try
    {
      if(s.toUpperCase()=="ERROR")
      {
        if(bDebug==true) { alert('Event: login-error'); }
        pageTracker._trackEvent('login','login-error');
      }
      else if(isPasswordReset=="1")
      {
        if(bDebug==true) { alert('Event: login-reset'); }
        pageTracker._trackEvent('login','login-reset');
      }
      else if(isLoggedIn=="1")
      {
        if(bDebug==true) { alert('Event: login-success'); }
        pageTracker._trackEvent('login','login-success',"errors",numErrors);
      }
    }
    catch(err){}
  }
  
  // _getHashParam - retrieves the a query parameter from the document hash
  function _gaGetHashParam(strParam){
    if(strParam =="")
      return "";
    var _pstr = document.location.hash.substring(1);
    var _uparams = _pstr.split("&");
    for(var i = 0; i < _uparams.length; i++){
      var np = _uparams[i].split("=");
      if(_gATrim(np[0].toLowerCase()) == strParam.toLowerCase())
      {
        return _gATrim(np[1]);
        break;
      }
    }
    return "";
  }
  
  // _gaGetParam - retrieves the a query parameter from the document URL
  function _gaGetParam(strParam){
    var _pstr = document.location.search.substring(1);
    var _uparams = _pstr.split("&");
    for(i = 0; i < _uparams.length; i++){
      var np = _uparams[i].split("=");
      if(_gATrim(np[0].toLowerCase()) == strParam.toLowerCase())
        return _gATrim(np[1]);
    }
    return "";
  }
  
  // _gaSetCookie(string Name, string Value, String Expire Days, String Domain) - sets a cookie
  function _gaSetCookie(cookieName,cookieValue,nDays,strDomain) {
    var today = new Date();
    var expire = new Date();
    var pdm = "";
    if (strDomain && strDomain!="") 
      pdm=" domain="+strDomain+";"; 
    else if(self._udn)
      pdm=" domain="+_udn+";";
      
    
    //if (nDays==null || nDays==0) nDays=1;
    if(nDays>0)
    {
      expire.setTime(today.getTime() + 3600000*24*nDays);
      document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + "; path=/;" + pdm;
    }
    else
      document.cookie = cookieName+"="+escape(cookieValue) + "; path=/;" + pdm;
  }

  // _gaGetCookie - retrieves a cookie from a name
  function _gaGetCookie(strParam){
    var _ucookies = document.cookie.split(";");
    for(i = 0; i < _ucookies.length; i++){
      var np = _ucookies[i].split("=");
      if(_gATrim(np[0].toLowerCase()) == strParam.toLowerCase())
      {
        var val ="";
        for(i=1;i<np.length;i++)
        {
          if(i>1)
            val += "=";
          
          val += np[i];
        }
        return _gATrim(val);
      }
    }
    return "";
  }
  
  // _gaTestMember - checks whether there is a im variable in the URL or whether the variable ismember is set as a Javascript variable
  function _gaTestMember()
  {
    var utmv = _gaGetCookie('__utmv');
    if(utmv != "" && utmv.indexOf('member')>0)
    {
      bIsMember=1;
      return true;
    }

    var isM =0;
    if(typeof('_galoginStatus') != "undefined")
    {
      try
      {
        if( _galoginStatus.toUpperCase()=="SUCCESS")
          isM=1;
      }
      catch(err) { }
    }
    if(typeof('_gaismember') != "undefined")
    {
      try
      {
        if( _gaismember == 1)
          isM=1;
      }
      catch(err) { }
    }
    
    var mq = _gaGetParam('im');
    if((mq != "" && mq.toLowerCase().indexOf('guest')<0) || isM==1 )
    {
      bIsMember=1;
      try
      {
        if(typeof(pageTracker) != "undefined")
        {
          if(bDebug)
            alert("Member: Yes");
          pageTracker._setCustomVar(1,"member","yes",1);
        }
      }
      catch(err) {}
    }
  }
  
  // _gaAddDownloadType(string t) - appends a new download type to the list
  function _gaAddDownloadType(t) 
  {
    if(t != "")
    {
      if(t.substr(0,1) != ".")
        t = "." + t;
      dTypes[dTypes.length] = t;
    }
  }
  
  // _gaCheckBannerClick(array str) - custom banner tracking
  function _gaCheckBannerClick(paramList)
  {
    for(i=0; i<paramList.length; i++)
    {
      var p = paramList[i];
      var b = _gaGetParam(p);
      var c = _gaGetHashParam(p);
      if(b != "" || c != "")
      {
        if (b=="")
          b = c; 
        
        if(bDebug)
          alert("Banner/Link: " + b);
        // set a page level custom variable to record the banner clicks
        pageTracker._setCustomVar(2,"banner",b,3);
        // record an event to ensure that the click is tracked
        pageTracker._trackEvent("Banners",b);
      }
    }
  }
  
  // _gaSetCustomSegment(string segmentName) - sets a custom variable to identify visitor segments
  function _gaSetCustomSegment(seg)
  {
    try
    {
      pageTracker._setCustomVar(3,"visitorsegment",seg,1);
    }
    catch(err) {}
  }
  
  // _gaAddEvent - adds an event to the DOM. Correctly handles the pointer for "this"
  function _gaAddEvent( obj, type, fn ) {
    if ( obj.attachEvent ) {
      obj['e'+type+fn] = fn;
      obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
      obj.attachEvent( 'on'+type, obj[type+fn] );
    } else
      obj.addEventListener( type, fn, false );
  }
  
  // _gaRemoveEvent - removes an event from the DOM
  function _gaRemoveEvent( obj, type, fn ) {
    if ( obj.detachEvent ) {
      obj.detachEvent( 'on'+type, obj[type+fn] );
      obj[type+fn] = null;
    } else
      obj.removeEventListener( type, fn, false );
  }
}

