objCommon={
  lng: 'en',
  loggedIn: 0,
  trafficLeft: 0,

  messages: {
    signup: {
      nameFirstIncorrect : { 'en': '<b>First name</b> is incorrect.' },
      nameLastIncorrect : { 'en': '<b>Last name</b> is incorrect.' },
      emailIncorrect: { 'en': '<b>E-mail</b> is incorrect.' },
      emailExists: { 'en': '<b>E-mail</b> is already registered. Try a password reminder.' },
      passwordIncorrect: { 'en': '<b>Password</b> must contain at least 5 characters.' },
      passwordMismatch: { 'en': '<b>Password confirmation</b> does not match password.' },
      tosNotAgreed: { 'en': 'You must agree to the <b>TOS</b> to sign up.' }
    },
    addTorrent: {
      errorTemporary: { 'en': 'Temporary error. Please try again later.' },
      searchIncorrectLink: { 'en': 'Incorrect link. Must start from <b>http://</b> or <b>magnet:?</b>.' },
      remoteIncorrectLink: { 'en': 'Incorrect link. Must start from <b>http://</b> or <b>magnet:?</b>.' },
      localIncorrectFile: { 'en': 'Incorrect file format: this is not a .torrent file.' },
      noTorrentsSpecified: { 'en': 'Please select the torrent to add using one of the proposed methods.' },
      torrentExists: { 'en': 'Torrent already exists at processing or downloads list.' },
      torrentAdded: { 'en': 'Torrent added.' },
      torrentProcessing: { 'en': 'adding torrent to downloads list...' }
    },
    processingTorrent: {
      Snew: { 'en': 'Waiting for refill' },
      Sprocessing: { 'en': 'Downloading' },
      Serror: { 'en': 'Error' },
      Sidle: { 'en': 'Idle' },
      Sinitializing: { 'en': 'Initializing' },
      tdSpreparing: { 'en': 'Preparing archive' },
      confirmDelete: { 'en': 'Are you sure you want to delete this torrent? Used traffic will not be returned. There is no ability to restore download after deleting.' }
    },
    downloadTorrent: {
      confirmDelete: { 'en': 'Are you sure you want to delete this torrent?' }
    },
    auth : {
      accountBlocked: { 'en': 'Account blocked.' },
      accountIncorrect: { 'en': 'Incorrect E-mail/password.' }
    },
    support : {
      emailIncorrect : { 'en': '<b>E-mail</b> is incorrect.' },
      nameIncorrect : { 'en': 'Please fill in your <b>Name</b>.' },
      messageIncorrect : { 'en': 'Please fill in your <b>message</b>.' },
      deptIncorrect : { 'en': 'Please select the department.' },
      captcha : { 'en': 'Please, enter the word you see in the image.' },
      ok : { 'en': 'Thank you! Your support request has been sent. You will receive a reply soon.' }
    },
    account : {
      passwordIncorrect : { 'en': '<b>Password</b> is incorrect.' },
      passwordConfirmIncorrect : { 'en': '<b>Confirm password</b> does not match the <b>Password</b>.' },
      passwordActiveIncorrect : { 'en': '<b>Active password</b> is incorrect.' },
      nameFirstIncorrect : { 'en': '<b>First name</b> is incorrect.' },
      nameLastIncorrect : { 'en': '<b>Last name</b> is incorrect.' },
      emailIncorrect : { 'en': '<b>E-mail address</b> is incorrect.' },
      emailExistsIncorrect : { 'en': '<b>E-mail address</b> already exists in the database.' },
      ok : { 'en': 'The data is changed.' }
    },
    reminder : {
      noSuchClient : { 'en' : '<b>E-mail/Order id</b> is incorrect.' },
      ok : { 'en' : 'Your account details have been sent to your e-mail account.' }
    }
  },

  parseTemplate : function(str){
    res=str.match(/\#([a-zA-z\.]+)\#/);
    if (res.length > 0)
      {
        for (i=1;i<res.length;i++)
        {
          str=str.replace('#'+res[i]+'#', eval(res[i]));
        }
      }
    return str;
  },

  formatDate : function(date)
  {
    if (date == 0) { return '-'; }
    D=new Date(date*1000);
    return D.toLocaleDateString();
  },

  formatSpeed : function(speed)
  {
    if (parseInt(speed) < 1) { return speed; }
    speed=parseInt(speed);
    return (speed/1024).toFixed(0)+' KB/s';
  },

  formatSize : function(size)
  {
    size=parseInt(size);
    if (parseInt(size) == 0) { return size; }

    if (Math.abs(size) < 1024) { size=size+' bytes'; }
    if (Math.abs(size) < 1024*1024) { size=(size/1024).toFixed(2)+' KB'; }
    if (Math.abs(size) < 1024*1024*1024) { size=(size/(1024*1024)).toFixed(2)+' MB'; }
    if (Math.abs(size) < 1024*1024*1024*1024) { size=(size/(1024*1024*1024)).toFixed(2)+' GB'; }

    return size;
  },

  formatTime : function(time)
  {
    min=parseInt(time/60);
    sec=parseInt(time%60);
    return (min > 0?min+' min ':'')+sec+' sec';
  },

  getHealth : function(sr,lr)
  {
    if (sr == 0 && lr > 10) { return 1; }
    if (sr == 1) { return 2; }
    if (sr > 0 && sr < 3) { return 3; }
    if (sr >= 3 && sr < 5) { return 4; }
    if (sr >= 5 && sr < 7) { return 5; }
    if (sr >= 7 && sr < 10) { return 6; }
    if (sr >= 10 && sr < 15) { return 7; }
    if (sr >= 15 && sr < 20) { return 8; }
    if (sr >= 20 && sr < 50) { return 9; }
    if (sr >= 50) { return 10; }
    return 0;
  },

  submitForm : function(params)
  {
    params.jq.find('div[msg=true]').removeClass().html('');
    params.jq.find(':input:visible').removeClass('msgErrorField');
    params.jq.find(':input[type=image],:input[type=submit]').attr('disabled','disabled').css('opacity',0.5);

    if (typeof(params.obj.beforeSubmitForm) != 'undefined')
      { params.obj.beforeSubmitForm(params); } 

    params.jq.ajaxSubmit({
      type:'POST',
      dataType:'json',
      success: function(t) { objCommon.processResponse(t, params); }
    });
    
    return false;
  },
  
  processResponse : function(data, params)
  {
    params.jq.find(':input[type=image],:input[type=submit]').attr('disabled','').css('opacity',1);
    params.obj.processResponse(data, params);
    return;
  },

  reportMessages : function(data, state, params)
  {
    msg='';
    for (i=0;i<data.messages.length;i++)
    {
      msg+=(msg == ''?'':'<br />')+eval('objCommon.messages.'+data.messages[i]+'.'+objCommon.lng);
    } 
    
    if (typeof(data.fields) != 'undefined')
      {
        for (i=0;i<data.fields.length;i++)
        {
          params.jq.find(':input[name='+data.fields[i]+']:visible').addClass('msgErrorField');
        }
      }

    params.jq.find('div[msg=true]').addClass('msg'+(state == "error"?"Error":"Notice")).html(msg);
    return;
  },

  setCookie: function(name,value,expiredays)
  {
    exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=name+'='+escape(value)+((expiredays==null)?'':';expires='+exdate.toGMTString());
    return;
  },
    
  getCookie: function(name)
  {     
    if (document.cookie.length>0)
      {
        c_start=document.cookie.indexOf(name+'=');
        if (c_start!=-1)
          {
            c_start=c_start+name.length+1;
            c_end=document.cookie.indexOf(';',c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
          }
      }
    return '';
  }

};

objOverallFunctions={
  updateTraffic: function(traffic){
    if (typeof(traffic) == 'undefined' || isNaN(traffic)) { traffic=0; }
    objCommon.trafficLeft=traffic;
    if (objCommon.trafficLeft <= 50*1024*1024)
      { $('#trafficLeft').addClass('traffic-low'); }
    $('#trafficLeft').html(objCommon.formatSize(objCommon.trafficLeft));
    setTimeout(function(){
      $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '?c=get-traffic&rnd='+Math.random(),
        success: function(data){
          objOverallFunctions.updateTraffic(data.traffic);
          return;
        }
      });
    }, 60*1000);

    preload=['http://static.quick-torrent.com/i/menu-download-a.jpg','http://static.quick-torrent.com/i/menu-processing-a.jpg','http://static.quick-torrent.com/i/menu-add-a.jpg','http://static.quick-torrent.com/i/en/txt-step1-add-a.gif','http://static.quick-torrent.com/i/en/txt-step2-processing-a.gif','http://static.quick-torrent.com/i/en/txt-step3-download-a.gif'];
    for(i=0;i<preload.length;i++)
    {
      img=new Image();
      img.src=preload[i];
    }

    return;
  },

  init:function(p){
    if (typeof(p.lng) != 'undefined') { objCommon.lng=p.lng; }
    if (typeof(p.loggedIn) != 'undefined') { objCommon.loggedIn=p.loggedIn; }

    $('.content').each(function(){
      height=parseInt($(this).css('height'));
      if (isNaN(height)) { height=0; }
      if (parseInt($(this).position().top)+height < parseInt($('#footer').position().top))
        {
          $(this).closest('table').find('tr:first').children('td').css('height', parseInt($('#footer').position().top)-parseInt($(this).position().top)-9);
          $(this).closest('table').find('tr:last').children('td').css('height','9px');
        }
    });
    $('td[button]').bind('mouseover',function(){
      $('td[button]').each(function(){
        image=$(this).css('backgroundImage');
        if (image.match(/-a.jpg/) == null) { return; }
        image=image.replace('-a.jpg','.jpg');
        $(this).css('backgroundImage',image);

        image=$(this).find('img').attr('src');
        image=image.replace('-a.gif','.gif');
        $(this).find('img').attr('src',image);
      });
      image=$(this).css('backgroundImage');
      image=image.replace(/\.jpg/i,'-a.jpg');
      $(this).css('backgroundImage', image);

      image=$(this).find('img').attr('src');
      image=image.replace('.gif','-a.gif');
      $(this).find('img').attr('src',image);
    })
    .bind('mouseout',function(){
      $('td[button]').each(function(){
        image=$(this).css('backgroundImage');
        if (image.match(/-a.jpg/) == null) { return; }
        image=image.replace('-a.jpg','.jpg');
        $(this).css('backgroundImage',image);

        image=$(this).find('img').attr('src');
        image=image.replace('-a.gif','.gif');
        $(this).find('img').attr('src',image);
      });
    })
    .bind('click',function(){
      if (objCommon.loggedIn == 0)
        {
          l='sign-up.html';
          if ($(this).attr('button') == 'add') { l='add-torrent.html'; }
          location=l; 
        }
      else
        {
          l='';
          if ($(this).attr('button') == 'add') { l='add-torrent.html'; }
          if ($(this).attr('button') == 'processing') { l='processing.html'; }
          if ($(this).attr('button') == 'download') { l='downloads.html'; }
          location=l;
        }
    })
    .css('cursor','pointer');

    if (objCommon.loggedIn > 0)
      { objOverallFunctions.updateTraffic(parseInt($('#trafficLeft').html())); }

    $('*[name=account_paid_till]').each(function(){
      $(this).html(objCommon.formatDate($(this).html()));
    });

    return;
  }
};

