var ERROR_DECAY = 3000;
var POLL_INT_1  = 10000;
var POLL_INT_2  = 10000;
var updateSpeed1 = POLL_INT_1; //for hour metrics
var updateSpeed2 = POLL_INT_2; //for content / refferers etc

var siteId;
//var ajaxEp = 'http://localhost/wtastats/statsInterface.aspx';
var ajaxEp = 'http://stats.webtrafficagents.com/statsInterface.aspx';
var LastPeriodDeltas;

//gets the online count + hour max,min,ave,uv & raw
function getDeltaStats(){
    if (_period)
    {
        if(_period == 0)
            runAjax(ajaxEp, 'i=' + siteId + '&r=2', onDeltaStatsRec);
        else if(_period == 1)
            runAjax(ajaxEp, 'i=' + siteId + '&r=8', onDeltaStatsRec);
        else
            runAjax(ajaxEp, 'i=' + siteId + '&r=9', onDeltaStatsRec);
    
    }else{
           runAjax(ajaxEp, 'i=' + siteId + '&r=2', onDeltaStatsRec);
    }
}

//receives object with values now update
function onDeltaStatsRec(obj){
     if(obj.Error){
      showError(obj.Error);
      SetOnineLabel(0);
      document.getElementById('lblOnlineAve').innerHTML = '0';
      document.getElementById('lblOnlineMax').innerHTML = '0';
      document.getElementById('lblOnlineMin').innerHTML = '0';
      document.getElementById('lbVisits').innerHTML = '0';
      document.getElementById('lblUniques').innerHTML = '0';
      document.getElementById('lbPagesViewed').innerHTML = '0';
    }else{
      try
       {
        SetOnineLabel(obj.OL);
        document.getElementById('lblOnlineAve').innerHTML = addCommas(obj.AV);
        document.getElementById('lblOnlineMax').innerHTML = addCommas(obj.MX);
        document.getElementById('lblOnlineMin').innerHTML= obj.MI;
        document.getElementById('lbVisits').innerHTML = addCommas(obj.RV);
        document.getElementById('lblUniques').innerHTML = addCommas(obj.UV);
        document.getElementById('lbPagesViewed').innerHTML = addCommas(obj.PV);
    
        setGraphHourOnline(obj.OL);
        showHourChangeDeltas(obj);
      }catch(e){}
      
      if(obj == null) {
        updateSpeed1 = updateSpeed1 + ERROR_DECAY;
        showError("Coms failed,call again in " + updateSpeed1 + " s");
        }
      else
         updateSpeed1 = POLL_INT_1;     
      
      setTimeout(getDeltaStats,updateSpeed1);
 
    }

}

function getContentStats(){
    runAjax(ajaxEp, 'i=' + siteId + '&r=4', onContentStatsRec);
}


//create  top content stats
function onContentStatsRec(obj){

if(obj.Error){
     showError(obj.Error);
    }else{
        var html = '';
         
         try
         {      
            if(obj.items){ 
               SetOnineLabel(obj.online);           
              for(var i=0;i<obj.items.length;i++){
                 if(obj.items[i].count > 0){
                    html+= "<div class='top-item'>" +
                       "<div class='count' >" + obj.items[i].count + "</div>" + 
                       "<div class='top-tag'><a target='_blank'  href='" + "http://" + obj.domain + obj.items[i].pageUrl + "'>" + 
                       "<span onmouseover=\"this.innerHTML='" + trimStr("http://" + obj.domain + obj.items[i].pageUrl,40) + "';\" " + 
                       " onmouseout=\"this.innerHTML='" + trimStr(obj.items[i].pageTitle,40) + "';\" >" + 
                       trimStr(obj.items[i].pageTitle,40) + "</span></a></div></div>";
                   }
                 }
                 
                 if(obj.items.length > 0)
                 html+="<br><div class='feed' ><a href='onlinedetail.aspx?s=" + siteId + "'>View users Details</a>&nbsp;<div>";
             }
           
           document.getElementById('topItems').innerHTML = html;
           
           }catch(e){}
           
       if(obj == null) {
        updateSpeed2 = updateSpeed2 + ERROR_DECAY;
        showError("Coms failed,call again in " + updateSpeed2 + " s");
        }
      else
        updateSpeed2 = POLL_INT_2;     

           setTimeout(getContentStats,updateSpeed2);
   
    }
}
//-------------------------------------------------------------------------------------------------
function getCurrentCountries(){
  runAjax(ajaxEp, 'i=' + siteId + '&r=3', onCurrentCountriesRec);
}

