var vars={
  traffic : 0
};

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

function format_size(size)
{
  return parseFloat(parseInt(size)/(1024*1024)).toFixed(2)+' Mb';
}

function format_account_traffic(traffic, op)
{
  traffic=parseInt(traffic);
  if (op == "init")
    { vars.traffic=traffic; }
  else { vars.traffic+=traffic; }

  $('#trafficBalance').removeClass('low'); 
  traffic=vars.traffic;

  if (traffic > 1024*1024*1024)
    { $('#trafficBalance').html('<span>'+parseFloat(traffic/1024/1024/1024).toFixed(2)+'</span> Gb'); }
  else if (traffic > 10*1024*1024)
    { $('#trafficBalance').html('<span>'+parseFloat(traffic/1024/1024).toFixed(2)+'</span> Mb'); }
  else
    {
      $('#trafficBalance').html('<span>'+parseInt(traffic/1024)+'</span> Kb').addClass('low'); 
    }
  return;
}

var reminderObj={

 errorMessages :
 {
   'noSuchClient' : '<b>E-mail/Order ID</b> is incorrect.',
   'ok' : 'Your account details have been sent to your e-mail.'
 },

 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('reminderObj.errorMessages.'+errors[i]);
   }
   $('#frmReminder div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponse : function(data)
 {
   if (data.code == 500) { reminderObj.errorReport(data.errorFields); }
   if (data.code == 200)
     {
       errormsg=eval('reminderObj.errorMessages.ok');
       $('#frmReminder div[msg=true]').addClass('msg-notice').html(errormsg);
     }

   return;
 }

};



var signupObj={

 errorMessages :
 {
   'emailIncorrect' : '<b>E-mail</b> is incorrect.',
   'emailExists' : '<b>E-mail</b> exists. Try <a href="password-reminder.html">password reminder</a>.',
   'passwordIncorrect' : '<b>Password</b> is incorrect (must be at least 5 chars long).',
   'passwordNotMatch' : '<b>Password</b> do not match.'
 },

 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('this.errorMessages.'+errors[i]);
   }
   $('#frmSignUp div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 downloadsCount : 0,

 processResponse : function(data)
 {
   if (data.code == 500) { signupObj.errorReport(data.errorFields); }
   if (data.code == 200)
     {
       signupObj.downloadsCount = parseInt(data.downloads);
       if (signupObj.downloadsCount > 0)
         { location='downloads.html'; }
       else { location='add-torrent.html'; }
     }

   return;
 }

};

var authObj={

 errorMessages :
 {
   'loginIncorrect' : 'Incorrect e-mail or password.'
 },

 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('this.errorMessages.'+errors[i]);
   }
   $('#frmAuth div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponse : function(data)
 {
   if (data.code == 500)
     {
       if (!location.href.match(/\/login.html($|\?)/))
         {
           location='login.html?loginIncorrect'; 
           return;
         }
       authObj.errorReport(data.errorFields);
     }
   if (data.code == 200)
     {
       location='add-torrent.html';
     }

   return;
 }

};

