/*!
 *  SDP - Web Application JS
 *  global.js
 * 
 *  Copyright (c) 2009 Tomnica, Inc
 *  http://www.tomnica.com
 * 
 *  Author: Laurent Luce
 * 
 */ 

var g_dialog_widget_id = '';
var g_widget_id = '';
var g_nb_widgets_open = 1;
var g_last_widget_id_open = '';
var g_z_index = 13;
var g_pb_interval = 0;
var g_mode = 0;
var g_device_id = 0;
var g_last_folders_config = new Date().getTime();
var g_oper = '';
var g_oper_user_id = 1;
var g_oper_device_id = 0;
var g_oper_option = 0;
var g_updateDeviceStatusFirst = true;
var g_status_progress = 0;
var g_apply_button_my_devices_toggle = 0;
var g_oper_data = '';
var g_oper_data2 = '';
var g_oper_element = undefined;
var g_count = 1;
var g_username = '';
var g_monitored = 0;
var g_compromised = 0;
var g_devices_name = [];
var g_devices_id = [];
var g_devices_time_bomb = [];
var g_sel_size = 0;
var g_progressbar_size = 0;
var g_delete_levels = 0;

MODE_FOLDERS_CONFIG = 1;

MSG_GET_FOLDERS = 1;
MSG_RESTORE_FOLDERS = 2;

function initTomnica()
{
}

function makeRequest(url)
{
  var httpRequest;

  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
    if (httpRequest.overrideMimeType) {
      httpRequest.overrideMimeType('text/xml');
    }
  }
  else if (window.ActiveXObject) { // IE
    try {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      try {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {}
    }
  }

  if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }

  httpRequest.onreadystatechange = function() { processRequest(httpRequest); };
  httpRequest.open('GET', url, true);
  httpRequest.send('');
}

// process the xml requests received from the server

function processRequest(httpRequest)
{
  var i, res;

  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      res = parseXML(httpRequest.responseText);
      }
    $('body').css('cursor', 'default');
  }
}

function parseXML(text)
{
  try //Internet Explorer
  {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(text);
  }
  catch(e)
  {
    try //Firefox, Mozilla, Opera, etc.
    {
      parser=new DOMParser();
      xmlDoc=parser.parseFromString(text,"text/xml");
    }
    catch(e)
    {
      //alert(e.message);
      return;
    }
  }

  var id;
  var element_status = xmlDoc.getElementsByTagName("status");
  var elements = xmlDoc.getElementsByTagName("tomnica");
  if(elements.length > 0)
  {
    elements = xmlDoc.getElementsByTagName("username");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "1")
        $("#username_unavailable").css("display", "");
      return;
    }

    elements = xmlDoc.getElementsByTagName("login");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "1")
        $("#login_status_failure").css("display", "");
      else
        window.location = '/sdp.fcgi/dashboard?';
      return;
    }
    
    elements = xmlDoc.getElementsByTagName("sign_up");
    if(elements.length > 0)
    {
      $("#register_alpha_status_success").css("display", "none");
      $("#register_alpha_status_duplicate").css("display", "none");
      $("#register_alpha_status_failure").css("display", "none");
      $("#register_alpha_status_recaptcha_failure").css("display", "none");
      if(element_status[0].childNodes[0].nodeValue == "0")
        $("#register_alpha_status_success").css("display", "");
      else if(element_status[0].childNodes[0].nodeValue == "2")
        $("#register_alpha_status_duplicate").css("display", "");
      else if(element_status[0].childNodes[0].nodeValue == "3")
        $("#register_alpha_status_recaptcha_failure").css("display", "");
      else
        $("#register_alpha_status_failure").css("display", "");
      return;
    }

    elements = xmlDoc.getElementsByTagName("logout");
    if(elements.length > 0)
    {
      window.location = '/';
      return;
    }
    
    elements = xmlDoc.getElementsByTagName("get_validation_key");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "0")
        updateTips(VALIDATION_KEY_SENT_STR, 'info');
      return;
    }
    
    elements = xmlDoc.getElementsByTagName("invite");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "0") {
        updateTips('Invitation(s) sent', 'info');
        setTimeout("updateTips('', 'info');$('#email_invite').val('');", 3000);
      }
      return;
    }
    
    elements = xmlDoc.getElementsByTagName("set_compromised");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "0") {
        updateTips(DEVICE_MARKED_COMPROMISED_STR, 'info');
        id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
        $(id).css('color', 'red');
        $(id).css('fontWeight', 'bold');
        $(id).parent().addClass('device_compromised');
      }
      else if(element_status[0].childNodes[0].nodeValue == "1")
        updateTips(INVALID_KEY_STR, 'error');
      return;
    }

    elements = xmlDoc.getElementsByTagName("set_uncompromised");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "0") {
        updateTips(DEVICE_MARKED_UNCOMPROMISED_STR, 'info');
        id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
        $(id).css('color', '#33CC33');
        $(id).css('fontWeight', 'normal');
        $(id).parent().removeClass('device_compromised');
      }
      else if(element_status[0].childNodes[0].nodeValue == "1")
        updateTips(INVALID_KEY_STR, 'error');
      return;
    }

    elements = xmlDoc.getElementsByTagName("delete_content");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "0")
        updateTips(CONTENT_DELETED_STR, 'info');
      else if(element_status[0].childNodes[0].nodeValue == "1")
        updateTips(INVALID_KEY_STR, 'error');
      return;
    }

    elements = xmlDoc.getElementsByTagName("del_account");
    if(elements.length > 0)
    {
      if(element_status[0].childNodes[0].nodeValue == "0") {
        window.location = '/';
      }
      else if(element_status[0].childNodes[0].nodeValue == "1")
        updateTips(INVALID_KEY_STR, 'error');
      return;
    }

    elements = xmlDoc.getElementsByTagName("info_recovery_get_validation_key");
    if(elements.length > 0)
    {
      $("#info_recovery_status_key_sent").css("display", "none");
      $("#info_recovery_status_invalid_email").css("display", "none");
      $("#info_recovery_status_success").css("display", "none");
      $("#info_recovery_status_key_failure").css("display", "none");

      if(element_status[0].childNodes[0].nodeValue == "0")
        $("#info_recovery_status_key_sent").css("display", "");
      else
        $("#info_recovery_status_invalid_email").css("display", "");
      return;
    }

    elements = xmlDoc.getElementsByTagName("set_info_recovery");
    if(elements.length > 0)
    {
      $("#info_recovery_status_key_sent").css("display", "none");
      $("#info_recovery_status_invalid_email").css("display", "none");
      $("#info_recovery_status_success").css("display", "none");
      $("#info_recovery_status_key_failure").css("display", "none");

      if(element_status[0].childNodes[0].nodeValue == "0")
        $("#info_recovery_status_success").css("display", "");
      else
        $("#info_recovery_status_key_failure").css("display", "");
      return;
    }

    $("#register_status_success").css("display", "none");
    $("#register_status_duplicate").css("display", "none");
    $("#register_status_failure").css("display", "none");
    $("#register_status_recaptcha_failure").css("display", "none");
    $("#register_status_key_failure").css("display", "none");
    $("#register_status_email_duplicate").css("display", "none");
    if(element_status[0].childNodes[0].nodeValue == "0")
    {
      // registration ok
      // hide sign up div
      $("#sign_up_div").hide();
      // login user
      makeRequest("/web_modules/process.py?request=login&id="+escape($("#id_username_signup").val())+"&password="+escape($("#id_password_signup").val()));
    }
    else if(element_status[0].childNodes[0].nodeValue == "2")
      $("#register_status_duplicate").css("display", "");
    else if(element_status[0].childNodes[0].nodeValue == "3")
      $("#register_status_recaptcha_failure").css("display", "");
    else if(element_status[0].childNodes[0].nodeValue == "4")
      $("#register_status_key_failure").css("display", "");
    else if(element_status[0].childNodes[0].nodeValue == "5")
      $("#register_status_email_duplicate").css("display", "");
    else
      $("#register_status_failure").css("display", "");
  }
}