function onCurrentCountriesRec(obj){

if(obj.Error){
   showError(obj.Error);
    }else{
        var html = '';
         try
         {      
            if(obj.items){ 
                 SetOnineLabel(obj.online);            
              for(var i=0;i<obj.items.length;i++){
                 if(obj.items[i].count > 0){
                    html+= "<div class='top-item'>" +
                       "<div class='count' >" + obj.items[i].count + "</div>" + 
                       "<div class='top-tag'>" +
                       "<img src='http://www.webtrafficagents.com/flags/"+ 
                       obj.items[i].countryISO2 +".gif' />&nbsp;"+ 
                       initCap(obj.items[i].countryName) +"</div></div>";
                   }
                 }
                 
                 if(obj.items.length > 0)
                  html+="<br><div class='feed' ><a href='onlinedetail.aspx?s=" + siteId + "'>View users Details</a>&nbsp;<div>";
              }
           
           document.getElementById('topItemCountries').innerHTML = html;
           
           }catch(e){}
           
       if(obj == null) {
        updateSpeed2 = updateSpeed2 + ERROR_DECAY;
        showError("Coms failed,call again in " + updateSpeed2 + " s");
        }
      else
        updateSpeed2 = POLL_INT_2;     

           setTimeout(getCurrentCountries,updateSpeed2);
   
    }
}

//-------------------------------------------------------------------------------------------------
//gets a detail list of current visitors
function getCurrentVisitors(){ 
  runAjax(ajaxEp, 'i=' + siteId + '&r=6', onCurrentVisitorsRec);
}

function getCurrentVisitorsInit(sid)
{    siteId = sid;
     getCurrentVisitors();
}


//returns an array of current visitors
function onCurrentVisitorsRec(obj){
var ico; var alt;var html='';var img='';

if(!obj || obj.Error){
    if(obj && obj.Error) showError(obj.Error);
   SetOnineLabel(0);
}else{
  try{      
       if(obj.items){
          SetOnineLabel(obj.online);
          for(var i=0;i<obj.items.length;i++){
                  if(obj.items[i].source == 2){
                    ico = "i/icon_web.gif";
                    alt = "visitor referred to site by another website,Pro accounts can navigate to link";
                    img = "<a  target=_blank href='" + obj.items[i].refererUrl + "'><img border='0' alt='" + alt + "' title='" + alt + "' width='50px' height='50px' src='" + ico + "' /></a>"; 
                  }else if(obj.items[i].source == 3){
                    ico = "i/icon_seo.gif";
                    alt = "visitor referred to site by Search Engine";
                    img = "<a  target=_blank href='" + obj.items[i].refererUrl + "'><img border='0' alt='" + alt + "' title='" + alt + "' width='50px' height='50px' src='" + ico + "' /></a>"; 
                 }else{
                    ico = "i/icon_design.gif";
                    alt = "visitor entered site url directly into browser";
                    img = "<img alt='" + alt + "' title='" + alt + "' width='50px' height='50px' src='" + ico + "' />"; 
                  }

                html+= "<div class='view-row'><div class='dur'>" +
                       formatDuration(obj.items[i].secondsOnline) + "</div>" +
                       "<div class='browser'><img height='32' width='32' src='i/" + obj.items[i].browser + ".gif' /></div>" +
                       "<div class='page-view top-tag'><a target='_blank'  href='" + "http://" + obj.domain + obj.items[i].pageUrl + "'>" + 
                       "<span onmouseover=\"this.innerHTML='" + trimStr("http://" + obj.domain + obj.items[i].pageUrl,50) + "';\" " + 
                       " onmouseout=\"this.innerHTML='" + trimStr(obj.items[i].pageTitle,50) + "';\" >" + 
                       trimStr(obj.items[i].pageTitle,50) + "</span></a></div>" +
                       "<div class='country'><img src='http://www.webtrafficagents.com/flags/"+ obj.items[i].countryISO2 +".gif' />&nbsp;"+ 
                       initCap(obj.items[i].countryName) +"&nbsp;(<a href='http://www.ipget.net/sites/" + obj.items[i].ip + "'>" + obj.items[i].ip +"</a>)&nbsp;"  +
                       displayEst(obj.items[i]) +
                       "</div>" + 
                        "<div class='visit'>" + getReturnVisitImage(obj.items[i].visits) + "</div>" +
                       "<div class='route'>" + img  + "</div>" +
                       "<div class='seo'>" + (obj.items[i].keyWords.length>0?  obj.items[i].keyWords : "")  + "</div>" +
                       "</div>";
                }
             
     }else{
       SetOnineLabel(0);
     }
     
     document.getElementById('lblUsers').innerHTML = html;
  
  }catch(e){ showError(e);}
  
       if(obj == null) {
        updateSpeed1 = updateSpeed1 + ERROR_DECAY;
        showError("Coms failed,call again in " + updateSpeed1 + " s");
        }
      else
         updateSpeed1 = POLL_INT_1;    
    
    setTimeout(getCurrentVisitors,updateSpeed1);
   
 }
}