var addTorrentObj={

 errorMessages :
 {
   'typeUndefined' : 'Please select upload method.<br />',
   'urlIncorrect' : '<b>Remote URL</b> is incorrect.<br />',
   'urlFailed' : 'Failed to get <b>Remote URL</b> content or wrong format received.<br />',
   'fileFailed' : 'Wrong <b>Local File</b> format.<br />',
   'fileExists' : 'File already exists in downloads list.<br />',
   'storageError' : 'Temporary error. Please try again later.<br />'
 },

 eventsInit : false,
 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('this.errorMessages.'+errors[i]);
   }
   $('#frmAddTorrent div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponse : function(data)
 {
   if (data.code == 500) { addTorrentObj.errorReport(data.errorFields); }
   if (data.code == 200)
     {
       if (typeof(data.resultsCount) != "undefined")
         {
           addTorrentObj.drawItems(data);
         }
       else
         {
           if (data.loggedIn == "1") { location='downloads.html'; }
           else { location="/sign-up.html"; }
         }
     }

   return;
 },

 drawItems : function(json)
 {
   $('#searchItems').show();
   $('#searchItems tbody tr').each(function(){
     $(this).remove();
   });

   for (i=0;i<json.results.length;i++)
   {
     row=$('<tr style="cursor:pointer;">').html(
       '<td style="width:400px;"><div>'+json.results[i].title+'</div></td>'+
       '<td class="tr">'+format_size(json.results[i].size)+'</td>'+
       '<td class="tc">'+format_date(json.results[i].date)+'</td>'+
       '<td class="tc">'+json.results[i].seed+'/'+json.results[i].leech+'</td>'+
       '<td class="tc"><input type="checkbox" name="url:'+json.results[i].url+'" value="'+json.results[i].title+'" /></td>'
     );
     $('#searchItems tbody').append(row);
   }

   if (!addTorrentObj.eventsInit)
     {
       $('#frmAddTorrent input').live('myChange', function() {
         if (this.checked)
           {
             $(this).parents('tr:first').addClass('selected');
           }
         else
           {
             $(this).parents('tr:first').removeClass('selected');
           }
       });

       $('#searchItems tbody tr td').live('click', function() {
         if (typeof($(this).children('input').attr('name')) == "undefined")
           {
             el=$(this).parents('tr:first').find('input');
             el.attr('checked', !el.attr('checked'));
             el.trigger('myChange');
           }
       });
 
 //    $('#frmAddTorrent input').bind('change', function() { $(this).trigger('myChange'); });
       $('#frmAddTorrent input[type=checkbox]').live('click', function() { $(this).trigger('myChange'); });
       $('#frmAddTorrent input[type=checkbox]').live('change', function() { $(this).trigger('myChange'); });
       addTorrentObj.eventsInit=true;
     }

   $('#searchItems tbody tr td:first-child div').each(function(){
     $(this).css({
      'overflow' : 'hidden',
      'white-space' : 'nowrap',
      'width' : '400px',
      'max-width' : '400px'
     });
   });
 }

};