function trim(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function showWidget(widget)
{
  if($("#"+widget).length > 0 && !($("#"+widget).is(':visible'))) {
    $("#"+widget).css('z-index',g_z_index++);
    // if last widget is an attached help then display this widget
    // below it
    if(g_last_widget_id_open.indexOf('_help') != -1)
      $("#"+widget).css('top',parseInt($("#"+g_last_widget_id_open).css('top'), 10)+parseInt($("#"+g_last_widget_id_open).css('height'), 10)+20);
    else if(widget.indexOf('_folders') != -1)
      g_pb_interval = window.setInterval(getProgressStatus, 10000);

    $("#"+widget).show();
    g_nb_widgets_open++;
    g_last_widget_id_open = $("#"+widget)[0].id;
  }
}

function placeWidgets(init, username)
{
  if(init)
    $("#layer_client_install").hide();

  if(username == "admin") {
    $("#layer_users").show();
    $("#layer_log").css('left',parseInt($("#layer_users").css('left'), 10)+parseInt($("#layer_users").css('width'), 10)+20);
    $("#layer_log").show();
  }
  else {
    $("#layer_my_devices").show();
    $("#layer_my_devices_tips").css('left',parseInt($("#layer_my_devices").css('left'), 10)+190);
    $("#layer_my_devices_tips").css('top',parseInt($("#layer_my_devices").css('top'), 10)+50);
    $("#layer_my_devices_tips").show();
    $("#layer_my_devices_privacy").css('left',parseInt($("#layer_my_devices").css('left'), 10)+190);
    $("#layer_my_devices_privacy").css('top',parseInt($("#layer_my_devices_tips").css('top'), 10) + 160);
    $("#layer_my_devices_privacy").show();
    $("#layer_my_online_storage").css('left',parseInt($("#layer_my_devices").css('left'), 10)+parseInt($("#layer_my_devices").css('width'), 10)+20);
    $("#layer_my_online_storage").show();
    $("#layer_my_online_storage_tips").css('left',parseInt($("#layer_my_online_storage").css('left'), 10)+140);
    $("#layer_my_online_storage_tips").css('top',parseInt($("#layer_my_online_storage").css('top'), 10)+50);
    $("#layer_my_online_storage_tips").show();
    $("#layer_usb_monitoring").css('left',parseInt($("#layer_my_devices").css('left'), 10)+parseInt($("#layer_my_devices").css('width'), 10)+20);
    //$("#layer_account").css('left',parseInt($("#layer_my_devices").css('left'), 10)+parseInt($("#layer_my_devices").css('width'), 10)+20);
    //$("#layer_account").show();
    //$("#layer_actions").css('left',parseInt($("#layer_account").css('left'), 10));
    //$("#layer_actions").css('top',parseInt($("#layer_account").css('top'),10)+125);
    //$("#layer_actions").show();
  }
}

function openDialog(widget)
{
  $('#key_'+g_dialog_widget_id).val('');
  $('#tips_'+g_dialog_widget_id).val('');
  $("#"+widget).dialog('open');
}

function closeDialog(widget)
{
  $("#"+widget).dialog('close');
}

function updateTips(t, type) {
  if($('#tips_'+g_widget_id).length > 0)
  {
    $('#tips_'+g_widget_id).text(t);
    if(type == 'info')
      $('#tips_'+g_widget_id).css('color', 'green');
    else
      $('#tips_'+g_widget_id).css('color', 'red');
  }
}


// tree
function getClientFolderIcon(val) {
  return '/media/img/directory_'+val+'.png';
}

function getFolderClass(action) {
  switch(action) {
    case 1:
      return 'backup';
    case 2:
      return 'protect_wipe';
    case 3:
      return 'backup_protect_wipe';
    case 4:
      return 'protect_encrypt';
    case 5:
      return 'backup_protect_encrypt';
    case 9:
      return 'not_set';
    default:
      return '';
  }
}

function getFolderAction(e) {
  if($(e).hasClass('backup'))
    return 1;
  else if($(e).hasClass('protect_wipe'))
    return 2;
  else if($(e).hasClass('backup_protect_wipe'))
    return 3;
  else if($(e).hasClass('protect_encrypt'))
    return 4;
  else if($(e).hasClass('backup_protect_encrypt'))
    return 5;
  else if($(e).hasClass('not_set'))
    return 9;
  else
    return 0;
}

function applyTree() {
  
  var type = '';
  var modified = 0;
  var p, backup, protect_wipe, protect_encrypt, folder, backup_diff, protect_wipe_diff, protect_encrypt_diff, device_id;
  var params = '';

  $('body').css('cursor', 'wait');
  // get all folders
  var folders = $("[id^=client_folder_],[id^=client_contacts_],[id^=client_calendar_],[id^=client_tasks_],[id^=client_notes_],[id^=client_phone_logs_],[id^=client_bookmarks_],[id^=client_sms_],[id^=client_mms_],[id^=client_m_folder],[id^=client_sd_card_]");
  // for each folder
  for(i=0;i<folders.length;i++)
  {
    if(($(folders[i]).data('action') != undefined) && ($(folders[i]).data('apply') == 0))
    {
      p = $(folders[i]).parent().parent();
      if (p == undefined)
        continue;

      backup = $(folders[i]).data('backup');
      protect_wipe = $(folders[i]).data('protect_wipe');
      protect_encrypt = $(folders[i]).data('protect_encrypt');
      folder = $(folders[i]).children()[0].rel;
      device_id = $(folders[i]).data('device_id');
      
      if(backup == $(p).data('backup')
        && protect_wipe == $(p).data('protect_wipe')
        && protect_encrypt == $(p).data('protect_encrypt')
        && $(p).attr('id').indexOf('client_folders_') == -1)
        continue;
      
      // if all childs are not marked with same state -> files only
      childs = $("a[rel^='"+folder+"']");
      if(childs && (backup || protect_wipe || protect_encrypt))
      {
        backup_diff = 0;
        protect_wipe_diff = 0;
        protect_encrypt_diff = 0;
        for(j=0;j<childs.length;j++)
        {
          if($(childs[j]).attr('rel') == folder)
            continue;

          if($(childs[j]).parent().attr('id').indexOf('client_folder_'+device_id+'_') == -1)
            continue;

          if($(childs[j]).parent().data('backup') != $(folders[i]).data('backup'))
            backup_diff = 1;
          
          if($(childs[j]).parent().data('protect_wipe') != $(folders[i]).data('protect_wipe'))
            protect_wipe_diff = 1;
          
          if($(childs[j]).parent().data('protect_encrypt') != $(folders[i]).data('protect_encrypt'))
            protect_encrypt_diff = 1;
        }
        
        if(protect_wipe && protect_wipe_diff) {
          protect_wipe += 1;
          $(folders[i]).data('protect_wipe', protect_wipe);
        }
        
        if(protect_encrypt && protect_encrypt_diff) {
          protect_encrypt += 1;
          $(folders[i]).data('protect_encrypt', protect_encrypt);
        }
        
        if(backup && backup_diff) {
          backup += 1;
          $(folders[i]).data('backup', backup);
        }
      }
     
      // update params list to send to server 
      params += folder.slice(0, -1) + ',' + backup + ',' + protect_wipe + ',' + protect_encrypt + ',' + device_id + ';';
      $(folders[i]).data('apply', 1);
      if(!modified)
        modified = 1;
    }
  }
 
  if(modified) {
    // send params to db
    url = "/web_modules/process.py?tb="+Math.random()+"&request=edit_client_folders";
    $.post(url, {params: params.slice(0, -1)});
    $('#apply_button_my_devices').toggle('pulsate',{},500);
    g_apply_button_my_devices_toggle = 0;
  }

  resetMode(); 
  $('body').css('cursor', 'default');
}

// t is the directory element
// val is the action value: 1=backup, 2=protect_wipe, 4=protect_encrypt
function setClientFolder(t, val) {
 
  var action, path, childs, device_id;

  g_last_folders_config = new Date().getTime();

  if($(t).attr('id').indexOf('client_folders_') != -1)
    return;

  action = $(t).data('action');
  if(!action)
    action = getFolderAction(t);
    
  if(action == 9)
    action = 0;

  if((action == 1 || action == 3 || action == 5) && (val == 1))
    action -= val;
  else if((action == 2 || action == 3) && (val == 2))
    action -= val;
  else if((action == 4 || action == 5) && (val == 4))
    action -= val;
  else if((action == 2 || action == 3) && (val == 4))
    action += val - 2;
  else if((action == 4 || action == 5) && (val == 2))
    action += val - 4;
  else
    action += val;

  if($(t).attr('id').indexOf('client_folders_') == -1)
  {
    removeClasses(t);
    $(t).addClass(getFolderClass(action));
    updateTreeNode(t, action);
    // update selected size
    var type;
    if(action == 1 || action == 3 || action == 5)
      type = 'add';
    else
      type = 'del';
    var anchor = $(t).children()[0];
    updateStorageSize($(anchor).text(), type, 'selected');
  }

  path = $(t).children()[0].rel;
  if(path == '/')
    path = '';
 
  device_id = getDeviceIdFromId($(t).attr('id'));

  // mark all childs the same
  childs = $("a[rel^='"+path+"']");
  for(i=0;i<childs.length;i++)
  {
    if($(childs[i]).attr('rel') == path)
      continue;

    if($(childs[i]).parent().attr('id').indexOf('client_folder_'+device_id+'_') != 0)
      continue;

    removeClasses($(childs[i]).parent());
    $(childs[i]).parent().addClass(getFolderClass(action));
    updateTreeNode($(childs[i]).parent(), action);
  }
  
  if(!g_apply_button_my_devices_toggle) {
    $('#apply_button_my_devices').toggle('pulsate',{},500);
    g_apply_button_my_devices_toggle = 1;
  }
}

function updateTreeIcons(dir) {
  
  var action, dir_action, path, childs, device_id;
  
  // if the childs of the toggled folder have never been
  // displayed and this folder has been modified (ie: present in the
  // array), then set all childs
  if($(dir).attr('id') != 'folders')
  {
    if($(dir).data('action') == undefined)
      dir_action = getFolderAction($(dir));
    else
      dir_action = $(dir).data('action');
   
    path = $(dir).children()[0].rel;
    device_id = getDeviceIdFromId($(dir).attr('id')); 
    childs = $("a[rel^='"+path+"']");
    for(i=0;i<childs.length;i++)
    {
      if($(childs[i]).attr('rel') == path)
        continue;

      if($(childs[i]).parent().attr('id').indexOf('client_folder_'+device_id+'_') == -1)
        continue;

      action = getFolderAction($(childs[i]).parent());
      if(action == 9 && dir_action != 9)
      {
        removeClasses($(childs[i]).parent());
        $(childs[i]).parent().addClass(getFolderClass(dir_action));
        updateTreeNode($(childs[i]).parent(), dir_action);
      }
    }

    $(dir).data('toggled', 1);
  }
}

function updateTreeNode(t, action) {
            
  $(t).data('device_id', getDeviceIdFromId($(t).attr('id')));
  $(t).data('action', action);
  if(action == 1 || action == 3 || action == 5)
    $(t).data('backup', 1);
  else
    $(t).data('backup', 0);
  if(action == 2 || action == 3)
    $(t).data('protect_wipe', 1);
  else
    $(t).data('protect_wipe', 0);
  if(action == 4 || action == 5)
    $(t).data('protect_encrypt', 1);
  else
    $(t).data('protect_encrypt', 0);
  $(t).data('apply', 0);
}

// end of tree

// progress bar
function getProgressStatus()
{
  $.get("/web_modules/process.py?tb="+Math.random()+"&request=get_progress_status&device_id=1", { },
    function(xml) {
      var text;
      var st = $("status",xml).text();
      var status_progress = $("status_progress",xml).text();
      if(st != "backup" && st != "restore") {
        var last_op = $("last_op",xml).text().capitalize();
        var last_op_time = $("last_op_time",xml).text();
        if(last_op != '')
          text = last_op+": "+last_op_time;
        else
          text = '';
      }
      else {
        text = $("status",xml).text().capitalize() + ": " + status_progress + "%";
      }
      updateProgressBar(text, status_progress);
  });
}

// end of progress bar

String.prototype.capitalize = function(){
  return this.replace(/\S+/g, function(a){
    return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
  });
};

function removeClasses(e) {
    $(e).removeClass('backup protect protect_encrypt protect_wipe backup_protect_wipe backup_protect_encrypt not_set');
}
  
function resetMode() {
  if(g_mode != 0)
  {
    if(g_mode == 1) {
      $.get("/web_modules/process.py?tb="+Math.random()+"&request=clean_folders_db");
      g_device_id = 0;
    }

    g_mode = 0;
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=set_mode&mode=0", { }, function(xml){});
  }
}

function manager() {
  if(new Date().getTime() - g_last_folders_config > 60000)
    resetMode();
}

function encodePath(path)
{
  if(path == undefined || path.length <= 1)
    return path;

  var i,a,res;

  a = path.split('/');
  for(i=0;i<a.length;i++)
    a[i] = encodeURIComponent(a[i]);
  res = a[0];
  for(i=1;i<a.length;i++)
    res += '/'+a[i];
  return res;
}

function getDeviceIdFromId(id)
{
  if(id.indexOf('backup_device_') != -1)
    return id.split('_')[3];
  else if(id.indexOf('device_') != -1)
    return id.split('_')[2];
  else if(id.indexOf('backup_client_folder') != -1)
    return id.split('_')[3];
  else if(id.indexOf('client_folder') != -1)
    return id.split('_')[2];
  else if(id.indexOf('backup_client_file') != -1)
    return id.split('_')[3];
  else
    return id.split('_')[id.split('_').length-1];
}

function getUserIdFromId(id)
{
  return id.split('_')[id.split('_').length-2];
}

function isDeviceCompromised(e) {
  if($(e).hasClass('device_compromised'))
    return 1;
  else
    return 0;
}

function isDeviceMonitored(e) {
  if($(e).hasClass('device_monitored'))
    return 1;
  else
    return 0;
}

function openDeviceCompromisedDialog(e) {
  
  var title, str;
          
  if($("#layer_compromised").length > 0) {
    str = 'compromised';
    g_widget_id = str;
  }
  else {
    g_dialog_widget_id = 'layer_uncompromised';
    str = 'uncompromised';
    g_widget_id = str;
  }
    
  g_dialog_widget_id = 'layer_'+str;
  
  if(g_compromised) {
    title = UNCOMPROMISED_STR;
    req = 'uncompromised';
  }
  else {
    title = COMPROMISED_STR;
    req = 'compromised';
  }
    
  if(str == 'compromised')
    g_layer_compromised_request = 'set_'+req;
  else
    g_layer_uncompromised_request = 'set_'+req;
    
  g_oper = 'set_'+req;
   
  $('#tips_'+g_widget_id).text(''); 
  $('#key_'+g_widget_id).val('');

  openDialog(g_dialog_widget_id);
  $("#ui-dialog-title-"+g_dialog_widget_id).text(title);
}

function setDeviceName(e) {
  g_oper = 'set_device_name';
  g_dialog_widget_id = 'input_dialog';
  $("#ui-dialog-title-input_dialog").text(DEVICE_NAME_STR);
  var id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
  var a = $(id).text().split(' - ');
  $("#input_dialog_input").val(a[0]);
  openDialog('input_dialog');
}

function removeDevice(e) {
  g_oper = 'remove_device';
  g_dialog_widget_id = 'confirmation_dialog';
  $("#ui-dialog-title-"+g_dialog_widget_id).text(REMOVE_DEVICE_STR);
  $("#confirmation_dialog_label").text(CONFIRM_REMOVE_DEVICE_STR);
  openDialog('confirmation_dialog');
}

function sendDeviceReport(e) {
  g_oper = 'device_send_report';
  g_dialog_widget_id = 'confirmation_dialog';
  $("#ui-dialog-title-"+g_dialog_widget_id).text(REPORT_DEVICE_STR);
  $("#confirmation_dialog_label").text(CONFIRM_REPORT_DEVICE_STR);
  openDialog('confirmation_dialog');
}

function setDeviceCompromised(e) {
  
  if(g_compromised) {
    title = UNCOMPROMISED_STR;
    req = 'uncompromised';
    label = CONFIRM_UNCOMPROMISED_STR;
  }
  else {
    title = COMPROMISED_STR;
    req = 'compromised';
    label = CONFIRM_COMPROMISED_STR;
  }
  g_oper = 'set_'+req;
  g_dialog_widget_id = 'confirmation_dialog';
  $("#ui-dialog-title-"+g_dialog_widget_id).text(title);
  $("#confirmation_dialog_label").text(label);
  openDialog('confirmation_dialog');
}

function openReportDataDialog() {
  g_oper = 'report_data';
  g_dialog_widget_id = 'confirmation_dialog';
  $("#ui-dialog-title-"+g_dialog_widget_id).text(USER_EXPERIENCE_DATA_STR);
  $("#confirmation_dialog_label").text(USER_EXPERIENCE_DATA_QUERY_STR);
  $("#confirmation_dialog").dialog('option', 'width', 400);
  $("#confirmation_dialog").dialog('option', 'height', 250);
  openDialog('confirmation_dialog');
}

function monitorDevice(e) {
  
  g_oper = 'monitor_device';
  if(g_monitored == 1) {
    g_oper_data = 0;
    label = CONFIRM_DISABLE_MONITORING_DEVICE_STR;
  }
  else {
    g_oper_data = 1;
    label = CONFIRM_ENABLE_MONITORING_DEVICE_STR;
  }
  g_dialog_widget_id = 'confirmation_dialog';
  $("#ui-dialog-title-"+g_dialog_widget_id).text(DEVICE_MONITORING_STR);
  $("#confirmation_dialog_label").text(label);
  openDialog('confirmation_dialog');
}

function inputDialogApply() {
  if(g_oper == 'set_device_name')
  {
    // set device name
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=set_device_name&name="+encodeURIComponent($('#input_dialog_input').val())+"&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { },
    function(xml){
      var id1 = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
      var id2 = "#backup_a_device_"+g_oper_user_id+"_"+g_oper_device_id;
      var arrIds = [ id1, id2 ];
      $.each(arrIds, function(idx, id) {
        var label = $(id).text();
        var a = label.split(' - ');
        a[0] = $('#input_dialog_input').val();
        label = '';
        for(i=0;i<a.length;i++) {
          label += a[i];
          if(i < a.length-1 && a[i+1] != '')
            label += ' - ';
        }
        $(id).text(label);
      });
    });
  }
  closeDialog(g_dialog_widget_id);
}

