function callserver(url){ 
  headElement = document.getElementsByTagName("head").item(0); 
  var script = document.createElement("script"); 
  script.setAttribute("type", "text/javascript"); 
  script.setAttribute("src",url); 
  headElement.appendChild(script); 
}

function getcurrentvideos() {
  var rnd = (new Date()).getTime();
  var file = 'http://static.utopianvision.co.uk/scripts/current-videos.js?rnd='+rnd;
  callserver(file);
}

function displaycurrentvideos(obj) {
  var numperrow = 3;
  var i;
  var html = '';
  html += '<div class="beingwatched" style="width: 100%;"><table cellpadding="0" cellspacing="2" width="100%">';
  for(i = 0; i < obj.length;i++) {
    if((i % numperrow) == 0) {
      html += '<tr>';
    }
    var title = ''+obj[i].title+ ' (Duration: '+obj[i].duration+')';
    title = title.replace(/</g,'&lt;');
    title = title.replace(/>/g,'&gt;');
    var esctitle = title.replace(/['"]/g,'\\\1');
    html += '<td align="center" class="minicap"><div class="videoitem vidwrap vidwrap80" style="margin: 0px auto 4px auto;"><a href="/bollywood/videos/?v='+obj[i].vid+'" title="'+title+'"><img src="'+obj[i].thumbnail_url+'" width="80" height="45" class="img" alt="'+title+'"><span class="videotimewrap"><span class="videotime" title="Duration">'+obj[i].duration+'</span></span></a></div></td>';
    if((i % numperrow) == (numperrow-1)) {
      html += '</tr>';
    }
  }
  html += '</table></div>';
  var div = document.getElementById('beingwatched');
  if(div) {
    div.innerHTML = html;
    if(window.addVideoThumbs) {
      addVideoThumbs('.beingwatched .videoitem');
    }
  }
  vid_timer_count = 100;
  last_vid_update = (new Date()).getTime();
}

function currentvideosresponse(request) {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var text = request.responseText;
      var ob = document.getElementById('beingwatched');
      if(ob) {
        ob.innerHTML = text;
        vid_timer_count = 100;
        last_vid_update = (new Date()).getTime();
      }
    }
  }
}

function updatevidtimer() {
  if(vid_timer_count >= 0) {
    var ob = document.getElementById('vidtimer');
    if(ob) {
      ob.style.width = vid_timer_count+'%';
    }
    vid_timer_count--;
  }
  if(vid_timer_count == 0) {
    getcurrentvideos();
  }
}

function stopvidtimer() {
  if(vid_timer) {
    clearInterval(vid_timer);
  }
}

function startvidtimer() {
  stopvidtimer();
  vid_timer = setInterval('updatevidtimer()',400);
}

function checkvidupdated() {
  if(vid_timer_count == -1) {
    var now = (new Date).getTime();
    if((now - last_vid_update) > (60*1000)) {
      getcurrentvideos();
    }
  }
}

var vid_timer_count = 100;
var vid_timer = null;
var last_vid_update = (new Date()).getTime();
startvidtimer();
setInterval('checkvidupdated()',10000);