var downloadsObj={

 json : '',
 refresh : true,
 states : {
   'waiting' : 'Waiting',
   'ready' : 'Processing',
   'processing' : 'Processing',
   'paused' : 'Paused',
   'error' : 'Error',
   'done' : 'Done'
 },

 processResponse :  function(req)
 {
   if (req.status == 200)
     {
       json=eval('('+req.responseText+')');
       if (json.action == "delete")
         {
           if (parseInt(json.deleted) > 0)
             {
             }
         }
       else if (json.action == "pause")
         {
           if (parseInt(json.paused) > 0)
             {
               downloadsObj.pauseObj(json.id, 1);
               downloadsObj.drawItems(); 
             }
         }
       else if (json.action == "resume")
         {
           if (parseInt(json.resumed) > 0)
             {
               downloadsObj.resumeObj(json.id, 1);
               downloadsObj.drawItems(); 
             }
         }
       else
         {
           for (i=0; i<json.downloadItems.length;i++)
           {
             for (j=i+1; j<json.downloadItems.length; j++)
             {
               if (json.downloadItems[i].date_start < json.downloadItems[j].date_start || json.downloadItems[j].state == "waiting" || json.downloadItems[j].state == "processing")
                 {
                   tmp=json.downloadItems[i];
                   json.downloadItems[i]=json.downloadItems[j];
                   json.downloadItems[j]=tmp;
                 }
             }
           }

           downloadsObj.drawItems(json); 
         }
     }
   else
     {
//       alert(req.responseText);
     }
 },

 drawItems : function(json)
 {
   if (typeof(json)=="undefined") { json=downloadsObj.json; }

   if (!downloadsObj.refresh) { return; }

   $('#downloadItems tbody tr').each(function(){
     $(this).remove();
   });

   total=0;
   for (i=0;i<json.downloadItems.length;i++)
   {
     pItem=json.downloadItems[i];
     if (pItem.size_total == 0) { pItem.size_total=1; }

     if (pItem.state == "waiting" || pItem.state == "processing")
       { total+=parseInt(pItem.size_total-pItem.size_downloaded); }

     state_text='';

     if (pItem.state == "done") { pItem.state_text=''; pItem.size_downloaded=pItem.size_total; }
     if (pItem.state == "error") { pItem.state_text='<a href="faq.html#error">'+pItem.state_text+'</a>'; }
     if (pItem.state_text == "no seeds")
       {
         state_text='<a href="faq.html#no seeds">no seeds</a>';
       }
     else if (pItem.state_text.match(/[\d\.]+ Kb\/s/))
       {
         state_text='<a href="faq.html#speed">'+pItem.state_text+'</a>';
       }
     else { state_text=pItem.state_text; } 

     percent=parseInt(Math.floor(pItem.size_downloaded*100/pItem.size_total));
     if (percent > 100) { percent=100; }
     if (pItem.size_total < pItem.size_downloaded && percent == 100 && pItem.state != "done") { percent='99.9'; }

     html='<td style="width:400px;"><div>'+(pItem.state == "done"?'<a title="'+pItem.title+'" href="http://'+pItem.download_url+'/d'+json.downloadItems[i].id+'d'+json.downloadItems[i].hash+'" onclick="window.open(this.href);return false;">':'')+
                   pItem.title+(pItem.state == "done"?'</a>':'')+'</div></td>'+
           '<td class="tr">'+format_size(json.downloadItems[i].size_total)+'</td>'+
           '<td style="border-right:0px;width:110px;" class="tc">'+'<div style="margin:auto;background-color:#a4e142;width:100px;height:8px;border:1px solid #CCC;"><div style="float:right;width:'+(100-percent)+'px;height:8px;background-color:#FFF;"></div></div></td>'+
           '<td style="border-left:0px;font:10px tahoma;width:25px;" class="tr">'+percent+'%</td>'+
           '<td class="tc">'+eval('downloadsObj.states.'+json.downloadItems[i].state)+(state_text == ''?'':': '+state_text)+'</td>'+
           '<td class="tc">'+downloadsObj.managePanel(json.downloadItems[i])+'</td>'

// we must check if there any rows in the table and insertBefore for new records with newest date_start
// also in else if old[i] can be not equal to new[i] if objecst added, so we must to check entrie array by id
//     oldRow=$('#downloadItems tbody #downloadId'+json.downloadItems[i].id);
//     if (typeof(oldRow.attr('id')) == "undefined")
       {
         row=$('<tr id="downloadId'+json.downloadItems[i].id+'">').html(html);
         $('#downloadItems tbody').append(row);
       }
//     else if (json.downloadItems[i].state != downloadsObj.json.downloadItems[i].state || json.downloadItems[i].size_downloaded != downloadsObj.json.downloadItems[i].size_downloaded)
//       {
//         if (oldRow.html() != html) { oldRow.html(html); }
//       }
   }

   $('#downloadItems tbody tr td:first-child div').each(function(){
     $(this).css({
      'overflow' : 'hidden',
      'white-space' : 'nowrap',
      'width' : '400px',
      'max-width' : '400px'
     });
   });

   if (vars.traffic < total)
     {
       $('#downloadBalanceWarning').show();
     } 

   downloadsObj.json=json;
   return;
 },

 getInfoUrl : function(url)
 {
   if (url.match(/^http\:\/\/torrents\.thepiratebay.org\//))
     {
       res=url.match(/torrents.thepiratebay.org\/(\d+)\/([\W\w]+?)(?:\.\d+)?\.TPB\.torrent$/);
       return 'http://thepiratebay.org/torrent/'+res[1]+'/'+res[2];
     }

   if (url.match(/^http\:\/\/(www\.)?mininova\.org\/get\//))
     {
       res=url.match(/mininova.org\/get\/(\d+)/);
       return 'http://www.mininova.org/tor/'+res[1];
     }

   if (url.match(/^http\:\/\/dl\.torrentreactor\.net\//))
     {
       res=url.match(/^http\:\/\/dl\.torrentreactor\.net\/download.php\?id\=(\d+)\&name\=([\W\w]+?)$/);
       return 'http://www.torrentreactor.net/torrents/'+res[1]+'/'+res[2];
     }

   return '';
 },

 managePanel : function(obj)
 {
   infoUrl=downloadsObj.getInfoUrl(obj.url);
   if (obj.state == "processing" || obj.state == "ready")
     {
       return (infoUrl == ''?'':'<img src="http://static.torrenthandler.com/img/info.gif" alt="Info page" title="Info page" style="cursor:pointer;" onclick="window.open(\''+infoUrl+'\');" /> ')+
              '<img src="http://static.torrenthandler.com/img/pause.gif" title="Pause" alt="Pause" style="cursor:pointer;" onclick="downloadsObj.pauseObj('+obj.id+');" /> '+
              '<img src="http://static.torrenthandler.com/img/delete.gif" alt="Delete" title="Delete" style="cursor:pointer;" onclick="downloadsObj.deleteObj('+obj.id+');" /> ';
     }
   else if (obj.state == "done")
     {
       return (infoUrl == ''?'':'<img src="http://static.torrenthandler.com/img/info.gif" alt="Info page" title="Info page" style="cursor:pointer;" onclick="window.open(\''+infoUrl+'\');" /> ')+
              '<img src="http://static.torrenthandler.com/img/download.gif" alt="Download" title="Download" style="cursor:pointer;" onclick="downloadsObj.download('+obj.id+',\''+obj.hash+'\',\''+obj.download_url+'\');" /> '+
              '<img src="http://static.torrenthandler.com/img/delete.gif" alt="Delete" title="Delete" style="cursor:pointer;" onclick="downloadsObj.deleteObj('+obj.id+');" /> ';
     }
   else if (obj.state == "paused")
     {
       return '<img src="http://static.torrenthandler.com/img/start.gif" title="Resume" alt="Resume" style="cursor:pointer;" onclick="downloadsObj.resumeObj('+obj.id+');" /> '+
              '<img src="http://static.torrenthandler.com/img/delete.gif" alt="Delete" title="Delete" style="cursor:pointer;" onclick="downloadsObj.deleteObj('+obj.id+');" /> ';
     }
   else if (obj.state == "error")
     { 
       return '<img src="http://static.torrenthandler.com/img/delete.gif" alt="Delete" title="Delete" style="cursor:pointer;" onclick="downloadsObj.deleteObj('+obj.id+');" /> ';
     }
   return '';
 },

 download : function(id, hash, host)
 {
   window.open('http://'+host+'/d'+id+'d'+hash);
   return;
 },

 deleteObj : function(id, force)
 {
   if (confirm('Delete torrent?'))
     {
       $.ajax({
         url:'downloads.html',
         data:'c=delete&id='+id+'&rnd='+Math.random(),
         dataType:"json",
         complete: downloadsObj.processResponse
       });
     }
 },

 pauseObj : function(id, force)
 {
   if (typeof(force) != "undefined")
     {
       for (i=0; i<downloadsObj.json.downloadItems.length;i++)
       {
         if (downloadsObj.json.downloadItems[i].id == id)
           { downloadsObj.json.downloadItems[i].state="paused"; }
       }
       return;
     }
   if (confirm('Pause torrent?'))
     {
       $.ajax({
         url:'downloads.html',
         data:'c=pause&id='+id+'&rnd='+Math.random(),
         dataType:"json",
         complete: downloadsObj.processResponse
       });
     }
 },

 resumeObj : function(id, force)
 {
   if (typeof(force) != "undefined")
     {
       for (i=0; i<downloadsObj.json.downloadItems.length;i++)
       {
         if (downloadsObj.json.downloadItems[i].id == id)
           { downloadsObj.json.downloadItems[i].state="waiting"; }
       }
       return;
     }
   if (confirm('Resume torrent?'))
     {
       $.ajax({
         url:'downloads.html',
         data:'c=resume&id='+id+'&rnd='+Math.random(),
         dataType:"json",
         complete: downloadsObj.processResponse
       });
     }

   return;
 }

};

var accountObj={

 errorMessages :
 {
   'emailIncorrect' : '<b>E-mail</b> is incorrect.',
   'emailExists' : '<b>E-mail</b> exists. Try <a href="password-reminder.html">password reminder</a>.',
   'passwordIncorrect' : '<b>Password</b> incorrect (must be at last 5 chars long).',
   'passwordNotMatch' : '<b>Password</b> do not match.',
   'passwordActiveNotMatch' : '<b>Active Password</b> is incorrect.',
   'notificationsIncorrect' : '<b>E-mail Notifications</b> not selected.',
   'okData' : 'Account data updated.',
   'okPassword' : 'Password updated.'
 },

 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('accountObj.errorMessages.'+errors[i]);
   }
   $('#frmAccountData div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponse : function(data)
 {
   if (data.code == 500) { accountObj.errorReport(data.errorFields); }
   if (data.code == 200)
     {
       $('#frmAccountData div[msg=true]').addClass('msg-notice').html(eval('accountObj.errorMessages.okData'));
       $('#frmAccountData :input').each(function(){
         if (this.tagName.toLowerCase() == "input" && this.type == "password") { this.value=''; }
       });
     }

   return;
 },

 errorReportPassword : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('accountObj.errorMessages.'+errors[i]);
   }
   $('#frmAccountPassword div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponsePassword : function(data)
 {
   if (data.code == 500) { accountObj.errorReportPassword(data.errorFields); }
   if (data.code == 200)
     {
       $('#frmAccountPassword div[msg=true]').addClass('msg-notice').html(eval('accountObj.errorMessages.okPassword'));
       $('#frmAccountPassword :input').each(function(){
         if (this.tagName.toLowerCase() == "input" && this.type == "password") { this.value=''; }
       });
     }

   return;
 }

};

var supportObj={

 errorMessages :
 {
   'emailIncorrect' : '<b>E-mail</b> is incorrect.',
   'nameIncorrect' : '<b>Name</b> is incorrect.',
   'messageIncorrect' : '<b>Message</b> is incorrect.',
   'okMsg' : 'Your support request has been sent.'
 },

 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('this.errorMessages.'+errors[i]);
   }
   $('#frmSupport div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponse : function(data)
 {
   if (data.code == 500) { supportObj.errorReport(data.errorFields); }
   if (data.code == 200)
     {
       $('#frmSupport div[msg=true]').addClass('msg-notice').html(eval('supportObj.errorMessages.okMsg'));
       $('#frmSupport :input').each(function(){
         if ((this.tagName.toLowerCase() == "input" || this.tagName.toLowerCase() == "textarea") && (this.type == "text" || this.type == "textarea"))
           { this.value=''; }
       });
     }

   return;
 }

};

var testimonialsObj={

 errorMessages :
 {
   'emailIncorrect' : '<b>E-mail</b> is incorrect.',
   'nameIncorrect' : '<b>Name</b> is incorrect.',
   'countryIncorrect' : '<b>Country</b> is incorrect.',
   'messageIncorrect' : '<b>Testimonial</b> is incorrect.',
   'okMsg' : 'Your testimonial has been submitted.'
 },

 errorReport : function(errors) 
 {
   errormsg='';
   for (i=0;i<errors.length;i++)
   {
     errormsg+=(errormsg == ''?'':"<br />")+eval('this.errorMessages.'+errors[i]);
   }
   $('#frmTestimonials div[msg=true]').addClass('msg-error').html(errormsg);
   return;
 },

 processResponse : function(data)
 {
   if (data.code == 500) { testimonialsObj.errorReport(data.errorFields); }
   if (data.code == 200)
     {
       $('#frmTestimonials div[msg=true]').addClass('msg-notice').html(eval('testimonialsObj.errorMessages.okMsg'));
       $('#frmTestimonials :input').each(function(){
         if ((this.tagName.toLowerCase() == "input" || this.tagName.toLowerCase() == "textarea") && (this.type == "text" || this.type == "textarea"))
           { this.value=''; }
       });
     }

   return;
 }

};



var refillObj={

 processResponse : function(data)
 {
   json=eval('('+data.responseText+')');
   if (json.code == 200 && json.url != "")
     {
//       format_account_traffic(json.traffic);
       window.open(json.url);
     }

   return;
 }

};

var balanceObj={

 json : '',

 processResponse :  function(req)
 {
   if (req.status == 200)
     {
       balanceObj.json=eval('('+req.responseText+')');
       balanceObj.drawItems(); 
     }
   else
     {
//       alert(req.responseText);
     }
 },

 drawItems : function()
 {
   json=balanceObj.json;

   $('#balanceItems').show();
   $('#balanceItems tbody tr').each(function(){
     $(this).remove();
   });

   for (i=0;i<json.balanceItems.length;i++)
   {
     row=$('<tr>').html(
       '<td>'+format_date(json.balanceItems[i].date)+'</td>'+
       '<td class="tc">'+json.balanceItems[i].sign+'</td>'+
       '<td class="tr">'+format_size(json.balanceItems[i].amount)+'</td>'+
       '<td>'+(json.balanceItems[i].sign == "+"?'Refill: $':'Download: ')+json.balanceItems[i].data
     );
     $('#balanceItems tbody').append(row);
   }
 }

};