function confirmationDialogApply() {
  if(g_oper == 'remove_device')
  {
    // remove device
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=remove_device&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { },
    function(xml){
      $("#device_"+g_oper_user_id+"_"+g_oper_device_id).remove();
      if($("#backup_device_"+g_oper_user_id+"_"+g_oper_device_id).length > 0)
        $("#backup_device_"+g_oper_user_id+"_"+g_oper_device_id).remove();
    });
  }
  else if(g_oper == 'device_send_report')
  {
    // report device
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=device_send_report&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { },
    function(xml){
    });
  }
  else if(g_oper == 'restore_folders')
  {
    // get device id to restore to
    g_oper_device_id = $("#select_dialog_select").val() 
    g_oper_data2 = $("#select_dialog_select2").val() 
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=add_message&type="+MSG_RESTORE_FOLDERS+"&data="+g_oper_data+"&option="+g_oper_option+"&state=1&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id+'&version='+g_oper_data2, { }, function(xml){});
    var a = $(g_oper_element).children()[0];
    $(a).css('color', '#6d84ab');
    $(a).css('fontWeight', 'bold');
    var id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
    var label = {text: $(id).text()};
    updateLabel(label, RESTORE_CAP_STR + ': 0%');
    $(id).text(label.text);
    $(id).css('color', '#6d84ab');
    $(id).css('fontWeight', 'bold');
    g_count = -1;
  }
  else if(g_oper == 'download_file')
  {
    // get device id to restore to
    g_oper_option = $("#select_dialog_select").val();
    sendDownloadFile(1);
  }
  else if(g_oper == 'delete_content')
  {
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=delete_content&folder="+g_oper_data+"&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { }, function(xml){});
    if($(g_oper_element).attr('id').indexOf('backup_client_folders_') != -1) {
      var e = $(g_oper_element).children()[1];
      $(e).remove();
    }
    else {
      $(g_oper_element).remove();
    }
    /*if(g_delete_levels == 0) {
      g_delete_levels = g_oper_data.split('/').length;
    }
    else if(g_delete_levels > g_oper_data.split('/').length) {
      // refresh panel
      $('#refresh_button_my_online_storage').click();
    }
    else {
      updateStorageSize(g_oper_data2, 'del', 'progressbar')
    }*/
  } 
  else if(g_oper == 'monitor_device')
  {
    // monitor device
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=set_monitor&monitor="+g_oper_data+"&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { },
    function(xml){
      var id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
      if(g_oper_data == '1') {
        $(id).parent().addClass('device_monitored');
      }
      else {
        $(id).parent().removeClass('device_monitored');
      }
    });
  }
  else if(g_oper == 'report_data')
  {
    // remove device
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=set_report_data", { },
    function(xml){
    });
  }
  else if(g_oper == 'set_compromised')
  {
    // compromised device
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=set_compromised&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { },
    function(xml){
      id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
      $(id).css('color', 'red');
      $(id).css('fontWeight', 'bold');
      $(id).parent().addClass('device_compromised');
    });
  }
  else if(g_oper == 'set_uncompromised')
  {
    // compromised device
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=set_uncompromised&device_id="+g_oper_device_id+"&user_id="+g_oper_user_id, { },
    function(xml){
      id = "#a_device_"+g_oper_user_id+"_"+g_oper_device_id;
      $(id).css('color', '#33CC33');
      $(id).css('fontWeight', 'normal');
      $(id).parent().removeClass('device_compromised');
    });
  }
  else if(g_oper == 'upgrade_plan')
  {
    // send information to server
    url = "/web_modules/process.py?tb="+Math.random()+"&request=checkout";
    $.post(url, {key: g_session_key, plan_id: $('#upgrade_plan_dialog_select').val()});
    // set form fields
    var plan_desc, plan_price;
    if($('#upgrade_plan_dialog_select').val() == '1') {
      plan_desc = g_plan_1_description;
      plan_price = g_plan_1_price;
    }
    else if($('#upgrade_plan_dialog_select').val() == '2') {
      plan_desc = g_plan_2_description;
      plan_price = g_plan_2_price;
    }
    $('[name=shopping-cart.items.item-1.item-name]').val(plan_desc);
    $('[name=shopping-cart.items.item-1.subscription.payments.subscription-payment-1.maximum-charge]').val(plan_price);
    $('[name=shopping-cart.items.item-1.item-description]').val(plan_desc);
    $('[name=shopping-cart.items.item-1.subscription.recurrent-item.item-name]').val(plan_desc);
    $('[name=shopping-cart.items.item-1.subscription.recurrent-item.item-description]').val(plan_desc);
    $('[name=shopping-cart.items.item-1.subscription.recurrent-item.unit-price]').val(plan_price);
    // post form to google
    $('#upgrade_plan_dialog_form').submit();
  }

  closeDialog(g_dialog_widget_id);
  $("#confirmation_dialog").dialog('option', 'width', 300);
  $("#confirmation_dialog").dialog('option', 'height', 180);
}

