var article_id,linkauthor,startHour,totalSec;
//var artStats = new ArtStats();


// Submit data as an outofbound call
function SubmitData(async,postdata)
{
  try
  {
    xmlRequest = new XMLHttpRequest();     
  }
  catch (e)
  {
    try
    { xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (err)
    { alert("AJAX error: "+err.description)
      return;
    }
  }  
  
  xmlRequest.open("POST","http://www.articles.co.il/artajax.php",async);
  xmlRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  xmlRequest.setRequestHeader("Content-length", postdata.length);    
  
  xmlRequest.send(postdata);    

  return xmlRequest.responseText;

}

// Calc elapsed time article was viewed
function stopWatch(start)
{  
  var d = new Date();

  if (start==1)
  {        
    startHour = d.getHours();
    totalSec= startHour*3600+d.getMinutes()*60+d.getSeconds();    
    
    return;
  }

  var h = d.getHours();

  if (h<startHour)
   if (startHour>12)
    h=h+24;
   else
    h=h+12;

  totalSec = (h*3600+d.getMinutes()*60+d.getSeconds())-totalSec;
  if (totalSec>600)
   totalSec=600;

  var postdata = "stats=dur&article_id="+encodeURI(article_id)+"&sec="+encodeURI(totalSec);
  SubmitData(false,postdata);

  
}

// Monitor users' clicks
function ClickedOnLink()
{  
  
  var link=this.href;

  // check if link is to user's profile
  if (this.href==undefined)
  { link="userprofile";
  }
  else 
   if (link.match(linkauthor)!=null)
     link="userprofile";
  

  var postdata = "stats=linkto&article_id="+encodeURI(article_id)+"&link="+encodeURI(link);
  SubmitData(true,postdata);
   
}

function ArtStats()
{ this.initStats = initStats;  
}

// initialize statistics collection object
function initStats(a,l)
{ 

  article_id = a;
  linkauthor = l;  
  document.body.onbeforeunload = stopWatch;

  stopWatch(1);

 // Collect relevant anchors to monitor
 
 var artContent = document.getElementById("article-content");
 var profLinks = document.getElementById("user_profile");

 var artlinks=artContent.getElementsByTagName("a"); 
 var proflinks=profLinks.getElementsByTagName("a");  

 for (i=0; i<artlinks.length; i++) 
 { 
   artlinks[i].onclick = ClickedOnLink;
   

 }

 for (i=0; i<proflinks.length; i++) 
 { 
   proflinks[i].onclick = ClickedOnLink;
   
 }
 
 // Check if article was referred from a link on another page
 var ref=document.referrer;

 if (ref!="")
 {
  
  var postdata = "stats=linkfrom&article_id="+encodeURI(article_id)+"&link="+encodeURI(ref);
  SubmitData(true,postdata);

 }

 
} // end initStats()