objSignUp={
  init: function()
  {
    if (location.search.match(/msg\=([^\&]+)/))
      {
        objCommon.reportMessages({messages:[location.search.match(/msg\=([^\&]+)/)[1].split(',')]}, 'error', {jq: $('#frmSignUp'), obj: objSignUp});
      }

    $('#frmSignUp :input[type=text],:input[type=password]:visible')
    .bind('focus',function(){
      $(this).css('backgroundColor','#f8f9ac');
    })
    .bind('blur',function(){
      $(this).css('backgroundColor','#fff');
    });

    $('#frmSignUp').bind('submit', function() {
      return objCommon.submitForm({jq: $(this), obj: objSignUp});
    })
    .find(':input:visible:first').focus();

    return;
  },

  processResponse : function(data, params)
  {
    if (data.code == 500)
      {
        objCommon.reportMessages(data, 'error', params);
      }
    if (data.code == 200)
      {
        if (typeof(data.url) != 'undefined')
          { location=data.url; }
        else
          { location='/'+objCommon.lng+'/'; }
      }
    return;
  }
};

objAccount={
  processResponse : function(data, params)
  {
    if (data.code == 500)
      {
        objCommon.reportMessages(data, 'error', params);
      }
    if (data.code == 200)
      {
        objCommon.reportMessages({messages: [ 'account.ok' ]}, 'notice', params);
        params.jq.find(':input[type=password][name=password]').val('');
      }
    return;
  }
};