function setUserPrefs()
{
  url = "/web_modules/process.py?tb="+Math.random()+"&request=set_user_prefs";
  $.post(url, {email: $('#user_prefs_dialog_email').val(), alt_email: $('#user_prefs_dialog_alt_email').val()}, function(xml) {
    if($("status",xml).text() == '0')
      updateTips(PREFERENCES_SAVED_STR, 'info');
  });
}

function setDevicePrefs()
{
  url = "/web_modules/process.py?tb="+Math.random()+"&request=set_device_prefs";
  $.post(url, {time_bomb: $('#device_prefs_dialog_time_bomb').val(), device_id: g_oper_device_id}, function(xml) {
    if($("status",xml).text() == '0')
      updateTips(PREFERENCES_SAVED_STR, 'info');
  });
}

function updateDevicesStatus() {

  // get devices status
  $.get("/web_modules/process.py?tb="+Math.random()+"&request=get_devices_info", { },
    function(xml) {
      if(g_count > 0) {
        // check each device status
        g_devices_name = [];
        g_devices_id = [];
        i = 0;
        $(xml).find('user').each(function() {
          var user_id = $(this).attr('id');
          g_user_id = user_id;
          $(this).find('device').each(function() {
            var device_name = $(this).find('name').text();
            g_devices_name[i] = device_name;
            g_devices_id[i] = $(this).find('device_id').text();
            g_devices_time_bomb[i] = $(this).find('time_bomb').text();
            var text = device_name + ' - ' + $(this).find('location').text().replace(' - ','/');
            if(g_username == 'admin') {
              s = $(this).find('storage').text() / 1073741824.0;
              text += ' - ' + s.toFixed(2) + ' GB';
            }
            var text_color = '#000000';
            var device_id = $(this).attr('device_id');
            var st = $(this).find('status').text();
            var status_progress = $(this).find('status_progress').text();
            var compromised = parseInt($(this).find('compromised').text(), 10);
            if(st != "backup" && st != "restore" && st != "encrypt" && st != "decrypt" && st != "delete" && st != 'initialize') {
              var last_op = $(this).find('last_op').text()
              // translate operation string
              last_op = translateStr(last_op).capitalize();
              var last_op_time = $(this).find('last_op_time').text();
              // translate datetime format
              last_op_time = translateDateTime(last_op_time);
              if ($(this).find('online').text() == 'True')
                text_color = '#33CC33';
              if(last_op != '')
                text += ' - '+last_op+": "+last_op_time;
            }
            else {
              g_status_progress = parseInt(status_progress, 10);

              if(g_status_progress >= 100) {
                text_color = '#33CC33';
              }
              else {
                var st = $(this).find('status').text();
                if(st != 'initialize')
                  stp = ": " + g_status_progress + "%";
                else
                  stp = "";
                st = translateStr(st).capitalize();
                text += ' - ' + st + stp;
                text_color = '#6d84ab';
              }
            }
            var id = "#a_device_"+user_id+"_"+device_id;
            $(id).text(text);
            if(compromised) {
              if(!$(id).hasClass('device_compromised'))
                $(id).addClass('device_compromised');
              $(id).css('color', 'red');
              $(id).css('fontWeight', 'bold');
            }
            else {
              $(id).css('color', text_color);
              if(text_color == '#6d84ab')
                $(id).css('fontWeight', 'bold');
              else
                $(id).css('fontWeight', 'normal');
            }
            i++;
          });
        });
      }
      g_count++;
    }
  );
  
}