function getReturnVisitImage(c){
if (c > 0)
 return "<img height='15px' width='11px' align='absmiddle' src='i/r.gif' title='" + c + " previous visits' alt='" + c + " previous visits'/>";
else
return "<img height='15px' width='17px' align='absmiddle' src='i/n.png' title='This Visitor is Absolutely Unique(new visitor to this site)' alt='This Visitor is Absolutely Unique(new visitor to this site)'/>";
}


//displays a reader 
function displayEst(ro){

if(ro.action)
{
return "<a href='#' class='tt'><img border='0' alt='Get Help on this' align='absmiddle' src='i/est.png' />"+
        "<span class='tooltip'><span class='top'></span>" +
        "<span class='middle'>&nbsp;<img border='0' alt='est' align='absmiddle' src='i/eSalesTracking158x25.png' /><br />" +
        "<hr /><table width='100%'>" +
        "<tr><td ><b>Event Desc:</b></td><td><b>" + ro.action + "</b></td></tr>" +
        "<tr><td><b>Orgional Referer:</b></td><td >" + ro.refererUrl + "</td></tr>" +
        "<tr><td><b>Event Value:</b></td><td style='font-size:11pt;'>" + ro.actionValue + "&nbsp;" + ro.actionCcy +  "</td></tr>" +
        "</table></span><span class='bottom'></span></span></a>";
// return "<img height='25px' width='41px' align='absmiddle' src='i/est.png' title='eSalesTracking -" + ro.action + "' alt='eSalesTracking -" + ro.action + "'/>";
}else{
return "";
}
}

//-------------------------------------------------------------------------------------------------



function getStats(sid)
{
    siteId = sid;
    getDeltaStats();
    getContentStats();
    getCurrentCountries();
    getTrafficSource();
}


//sets the now element in the hour graph online righr now
function setGraphHourOnline(online){
 var xct = 24;
try
{ 
  if(_xCount) xct = _xCount;

   //get the json data object and set to our new value
   data['elements'][1]['values'][xct]['value'] = online;

  //we need to check that the max on our graph is not less than this online number
  if(online > _yMax){
      data['y_axis']['max'] = online;
      data['y_axis']['steps'] = parseInt(online/8);
  }else{
     data['y_axis']['max'] = _yMax;
     data['y_axis']['steps'] = parseInt(_yMax/8);
  }
  //now reload the json chart data      
  tmp = document["my_chart"];
  x = tmp.load( JSON.stringify(data));

}catch(e){}

}

function getTrafficSource(){ 
  runAjax(ajaxEp, 'i=' + siteId + '&r=14', onTrafficSourceRec);
}


