var ttwidth = 80;
var ttfullwidth = ttwidth + 10;
var ttlasthtml = '';
var imgratings = new Array('Poor','Not Bad','Good','Great','Amazing');

function getheight() {
  var h = 0;
  if(document.all) {
    h = document.body.offsetHeight;
  }
  return h;
}

function getobj(id) {
  var obj = null;
  if(document.all) {
    obj = document.all[id];
  } else if(document.getElementById) {
    obj = document.getElementById(id);
  }
  return obj;
}

function getscrollleft() {
  var res = null;
  if(window.pageXOffset != null) {
    res = window.pageXOffset;
  } else {
    res = document.body.scrollLeft;
  }
  return res;
}

function getscrolltop() {
  var res = null;
  if(window.pageYOffset != null) {
    res = window.pageYOffset;
  } else {
    res = document.body.scrollTop;
  }
  return res;
}

function getval(n) {
  var res = "";
  var pairs = document.location.search.substring(1).split("&");
  for(var i = 0; i < pairs.length;i++) {
    var p = pairs[i].split("=");
    if((p.length == 2) && (p[0] == n)) {
      res = unescape(p[1]);
      break;
    }
  }
  return res;
}

function getwidth() {
  var w = 0;
  if(document.all) {
    w = document.body.scrollWidth;
  }
  return w;
}

function validemail(email) {
  var ok = true;
  if(email == "") {
    ok = false;
  } else if(!email.match(/@/)) {
    ok = false;
  }
  return ok;
}

function writeobject() {
  var divid = '';
  var debug = 0;
  var data = [];
  var objattrs = [];
  var objparams = [];
  var embattrs = [];
  var noobj = '';
  var isattr = [];
      isattr["id"] = 1;
      isattr["classid"] = 1;
      isattr["width"] = 1;
      isattr["height"] = 1;
      isattr["style"] = 1;
      isattr["type"] = 1;

  if((arguments.length % 2) != 0) {
    alert('An even number of parameter is required.');
    return;
  }
  var i;
  var name;
  var value;
  for(i = 0;i < arguments.length;i+=2) {
    data[arguments[i]] = arguments[i+1];
  }

  if(data['divid']) {
    divid = data['divid'];
    delete data['divid'];
  }
  if(data['src']) {
    // Change src values to be tag specific.
    data['obj#url'] = data['src'];
    data['emb#src'] = data['src'];
    delete data['src'];
  }
  if(data['id']) {
    data['obj#id'] = data['id'];
    data['emb#name'] = data['id'];
    delete data['id'];
  }
  if(data['noobj']) {
    noobj = data['noobj'];
    delete data['noobj'];
  }

  for(name in data) {
    value = data[name];
    if(name.indexOf("obj#") == 0) {
      // For object tag only.
      name = name.substring(4);
      if(isattr[name]) {
        objattrs[name] = value;
      } else {
        objparams[name] = value;
      }
    } else if(name.indexOf("emb#") == 0) {
      // For embed tag only.
      name = name.substring(4);
      embattrs[name] = value;
    } else {
      // For object and embed tag.
      if(isattr[name]) {
        objattrs[name] = value;
      } else {
        objparams[name] = value;
      }
      embattrs[name] = value;
    }
  }

  // Build tag.
  var html = '<object ';
  for(name in objattrs) {
    html += name + '="' + objattrs[name] + '" ';
  }
  html += '>\n';
  for(name in objparams) {
    html += '<param name="' + name + '" value="' + objparams[name] + '" />\n';
  }
  html += noobj;
  html += '<embed ';
  for(name in embattrs) {
    html += name + '="' + embattrs[name] + '" ';
  }
  html += '></embed>\n';
  html += '</object>';

  var d = document.getElementById(divid);
  d.innerHTML = html;
}

function uvbookmark(site){
  var title = document.title;
  var url = document.location;
  if(site) {
    title = 'Utopian Vision';
    url = 'http://utopianvision.co.uk';
  }
  if (document.all) {
    window.external.AddFavorite(url, title);
  } else if (window.sidebar) {
    window.sidebar.addPanel(title, url, "");
  }
}

function uvdecode(s) {
  var res = '';
  var list = s.split(/-/);
  var i;
  var code;
  for(i = 0; i < list.length;i++) {
    res += String.fromCharCode(list[i]);
  }
  return res;
}

function uvencode(s) {
  var len = s.length;
  var i;
  var res = '';
  var code = 0;
  for(i = 0;i < len;i++) {
    code = s.charCodeAt(i);
    res += (i > 0) ? '-'+code : code;
  }
  return res;
}