function setupDevicesTree(panel)
{
  if(panel & 1)
    $("[id^=a_device_]").trigger('click');
  if(panel & 2)
    $("[id^=backup_a_device_]").trigger('click');
}

function restoreFolders(e, full, file)
{
  g_oper = 'restore_folders';
  g_dialog_widget_id = 'select_dialog';
  g_oper_option = getDeviceIdFromId($(e).attr('id'));
  g_oper_element = e

  // populate select options
  var html = '';
  var os_type = getDeviceOsType(g_oper_option, 1);
  for(i=0;i<g_devices_name.length;i++) {
    // add to drop down only if same os type
    if(os_type == getDeviceOsType(g_devices_id[i], 0)) {
      html += "<option value=\""+g_devices_id[i]+"\" ";
      if(g_devices_id[i] == g_oper_option)
        html += "selected";
      html += ">"+g_devices_name[i]+"</option>";
    }
  }
  $("#select_dialog_select").html(html);
  
  if(full)
    path = '';
  else {
    if(file)
      path = $(e).children()[0].rel
    else
      path = $(e).children()[0].rel.slice(0, -1)
  }

  if(file) { 
    $("#select_dialog_select2").show();
    $("#select_dialog_select2").html("<option value=\"\">"+LOADING_STR+"</option>");
    $.get("/web_modules/process.py?tb="+Math.random()+"&request=get_file_versions&path="+encodePath(path)+"&device_id="+g_oper_option, { },
    function(xml) {
      // populate select options
      var html = '';
      html += "<option value=\"0\">"+LATEST_STR+"</option>";
      var i = 1;
      $(xml).find('version').each(function() {
          html += "<option value=\""+i+"\" ";
          var tzo=(new Date().getTimezoneOffset()/60)*(-1);
          var d = new Date((parseInt($(this).text(), 10)+(tzo*3600))*1000);
          var ds = d.toUTCString();
          html += ">"+translateUTCDateTime(ds.substring(0,ds.length-4))+"</option>";
          i++;
        });
      $("#select_dialog_select2").html(html);
    });
    $("#select_dialog_label").text(SELECT_DEVICE_FILE_RESTORE_STR);
    $("#"+g_dialog_widget_id).dialog('option', 'height', 220);
  } 
  else {
    $("#select_dialog_select2").hide();
    $("#select_dialog_label").text(SELECT_DEVICE_RESTORE_STR);
    $("#"+g_dialog_widget_id).dialog('option', 'height', 180);
  }

  g_oper_data = encodePath(path);

  $("#ui-dialog-title-"+g_dialog_widget_id).text(RESTORE_CAP_STR);
  openDialog('select_dialog');
}