objSupport={
  processResponse : function(data, params)
  {
    if (data.code == 500)
      {
        objCommon.reportMessages(data, 'error', params);
      }
    if (data.code == 200)
      {
        objCommon.reportMessages({messages: [ 'support.ok' ]}, 'notice', params);
        params.jq.find(':input:visible').each(function(){
          $(this).val('');
        });
        params.jq.find('tr').each(function(){
          if (typeof($(this).find('div[msg=true]').attr('msg')) == 'undefined')
            { $(this).hide(); }
        });
      }
    return;
  }
};

objReminder={
  processResponse : function(data, params)
  {
    if (data.code == 500) { objCommon.reportMessages(data, 'error', params); }
    if (data.code == 200)
      {
        objCommon.reportMessages({messages: [ 'reminder.ok' ]}, 'notice', params);
        params.jq.find(':input:visible').each(function(){
          $(this).val('');
        });
      }
    return;
  }
};

objAuth={
  init: function()
  {
    if (location.search.match(/msg\=([^\&]+)/))
      {
        objCommon.reportMessages({messages:[location.search.match(/msg\=([^\&]+)/)[1].split(',')]}, 'error', {jq: $('#frmAuth'), obj: objAuth});
      }

    $(':input:visible:first').focus();

    $('#frmAuth').bind('submit', function() {
      return objCommon.submitForm({jq: $(this), obj: objAuth});
    });
  },

  processResponse : function(data, params)
  {
    if (data.code == 500)
      {
        objCommon.reportMessages(data, 'error', params);
      }
    if (data.code == 200)
      {
        if (data.state == "active")
          {
            if (typeof(data.url) != 'undefined')
              { location=data.url; }
            else
              { location='/'; }
          }
        else if (data.state == "blocked") { objCommon.reportMessages({messages:['auth.accountBlocked']}, 'error', params); }
      }
    return;
  }
};