function onTrafficSourceRec(obj){
var values = "";
if(obj.Error){
   showError(obj.Error);
  SetOnineLabel(0);
}else{
  try{      
       if(obj.items){
          SetOnineLabel(obj.online);
          for(var i=0;i<obj.items.length;i++){
            //create values and labels  
              values += "{\"value\":" + obj.items[i].count + ", \"label\": \"" + obj.items[i].source + "\" },";
            }
            
             if (values.length > 0)
                values = values.substring(0, values.length - 1);
                  
          
        var  jsonData = "{\"elements\":" +
                   "[ { \"type\": \"pie\"" +
                   ",\"alpha\":0.7" +
                   ",\"animate\": [ " +
                   "{ \"type\":\"fade\" }" +
                   ",{\"type\":\"bounce\"" + 
                   ",\"distance\":5}"+ 
                   "]" +
                   ",\"tip\": \"#label# #val# (#percent#)\"" +
                   ",\"start-angle\":0" +
                   ",\"colours\": [ \"#d01f3c\", \"#356aa0\", \"#C79810\" ]" +
                   ",\"values\": [" + values + "]" +
                   "}]" +
                   ",\"title\": { \"text\": \"\", \"style\": \"color: #f0f0f0; font-size: 20px\"}" +
                   ", \"bg_colour\": \"#ffffff\" }";
          
          
           tmp = document["source_chart"];
            //x = tmp.load( JSON.stringify(data));
            x = tmp.load( jsonData);
          
         }

        
      }catch(e){}
           
       if(obj == null) {
        updateSpeed2 = updateSpeed2 + ERROR_DECAY;
        showError("Coms failed,call again in " + updateSpeed2 + " s");
        }
      else{updateSpeed2 = POLL_INT_2;}     

      setTimeout(getTrafficSource,updateSpeed2);

 }
}


//calc and shows the change deltas, against the previous period
function  showHourChangeDeltas(obj)
{ 
    if(LastPeriodDeltas)
    {
        setDelta(LastPeriodDeltas.RV,obj.RV,'lbVisitsChg',true);
        setDelta(LastPeriodDeltas.UV,obj.UV,'lblUniquesChg',true);
        setDelta(LastPeriodDeltas.PV,obj.PV,'lbPagesViewedChg',true);
        setDelta(LastPeriodDeltas.MX,obj.MX,'lblOnlineMaxChg',false);
        setDelta(LastPeriodDeltas.MI,obj.MI,'lblOnlineMinChg',false);
        setDelta(LastPeriodDeltas.AV,obj.AV,'lblOnlineAveChg',false);
    }
}

//weights previous period delta
function setDelta(last_x,now_x,spanId,weight){
   var x2 = 100;var x1 =0;
  // alert('lt=' + last_x + ',now=' + now_x);
  if(weight){
      var d = new Date();
       if(_period == 0){
            x1 = (last_x/60)* d.getMinutes();
        }else if (_period ==1){
            x1 = (last_x/1440)* ((d.getHours()*60)+ d.getMinutes());
       }else if (_period ==2){
            x1 = (last_x/1440)* ((d.getHours()*60* d.getDate()) + d.getMinutes());
       }
            x2 = ((now_x-x1)/x1)*100;
       
       
   }else{
     x2 = last_x > 0 ?((now_x-last_x)/last_x)*100 : 100;
   }
   
   if(x2 > 1000) x2=1000;
   
   if(last_x == now_x){
     document.getElementById(spanId).innerHTML = "<img alt='no change' src='i/arrow_blue_left.gif' align='absmiddle' />";
   }else if (x2 > 0){
     document.getElementById(spanId).innerHTML = "<span class='delta-pos'>" + 
     "+" + roundNumber(x2,2) + "%&nbsp;<img alt='rising' src='i/arrow_green_up.gif' align='absmiddle' /></span>";
   }else{
     document.getElementById(spanId).innerHTML = "<span class='delta-neg'>" + 
     roundNumber(x2,2) + "%&nbsp;<img alt='falling' src='i/arrow_red_down.gif' align='absmiddle' /></span>";
     }
}



//----------------------------------------------------------------------------------------------------------------

function createXHR() { var xhrObj; if (window.XMLHttpRequest) {try {xhrObj=new XMLHttpRequest();}catch(e){xhrObj = null;}}else if (window.createRequest){try {xhrObj = window.createRequest();}catch(e){xhrObj=null;}}else if(window.ActiveXObject){try{xhrObj=new ActiveXObject("Msxml2.XMLHTTP");} catch(e){try{xhrObj = new ActiveXObject("Microsoft.XMLHTTP");}catch(e){xhrObj = null;}}}return xhrObj;}