function deleteContent(e, file)
{
  g_oper = 'delete_content';
  g_dialog_widget_id = 'confirmation_dialog';
  g_oper_user_id = getUserIdFromId($(e).attr('id'));
  g_oper_device_id = getDeviceIdFromId($(e).attr('id'));
  g_oper_element = e;
  
  if(file)
    g_oper_data = encodePath($(e).children()[0].rel);
  else
    g_oper_data = encodePath($(e).children()[0].rel.slice(0, -1));
    
  g_oper_data2 = $(e).children()[0].text;

  $("#ui-dialog-title-"+g_dialog_widget_id).text(DELETE_STR);
  if(file)
    $("#confirmation_dialog_label").text(CONFIRM_DELETE_FILE_STR);
  else
    $("#confirmation_dialog_label").text(CONFIRM_DELETE_FOLDER_STR);
  openDialog('confirmation_dialog');
}

function displayFiles(t, type)
{
  window.open('/web_modules/process.py?request=slideshow&type='+type+'&user_id='+g_oper_user_id+'&device_id='+g_oper_device_id+'&tb='+Math.random(), type, 'menubar=no,width=900,height=600,toolbar=yes,status=no,location=no,screenX=50,screenY=100');
}

function updateLabel(label, text)
{
  var a = label.text.split(' - ');
  if(a.length == 2) {
    if(text != '')
      label.text += ' - ' + text;
  }
  else {
    a[2] = text;
    label.text = '';
    for(i=0;i<a.length;i++) {
      label.text += a[i];
      if(i < a.length-1 && a[i+1] != '')
        label.text += ' - ';
    }
  }
}