function uvhelp(topic,lang) {
  var url = "/help/?topic="+escape(topic);
  if(lang) {
    url += "&amp;lang="+escape(lang);
  }
  var win = window.open(url,'help','width=300,height=300,scrollbars=1,menubar=0,status=1');
  win.focus();
}

function uvmovett(e) {
  var iebody = null;
  if(document.all) {
    iebody = (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body;
  }
  var curx = typeof(e.pageX) != "undefined" ? e.pageX : e.clientX+iebody.scrollLeft;
  var cury = typeof(e.pageY) != "undefined" ? e.pageY : e.clientY+iebody.scrollTop;
  var bw = ((document.all && !window.opera) ? iebody.clientWidth : window.innerWidth) - 25 - ttfullwidth;
  var bh = (document.all && !window.opera) ? iebody.clientHeight : window.innerHeight;
  var tt = document.getElementById('uvtt');

  if(tt) {
    var newx = curx+10;
    var newy = cury+10;
    if(newx > bw) {
      newx = curx - 10 - ttfullwidth;
    }
    tt.style.left = newx;
    tt.style.top = newy;
  }
}

function uvtt(text,moreinfotext) {
  var tt = document.getElementById('uvtt');
  if(tt) {
    if(text) {
      var html = '<div style="width: '+ttwidth+'px; overflow: hidden;"><div style="color: #900;">'+text+'</div>';
      if(!moreinfotext) {
        moreinfotext = 'Click for more information';
      } else {
        moreinfotext = unescape(moreinfotext);
      }
      html += moreinfotext+'</div>';
      if(html != ttlasthtml) {
        ttlasthtml = html;
        tt.innerHTML = html;
      }
    }
    tt.style.visibility = text ? 'visible' : 'hidden';
    tt.style.left = '-1000px';
  }
}

function pagetools(hideimages) {
  document.write('<a href="javascript:uvbookmark();" title="Bookmark this page">');
  if(!hideimages) {
    document.write('<img src="http://static.utopianvision.co.uk/images/icons/icon_bookmark.gif" width="15" height="14" border="0" alt="Bookmark" style="vertical-align: middle;">');
  }
  document.write('Bookmark page</a>');
  var loc = ''+document.location.pathname+document.location.search;
  
  if(loc.indexOf('tell-a-friend') == -1) {
    document.write(' | ');
    document.write('<a href="/home/tell-a-friend/?page='+escape(loc)+'" title="Send this page to a friend" rel="nofollow">');
    if(!hideimages) {
      document.write('<img src="http://static.utopianvision.co.uk/images/icons/icon_email.gif" width="14" height="12" border="0" alt="Send this page to a friend" style="vertical-align: middle;">');
    }
    document.write('Email page</a>');
  }
}

function addtoalbum(id,li) {
  if(li) {
    var url = '/home/mystuff/album/?add='+escape(id);
    var win = window.open(url,'_top');
  } else {
    alert('Please log in to use this feature.');
  }
}

function albumlink(id,li) {
  document.write('<a href="javascript:addtoalbum('+id+','+li+')">Add to my album</a>');
}

function ratehl(rating,current,numratings) {
  var i;
  for(i = 1;i <= imgratings.length;i++) {
    var ob = document.getElementById('rateimg'+i);
    if(ob) {
      var cls = 'icn_star_empty';
      if(rating >= i) {
        cls = 'icn_star_full';
      } else if(current >= i) {
        cls = 'icn_star_full';
      } else if(current >= (i-0.5)) {
        cls = 'icn_star_half';
      }

      ob.className = cls;
    }
  }
  var ob2 = document.getElementById('ratingmsg');
  var msg = '';
  if(numratings > 0) {
    msg = numratings + ' rating' + ((numratings == 1) ? '' : 's');
  }
  if(ob2) {
    ob2.innerHTML = ((rating > 0) ? imgratings[rating-1] : msg);
  }
}

function addInfoBoxes(options) {
  var prefix = ".moreinfo";
  if(options && options.id) {
    prefix = "#" + options.id + " " + prefix;
  }
  $(prefix+" a").removeAttr("title");
  $(prefix).hover(function(ev) {
    if(!$("#infobox").length) {
      var box = '<div style="position: absolute; z-index: 3000;"><div id="infobox">'
              + '<div class="i1">'
              + '<div class="i2">'
              + '<div class="icontent"></div>'
              + '</div>'
              + '</div>'
              + '</div></div>';
      $("body").prepend(box);
      $("#infobox").hover(function() {
        $(this).stop();
      },function() {
        $(this).hide();
      });
    }
    var id = $(this).attr("id") + '_moreinfo';
    var html = $("#"+id).html();
    $("#infobox").find(".icontent").html(html);

    var offset = $(this).offset();
    var st = $("body").get(0).scrollTop;
    var sl = $("body").get(0).scrollLeft;
    var bw = $(window).width();
    var bh = $(window).height();
    var w = $("#infobox").width();
    var h = $("#infobox").height();
    var left = offset.left + $(this).width() - 5; //ev.pageX+5; //offset.left + 60;
    var top = offset.top + 15; //ev.pageY+5; //offset.top + 20;
    if((left+w) > (sl+bw)) {
      left = (sl+bw) - (w + 20);
    }
    if((top+h) > (st+bh)) {
      top = (st+bh) - (h + 20);
    }
    var pos = {};
    pos.left = left + 'px';
    pos.top = top + 'px';
    pos.opacity = '0.9';
    pos.zIndex = '2000';
    $("#infobox").stop().css(pos).show();

  }, function(ev) {
    $("#infobox").animate({margin: '0px'},1000,function() {
      $(this).hide();
    });
  });
}

function sharePage(compact) {
  var links = [
    'Delicious|http://delicious.com/save?v=5&noui&jump=close&url=[u]&title=[t]',
    'Digg|http://digg.com/submit?url=[u]&title=[t]&bodytext=[desc]&media=[media]&topic=[topic]',
    'Facebook|http://www.facebook.com/sharer.php?u=[u]&t=[t]',
    'Google|http://www.google.com/bookmarks/mark?op=add&bkmk=[u]&title=[t]&labels=[k]',
    'MySpace|http://www.myspace.com/Modules/PostTo/Pages/?t=[t]&u=[u]&c=[content]&l=1',
    'Reddit|http://www.reddit.com/submit?url=[u]&title=[t]',
    'StumbleUpon|http://www.stumbleupon.com/submit?url=[u]&title=[t]',
    'Yahoo!|http://myweb2.search.yahoo.com/myresults/bookmarklet?t=[t]&u=[u]'
  ];
  var media = '';
  var topic = '';
  var url = ''+document.location;
  var title = ''+document.title;
  var desc = '';
  var con = '';
  if(title.match(/\s+-\s+(.*)$/)) {
    desc = RegExp.$1;
    title = title.replace(/\s+-\s+.*$/,'');
  }
  var kw = $("meta[name='keywords']").attr('content');
  desc += '\n'+kw;
  var img = $("link[rel='image_src']").attr('href');
  if(img) {
    con = '<a href="'+url+'"><img src="'+img+'" /></a>';
  }
  var i;
  var cls = compact ? 'sharelinkscompact' : 'sharelinks';
  var res = '<div class="'+cls+'">';
  if(!compact) {
    res += 'Share/bookmark this page on: ';
  }
  for(i = 0;i < links.length;i++) {
    var fields = links[i].split("\|");
    var key = fields[0].toLowerCase();
        key = key.replace(/[^a-z]/g,"");
    var link = fields[1];
    link = link.replace("[u]",escape(url));
    link = link.replace("[t]",escape(title));
    link = link.replace("[desc]",escape(desc));
    link = link.replace("[k]",escape(kw));
    link = link.replace("[topic]",escape(topic));
    link = link.replace("[media]",escape(media));
    link = link.replace("[content]",escape(con));
    res += '<a href="'+link+'" onclick="track(\''+key+'\',this.href,document.location)" target="_blank" title="Share this page on '+fields[0]+'"><img src="http://static.utopianvision.co.uk/images/t.gif" width="16" height="16" class="share_'+key+'"/>';
    res += '</a>';
  }
  res += '</div>';
  document.write(res);
}


function track(name,url,ref) {
  var app = 'http://utopianvision.co.uk/track.php';
  var params = {'name': name,'url':url,'ref':ref};
  var req = app+'?name='+escape(name)+'&url='+escape(url)+'&ref='+escape(ref);
  var img = new Image();
  img.src = req;
}

function sendAction(params) {
  var url = '/misc/action.php';
  $.post(url,params,function(data) {
    $("#actionbox").html(data.content).slideDown();
  },'json');
}

function closeActionBox() {
  $("#actionbox").slideUp();
}

function addRating(type,item,rating) {
  var params = {'action':'rate-'+type,'item':item,'rating':rating};
  sendAction(params);
}

function addToFavourites(type,item) {
  var params = {'action':'favourite-'+type,'item': item};
  sendAction(params);
}