function runAjax(url,qs,callback) {
      var xhr = createXHR();
      /* Inner function to bind handler and create closure */
      function bindCallback() {
          if (xhr.readyState == 4) {
              try {
                  if (xhr.status == 200)
                    callback( eval('(' +  xhr.responseText + ')') );
                 else{
                     showError("Status error:" + xhr.status)
                     callback(null);
                     }
             } catch (e) { showError(e);callback(null);
            }
         }
     }
                
     if (xhr) {
         try {
             xhr.onreadystatechange = bindCallback;
             xhr.open('GET', url + '?u=' + (Math.random()*Math.random()) + '&' + qs, true);
             xhr.send(null);
         } catch (e) {
             showError(e);callback(null);
        }
     }
 } //eof runAjax
 
 
 function runAjaxNOJSON(url,qs,callback) {
      var xhr = createXHR();
      /* Inner function to bind handler and create closure */
      function bindCallback() {
          if (xhr.readyState == 4) {
              try {
                  if (xhr.status == 200)
                    callback( xhr.responseText );
                 else{
                     showError("Status error:" + xhr.status)
                     callback(null);
                     }
             } catch (e) { showError(e);callback(null);
            }
         }
     }
                
     if (xhr) {
         try {
             xhr.onreadystatechange = bindCallback;
             xhr.open('GET', url + '?u=' + (Math.random()*Math.random()) + '&' + qs, true);
             xhr.send(null);
         } catch (e) {
             showError(e);callback(null);
        }
     }
 } //eof runAjax
 
 
//--------------------------------------------------------------------------------------------------
 function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {x1 = x1.replace(rgx, '$1' + ',' + '$2');}
	return x1 + x2;
}


function trimStr(s,l){
 var j = s.length > l?l:s.length;
 return s.substr(0,j);
}

function roundNumber(num, dec) {return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);}

function initCap(s){
 var res = "";
 if(s!= null){  
 var w = s.split(' ');
 for(var i=0;i<w.length;i++)
    res += w[i].substring(0,1).toUpperCase() + w[i].substring(1).toLowerCase() + " ";
 }
return res;
}


function formatDuration(num){
 if(num>60){
    var m =  parseInt(num/60) ;
    var s =  num - (m * 60);
        
    return "<span class='dnum'>" + m + "</span><span class='dv'>m</span><span class='dnum'>" + (s < 10 ? "0" + s : s) + "</span><span class='dv'>s</span>";
 }else{
     return "<span class='dnum'>" +  num + "</span><span class='dv'>s</span>";
 }
}

function SetOnineLabel(n){
 var r="";
    if(n==1)
     r+= "<span class='olCount'>" + n + "</span><span class='olUser'>&nbsp;user online</span>";
    else if(n>1)
     r+= "<span class='olCount'>" + addCommas(n) + "</span><span class='olUser'>&nbsp;users online</span>";
    else 
    r+= "<span class='olUser'>No&nbsp;users online</span>";
   
    document.getElementById('lblOnlineCt').innerHTML = r;
}

//ajax fail  - 
function showError(e)
{
  document.getElementById('errorInf').innerHTML = e;

}


//--------------------------------------------------------------------------------------------

function pageTS(siteId,actionId,range,sort,page){
   var qs = 'i=' + siteId + '&r=15' + "&a=" + actionId + "&sr=" + range + "&p=" + page + "&st=" + sort;
   runAjaxNOJSON(ajaxEp, qs, onpageTSRec);
}

function onpageTSRec(obj){
   try{ document.getElementById('trafficSources').innerHTML = obj; }catch(e){}
}

function showActionLink(siteId,actionId,selActionId,range){
    var qs = 'i=' + siteId + '&r=16' + "&a=" + actionId + "&sr=" + range + "&sa=" + selActionId;
    runAjax(ajaxEp, qs, onshowActionLinkRec);
}

function onshowActionLinkRec(obj){
    document.getElementById('actionLinkPc').innerHTML = obj.pc;
    document.getElementById('actionLinkSel').innerHTML = obj.html;
}

function showActionGraph(siteId,actionId,range,graphType){
  var qs = 'i=' + siteId + '&r=17' + "&a=" + actionId + "&sr=" + range + "&agt=" + graphType;
  runAjax(ajaxEp, qs, onshowActionGraphRec);
}

function onshowActionGraphRec(obj){
  document.getElementById('graphLabel').innerHTML = obj.label;
  tmp = document["my_chart"];
  x = tmp.load( obj.data);
}