function translateStr(str)
{
  switch(str)
  {
    case 'backup':
      return BACKUP_STR;
    case 'restore':
      return RESTORE_STR;
    case 'encrypt':
      return ENCRYPT_STR;
    case 'decrypt':
      return DECRYPT_STR;
    case 'delete':
      return DELETE_STR;
    case 'quit':
      return QUIT_STR;
    case 'initialize':
      return INITIALIZE_STR;
    default:
      return '';
  }
}

function translateDateTime(str)
{
  a = str.split(' ');
  if(a.length == 5)
    ret = translateDay(a[0]) + ' ' + translateMonth(a[1]) + ' ' + a[2] + ' ' + a[3] + ' ' + a[4];
  else
    ret = str;
  
  return ret;
}

function translateUTCDateTime(str)
{
  a = str.split(' ');
  if(a.length == 5)
    ret = translateDay(a[0].replace(',','')) + ', ' + a[1] + ' ' +translateMonth(a[2]) + ' ' + a[3] + ' ' + a[4];
  else
    ret = str;
  
  return ret;
}

function translateDay(str)
{
  switch(str)
  {
    case 'Mon':
      return MON_STR;
    case 'Tue':
      return TUE_STR;
    case 'Wed':
      return WED_STR;
    case 'Thu':
      return THU_STR;
    case 'Fri':
      return FRI_STR;
    case 'Sat':
      return SAT_STR;
    case 'Sun':
      return SUN_STR;
    default:
      return str;
  }
}

function translateMonth(str)
{
  switch(str)
  {
    case 'Jan':
      return JAN_STR;
    case 'Feb':
      return FEB_STR;
    case 'Mar':
      return MAR_STR;
    case 'Apr':
      return APR_STR;
    case 'May':
      return MAY_STR;
    case 'Jun':
      return JUN_STR;
    case 'Jul':
      return JUL_STR;
    case 'Aug':
      return AUG_STR;
    case 'Sep':
      return SEP_STR;
    case 'Oct':
      return OCT_STR;
    case 'Nov':
      return NOV_STR;
    case 'Dec':
      return DEC_STR;
    default:
      return str;
  }
}

function openPrefsDialog()
{
  g_oper = 'set_user_prefs';
  g_dialog_widget_id = 'user_prefs_dialog';
  g_widget_id = 'user_prefs_dialog';

  $("#ui-dialog-title-"+g_dialog_widget_id).text(PREFERENCES_STR);
  $("#"+g_dialog_widget_id).dialog('option', 'width', 300);
  $("#"+g_dialog_widget_id).dialog('option', 'height', 300);
  $('#tips_'+g_widget_id).text('');
  openDialog(g_dialog_widget_id);
}