objAddTorrent={
  files: [],
  init:function(){
    $('div[name]').hide();

    if (location.hash.match('\#(.*)'))
      { $('div[name='+location.hash.match('\#(.*)')[1]+']').show(); }
    else { $('div[name]:first').show(); }

    $('h2').css('cursor','pointer').bind('click',function(){
      $('div[name]').hide();
      $(this).next('div[name]:first').show();
    });
    $('#frmAddSearch').bind('submit', function() {
      return objCommon.submitForm({jq: $(this), obj: objAddTorrent});
    })
    .find(':input[name=q]').bind('focus',function(){
      if ($(this).val() == 'most popular torrents') { $(this).val(''); }
    })
    .bind('blur',function(){
      if ($(this).val() == '') { $(this).val('most popular torrents'); }
    });

    $('#frmAddTorrent').bind('submit', function() {
      objAddTorrent.files=[];
      search='';
      $('#searchResults tbody tr').each(function(){
        if ($(this).attr('class').match(/active/)==null) { return; }
        objAddTorrent.files.push({id:0, title:$(this).find('td:first').html(), source:$(this).attr('url'), err:''});
        search+=$(this).attr('url')+"\n";
      });
      $(this).find(':input[name=search]').val(search);

      res=$(this).find(':input[name=remote]').val().split(/\r?\n/);
      for (i=0;i<res.length;i++)
      {
        err='';
        if (res[i] == '') { continue; }
        if (res[i].match(/^(http\:\/\/|magnet\:\?)/) == null) { err='remoteIncorrectLink'; }
        objAddTorrent.files.push({id:0, title:'', source:res[i], err:err});
      }

      for (i=1;i<6;i++)
      {
        val=$(':input[name=local'+i+']').val();
        err='';
        if (val == '') { continue; }
        if (val.match(/\.torrent$/) == null)
          {
            err='localIncorrectFile';
          }
        objAddTorrent.files.push({id:0, title:'', source:val, err:err});
      }
      return objCommon.submitForm({jq: $(this), obj: objAddTorrent});
    });

    if (location.href.match(/(?:\#|^)similar=(.*)(?:$|\&)/))
      {
        res=location.href.match(/(?:\#|^)similar=(.*)(?:$|\&)/);
        $('#frmAddSearch input[name=q]').val(unescape(res[1]));
        $('#frmAddSearch').submit();
      }

    return;
  },
  reportError: function(msgs)
  {
    msg='';
    for (i=0;i<msgs.length;i++)
    {
      msg+=(msg == ''?'':'<br />')+eval('objCommon.messages.addTorrent.'+msgs[i]+'.'+objCommon.lng);
    }
    $('div[name=uploadProgress]').show().addClass('msgError').html(msg);
  },
  processResponse : function(data, p)
  {
    if (p.jq.find(':input[name=c]').val() == 'add')
      {
        if (data.code == 500 || typeof(data.code) == 'undefined')
          {
            objAddTorrent.reportError(['errorTemporary']);
          }
        else if (data.code == 200)
          {
            data.items.pop();
            if (data.items.length < 1)
              {
                objAddTorrent.reportError(['noTorrentsSpecified']);
                return;
              }

            for (i=0;i<objAddTorrent.files.length;i++)
            {
              for (j=0;j<data.items.length;j++)
              {
                if (objAddTorrent.files[i].source == data.items[j].source)
                  {
                    objAddTorrent.files[i].id=data.items[j].id;
                    objAddTorrent.files[i].err=data.items[j].err;
                  }
              }
            }

            html='';
            processing=[];
            errors=0;
            for (i=0;i<objAddTorrent.files.length;i++)
            {
              html+='<div'+(objAddTorrent.files[i].err == ''?'':' class="msg'+(objAddTorrent.files[i].err == 'torrentAdded'?'Notice':'Error')+'"')+'>';
              if (typeof(objAddTorrent.files[i].title) == 'undefined' || objAddTorrent.files[i].title == '')
                { html+=objAddTorrent.files[i].source; }
              else { html+=objAddTorrent.files[i].title; }
              html+=': '+eval('objCommon.messages.addTorrent.'+(objAddTorrent.files[i].err == ''?'torrentProcessing':objAddTorrent.files[i].err)+'.'+objCommon.lng)+
                    '</div>';
              if (objAddTorrent.files[i].err != '' && objAddTorrent.files[i].err != 'torrentAdded') { errors++; }
              if (objAddTorrent.files[i].id > 0 && objAddTorrent.files[i].err == '') { processing.push(objAddTorrent.files[i].id); }
            }
            $('div[name=uploadProgress]').show().attr('class','').html(html);

            if (processing.length > 0)
              {
                setTimeout(function(){
                  $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    url: 'add-torrent.html?c=get-state&ids='+processing.join(',')+'&rnd='+Math.random(),
                    success: function(data){
                      objAddTorrent.processResponse(data, {jq:$('#frmAddTorrent'), obj: objAddTorrent});
                      return;
                    }
                  });
                }, 1000);
              }
            else
              {
                if (errors == 0) { location='processing.html'; }
                else { $('div[name=goToProcessing]').show(); }
              }
          }// code 200
      }

    else if (p.jq.find(':input[name=c]').val() == 'search')
      {
        $('div[name=searchSearching]').hide();
        if (data.code == 500)
          {
            $('div[name=searchError]').show();
          }
        else if (data.code == 200)
          {
            data.items.pop();
/*            i=0;
            while(i<data.items.length)
            {
              if (data.items[i].sr == 0) { data.items.splice(i, 1); }
              else { i++; }
            }
*/
            if (data.items.length < 1)
              {
                $('div[name=searchNoResults]').show();
                return;
              }

            $('#searchResults tbody tr').remove();
            spl='<td><div style="height:23px;border-left:1px solid #afcfed;width:1px;margin:auto;"></div></td>';
            html='';

            for(i=0;i<data.items.length;i++)
            {
              html+='<tr url="'+data.items[i].url+'">'+
                    '<td style="text-align:left;">'+data.items[i].title+'</td>'+spl+
                    '<td class="nw" style="text-align:right;">'+objCommon.formatSize(data.items[i].size)+'</td>'+spl+
                    '<td>'+objCommon.formatDate(data.items[i].date)+'</td>'+spl+
                    '<td><img src="http://static.quick-torrent.com/i/health-'+objCommon.getHealth(data.items[i].sr,data.items[i].lr)+'.gif" alt="Torrent Health" /></td>'+spl+
                    '<td><input type="checkbox" name="" value="" /></td>'+
                    '</tr>';
            }
            $('#searchResults tbody').html(html);

            $('#searchResults').show().find('tbody tr')
            .css('cursor','pointer')
            .bind('mouseover',function(){
              $(this).find('td').addClass('hovered');
            })
            .bind('mouseout',function(){
              $(this).find('td').removeClass('hovered');
            })
            .bind('click',function(){
              if ($(this).attr('class').match(/active/) != null)
                {
                  $(this).removeClass('active'); 
                  $(this).find(':input[type=checkbox]').attr('checked', '');
                }
              else
                {
                  $(this).addClass('active'); 
                  $(this).find(':input[type=checkbox]').attr('checked', 'checked');
                }
            })
            .find(':input[type=checkbox]').bind('change',function(){
              if ($(this).attr('checked'))
                {
                  $(this).addClass('active');
                }
              else
                {
                  $(this).removeClass('active');
                }
            });
          }
        return;
      }
  },
  beforeSubmitForm: function(p)
  {
    if (p.jq.find(':input[name=c]').val() == 'search')
      {
        $('div[name=searchSearching]').show();
        $('div[name=searchNoResults]').hide();
        $('#searchResults').hide();
        $('div[name=searchError]').hide();
      }
    else if (p.jq.find(':input[name=c]').val() == 'add')
      {
        $('div[name=goToProcessing]').hide();
        $('div[name=uploadProgress]').attr('class','').html('').hide();
      }
    return;
  }
};

objRefill={
  wnd: undefined,
  lastClick: {x:0, y:0},
  init:function()
  {
    if (typeof($('table[name=disk]').attr('name')) != 'undefined')
      {
        $(':input[type=radio][name=method]').bind('click',function(){
          var val=$(this).val();

          $(':input[type=radio][name=method]').each(function(){
            if ($(this).val() == val) { $(this).attr('checked', 'checked'); }
          });

          if (val == 'paypal')
            {
              $('table[name=disk]').css('backgroundImage','url(http://static.quick-torrent.com/i/paypal.png)');
            }
          else
            {
              $('table[name=disk]').css('backgroundImage','url(http://static.quick-torrent.com/i/avangate-small.jpg)');
            }
        });

        $('table[name=disk]').find('form').each(function(){
          $(this).bind('submit',function(){
            objRefill.selectPlan($(this).find(':input[name=group]').val(),$(this).find(':input[name=method]:checked').val());
            return false;
          });
        });

        $(':input[type=image][src*=disk-buy-now]').bind('click',function(){
          objRefill.wnd=window.open('about:blank','wndRefill');
          objRefill.wnd.document.write('<html><head><title>loading...</title></head><body>Loading checkout page...</body></html>');
        });

/*        $('*').bind('click',function(e){
          if (e.pageX == objRefill.lastClick.x && e.pageY == objRefill.lastClick.y) { return; }
          (new Image).src='http://www.quick-torrent.com/click/?c=refill&x='+e.pageX+'&y='+e.pageY+'&obj='+$(this).html();
          objRefill.lastClick={x:e.pageX,y:e.pageY};
          return;
        });
*/

        return;
      }

    var variant=objCommon.getCookie('variant');
    if (variant != '1' && variant != '2' && variant != '3' && variant != '4')
      {   
        u=0;l=5;
        variant=Math.floor((Math.random()*(u-l+1))+l);
        objCommon.setCookie('variant',variant,30);
        if (document.images)
          {
            (new Image).src='http://www.quick-torrent.com/i/variant/refill:'+variant+'.gif';
          }
      }
    $('*[variant='+variant+']').show();

    $('td[name=plan]').css('cursor','pointer')
    .bind('mouseover',function(){
      left=24;
      $(this).prevAll().each(function(){
        left+=$(this).width();
      });

      $('table[name=plans]').css('background','url(http://static.quick-torrent.com/i/refill-bg-highlight.png) '+left+'px 31px no-repeat');
//      $(this).css('color','#fff');
/*      $(this).find('img').each(function(){
        if ($(this).attr('src').match(/refill\-\d\.gif/) == null) { return; }
        src=$(this).attr('src');
        src=src.replace('.gif', '-a.gif');
        $(this).attr('src',src);
      });
*/
    })
    .bind('mouseout',function(){
      $('table[name=plans]').css('background','none');
//      $('td[name=plan]').css('color','#000');
/*      $(this).find('img').each(function(){
        if ($(this).attr('src').match(/refill\-\d\-a\.gif/) == null) { return; }
        src=$(this).attr('src');
        src=src.replace('-a.gif', '.gif');
        $(this).attr('src',src);
      });
*/
    });
    return;
  },
  ppRefill: function(amount, title, payment_id)
  {
    var div=$('<div/>');
    $('body').append(div);

    div.html('<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="ppForm" target="wndRefill" style="display:none;">'+
             '<input type="hidden" name="cmd" value="_xclick">'+
             '<input type="hidden" name="business" value="paypal@quick-torrent.com">'+
             '<input type="hidden" name="item_name" value="'+title+'">'+
             '<input type="hidden" name="amount" value="'+amount+'">'+
             '<input type="hidden" name="currency_code" value="USD">'+
             '<input type="hidden" name="button_subtype" value="services">'+
             '<input type="hidden" name="no_note" value="1">'+
             '<input type="hidden" name="lc" value="US">'+
             '<input type="hidden" name="no_shipping" value="1">'+
             '<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG_wCUP.gif:NonHosted">'+
             '<input type="hidden" name="invoice" value="'+payment_id+'">'+
             '<input type="hidden" name="notify_url" value="http://www.quick-torrent.com/yGaGU21p2V9k32dQHJ3fg36U5yBzoCJ4">'+
             '<input type="hidden" name="page_style" value="quicktorrent">'+
             '<input type="image" src="https://www.paypal.com/en_GB/HK/i/btn/btn_buynowCC_LG_wCUP.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online." />'+
             '<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">'+
             '</form>');
    $('#ppForm').submit();
    return;
  },
  selectPlan: function(id,method)
  {
    $.ajax({
      type: 'GET',
      dataType: 'json',
      url: 'refill.html?c=refill&method='+method+'&plan='+id+'&rnd='+Math.random(),
      success: function(data) {
        if (data.source == "paypal")
          {
            objRefill.ppRefill(data.amount,data.title,data.id);
          }
        else if (data.source == "avangate")
          {
            objRefill.wnd.location=data.url;
//            location=data.url;
          }
        else if (typeof(data.url) != 'undefined')
          {
            location=data.url;
          }
        return;
      }
    });
    return;
  },
  planWindow: function()
  {
    div=$('<div/>');
    $('body').append(div);
    div.css({
      'top':'0px',
      'left':'0px',
      'width':'100%',
      'height':'100%',
      'position':'fixed',
      'opacity': '0.7',
      'backgroundColor':'#000',
      'z-index':'9999'
    });

    $('#wndPlans').css({
      'top':'90px',
      'left':(($('body').width()-580)/2),
      'width':'580px',
      'position':'absolute',
      'z-index':'99999'
    }).show();

    $('#tblPlans tr').bind('click',function(){
      $('#tblPlans tr')
       .removeClass('a')
       .find('td:first').css('background','none')
       .closest('tr')
       .find('td:last').css('background','none');
 
      $(this).addClass('a');
      $(this).find(':input[type=radio]').attr('checked','checked');
      $(this).find('td:first').css('background','url(http://static.quick-torrent.com/i/wnd-plans-shape.jpg) 0px 0px no-repeat');
      $(this).find('td:last').css('background','url(http://static.quick-torrent.com/i/wnd-plans-shape.jpg) -5px 0px no-repeat');
    });

    $('#tlbMethods tr').bind('click',function(){
      $(this).find(':input[type=radio]').attr('checked','checked');
    });

    $('#tblPlans tr:visible:eq(2)')
     .addClass('a')
     .find(':input[type=radio]').attr('checked','checked')
     .closest('tr')
     .find('td:first').css('background','url(http://static.quick-torrent.com/i/wnd-plans-shape.jpg) 0px 0px no-repeat')
     .closest('tr')
     .find('td:last').css('background','url(http://static.quick-torrent.com/i/wnd-plans-shape.jpg) -5px 0px no-repeat');

    $('#wndPlans').find('img[src*=btn-proceed]')
    .bind('click',function(){
      objRefill.selectPlan($('#wndPlans').find(':input[name=group]:checked').val(),$('#wndPlans').find(':input[name=method]:checked').val());
    })
    .css({'cursor':'pointer'});
 
    return;
  }
};

objIndexPage={
  init:function()
  {
    z=$('#hint').clone();
    $('body').append(z);
    z.css({
      'position':'absolute',
      'top':$('#hint').position().top,
      'left':$('#hint').position().left,
      'width':$('#hint').width(),
      'z-index':9999
    })
    .attr('id','hintOver');

    $('.index-benefits').find('b').siblings('div').css('display','none');
    $('.index-benefits').find('b').siblings('div:first').css('display','');
    $('.index-benefits').find('b').closest('td').bind('mouseover',function(){
      $('.index-benefits').find('b').siblings('div').css('display','none');
      $(this).find('b').siblings('div:first').css('display','');
    });
    swfobject.embedSWF('http://static.quick-torrent.com/f/player.swf', 'splash', 435, 277, '8.0.0', undefined, {file:'http://static.quick-torrent.com/f/splash.flv',backcolor:'accdec',stretching:'fill',image:'http://static.quick-torrent.com/f/splash.jpg'}, {allowfullscreen:true});
    return;
  }
}; 

objLanding={
  id: '',
  init:function(id)
  {
    if (id == '')
      {
        $('div[name=lnFetching]').hide();
        $('div[name=lnTorrentInfo]').show(); 
        objLanding.calculateDlTime();
        $('*[name=torrentSize]').html(objCommon.formatSize($('*[name=torrentSize]').html()));
        return;
      }

    if (id == -1)
      {
        location='add-torrent.html';
        return;
      }

    objLanding.id=id;
    objLanding.getState();
    return;
  },
  getState:function()
  {
    $.ajax({
      type: 'GET',
      dataType: 'json',
      url: 'download.html?c=get-state&id='+objLanding.id+'&rnd='+Math.random(),
      success: function(data){
        if (data.state == "done")
          {
            $('div[name=lnTorrentInfo] a').each(function(){
              res=$(this).attr('href').match(/(\&|\?)hash\=($|\&)/);
              if (res != null)
                {
                  href=$(this).attr('href');
                  href=href.replace(res[1]+'hash=',res[1]+'hash='+data.hash);
                  $(this).attr('href', href)
                }
            });
            $('a[name=lnTorrentTitle]').html(data.title);
            $('img[name=lnTorrentType]').attr('src','http://static.quick-torrent.com/i/types/'+data.type+'.png');
            $('div[name=lnFetching]').hide();
            $('div[name=lnTorrentInfo]').show();
            $('b[name=torrentDlCount]').html(data.downloads);
            $('*[name=torrentSize]').html(data.size);
            objLanding.calculateDlTime();
            $('*[name=torrentSize]').html(objCommon.formatSize(data.size));
            return;
          }
        else if (data.state == "error")
          {
            location='add-torrent.html';
            return;
          }
        setTimeout(function(){ objLanding.getState(); }, 1000);
        return;
      }
    });
    return;
  },
  calculateDlTime:function()
  {
    seconds=parseInt($('b[name=torrentSize]').html())/(1024)/parseInt($('b[name=torrentDlSpeed]').html());
    $('*[name=torrentDlTime]').html(parseInt(seconds/60)+'m '+parseInt(seconds%60)+'s');
    return;
  }
};

objDownload={
  init:function(){
    objDownload.getList({refresh:1});
    return;
  },
  refreshInterval: 5,
  refreshStop: function(){
    objDownload.refreshInterval=0;
    $('p[name=dlStart]').hide();
    $('p[name=dlStop]').show();
    return;
  },
  refreshStart: function(){
    objDownload.refreshInterval=5;
    objDownload.getList({refresh:1});
    $('p[name=dlStart]').show();
    $('p[name=dlStop]').hide();
    return;
  },

  loadingDiv: undefined,
  loadingShow: function(){
    return;
// not showing loading image
    if (typeof(objDownload.loadingDiv) != 'undefined') { objDownload.loadingDiv.remove(); }
    objDownload.loadingDiv=$('<div/>');
    $('body').append(objDownload.loadingDiv);
    objDownload.loadingDiv
      .css({
        'position':'absolute',
        'z-index':999,
        'left':$('body').offset().left+10,
        'top':$('body').offset().top+3
      })
      .html('<img src="http://static.quick-torrent.com/i/loading.gif" alt="Loading..." />');
    return;
  },
  loadingHide: function(){
//    objDownload.loadingDiv.remove();
    return;
  },
 
  getList:function(p){

    if (typeof(p) == 'undefined') { p={}; }
    objDownload.loadingShow();

    $.ajax({
      type: 'GET',
      dataType: 'json',
      url: 'downloads.html?c=get-list&rnd='+Math.random(),
      success: function(data){ objDownload.gotList(data,p); }
    });

    return;
  },

  gotList:function(data,p)
  {
    if (typeof(p) == 'undefined') { p={}; }
    objDownload.loadingHide();

    $('p[name=prNoItems]').hide();
    $('p[name=prMagnetDescr]').hide();
    $('p[name=prIdle]').hide();
    $('p[name=prNoFunds]').hide();
    $('p[name=dlBrowserNoLargeFiles]').hide()
    $('p[name=dlFinishedMsg]').hide();

    if (data.itemsDone.length < 1 && data.itemsProcessing.length < 1)
      {
        $('p[name=prNoItems]').show();
      }

    objDownload.parseDoneList(data.itemsDone);
    objDownload.parseProcessingList(data.itemsProcessing);

    $('div[name=error]').each(function(){
     if ($(this).outerWidth(true) < $(this).attr('scrollWidth') || $(this).outerHeight(true) < $(this).attr('scrollHeight'))
       {
         if (typeof($(this).attr('cloned')) != 'undefined') return;
         $(this).css({
           'background':'url(http://static.quick-torrent.com/i/downloads-error-box.gif) 235px 12px no-repeat',
           'cursor':'pointer'
         })
         .bind('click',function(){
           div=$(this).clone();
           $('body').append(div);
           div.css({
             'position':'absolute',
             'height':'auto',
             'left': $(this).offset().left,
             'top': $(this).offset().top,
             'z-index': 55555,
             'background':'#fff url(http://static.quick-torrent.com/i/downloads-error-box-a.gif) 235px 12px no-repeat'
           })
           .attr('cloned','1')
           .bind('click',function(){$(this).remove();})
           .find('td').css({'line-height':'15px','padding':'10px 0px'});
           return;
         });
       }
    });

    if (objDownload.refreshInterval > 0 && typeof(p.refresh) != 'undefined')
      {
        setTimeout(function(){
          if (objDownload.refreshInterval == 0) { return; }
          objDownload.getList(p);
        }, objDownload.refreshInterval*1000); 
      }

    return;
  },
  parseDoneList:function(items){

    $('#tblDownload').hide();
    if (items.length < 1) { return; }

    $('p[name=dlFinishedMsg]').show();

    items.sort(function(a,b){
      if (a.state == "done") return -1;
      if (a.state == "error") return 1;
      return 0;
    });

    html='';
    spl='<td class="spl"><div></div></td>';

    for(i=0;i<items.length;i++)
    {
      link='http://'+items[i].host+'/'+items[i].uid+'/'+items[i].id+'/'+items[i].hash;
      if (items[i].state == 'done')
        {
          html+='<tr>'+
            '<td style="text-align:left;"><a onclick="window.open(this.href);return false;" href="'+link+'">'+items[i].title+'</a></td>'+spl+
            '<td style="width:90px" class="nw" style="text-align:right;">'+objCommon.formatSize(items[i].size)+'</td>'+spl+
            '<td style="width:150px" class="nw">'+objCommon.formatDate(items[i].dateValid)+'</td>'+spl+
            '<td style="white-space:nowrap;"><a onclick="window.open(this.href);return false;" href="'+link+'"><img style="cursor:pointer;margin:1px 12px 0px 8px;" src="http://static.quick-torrent.com/i/ico-download.gif" alt="Download" /></a>'+
                '<img style="cursor:pointer;" onclick="objDownload.deleteTorrent('+items[i].id+',\''+items[i].state+'\');" src="http://static.quick-torrent.com/i/ico-delete.gif" alt="Delete" />'+
            '</td>'+
            '</tr>';
        }
      else if (items[i].state == 'error')
        {
          html+='<tr>'+
            '<td style="text-align:left;">'+items[i].title+'</td>'+spl+
            '<td colspan="3"><div name="error" style="margin:auto;overflow:hidden;width:250px;border:2px solid #df0024;height:25px;text-align:left;"><table style="width:250px;" cellspacing="0" cellpadding="0"><tr><td class="vat" style="width:36px;"><img src="http://static.quick-torrent.com/i/ico-error.gif" alt="error" style="margin:2px 8px 0px 5px;" /></td><td style="font:11px tahoma;color:#900000;line-height:25px;">'+items[i].stateString+'</td><td style="width:15px;"></td></tr></table></div></td>'+spl+
            '<td style="white-space:nowrap;">'+
              '<a href="add-torrent.html#similar='+escape(items[i].title)+'"><img style="margin:1px 8px 0px 0px;cursor:pointer;" src="http://static.quick-torrent.com/i/en/ico-similar.gif" alt="Find Similar" /></a>'+
              '<img style="cursor:pointer;" onclick="objDownload.deleteTorrent('+items[i].id+',\''+items[i].state+'\');" src="http://static.quick-torrent.com/i/ico-delete.gif" alt="Delete" />'+
            '</td>'+
            '</tr>';
        }
      if (items[i].size > 2*1024*1024*1024 && !$.browser.mozilla) { $('p[name=dlBrowserNoLargeFiles]').show(); }
    }

    $('#tblDownload').show().children('tbody').html(html).children('tr')
    .bind('mouseover',function(){
      $(this).children('td').addClass('hovered');
    })
    .bind('mouseout',function(){
      $(this).children('td').removeClass('hovered');
    });

    return;
  },

  parseProcessingList:function(items){

    $('#tblProcessing').hide();
    if (items.length < 1) { return; }

    html='';
    spl='<td class="spl"><div></div></td>';

    items.sort(function(a,b){
      if (a.state == "error") return 1;
      return -1;
    });

    totalSize=0; 
    for(i=0;i<items.length;i++)
    {
      size=items[i].sizeTotal;
      if (size == 0) { size='?'; }
      else { size=objCommon.formatSize(size); }

      if (items[i].state == 'new')
        { totalSize+=(size == '?'?1:items[i].sizeTotal); }

      progress=0;
      if (size != '?' && items[i].sizeTotal > 0 && items[i].sizeDone > 0)
        {
          progress=parseInt(items[i].sizeDone*100/(items[i].sizeTotal == 0?1:items[i].sizeTotal));
          if (progress > 100) { progress=100; }
        }

      html+='<tr>'+
        '<td style="text-align:left;">'+items[i].title+'</td>'+spl+
        '<td class="nw" style="text-align:right;">'+size+'</td>'+spl+
        '<td class="nw">'+objDownload.getState(items[i])+'</td>'+spl+
        '<td style="width:83px;vertical-align:top;"><table style="margin-top:3px;width:83px;background:url(http://static.quick-torrent.com/i/progressbar.gif) 0px 0px no-repeat;" cellspacing="0" cellpadding="0"><tr style="height:20px;"><td style="padding:2px;vertical-align:top;text-align:right;"><div style="margin-left:auto;height:16px;background-color:#fff;width:'+parseInt(79*((100-progress)/100))+'px"></div></td></tr></table></td><td>'+progress+'%</td>'+spl+
        '<td style="white-space:nowrap;"><img style="cursor:pointer;" onclick="objDownload.deleteTorrent('+items[i].id+',\''+items[i].state+'\');" src="http://static.quick-torrent.com/i/ico-delete.gif" alt="Delete" /></td>'+
        '</tr>';
      if (items[i].title == '?' || size == '?') { $('p[name=prMagnetDescr]').show(); }
    }

    $('#tblProcessing').show().children('tbody').html(html).children('tr')
    .bind('mouseover',function(){
      $(this).children('td').addClass('hovered');
    })
    .bind('mouseout',function(){
      $(this).children('td').removeClass('hovered');
    });

    if (totalSize > objCommon.trafficLeft) { $('p[name=prNoFunds]').show(); }

    return;
  },
  getState: function(itm)
  {
    state=eval('objCommon.messages.processingTorrent.S'+itm.state+'.'+objCommon.lng);
    if (itm.state == 'error') { state+=': '+itm.errorString; }
    else if (itm.tdState == 'storing' || itm.tdState == 'done' || itm.tdState == 'downloading') { state=eval('objCommon.messages.processingTorrent.tdSpreparing.'+objCommon.lng); }
    else if (itm.state == 'processing' && itm.dataSpeed > 0) { state+=': '+objCommon.formatSpeed(itm.dataSpeed); }
    else if (itm.state == 'processing' && itm.dataSpeed < 1 && itm.timeProcessing < 300 && itm.sizeDone < 1)
      {
        state=eval('objCommon.messages.processingTorrent.Sinitializing.'+objCommon.lng);
      }
    else if (itm.state == 'processing' && itm.dataSpeed < 1)
      {
        $('p[name=prIdle]').show();
        state=eval('objCommon.messages.processingTorrent.Sidle.'+objCommon.lng);
      }
    return state;
  },
  deleteTorrent: function(id,state)
  {
    if (confirm(eval('objCommon.messages.'+(state.match(/^(done|error)$/)?'download':'processing')+'Torrent.confirmDelete.'+objCommon.lng)))
      {
        $.ajax({
          type: 'GET',
          dataType: 'json',
          url: location.pathname+'?c=delete&id='+id+'&rnd='+Math.random(),
          success: function(data){
            objDownload.getList();
            return;
          }
        });
      }
    return;
  }
};


objStatistics={
  init:function(){
    objStatistics.getList();
    return;
  },
  getList:function(){

    $('div[name=statsLoading]').show();
    $.ajax({
      type: 'GET',
      dataType: 'json',
      url: 'statistics.html?c=get-list&rnd='+Math.random(),
      success: function(data){
        $('div[name=statsLoading]').hide();
        data.items.pop();
        objStatistics.parseList(data.items);
        return;
      }
    });

    return;
  },
  parseList:function(items){
    $('div[name=statsNoItems]').hide();

    $('#tblStatistics tbody tr').remove();
    if (items.length < 1)
      {
        $('div[name=statsNoItems]').show();
        return;
      }

    items.sort(function(a,b){
      return b.date-a.date;
    });

    html='';
    spl='<td class="spl"><div></div></td>';

    balance=0;
    for(i=0;i<items.length;i++)
    {
      if (items[i].type == '-') { balance-=parseInt(items[i].amount); }
      else { balance+=parseInt(items[i].amount); }
    }

    for(i=0;i<items.length;i++)
    {
      if (i > 0)
      {
        if (items[i-1].type == '-') { balance+=parseInt(items[i-1].amount); }
        else { balance-=parseInt(items[i-1].amount); }
      }

      html+='<tr>'+
            '<td class="nw">'+objCommon.formatDate(items[i].date)+'</td>'+spl+
            '<td>'+items[i].type+'</td>'+spl+
            '<td class="nw" style="text-align:right;">'+objCommon.formatSize(items[i].amount)+'</td>'+spl+
            '<td class="nw" style="text-align:right;">'+objCommon.formatSize(balance)+'</td>'+spl+
            '<td style="text-align:left;">'+(items[i].type=='+'?'Refill: $'+items[i].pAmount:'Download: '+items[i].dTitle)+'</td>'+
            '</tr>';
    }

    $('#tblStatistics').show().children('tbody').html(html).children('tr')
    .bind('mouseover',function(){
      $(this).children('td').addClass('hovered');
    })
    .bind('mouseout',function(){
      $(this).children('td').removeClass('hovered');
    })

    return;
  }
};