function openDevicePrefsDialog(e) {
  g_oper = 'set_device_prefs';
  g_dialog_widget_id = 'device_prefs_dialog';
  g_widget_id = 'device_prefs_dialog';

  $("#ui-dialog-title-"+g_dialog_widget_id).text(PREFERENCES_STR);
  $("#"+g_dialog_widget_id).dialog('option', 'width', 300);
  $("#"+g_dialog_widget_id).dialog('option', 'height', 250);
  $('#tips_'+g_widget_id).text('');
  $("#device_prefs_dialog_time_bomb").val(g_devices_time_bomb[getIndexFromDeviceId(g_oper_device_id)]/86400);
  openDialog(g_dialog_widget_id);
}

function openUpgradePlanDialog()
{
  g_oper = 'upgrade_plan';
  g_dialog_widget_id = 'upgrade_plan_dialog';

  $("#ui-dialog-title-"+g_dialog_widget_id).text(UPGRADE_PLAN_STR);
  $("#"+g_dialog_widget_id).dialog('option', 'width', 350);
  openDialog(g_dialog_widget_id);
}

function openDownloadFileDialog(e, type)
{
  var path, id;
  g_oper = 'download_file';
  g_dialog_widget_id = 'select_dialog';
  g_oper_element = e

  if($(e.target).is("a") || $(e).is("a")) {
    path = $(e).attr('rel');
    id = $(e).parent().attr('id');
  }
  else {
    path = $(e).children()[0].rel;
    id = $(e).attr('id');
  }
  
  var device_id = getDeviceIdFromId(id);
  
  g_oper_data = path
  g_oper_device_id = device_id;
    
  $("#select_dialog_select").html("<option value=\"\">"+LOADING_STR+"</option>");
  $("#select_dialog_select2").hide();

  $.get("/web_modules/process.py?tb="+Math.random()+"&request=get_file_versions&path="+encodePath(path)+"&device_id="+device_id, { },
  function(xml) {
    // populate select options
    var html = '';
    html += "<option value=\"0\">"+LATEST_STR+"</option>";
    var i = 1;
    $(xml).find('version').each(function() {
        html += "<option value=\""+i+"\" ";
        var tzo=(new Date().getTimezoneOffset()/60)*(-1);
        var d = new Date((parseInt($(this).text(), 10)+(tzo*3600))*1000);
        var ds = d.toUTCString();
        html += ">"+translateUTCDateTime(ds.substring(0,ds.length-4))+"</option>";
        i++;
      });
    $("#select_dialog_select").html(html);
  });

  $("#"+g_dialog_widget_id).dialog('option', 'height', 180);
  $("#ui-dialog-title-"+g_dialog_widget_id).text(DOWNLOAD_FILE_STR);
  $("#select_dialog_label").text(SELECT_DOWNLOAD_FILE_STR);
  openDialog('select_dialog');
}

function downloadFile(e, type)
{
  if($(e.target).is("a") || $(e).is("a")) {
    path = $(e).attr('rel');
    id = $(e).parent().attr('id');
  }
  else {
    path = $(e).children()[0].rel;
    id = $(e).attr('id');
  }
  
  g_oper_data = path
  g_oper_device_id = getDeviceIdFromId(id);
  g_oper_option = 0;
  sendDownloadFile(type);
}

function sendDownloadFile(type)
{
  if(type)
    location.href="/web_modules/process.py?tb="+Math.random()+"&request=download_file&path="+encodePath(g_oper_data)+"&device_id="+g_oper_device_id+"&version="+g_oper_option;
  else
    window.open("/web_modules/process.py?tb="+Math.random()+"&request=download_file&path="+encodePath(g_oper_data)+"&device_id="+g_oper_device_id+"&version="+g_oper_option);
}

function updateStorage()
{
  var a, size = 0.00;
  var devices_labels = $("[id^=backup_a_device_]");
  for(i=0;i<devices_labels.length;i++) {
    a = $(devices_labels[i]).text().split('-');
    d = a[a.length-1];
    if(d.indexOf('GB') != -1) {
      size += parseFloat(d.substr(1, 4));
    }
  }
  g_progressbar_size = size * 1073741824;
  updateProgressBar(size.toString()+' / '+g_quota.toString()+' GB', size * (100/g_quota));
}

function updateProgressBarSize()
{
}

function updateStorageSize(label, op, type)
{
  var a = label.split('-');
  if(a.length <= 1)
    return;

  var d = a[a.length-1];
  var size;

  if(d.indexOf('GB') != -1)
    size = parseFloat(d.substr(1, 4)) * 1073741824;
  else if(d.indexOf('MB') != -1)
    size = parseFloat(d.substr(1, 4)) * 1048576;
  else if(d.indexOf('KB') != -1)
    size = parseFloat(d.substr(1, 4)) * 1024;

  if(type == 'selected') {
    if(op=='add')
      g_sel_size += size;
    else
      g_sel_size -= size;

    if(g_sel_size < 0)
      g_sel_size = 0;

    $('#backup_sel_size_my_devices').text(getSizeStr(g_sel_size)+' '+SELECTED_STR);
  }
  else {
    if(op=='add')
      g_progressbar_size += size;
    else
      g_progressbar_size -= size;

    if(g_progressbar_size < 0)
      g_progressbar_size = 0; 
 
    size = (g_progressbar_size/1073741824.0).toFixed(2);
    updateProgressBar(size.toString()+' / '+g_quota.toString()+' GB', size * (100/g_quota));
  }
}

function getSizeStr(s)
{
  if(s > 10737418)
    return (s/1073741824.0).toFixed(2) + ' GB';
  else if(s > 10485)
    return (s/1048576.0).toFixed(2) + ' MB';
  else
    return (s/1024.0).toFixed(2) + ' KB';
}

function getIndexFromDeviceId(device_id)
{
  for(i=0;i<g_devices_id.length;i++)
  {
    if(g_devices_id[i] == device_id)
      return i;
  }

  return 0;
}

function getDeviceOsType(device_id, backup)
{
  var id = '';
  if(backup)
    id += 'backup_';
  id += 'device_'+g_oper_user_id+'_'+device_id;

  var e = $('#'+id);

  if($(e).hasClass('device_win'))
    return 'win';
  else if($(e).hasClass('device_blackberry'))
    return 'blackberry';
  else if($(e).hasClass('device_android'))
    return 'android';
  
  return '';
}

