function getUniqueValues(_array) {
  var hash = new Object();
  for (j = 0; j < _array.length; j++) {
    hash[_array[j]] = true;
  }
  var array = new Array();
  for (value in hash) {
    array.push(value);
  }
  return array;
}
function RPCCall(functionName,data,loadCallback){
  postItems = JSON.stringify({
    id:(new Date()).getTime(),
    method:functionName,
    params:[data]
  });

  jQuery.ajax({
    "type": "POST",
    'cache':false,
    "url": "/api/jsonrpc",
    "contentType":"application/json-rpc; charset=UTF-8",
    "dataType": "json",
    "data":postItems,
    //processData: false,
    "success":  function(msg){
      if(callBack != null){
        BL.lastUpdate = msg.stamp;
        loadCallback(msg.result);
      }
      BL.postTalkToServer();
    },
    "error": function (XMLHttpRequest, textStatus, errorThrown) { 
      BL.error(errorThrown);
    }
  });
}

function dump(obj) {
  var dump_text = '';
  try {
    for (x in obj) {
      try {
        var str = obj[x];
        if(x == 'innerHTML') { 
          str = str.replace(/</g, '&lt;');
          str = str.replace(/>/g, '&gt;');
          str = str.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
          str = str.replace(/\n/g, '<br>\n');
        }
        dump_text += "<br><strong>" + x + "</strong> => " + str;
      } catch(e) {

      }
    }
  } catch(e) {
    alert("Error dumping object");
  }
  var WindowDump = window.open('','','left=0,top=0,width=610,height=600,toolbar=0,scrollbars=1,status=0');
  WindowDump.document.write(dump_text);
}

var short_month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function prettyDate(string){
  var matches;
  if (string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})/)) {
    date = new Date((string || "").replace(/-/g,"/").replace(/[TZ]/g," "));
    now = new Date();
    thisYear = now.getFullYear();
    time = now.getTime();
    blinked = date.getTime();
    if((time - blinked) < 86400000){
      hour = date.getHours();
      if(hour > 12){ hour -= 12; a = 'pm'; }else{ a = 'am'; }
      return hour + ":" + date.getMinutes() + ' ' + a;
    }else{
      if(date.getFullYear() != thisYear){
        return short_month_names[date.getMonth()] + " " + date.getDate() + " " + date.getFullYear();
      }else{
        return short_month_names[date.getMonth()] + "  " + date.getDate();
      }
    }
  } else {
    return string;
  };
}

ui = {};
ui.actionControl = function(){
  var checked = $('#content .selected').length;
  if(checked == $('#rTo').text()){
    $('#select-all').attr('checked', true);
  }
  ui.addToRemoveTagList();
  return false;
}

ui.addToRemoveTagList = function(){
  selectedTags = new Array();
  text = '';
  $('.selected .lists span:not(.l_domain)').each(function(){selectedTags.push($(this).text())});
  listX = getUniqueValues(selectedTags).sort(function(a, b){ a = a.toLowerCase(); b = b.toLowerCase(); if (a>b) return 1; if (a <b) return -1; return 0; });
  for(z = 0; z < listX.length; z++){
    if(listX[z] != ''){ text += '<option value="'+ listX[z] +'">&nbsp;&nbsp;&nbsp;'+ listX[z] +'</option>'; }
  }
  $('#removeOptgroup').html(text);
}

$(function(){
  ui.setAppHeight();
  window.onresize = ui.setAppHeight;
  ui.initUI();
  ui.bindListButtonsToFunctions();
  $('.activelists a').click(function(){ BL.getLinksOfTag($(this).html()); return false; });
  $(".activelists").draggable({ helper: 'clone', revert: true, delay:100, scroll:true, revert:'invalid'});
  if($('#username').length == 1){
    text = '<a href="#" onclick="ui.displayModuleWindow(\'#page-gears\');return false;">Why enable it?</a>';
    if(BL.hasGears == false){
      if(BL.hasGearsButNoPermition || BL.optionalGearsDisable){
        $('.gears-enable').show();
        $('#gearsStatusOff').show();
        ui.setSystemMessage('Google Gears disabled. ' + text);
      }else{
        ui.setSystemMessage('Google Gears not detected. ' + text);
        $('.gears-install').show();     
      }
      BL._lastPagedQueryData = {begin:0,amount:BL._resultsPerPage};
      BL._lastPagedQueryAction = "initUser";
      BL.showRowCount();
      BL.setPageStats(0);
      BL.talkToServer('getUserTags',{withFoldersOnly:true},BL.showTagsFromResult);
    }else{
      $('#content').hide();
      $('#settings-over .gears-disable').show();
      $('#gearsStatusOn').show();
    }
  }
});

ui.checkAllCheckboxes = function(){
  $('input:checkbox').attr('checked', true);
  $('#content .link').addClass('selected');
  ui.addToRemoveTagList();
}

ui.checkNoneCheckboxes = function(){
  $('input:checkbox').attr('checked', false);
  $('#content .link').removeClass('selected');
  ui.addToRemoveTagList();
}

ui.triggerClickAndCallback = function(callBack){
  checked = $('#content .selected');
  value = $('#dropdownList option:selected').val();
  if(checked.length == 0){
    ui.setSystemMessage('No links were selected');
  }
  else{
    for(z = 0; z < checked.length; z++ ){
      id = checked[z].id.substr(4);
      callBack(id,value);
    }	
  }
}

ui.setPrivacy = function(id,value){
  if($('#private_'+id).hasClass('public') == value){
    $('#private_'+id).trigger('click');
  }
}

ui.markPrivate = function(id){
  ui.setPrivacy(id,true);
}

ui.markPublic = function(id){
  ui.setPrivacy(id,false);
}

ui.addToSharedList = function(id,value){
  value = $('#dropdownList option:selected').text().replace(/^\s+|\s+$/g,"");
  ui.addToList(id,value);
}

ui.addToList = function(id,value){
  value = $.trim(value);

  tags = $('#tags_'+id+' span:not(.l_domain, .l_shared)');
  found = false;
  newtags = '';

  for(x=0; x < tags.length; x++){
    tag = $(tags[x]).text();
    if(tag == value) {
      found = true;
      break;
    }
    newtags += tag + ',';
  }

  if(!found){
    $('#tags_'+id).append('<span>'+value+'</span>');
    $('#tags_'+id+' span:last').click(function(){
      ui.highlightMe(this);
      ui.showOptions('showTags');
      BL.getLinksOfTag($(this).text());
      return false;
    });
    newtags += value;
    dataToSend = {
      id:id,
      link:$('#link_'+id).attr('href'),
      tags:newtags
    };
    BL.url(dataToSend.url).update(BL.cleanNullProps(dataToSend));
  }
}

ui.removeFromList = function(id,value){
  value = $.trim(value);
  tags = $('#tags_'+id+' span:not(.l_domain, .l_shared)');
  found = false;
  newtags = '';

  for(x=0; x < tags.length; x++){
    tag = $(tags[x]).text();
    if(tag == value) {
      found = true;
      $(tags[x]).remove();
    }else{
      newtags += tag + ',';
    }
  }

  if(found){
    dataToSend = {
      id:id,
      // link:$('#link_'+id).attr('href').replace('/link/view/?url=',''),
      link:$('#link_'+id).attr('href'),
      tags:newtags
    };
    BL.url(dataToSend.url).update(BL.cleanNullProps(dataToSend));
  }
}

ui.bindFunctionToDropdownMenu = function(){
  $("#dropdownList").change(function(){
    switch($('#dropdownList option:selected').parent().attr('id')){
      case 'mainOptgroup':
        switch($(this).val()){
          case 'markPrivate':
            ui.triggerClickAndCallback(ui.markPrivate);
            ui.setSystemMessage('Your link is now private ');
            break;
          case 'markPublic':
            ui.triggerClickAndCallback(ui.markPublic);
            ui.setSystemMessage('Your link is now public');
            break;
        }
        break;
      case 'sharedOptgroup':
        ui.triggerClickAndCallback(ui.addToSharedList);
        break;
      case 'listOptgroup':
        ui.triggerClickAndCallback(ui.addToList);
        break;
      case 'removeOptgroup':
        ui.triggerClickAndCallback(ui.removeFromList);
        break;
    }
    ui.addToRemoveTagList();
    $(this).val('initialOption');
  });
}

ui.ClearMenuWhenClickOutside = function(){
  $().click(function(e) {
    if(!((e.target && e.target.id) && (e.target.id == 'add-over-toggle' || e.target.id == 'settings-over-toggle' ))){
      ui.hideContextMenu('both');
      $(this).unbind();
    }
  });
}

ui.displayModuleWindow = function(toDisplay){
  ui.hideContextMenu('both');
  BL.openModule = toDisplay;
  BL.closeModuleEscFun = function(e) { if(e.which == 27){ $(BL.openModule).toggle(); $().unbind();}};
  $(toDisplay).toggle();
  if($(toDisplay).css('display') != 'none'){
    $().keydown(BL.closeModuleEscFun);  
    $(BL.openModule).click(function(){
      $(BL.openModule).unbind();
      $().unbind();
      $().keydown(BL.closeModuleEscFun);
    });  
  }else{
    $().unbind();
  }
}


ui.getUserLinks = function(){
  var username;
  username = $(this).attr('title');
  if(username != $('#username').val()){
    BL._currentPage = 0;
    BL.searchFocus = 'friends';
    BL.searchFocusParams = username;
    ui.highlightMe(this);
    BL.talkToServer('getLinksByFriends',{'friendUsername':username,begin:0,amount:BL._resultsPerPage},function(result){
      ui.showOptions('profile');
      $('#addFriend').show();
      $('#deleteFriend').hide();
      BL.showListFromResult(result,'freindCount');
      $('#mainTitle').html('<image src="/user/avatar/'+username+'" alt="'+username+'" class="avatar"/> ' + '<a href="#" id="mainTitleUsername" title="'+ username +'">' + username + '</a>' );
      $('#mainTitleUsername').click(ui.getUserLinks);
      $('#friendsList a:contains("'+username+'")').each(function(){
        if(!($.trim($(this).text()) != username)){
          $('#deleteFriend').show();
          $('#addFriend').hide();
          ui.highlightMe(this);
        }
      });
      BL.talkToServer('getFriendBlurb',{'friendUsername':username},function(result){
        $('#blurb').html(result).show();
      });
    });
  }else{
    $('#allLinks').trigger('click');
  }
  return false;
}

ui.displayFolderStuff = function(_name){
  $('#mainTitle').html(_name);
  $('#content').attr('class','folder');
  ui.showOptions('folderOptions');
}

ui.toggleGearsCookie = function(){
  ui.hideContextMenu('both');
  if($(this).hasClass('gears-disable')){
    $.cookie('gears', false, { expires: 300 });
  }else{
    google.gears.factory.getPermission('BlinkList.com','/css/images/blicon.png','Mark the check box and click "Allow" to make BlinkList 5x faster and save web pages offline.');
    if(google.gears.factory.hasPermission){
      $.cookie('gears', true, { expires: 300 });
    }else{
      alert('You have denied google gears from working on this page, click on this link for instructions on how to enable access');
      return false;
    }
  }
  if(confirm('You need to refresh the page for the changes to take effect')){
    window.location = (""+window.location).replace('#','');
  }
  return false;
}

ui.initUI = function(){
  $('._close').click(function(){
    if($(this).hasClass('noToggle')){
      $('#getting-started').hide();
      $.cookie('showGSJS', 'xxxx', { expires: 3000 });
    }else{
      ui.displayModuleWindow(BL.openModule);
    }
    return false;
  });

  $('.gears-disable').click(ui.toggleGearsCookie);
  $('.gears-enable').click(ui.toggleGearsCookie);

  if($.cookie('showGSJS') == null){
    if($.cookie('showGS') === 'true') {
      $('#getting-started').show();	
    }
  }

  if(!BL.hasGears){
    $('#discovery').show();
    $('#shared').show();
  }

  $('#discovery li.folder > a.toggle').click(function(){
      $(this).parent().toggleClass('open');
      $(this).parent().children('ul').slideToggle();
      return false;
  });

  ui.bindFunctionToDropdownMenu();

  $('#sourcelist').droppable({
    accept: ".activelists, .sort",
    hoverClass: 'droppable-hover',
    drop: function(ev, me) {
      iWasAt = me.draggable.parent().attr('id');
      nowAt = 'myLinks';
      tagName = me.draggable.text();
      if(iWasAt != nowAt){
        if(me.draggable.hasClass('activelists')){
          tagsFound = $('#myLinks li.sort a:contains("'+tagName+'")');
          if(tagsFound.length != 0){
            tagsFound.each(function(index, domEle){
              if($(domEle).text() == tagName){
                myParent = $(domEle).parent();
                if(myParent.parent().hasClass('listContainer')){
                  if(!myParent.parent().parent().hasClass('open')){
                    myParent.parent().parent().find('.toggle').trigger('click');
                  }
                }
                ui.setSystemMessage('This list is already in one of the folders.');
              }
            });
            return false;
         }
         me.draggable.addClass('sort').removeClass('activelists');
        }
        $("#myLinks").append(me.draggable);
        $('#staredList').addClass('active');
        BL.tag(tagName).setFolder(BL.noFolderList);
        return true;  
      }else{
        return false;
      }
    }
  });

  $('#invite').bind('click',function(){
    var emails = $('#emails').val();
    var message = $('#message').val();
    $('#sending').show();
    BL.talkToServer('invite',{emails:emails, message:message},function(result){
      if (result) {
      $('#sending').hide();
      $('#done').show();
      }
    });
    return false;
  });

  $("form#searchForm").submit(function() {
    $('#af-results').hide();
    var username = $("#friendName").val();
    if (username.length < 4) {
      alert('Please enter at least 3 lettes');
    } else {
      ui.getFriends(username, 0, 5, 5);
    }
    return false;
  });

  // Delete a friend
  $('#deleteFriend').bind('click', function(){
    var friendName = $.trim($('#mainTitle').text());
    if(confirm("Do you want to delete " + friendName + " from your Friends?")) {
      BL.talkToServer('deleteFriend',{friendName:friendName},function(){
        $('.selected').remove();
        $('#showAllFriends').trigger('click');
      });
    }
    return false;
  });

  $('#addFriend').bind('click', function(){
    ui.addFriendAction($.trim($('#mainTitle').text().split(' | ')[0]));
    return false;
  });

  // Delete shared list
  $('#deleteSharedList').bind('click',function(){
    if(confirm("Do you want to delete this shared list?")) {
      sharedTagId = $('#deleteSharedList').attr('focusID');
      BL.talkToServer('deleteSharedList',{sharedtagid:sharedTagId},function(result){
        if (result == 'true') {
          $('#sharedTag-' + sharedTagId).parent().remove();
          $('#inboxLinks').trigger('click');
        }
      });
    }
    return false;
  });

  $('#import-user').bind('click',function(){
    BL.talkToServer('importUser',{},function(result){
      alert('Thank you! Your links will apear soon');
    });
    return true;
  });

  // Extension page
  $('.firefox-cp').bind('click',function(){
    ui.hideContextMenu('settings');
    $('#installer').slideDown('fast');
    $('#dashboard').animate({marginTop: 90}, 'fast');
    return false;
  });

  // Profile page
  $('.profile-cp').bind('click',function(){
    $("#profile-password0").val('');
    $("#profile-password1").val('');
    $("#profile-password2").val('');
    ui.displayModuleWindow('#page-profile');
    return false;
  });

  // New shared list window
  $('.new-sl-cp').bind('click',function(){
    $('#new-sl-name').val('');
    $('#administratorsTable').val('');
    $('#collaboratorsTable').val('');
    ui.displayModuleWindow('#page-new-sl');
    return false;
  });

  // Rename shared list window
  $('.rename-sl-cp').bind('click',function(){
    $('#rename-sl-name').val('');
    ui.displayModuleWindow('#page-rename-sl');
    return false;
  });

  // New folder window
  $('.new-folder-cp').bind('click',function(){
    $('#new-folder-name').val('');
    ui.displayModuleWindow('#page-new-folder');
  });

  // Rename folder window
  $('.rename-folder-cp').bind('click',function(){
    $('#rename-folder-name').val($.trim($('#mainTitle').text()));
    ui.displayModuleWindow('#page-rename-folder');
    return false;
  });

  // Rename list window
  $('.rename-list-cp').bind('click',function(){
    $('#rename-list-name').val($.trim($('#mainTitle').text().replace('*','')));
    ui.displayModuleWindow('#page-rename-list');
    return false;
  });

  // Collaborate bookmarks page
  $('.collaborate-cp').bind('click',function(){
    $('#collaborators-collaborators').val('');
    ui.displayModuleWindow('#page-collaborate');
    return false;
  });

  // Import bookmarks page
  $('.bookmarks-cp').bind('click',function(){
    ui.displayModuleWindow('#page-bookmarks');
    return false;
  });

  // Import bookmarks from delicious page
  $('.delicious-cp').bind('click',function(){
    ui.displayModuleWindow('#page-delicious');
    return false;
  });

  // Export bookmarks from page
  $('.export-cp').bind('click',function(){
    ui.displayModuleWindow('#page-export');
    return false;
  });

  // Language page
  $('.language-cp').bind('click',function(){
    ui.displayModuleWindow('#page-language');
    return false;
  });

  // Friends page
  $('.friends-cp').bind('click',function(){
    $("#friendName").val('');
    $("#_content").html('');
    ui.displayModuleWindow('#page-friends');
    return false;
  });

  // Buttons page
  $('.buttons-cp').bind('click',function(){
    ui.displayModuleWindow('#page-buttons');
    return false;
  });

  // Gears page
  $('.gears-cp').bind('click',function(){
    ui.displayModuleWindow('#page-gears');
    return false;
  });


  $('#close-photo').bind('click', function() {
    $('#change-photo').hide();
  })

  // Add button
  $('.ab-video').bind('click',function() {
    $('#ab-tab-instructions').toggleClass('_active');
    $('#ab-tab-video').toggleClass('_active');
    $('#ab-view-instructions').hide();
    $('#ab-view-video').show();
  });

  $('#ab-instructions').bind('click',function() {
    $('#ab-tab-video').toggleClass('_active');
    $('#ab-tab-instructions').toggleClass('_active');
    $('#ab-view-video').hide();
    $('#ab-view-instructions').show();
  });

  $('#ab-change').bind('click', function() {
    $('#ab-browser-toggle').toggle();

    $('.ab-oo').bind('click',function() {
      $('#ab-browser-name').html(this.innerHTML);
      $('.ab-text-instructions').hide();
      $('.ab-text-video').hide();
      $('#ab-ob-instructions').show();
      $('#ab-ob-video').show();
      $('.ab-click').hide();
      $('.ab-drag').show();
    });

    $('.ab-ff').bind('click',function() {
      $('#ab-browser-name').html(this.innerHTML);
      $('.ab-text-instructions').hide();
      $('.ab-text-video').hide();
      $('#ab-ff-instructions').show();
      $('#ab-ff-video').show();
      $('.ab-button').toggle();
      $('.ab-click').hide();
      $('.ab-drag').show();
    });

    $('.ab-ie').bind('click',function() {
        $('#ab-browser-name').html(this.innerHTML);
        $('.ab-text-video').hide();
        $('.ab-text-instructions').hide();
        $('#ab-ie-instructions').show();
        $('#ab-ie-video').show();
        $('.ab-button').toggle();
        $('.ab-click').show();
        $('.ab-drag').hide();			
    });
  });

  // Import bookmarks
  $('#ai-change').bind('click', function() {
    $('#ai-browser-toggle').toggle();
    $('.ai-ob').bind('click', function() {
      $('.ai-iob').hide();
      $('#ai-browser-name').html(this.innerHTML);
    })
    $('#ai-ie7').bind('click',function() {
      $('#ai-iie7').toggle();
    })
    $('#ai-ie8').bind('click',function() {
      $('#ai-iie8').toggle();
    })
    $('#ai-ff2').bind('click',function() {
      $('#ai-iff2').toggle();
    })
    $('#ai-ff3').bind('click',function() {
      $('#ai-iff3').toggle();
    })
    $('#ai-safari').bind('click',function() {
      $('#ai-isafari').toggle();
    })
  });	

  // User profiles
  $('.uo-menu').bind('click',function(_this) {
    $('.uo-menu').removeClass('_active');
    $('.uo-view').hide();
  })
  $('#uo-profile').bind('click',function(_this) {
    $('#uo-profile').addClass('_active');
    $('#uo-view-profile').show();
  });
  $('#uo-password').bind('click',function(_this) {
    $('#uo-password').addClass('_active');
    $('#uo-view-password').show();
  });
  $('#uo-delete').bind('click',function(_this) {
    $('#uo-delete').addClass('_active');
    $('#uo-view-delete').show();
  });

  // Find Friends
  $('.ff-menu').bind('click',function(_this) {
    $('.ff-menu').removeClass('_active');
    $('.ff-view').hide();
  })
  $('#ff-invite').bind('click',function(_this) {
    $('#ff-invite').addClass('_active');
    $('#ff-view-invite').show();
  });
  $('#ff-instructions').bind('click',function(_this) {
    $('#ff-instructions').addClass('_active');
    $('#ff-view-instructions').show();
  });
  $('#ff-search').bind('click',function(_this) {
    $('#ff-search').addClass('_active');
    $('#ff-view-search').show();
  });

  // Manage shared lists
  $('.sl-menu').bind('click',function(_this) {
    $('.sl-menu').removeClass('_active');
    $('.sl-view').hide();
  })
  $('#sl-manage').bind('click',function(_this) {
    $('#sl-manage').addClass('_active');
    $('#sl-view-manage').show();
  });
  $('#sl-instructions').bind('click',function(_this) {
    $('#sl-instructions').addClass('_active');
    $('#sl-view-instructions').show();
  });

  // Add link page
  $('.addlink-cp').bind('click',function(){
    $('#f1').val('');
    $('#f3').val('');
    $('#f4').val('');
    $('#f5').val('');
    $('#page-addlink .buttons button').text('Blink it!');
    $('#isPrivate').removeClass('checked');

    ui.displayModuleWindow('#page-addlink');
    return false;
  });

  // getting started
  $('.starting-cp').click(function(){
    ui.hideContextMenu('settings');
    $('#getting-started').show();
    ui.setAppHeight();
    return false;
  });

  $('form#comment-form').submit(function() {
    var linkId = $('#current-linkid').val();
    var linkUrl = $('#current-linkurl').val();
    var comment = $('#comment-body').val();
    if (comment.length > 0) {			
      BL.talkToServer('addComment',BL.cleanNullProps({linkid:linkId,linkurl:linkUrl,comment:comment}),function(result){
        if (result.error == "true") {
          alert(result.message);
        } else {
          var s = '<div class="comment">' +
          '<div class="comment-author">' +
          '<div class="gravatar"> <img src="/avatars/' + result.comment.avatar + '" alt="gravatar image" /> </div>' +
          '<p>by <a href="/' + result.comment.username + '">' + result.comment.username + '</a> ' + result.comment.dateAdd + '</p>' +
          '</div>' +
          '<div class="comment-body">' +
          '<p>' + result.comment.comment + '</p>' +
          '</div>' +
          '</div>';
          $('#comments-stream').append(s);
          if (linkId) {
            $('#comments-'+linkId).html((parseInt($('#comments-'+linkId).html())+1)+' comments');
          }
        }
      });
    } else {
      alert('Error: Comment body cannot be empty');
    }
    return false;
  });

  $('#isPrivate').click(function(){
    $(this).toggleClass('checked');
  });

  ui.validateAddForm = function(){
    if($("#f1").val().length > 0 && $("#f3").val().length > 0){
      return true;
    }else{
      alert('Some Fields are missing');
    }
    return false;
  }

  $('form#addlink-form').submit(function() {
    if(ui.validateAddForm()){
      var link = $("#f1").val();
      var izPrivate = $('#isPrivate').hasClass('checked');
      var name = $("#f3").val();
      var description = $("#f4").val();
      var tags = $("#f5").val(); 

      if(link.match(/^([a-z]+:\/{0,2})/ig) == null){
        link = 'http://' + link;
      }

      if (link != undefined) {
        data = {link:link,private:izPrivate,name:name,description:description,tags:tags};
        if($('#page-addlink .buttons button').text() == 'Save'){
          BL.editUrl(BL.EDITID);
          $('#page-addlink').toggle();
          return false;
        }else{
          if(BL.hasGears){
          $('#page-addlink').toggle();
          BL.url(link).add(data);
          $('#allLinks').trigger('click');
          }else{
            BL.talkToServer('saveLink',BL.cleanNullProps(data),function(result){
              $('#page-addlink').toggle();
              $('#allLinks').trigger('click');
            });
          }
        }
      }
    }
    return false;
  });


  $('form#profile-form').submit(function() {
    var firstname = $("#profile-firstname").val();
    var email = $("#profile-email").val();
    var url = $("#profile-url").val();
    var profile = $("#profile-profile").val();
    BL.talkToServer('updateProfile',BL.cleanNullProps({firstname:firstname,email:email,profile:profile,url:url}),function(result) {
      alert(result['message']);
    });	
    return false;
  });

  $('form#profile-delete-form').submit(function(){
    if (confirm("Are you sure you want to delete this account?")) {
      if (confirm("Are you really sure? All of your data will be permanently lost?")) {
        BL.talkToServer('deleteAccount',{},function(result) {
          alert('Your account was deleted. Now you will be redirecting to the main page.');
          window.location = 'http://www.blinklist.com';
        });
      }
    }
  });

  $('form#password-form').submit(function() {
    var isOpenIdUser = ($("#openid-user").val() == undefined) ? 0:1;
    var password0 = $("#profile-password0").val() ? $("#profile-password0").val() : null;
    var password1 = $("#profile-password1").val() ? $("#profile-password1").val() : null; 
    var password2 = $("#profile-password2").val() ? $("#profile-password2").val() : null;
    var openid = $("#profile-openid").val();
    if (!isOpenIdUser) {
      BL.talkToServer('updatePassword',BL.cleanNullProps({password0:password0,password1:password1,password2:password2,isopeniduser:isOpenIdUser}),function(result) {
        alert(result['message']);
      });	
    }else{
      BL.talkToServer('updatePassword',BL.cleanNullProps({openid:openid,isopeniduser:isOpenIdUser}),function(result) {
        alert(result['message']);
      });	
    }
    return false;
  });

  $('form#new-sl-form').submit(function() {
    var sharedTag = $('#new-sl-name').val();
    if(sharedTag != '') {
      sharedTag = sharedTag.replace('#','');
      BL.talkToServer('addSharedTag',{tag:sharedTag },function(result){
        $('#page-new-sl').hide();
        var username = $('#username').val();
        $('#discovery > h1:not(.collapsed) > a').trigger('click');
        $('#my-links > h1:not(.collapsed) > a').trigger('click');
        $('#shared > h1.collapsed > a').trigger('click');
        $('#shared > ul').append('<li><a href="#info" rel="facebox" class="sharedTag" id="sharedTag-'+result.sharedtagId+'" title="#'+result.name+' ('+username+')">#'+result.name+' ('+username+')</a></li>');	
        $('#sharedOptgroup').append('<option value="#'+result.name+' ('+username+')">&nbsp;&nbsp;&nbsp;#'+result.name+' ('+username+')</option>');	
        $('#sharedTag-'+result.sharedtagId).bind('click',function (){
          ui.highlightMe(this);
          ui.bindActionsToSharedTag(this);
          $('.sharedlistName').html('#' + result.name);
          $('.sl-name').html('#' + result.name + ' (' + username + ')');
        }).trigger('click');
        $('#administratorsCount').html('0');
        $('#administratorsTable').html('<tbody></tbody>');
        $('#collaboratorsCount').html('0');
        $('#collaboratorsTable').html('<tbody></tbody>');
        $('#manageSharedListLink').trigger('click');
      });
    }
    return false;
  });

  $('form#rename-sl-form').submit(function(){
    var name = $('#rename-sl-name').val();
    var sharedTagId = $('#editSharedList').attr('sharedlistid');
    BL.talkToServer('setSharedListName',{sharedtagid:sharedTagId, sharedtagname: name },function(result){
      if (result == 'true') {
        var items = Array();
        items = $('#sharedTag-' + sharedTagId).attr('title').match(/^#(.*) \((.*)\)$/);
        name = '#' + name + ' (' + items[2] + ')';
        $('#sharedTag-' + sharedTagId).html(name);
        $('#sharedTag-' + sharedTagId).attr('title', name);
        $('#mainTitle').html(name);
        $('.sl-name').html(name);
        $('#page-rename-sl').hide();
      }
    });
    return false;
  });

  $('form#new-folder-form').submit(function() {
    var name = $('#new-folder-name').val();
    if(name != ''){
      BL.createFolder(name);
      $('#page-new-folder').hide();
      $('#folder_'+name.replace(/[^0-9A-Za-z_]/g, '_')).parent().find('.folderName').click(function(){
        ui.highlightMe(this);
        BL.showStartupPage($(this).html());
        $('#mainTitle').html('Folder View: ' + $(this).html());
        ui.showOptions('folderOptions');
        return false;
      });
    }
    return false;
  });

  $('form#rename-folder-form').submit(function() {
    var name = $('#rename-folder-name').val();
    if(name != '') {
      if(name.length > 0) {
        folderName = $.trim($('#mainTitle').text());
        me = $('#folder_'+folderName.replace(/[^0-9A-Za-z_]/g, '_'));
        me.attr('id','folder_'+name.replace(/[^0-9A-Za-z_]/g, '_'));
        folderContainer = me.prev().text(name);
        $('#mainTitle').text(name);
        BL.tag(name).renameFolder(folderName);
      }
    }
    return false;
  });

  $('form#rename-list-form').submit(function() {
    var name = $('#rename-list-name').val();
    if(name != '') {
     name = name.replace('#','');
      oldName = $.trim($('#mainTitle').text().replace('*',''));
      $('.link .lists span:not(.l_domain, .l_shared):contains('+oldName+')').each(function(){
        if($(this).text() == oldName){
          $(this).text(name);
        }
      });
      BL.tag(oldName).rename(name);
      ui.showTagSidebarOptions(name);
      $('#page-rename-list').hide();
    }
    return false;
  });

  $('form#language-form').submit(function() {
    var spacedomainId = $('#spacedomain').val();
    BL.talkToServer('setSpacedomain',{spacedomainid:spacedomainId},function(result){
      ui.setSystemMessage('Updated');
    });
    return false;
  });


  $('form#collaborators-form').submit(function() {
    var usertype = $(".radio:checked").val();
    var collaborators = $("#collaborators-collaborators").val();
    BL.talkToServer('addCollaborators',BL.cleanNullProps({usertype:usertype,collaborators:collaborators,sharedtag:sharedTag,sharedtagid:sharedTagId}),function(result) {
      if (result.error == "true") {
        alert(result.message);
      }else{
        if (result.collaborators.length > 0) {
          $('#collaboratorsCount').html(parseInt($('#collaboratorsCount').html())+result.collaborators.length);
          var s = '';
          for (var i=0; i< result.collaborators.length; i++) {
            s += '<tr id="coll'+result.collaborators[i].useremailId+'"><td>'+result.collaborators[i].username+'</td><td><a href="#" id="'+result.collaborators[i].useremailId+'" onclick="ui.removeCollaborator(this);return false;" class="remove collaborator"><span>Remove</span></a></td></tr>';
          }
          $('#collaboratorsTable').append(s);
        } 
        if (result.administrators.length > 0) {
          $('#administratorsCount').html(parseInt($('#administratorsCount').html())+result.administrators.length);
          var s = '';
          for (var i=0; i< result.administrators.length; i++) {
            s += '<tr id="coll'+result.administrators[i].useremailId+'"><td>'+result.administrators[i].username+'</td><td><a href="#" id="'+result.administrators[i].useremailId+'" onclick="ui.removeCollaborator(this);return false;" class="remove administrator"><span>Remove</span></a></td></tr>';
          }
          $('#administratorsTable').append(s);
        } 
        ui.setSystemMessage("Shared group updated");
        $('#page-collaborate').toggle();				
      }
    });	
    return false;
  });


  $('#votedLinks').bind('click',function(){
    return false;
  });

  $('#recommendedLinks').bind('click',function(){
    $('#prompt_arrow').remove();
    BL._currentPage = 0;
    BL.searchFocus = 'recomm';
    ui.highlightMe(this);
    BL.talkToServer('getRecommendedLinks',{begin:0,amount:BL._resultsPerPage},function(result){
      $('#qResults').text(result.length);
      ui.showOptions('recommendedLinks');
      $('#mainTitle').html('Recommended');
      BL.showListFromResult(result,'recomm');
    });
    return false;
  });

  $('#inboxLinks').bind('click', function() {
    BL.searchFocus = 'shared';
    ui.showOptions('shared');
    ui.highlightMe(this);
    BL.talkToServer('getInboxLinks',{begin:0,amount:BL._resultsPerPage},function(results){
      BL.showListFromResult(results,'sharedInbox');
      $('#mainTitle').html('All Shared Links');
      $('#inboxLinks').text('All Shared Links (0)');
    });
    return false;
  });

  $('.sharedTag').bind('click',function(){
    BL.searchFocus = 'shared';
    ui.highlightMe(this);
    ui.bindActionsToSharedTag(this);
    return false;
  });

  $('.profile').click(ui.getUserLinks);

  $('#popularLinks').bind('click',function(){
    $('#prompt_arrow').remove();
    BL._currentPage = 0;
    BL.searchFocus = 'popular';
    ui.highlightMe(this);
    BL.talkToServer('getPopularLinks',{begin:0,amount:BL._resultsPerPage},function(result){
      ui.showOptions('pop');
      BL.showListFromResult(result,'popularCount');
      $('#mainTitle').html('Popular');
    });
    return false;
  });

  $('#addList').bind('click',function(){
    name = prompt('Please give a name for the list.');
    if(name != ''){
      BL.createActiveLists(name,'newLinks','<li class="sort">x</li>');
      $('#list_'+name.replace(/[^0-9A-Za-z_]/g, '_')).parent().draggable({ helper: 'clone', revert: "invalid", delay:100, scroll:true, revert:'invalid'});
    }
    return false;
  });

  $('#select-all').click(function(){
    if ($(this).attr('checked')) {
      ui.checkAllCheckboxes();
    }else{
      ui.checkNoneCheckboxes();
    }
    ui.actionControl();
    return false;
  });

  var searchBehavior = function(){
    var searchTerm = $.trim($('#searchfield').val());
    if(searchTerm.length == 0){
      //TODO: add this to a single function in BL namespace
      if(!BL.hasGears){
        callBack = BL.showListFromResult;
        BL.talkToServer('initUser',{begin:0,amount:BL._resultsPerPage},callBack); 
      }else{
        BL.showListFromResult(BL.db.showAll(0,BL._resultsPerPage));
      }
    }else{
      if (2 < searchTerm.length) {
        BL.find(searchTerm);
        ui.showOptions('evertything');
        if(BL.searchFocus != null){
          $('#mainTitle').html( $('#mainTitle').html().split(' | ')[0] + ' | ' + 'Search results for: ' + searchTerm);
        }else{
          $('#mainTitle').html('Search results for: ' + searchTerm);
        }
      }else{
        $('#mainTitle').html("Search string too short");
      }
    }
  }

  $('#searchfield').click(function(){
    if($('#searchfield').val() == 'Search my lists'){
      $('#searchfield').val('');
    }
  });

  $('#searchfield').keypress(function(e){
    if (e.which == 13) {
      searchBehavior();
    }
  });

  $('#searchButton').click(function(){
    searchBehavior();
    return false;
  });

  $('#back').click(function(){
    ui.checkNoneCheckboxes();
    BL.goToPage('back');
    return false;
  });

  $('#next').click(function(){
    ui.checkNoneCheckboxes();
    BL.goToPage('next');
    return false;
  });

  $('#Delete').click(function(){
    BL.deleteUrl();
    return false;
  });


  $('#add-over-toggle').click( function() {
    $('#prompt_arrow').remove();
    ui.hideContextMenu('settings');
    $(this).toggleClass('over');
    $('#add-over').toggle();
    ui.ClearMenuWhenClickOutside();
    return false;
  });

  $('#settings-over-toggle').click( function() {
    $('#prompt_arrow').remove();
    ui.hideContextMenu('add');
    $(this).toggleClass('over');
    $('#settings-over').toggle();
    ui.ClearMenuWhenClickOutside();
    return false;
  });


  $('#allLinks').click(function(){
    BL._currentPage = 0;
    BL.searchFocus = null;
    BL.searchFocusParams = null;
    ui.highlightMe(this);
    if(BL.hasGearsAvtive){
      ui.showOptions('allLinks');
      BL.showListFromResult(BL.db.query('*'));
      $('#mainTitle').html('All Links');
    }else{
      BL.talkToServer('initUser',{begin:BL._currentPage,amount:BL._resultsPerPage},function(results){
        ui.showOptions('allLinks');
        BL.showListFromResult(results);
        $('#mainTitle').html('All Links');
      });
    }
    return false;
  });


  $('#showAllFriends').click(function(){
    $('#prompt_arrow').remove();
    ui.highlightMe(this);
    BL.talkToServer('getFriendsLinks',{},function(results){
      ui.showOptions('freindFolder');
      BL.custructStarupPage(results,'withAvatar');
      $('#mainTitle').html('Friends');
    });
    return false;
  });

  $('.section > h1 > a').click(function(){
    $('#prompt_arrow').remove();
    $(this).parent().toggleClass('collapsed');
    $(this).parent().parent().children('ul').slideToggle();
    return false;
  });

  BL._viewType = ($.cookie('viewType') != null) ? $.cookie('viewType') : 'thumbnail';
  if(BL._viewType == 'list'){
    $('#mainOptgroup').hide();
  }else{
    $('#mainOptgroup').show();
  }


  $('#plexobutton').click(function(){
    url = 'http://www.plaxo.com/css/m/js';
    $.getScript(url + "/util.js",function(){
      $.getScript(url + "/basic.js", function(){
        $.getScript(url + "/abc_launcher.js", function(){
          function onABCommComplete() {};
          showPlaxoABChooser('emails', '/user/plaxo');
        },true);
      },true);
    },true);
    return false;
  });

  $('#totalRemove').click(function(){
    name = $.trim($('#mainTitle').text().replace('*',''));
    if(confirm('Are you sure you want to remove the list '+name+' completly?')){
      $('#myLinks .selected a:contains("'+name+'")').parent().remove();
      BL.tag(name).remove();
      $('#allLinks').trigger('click');
    } 
    return false;
  });


  $('#deleteFolder').click(function(){
    if(confirm('Are you sure you want to delete the folder?')){
      folderName = $('#mainTitle').text().replace('Folder View: ','');
      $('#folder_'+folderName.replace(/[^0-9A-Za-z_]/g, '_')).parent().remove();
      BL.tag().removeFolder(folderName);
    }
    return false;
  });


  $('#view-menu a').click(function(){
    ui.setView($(this).attr('id'));
    return false;
  });

  $('.u_options').click(function(){
    $('#settings-over-toggle').trigger('click');
    return false;
  });

  $('.triggerAdd').click(function(){
    $('#add-over-toggle').trigger('click');
    return false;
  });

} //end of initUI


ui.appendToSuggestList = function(arrayOfTags){
  BL.autoSuggestArray = arrayOfTags;
  $('#searchfield').autocomplete(arrayOfTags, {
    multiple: true,
    multipleSeparator: ' ',
    selectFirst: false,
    matchContains: true
  });
  $('#f5').autocomplete(arrayOfTags, {
    multiple: true,
    multipleSeparator: ',',
    selectFirst: false,
    matchContains: true
  });
}

ui.blinkLink = function(linkId){
  if (linkId) {
    BL.talkToServer('blinkLink',{linkId:linkId},function(result){
      if (result.link.length > 0) {
        $('#blink-'+linkId).html('Blinked');		
      }
    });
  }
}

ui.getFriends = function(username, begin, amount) {
  BL.talkToServer('searchFriends',{username:username,begin:begin,amount:amount},function(result){
    if (begin+amount < result.total && result.total > 5) {
      $('#friends-right').attr('href','javascript:ui.getFriends('+'"'+username+'"'+','+(begin+amount)+','+amount+')');
    }
    if (begin-amount >= 0) {
      $('#friends-left').attr('href','javascript:ui.getFriends('+'"'+username+'"'+','+(begin-amount)+','+amount+')');
    }
    var max = ((begin+amount+1) < result.total) ? (begin+amount+1) : result.total;
    $('#results-amount').html('Showing '+(begin+1)+' - '+max+' of '+result.total);
    $('#af-results').show();
    $("#results-content").html('');
    var HTML = '<div class="_item"><div class="profile-pic"><img alt="{username}" src="{avatar}"/></div><div class="profile-meta"><ul>'+
               '<li class="username">{username}</li><li><a id="friendId-{id}" class="addFriend" href="#">Add friend</a></li></ul></div></div>';

    for (i=0; i<result.data.length; i++) {
      var html = '';		
      var username_short = (username.length > 12) ? result.data[i].username.substring(0,12) : result.data[i].username;
      html = HTML.replace(/{username}/g, username_short);			
      html = html.replace(/{avatar}/g, result.data[i].avatar);		
      html = html.replace(/{id}/g, result.data[i].id);	
      $("#results-content").append(html);
      $('#friendId-'+result.data[i].id).click(function(){
        var friendId = $(this).attr('id').replace(/friendId-/,'');
        ui.addFriendAction(friendId);	
        return false;
      });
    }
  });
}

ui.addFriendAction = function(friendId){
  BL.talkToServer('addFriend',{friendId:friendId},function(result){
    if (result.error != "true") {
      $('#shared > h1:not(.collapsed) > a').trigger('click');
      $('#my-links > h1:not(.collapsed) > a').trigger('click');
      $('#discovery > h1.collapsed > a').trigger('click');
      $('#friendId-'+friendId).html('Added');
      $('#friendsList', top.document).append('<li><a href="#" title="'+result.username+'" id="'+result.username+'" class="profile">'+result.username+'</a></li>');
      $('#'+result.username).click(ui.getUserLinks);
      $('#'+result.username).trigger('click');
      if(!$('.friends').hasClass('open')){
        $('#friendLinks').trigger('click');
      }
    }else{
      $('#friendId-'+friendId).html('Friend');
    }
  });
}

ui.likeIt = function(linkId){
  if (linkId) {
    BL.talkToServer('addVote',{linkId:linkId,vote:1},function(result){
      if (result.error == "false") {
        $('#like-'+linkId).addClass('_selected');	
        $('#dislike-'+linkId).removeClass('_selected');	
      }
    });
  }
}

ui.dislikeIt = function(linkId){
  if (linkId) {
    BL.talkToServer('addVote',{linkId:linkId,vote:-1},function(result){
      if (result.error == "false") {
        $('#like-'+linkId).removeClass('_selected');	
        $('#dislike-'+linkId).addClass('_selected');	
      }
    });
  }
}

ui.showComments = function(params){
  if (params.linkId) {
    var linkId = params.linkId;
    $('#current-linkid').val(linkId);		
  } else {
     if (params.linkUrl) {
      var linkUrl = params.linkUrl;
      $('#current-linkurl').val(linkUrl);
     }
  }

  $('#comments-stream').html('');
  $('#comment-body').html('');
  BL.talkToServer('getComments',BL.cleanNullProps({linkid:linkId,linkurl:linkUrl}),function(result){
    ui.displayModuleWindow('#page-comments');
    $('#comment-body').html();

    trim = 60;
    window_h = $(window).height();
    wrap_h = Math.floor(window_h * 0.8);
    $('#page-comments ._wrap').css('height', wrap_h + 'px');
    $('#comments-stream').css('height', (wrap_h - $('#comments-header').height() - $('#add-comment').height() - trim)  + 'px');

    if (result.comments.length > 0) {
      for (i=0; i<result.comments.length; i++) {
        var s = '<div class="comment"><div class="comment-author">' +
        '<div class="gravatar"> <img src="/avatars/' + result.comments[i].avatar + '" /> </div>' +
        '<p>by <a href="#">' + result.comments[i].username + '</a> ' + result.comments[i].dateAdd + '</p>' +
        '</div><div class="comment-body">' +
        '<p>' + result.comments[i].comment + '</p></div></div>';
        $('#comments-stream').append(s);
      }
    }
  });
}

ui.showPromptlet = function(linkId){
  $('._promptlet').hide();
  $('._promptlet').html('');
  $('#promptlet-'+linkId).html('<p>To vote, comment or blink a link, <a href="/user/login">login</a> or <a href="/user/join">join BlinkList</a> for free. <a class="_close"><span>Close</span></a></p>');
  $('#promptlet-'+linkId).show();
  $('._close').click(function() {$('._promptlet').hide()});
}

ui.removeCollaborator = function(_this){
  var useremailId = $(_this).attr('id');	
  if($(_this).hasClass('administrator')) {
    var remove = 'administrator';
  }else{
    if ($(_this).hasClass('collaborator')) {
      var remove = 'collaborator';
    }
  }
  BL.talkToServer('removeCollaborator',{sharedtagid:sharedTagId, useremail:useremailId,remove:remove},function(result){
    if (result.error == "false") {
      $('#coll'+useremailId).remove();
      res = parseInt($('#'+remove+'sCount').html())-1;
      $('#'+remove+'sCount').text(res);
    }else{
      alert(result.message);
    }
  });
}

// these are global variables. don't delete them
var sharedTag;
var sharedTagId;

ui.bindActionsToSharedTag = function(_this){
  id = $(_this).attr('id');
  sharedTagId = id.substring(10,id.length);
  $('#deleteSharedList').attr('focusID',sharedTagId);
  BL.talkToServer('getSharedListLinks',{sharedtagid:sharedTagId,begin:0,amount:BL._resultsPerPage},function(results){
    ui.showOptions('sharedTag');
    BL.showListFromResult(results,'sharedListCount');
    $('#mainTitle').html($(_this).attr('title'));
    $('.sl-name').html($(_this).attr('title'));
  });
  sharedTag = $(_this).html();
  username = $('#username').val();
  $('.sharedlistName').html(sharedTag);
  BL.talkToServer('getSharedListGroups',{sharedtag:sharedTag,sharedtagid:sharedTagId},function(result){
  
    $('#administratorsCount').html('0');
    $('#administratorsTable').html('<tbody></tbody>');
    $('#collaboratorsCount').html('0');
    $('#collaboratorsTable').html('<tbody></tbody>');

    if (result.administrators.length > 0) {
      $('#administratorsCount').html(result.administrators.length);
      s = '';
      for (var i=0; i< result.administrators.length; i++) {
        var _s = (i % 2 == 0) ? ' class="alt"':'';
        s += '<tr id="coll'+result.administrators[i].useremailId+'" '+_s+'><td>'+result.administrators[i].username+'</td><td><a href="#" id="'+result.administrators[i].useremailId+'" onclick="ui.removeCollaborator(this);return false;" class="remove administrator"><span>Remove</span></a></td></tr>';
      }
      $('#administratorsTable').html(s);
    }

    if (result.collaborators.length > 0) {
      $('#collaboratorsCount').html(result.collaborators.length);
      s = '';
      for (var i=0; i< result.collaborators.length; i++) {
        var _s = (i % 2 == 0) ? ' class="alt"':'';
        s += '<tr id="coll'+result.collaborators[i].useremailId+'" '+_s+'><td>'+result.collaborators[i].username+'</td><td><a href="#" id="'+result.collaborators[i].useremailId+'" onclick="ui.removeCollaborator(this);return false;" class="remove collaborator"><span>Remove</span></a></td></tr>';
      }
      $('#collaboratorsTable').html(s);
    }	
  }); 

  BL.talkToServer('getSharedListRights',{sharedtagid:sharedTagId},function(result){
    if (result == 'owner') {
      $('#editSharedList').attr('sharedlistid', sharedTagId).show();
    } else {
      $('#editSharedList').hide();		
    }
    if (result == 'collaborator') {
      $('#manageSharedList').hide();
    }else{
      $('#manageSharedList').show();
    }
  });
}

ui.hideContextMenu = function(menuName){
  if(menuName != 'both'){
    $('#' + menuName + '-over-toggle').removeClass('over');
    $('#' + menuName + '-over').hide();    
  }
  else{
    ui.hideContextMenu('settings');
    ui.hideContextMenu('add');
  }
}

ui.removeLinkUI = function(id){
  $('#row_' + id).remove();
  $('#edit_' + id).remove();
}

ui.setMessage = function(message){
  $('#activity-msg').html(message).show();
}

ui.hideMessage = function(){
  $('#activity-msg').hide();
}

var sysTimeout;
ui.setSystemMessage = function(m,undo){
  if(undo == null){
    undo = '';
  }else{
    undo = '<a href="#">Undo</a>';
  }
  $('#system-msg').show().html('<p>' + m + ' ' + undo + '</p>');
  clearTimeout(sysTimeout);
  sysTimeout = setTimeout(function() {$('#system-msg').hide()}, 5000);
}

ui.renderListOptgroup = function(list){
  listX = new Array();
  for(x = 0; x < list.length; x++){
    if(list[x].name != ''){ listX.push(list[x].name); }
  }
  listX = getUniqueValues(listX).sort( function(a, b){ a = a.toLowerCase(); b = b.toLowerCase(); if (a>b) return 1; if (a <b) return -1; return 0; });
  VAL = '';
  for(x = 0; x < listX.length; x++){
    VAL += '<option value="'+listX[x]+'">&nbsp;&nbsp;&nbsp;'+listX[x]+'</option>';
  }
  $("#listOptgroup").html(VAL);
}


ui.showTagSidebarOptions = function(_text,option){
  $('#staredList').unbind().click(function(){
    tagName = $.trim($('#mainTitle').text().replace('*',''));
    $(this).toggleClass('active');
    if($(this).hasClass('active')){
      tag = $('#activelists ._viewport .selected').clone(true).removeClass('activelists').addClass('sort');
      tag.find('a').text(tagName);
      $("#myLinks").append(tag);
      BL.tag(tagName).setFolder(BL.noFolderList);
    }else{
      $('#myLinks .selected a:contains("'+tagName+'")').parent().remove();
      BL.tag(tagName).removeFromSideBar();
    }
    return false;
  });

  tagsFound = $('#myLinks li.sort a:contains("'+_text+'")');
  if(tagsFound.length != 0){
    tagsFound.each(function(index, domEle){
      if($(domEle).text() == _text){
        $('#staredList').addClass('active');
        myParent = $(domEle).parent();
        myParent.addClass('selected');
        if(myParent.parent().hasClass('listContainer')){
          if(!myParent.parent().parent().hasClass('open')){
            myParent.parent().parent().find('.toggle').trigger('click');
          }
        }
        return false;
      }
    });
  }
}

ui.highlightMe = function(me){
  $('.selected').removeClass('selected');
  $(me).parent().addClass('selected');
}

ui.bindListBehavior = function(){
  $('#myLinks .sort > a').click(function(){
    ui.highlightMe(this);
    BL.searchFocus = null;
    BL.searchFocusParams = null;
    list = $(this).text();
    BL.getLinksOfTag(list);
    return false;
  }).parent().draggable({ helper: 'clone', revert: "invalid", delay:100, scroll:true, revert:'invalid'});
}

ui.enableDeleteButton = function(target){
  if(target != null){
    target = '#del_' + target;
  }
  else{
    target = '#content .u_delete a';
  }

  $(target).click(function(){
      BL.deleteUrl($(this).attr('id').substr(4));
  });
}

ui.enableEditButton = function(target){
  if(target != null){
    target = '#t_' + target;
  }
  else{
    target = '#content .u_edit a';
  }

  $(target).click(function(){
    id = $(this).attr('id').substr(2);
    BL.EDITID = id;
    // url = $('#link_'+id).attr('href').replace('/link/view/?url=','');
    url = $('#link_'+id).attr('href');
    title = $('#link_'+id).text();
    description = $('#desc_'+id).text();
    tagsArray = $('#tags_'+id+' span:not(.l_domain)');
    tags = '';
    times = tagsArray.length;

    for(y=0; y < times; y++){
      tags += $(tagsArray[y]).text();
      tags += (y != times-1) ? ', ' : '';
    }

    $('#page-addlink .buttons button').text('Save');

    ui.displayModuleWindow('#page-addlink');

    $('#f1').val(url);
    $('#f3').val(title);
    $('#f4').val(description);
    $('#f5').val(tags);

    if($('#private_'+id).hasClass('public')){
      $('#isPrivate').removeClass('checked');
    }else{
      $('#isPrivate').addClass('checked');
    }
    return false;
  });
}

ui.bindListButtonsToFunctions = function(target){
  if(target != null){
    checkTarget = '#row_'+target+' input:checkbox';
  }
  else{
    checkTarget = '#content .link input:checkbox';
  }

  $(checkTarget).click(function(){
    myparent = (BL._viewType == 'list') ? $(this).parent().parent() : $(this).parent();
    if(this.checked){ myparent.addClass('selected') }
    else{ myparent.removeClass('selected') }
    ui.actionControl();
  });

  ui.enableListInlineButtons(target);

  if(BL._viewType == 'thumbnail'){
    ui.enablePrivacyToggleButton(target);
    ui.enableEditButton(target);
    ui.enableDeleteButton(target);
    ui.enableComments(target);
    ui.enableUserClick(target);
    ui.enableVote(target);
  }
}

ui.doVote = function(){
  if($(this).hasClass('v_down')){
    me = '.v_down'; other = '.v_up';
  }else{
    me = '.v_up'; other = '.v_down';
  }

  if(!$(this).hasClass('_selected')){
    myParent = $(this).parent();
    otherNode = myParent.find(other);

    incremnet = 1;
    if(otherNode.hasClass('_selected')){
      incremnet++;
      otherNode.removeClass('_selected');
    }    

    $(this).addClass('_selected');
    voteNumber = myParent.find('.voteCount');
    id = voteNumber.attr('id').substr('5');
    // url = $('#link_'+id).attr('href').replace('/link/view/?url=','');
    url = $('#link_'+id).attr('href');

    valueOfVote = (me != '.v_down') ? 1 : -1;

    voteChange = parseInt(voteNumber.text()) + (incremnet * valueOfVote);
    BL.talkToServer('addVote',{linkurl:url,vote:valueOfVote},function(){
      ui.setSystemMessage('Vote Updated');
    });
    voteNumber.text(voteChange);
  }
}

ui.enableVote = function(target){
  $('.v_up').click(ui.doVote);
  $('.v_down').click(ui.doVote);
}


ui.enableListInlineButtons = function (target){
  if(target != null){
    target = '#tags_' + target;
  }
  else{
    target = '.lists';
  }

  $(target+' span:not(.l_domain, .l_shared)').click(function(){
    BL.getLinksOfTag($(this).text());
    return false;
  });

  $(target+' .l_shared').click(function(){
    $('#shared > h1.collapsed > a').trigger('click');
    $('#shared .sharedTag:contains('+$(this).text()+')').trigger('click');
    return false;
  });

  $(target+' .l_domain').click(function(){
    text = $(this).text();
    if(BL.searchFocus != null){
      $('#mainTitle').html($('#mainTitle').html().split(' | ')[0] + ' | ' + text);
      switch(BL.searchFocus){
        case 'popular':
          BL.find(text,'popDomains');
          break;
        case 'recomm':
          BL.find(text,'recommDomains');
          break;
        case 'friends':
          BL.find(text,'domain');
          break;
      }
    }else{
      BL.find(text,'domain');
      $('#mainTitle').text(text);
    }
    ui.highlightMe(this);
    ui.showOptions('domain');
    return false;
  });
}

ui.makeAltDividers = function(){
  $('#content .link:odd').addClass('alt');
  $('#content .link:even').removeClass('alt');
}

ui.enablePrivacyToggleButton = function(target){
  if(target == null){
    target = '.toggle-privacy';
  }else{
    target = '#private_' + target;
  }

  $(target).click(function(){
    $(this).toggleClass('public');
    id = $(this).attr("id").replace('private_','');
    BL.ChangePrivateSettings(id);
    return false;
  });
}

ui.lastShown = null;
ui.showOptions = function(option){
  if(ui.lastShown != option){
    ui.lastShown = option;
    allOptions = {
      'pager':'#pager',
      'tableTopHeader':'#tableTopHeader',
      'actions':'.actions',
      'folderOptions':'#folderOptions',
      'listOptions':'#listOptions',
      'manageSharedList':'#manageSharedList',
      'editSharedList':'#editSharedList',
      'tagOptions':'#tagOptions',
      'freindOptions':'#freindOptions',
      'deleteSharedList':'#deleteSharedList',
      'uAllLinks':'#uAllLinks',
      'uFriendFolder':'#uFriendFolder',
      'uInbox':'#uInbox',
      'blurb':'#blurb'
    };

    for (x in allOptions){
      $(allOptions[x]).hide();
    }

    switch (option){
      case 'domain':
      case 'search':
        if(BL.searchFocus == null){
          $('.actions').show();
        }
        break;
      case 'pop':
        $('#tableTopHeader th:first').hide();
        break;
      case 'allLinks':
        $('#tableTopHeader th:first').show();
        $('#uAllLinks').show();
        $('.actions').show();
        break;
      case 'shared':
        $('#tableTopHeader th:first').hide();
        $('#uInbox').show();
        break;
      case 'folderOptions':
        $('#listOptions').show();
        $('#folderOptions').show();
        break;
      case 'sharedTag':
        $('#tableTopHeader th:first').hide();
        $('#listOptions').show();
        $('#editSharedList').show();
        $('#manageSharedList').show();
        $('#deleteSharedList').show();
        break;
      case 'recommendedLinks':
        $('#tableTopHeader th:first').hide();
        break;
      case 'freindFolder':
        $('#listOptions').show();
        $('#uFriendFolder').show();
        break;
      case 'profile':
        $('#tableTopHeader th:first').hide();
        $('#listOptions').show();
        $('#freindOptions').show();
        break;
      case 'linkView':
        $('.actions').show();
      case 'createActiveLists':
        $('.actions').show();
      case 'showTags':
        $('#tableTopHeader th:first').show();
        $('#listOptions').show();
        $('#tagOptions').show();
        if(BL.searchFocus == null){
          $('.actions').show();
        }
        break;
      default:
    }
  }
}

ui.enableComments = function(target) {
  if(target != null){
    target = '#comments_' + target;
  }else{
    target = '.u_comments a';
  }

  $(target).bind('click',function(){
    id = $(this).attr('id').substr(9);
    url = $('#link_'+id).attr('href');
    title = $('#link_'+id).text();
    ui.showComments({'linkUrl':url});
    $('#comment-body').val('');
    $('#commentsTitle').html($(this).text().toUpperCase() + ' " <a target="_blank" href="'+url+'">'+title+'</a> "');
    return false;
  });
}

ui.enableUserClick = function(target){
  $('.blinkerUsername').click(ui.getUserLinks);
}

ui.setView = function(_id){
  if(_id != null){
    if(!$('#'+_id).hasClass('disabled')){
      $('#view-list').removeClass('active');
      $('#view-thumbnail').removeClass('active');
      BL._viewType = _id.replace('view-','');
      $.cookie('viewType', BL._viewType, { expires: 300 });
      BL.taskAfterSwitchView();
    }
  }
  if(BL._viewType == 'list'){ $('#mainOptgroup').hide(); } else{  $('#mainOptgroup').show();  }
  return false;
}

ui.setAppHeight = function(){
  trim = 1;
  window_h = $(window).height();
  toolbar_h = $('#toolbar').height();
  bottombar_h = $('#bottombar').height();
  scopebar_h = $('#scopebar').height();
  activelists_h	= $('#activelists').height();
  $('#sourcelist').height(window_h - (toolbar_h + bottombar_h + activelists_h + trim));
  $('#content').height(window_h - (toolbar_h + scopebar_h + trim));
  $('#overlay').height(window_h);
  if ($('td.list-link').length > 0) {
    zwidth = $('th#list-th-link').width() - 32;
    $('td.list-link div').css('width',zwidth + 'px');
  }
  $('#getting-started').width($('#scopebar').width()-40); // TODO: fix this for all the broswers
  if($('#page-comments').css('display') != 'none'){
    trim = 60;
    window_h	= $(window).height();
    wrap_h = Math.floor(window_h * 0.8);
    $('#page-comments ._wrap').css('height', wrap_h + 'px');
    $('#comments-stream').css('height', (wrap_h - $('#comments-header').height() - $('#add-comment').height() - trim)  + 'px');
  }
}
BL = {
  _messages: [],
 _currentDataSent: '',
 _lastServerActionType: null,
 _lastDataSentToServer: null,
 _lastSelectQuery: 'select name,url,description,fulltextTable.rowid,dateAdd,private,tags from fulltextTable,links where fulltextTable.rowid = links.rowid ORDER BY links.dateAdd DESC ',
 _currentPage: 0,
 _timeOutVar: null,
 _viewType:($.cookie('viewType') != null) ? $.cookie('viewType') : 'thumbnail',
 _resultsPerPage:50,
 _lastPageResult:null,
 _downloadPerWorker:500,
 _downloadPerWorkerCycle:0,
 _limitTagsToShow:500,
 _registry:null,
 hasGears: false,
 hasGearsAvtive: false,
 apiKey:123123123,
 changed: true,
 hash:$.cookie('blinklistCom'),
 cookie:$.cookie('blinklistCom'),
 firstLoad:true,
 xx:null,
 noFolderList:'Mz12DE389XF981',
 doSlurp:false,
 searchFocus:null,
 searchFocusParams:null,

 find:function(text,options){
             text = $.trim(text);
             //debug('BL.find');
             BL._currentPage = 0;
             ui.highlightMe(this);

             //TODO: check the search scope or myabe no need

             if(BL.hasGearsAvtive){
               switch(options){
                 case 'domain': text = 'url:"'+text+'"'; break;
               }
               BL.showListFromResult(BL.db.query(text),'fullTextCount');
               ui.showOptions('search');
               $('#content').each(function() { 
                   highlights = text.split(' ');
                   for(x = 0; x < highlights.length; x++ ) $.highlight(this, highlights[x].toUpperCase()) 
                   });
             }else{
               BL.talkToServer('getFullTextSearch',BL.cleanNullProps({begin:0,amount:BL._resultsPerPage,token:text,username:BL.searchFocusParams,options:options}),function(result){
                   BL.showListFromResult(result,'fullTextCount');
                   ui.showOptions('search');
                   $('#content').each(function() { 
                     highlights = text.split(' ');
                     for(x = 0; x < highlights.length; x++ )  $.highlight(this, highlights[x].toUpperCase()) 
                     });
                   });
             }
           },

           // UI creation
goToPage: 
           function(direction){
             BL._currentPage = (direction == "next") ? ++BL._currentPage : --BL._currentPage;
             begin = BL._currentPage * BL._resultsPerPage;
             amount = BL._resultsPerPage;
             BL.setPageStats(BL._currentPage);

             if(BL.hasGears && BL.hasGearsAvtive && BL.searchFocus == null){
               BL.showListFromResult(BL.db.queryAgainFrom(begin),'noAskCount');
               //ui.hideMessage();
             }
             else{
               data = BL._lastPagedQueryData;
               data.begin = begin;
               data.amount = amount;
               BL.talkToServer(BL._lastPagedQueryAction,data,function(result){
                   BL.showListFromResult(result,'noAskCount');
                   }); 
             }
           },


displayLinkAsThumbView: 
           function (result,edit){ 
             edit = (edit != null) ? edit : false;

             TEXT = '';
             TAGS = '';

             for (x = 0; x < result.length; x++) {

               data = result[x];
               data.id = (data.rowid != null) ? data.rowid : data.userlinkid;
               data.outUrl = data.url;

               if(null != data.url){
                 domain = (d = data.url.replace(/http\:\/\/|https:\/\/|ftp:\/\//,'').replace(/^www\./i,'').match(/([^/\:]+)/ig)) ? d[0] : null;
               }else{
                 continue;
               }

               TAGS += (typeof(data.tags) != 'undefined' && data.tags != '' && data.tags != null) ? data.tags + ',' :  '';

               izPrivate = (data.private == "1") ? "" : " public";
               if(data.tags == null) { data.tags = ''; }

               if(!edit) TEXT += '<div id="row_' + data.id + '" class="link">';
               if(!(data.username != null)) TEXT += '  <input type="checkbox" class="select-link"/>';
               TEXT += '  <div class="screenshot"> <a target="_blank" href="' + data.outUrl + '"><img alt="" src="http://thumb.blinklist.com/get?url=' + data.url + '"/></a>';

               if(data.votes != null){
                 if(data.votes === true){
                   TEXT += data.voteHTML;
                 }else{
                   if(data.username != null) TEXT += '    <div class="vote"><a href="#" class="v_down'+((data.vote != -1) ? '' : ' _selected')+'"><span>-</span></a><span class="v_count"><span id="vote_'+data.id+'" class="voteCount">'+ data.votes +'</span> Votes</span><a href="#" class="v_up'+((data.vote != 1) ? '' : ' _selected')+'"><span>+</span></a></div>';
                   else {
                     if(data.votes !== false){
                       TEXT += '    <div class="vote"><span class="v_count">' + data.votes +' Votes</span></div>';
                     }
                   }
                 }
               }

               TEXT += '  </div>';
               TEXT += '  <div class="meta">';
               TEXT += '    <h2><a id="link_' + data.id + '" target="_blank" href="' + data.outUrl + '">' + ((data.name != '') ? data.name : data.url) + '</a></h2>';
               TEXT += '    <div class="description">';
               TEXT += '      <p id="desc_'+data.id+'">' + data.description + '</p>';
               TEXT += '    </div>';
               TEXT += '    <div class="lists" id="tags_'+data.id+'">';
               TEXT += '    	<span class="l_domain">'+ domain +'</span>';
               TEXT += ((data.tags != '') ?  '<span>' + data.tags.replace(/,/ig,'</span><span>') + '</span>' : '');
               if(data.sharedTags != null){
                 TEXT += ((data.sharedTags != '') ?  '<span class="l_shared">' + data.sharedTags.replace(/,/ig,'</span><span class="l_shared">') + '</span>' : '');
               }
               TEXT += '    </div>';
               TEXT += '    <div class="utility">';
               TEXT += '      <ul>';

               //TEXT += '<li>'+(x+1)+'</li>';

               TEXT += '<li class="u_comments"><a href="#" id="comments_'+data.id+'">';
               if(data.comments != null){
                 TEXT +=  data.comments+' Comments';
               }else{
                 TEXT += 'View Comments';
               }
               TEXT += '</a></li>';

               if(data.username != null){
                 if(data.blinked == 1){
                   TEXT += '        <li class="u_privacy"><a id="private_'+data.id+'" class="toggle-privacy'+ izPrivate +'" href="#"><span>*</span></a></li>';
                   TEXT += '        <li class="u_edit"><a href="#" id="t_'+data.id+'">Edit</a></li>';
                   TEXT += '        <li class="u_delete""><a href="#" id="del_' + data.id + '">Delete</a></li>';
                 }
                 TEXT += '          <li class="u_blinked">Blinked by <a href="#" class="blinkerUsername" title="' + data.username + '">' + data.username + '</a> ' + prettyDate(data.dateAdd) + '</li>';
               }
               else{
                 TEXT += '          <li class="u_privacy"><a id="private_'+data.id+'" class="toggle-privacy'+ izPrivate +'" href="#"><span>*</span></a></li>';
                 TEXT += '          <li class="u_edit"><a href="#" id="t_'+data.id+'">Edit</a></li>';
                 TEXT += '          <li class="u_delete""><a href="#" id="del_' + data.id + '">Delete</a></li>';
                 TEXT += '          <li class="u_blinked">Blinked ' + prettyDate(data.dateAdd) + '</li>';
                 if(data.cached == 'true'){
                   TEXT += '        <li class="u_cached"><a href="file://'+data.location+'" class="cached">Saved web page</a></li>';
                 }
                 /* THIS IS FOR THE CACHED -
                    else{
                    TEXT += '        <li class="u_savelink"><a href="'+data.outUrl+'" class="'+BL.noFolderList+'">Save Link</a></li>';
                    }
                  */
               }
               TEXT += '      </ul>';
               TEXT += '    </div>';
               TEXT += '  </div>';
               if(!edit) TEXT += '</div>';

             }

             BL.createActiveLists(TAGS,'#activelists ._viewport ul','<li class="activelists">x</li>',edit);

             return TEXT;
           },

displayLinkAsListView: function (result,edit){
                         edit = (edit != null) ? edit : false;

                         TEXT = '';
                         TAGS = '';

                         for (x = 0; x < result.length; x++) {


                           data = result[x];
                           data.id = (data.rowid != null) ? data.rowid : data.userlinkid;

                           data.outUrl = data.url;

                           if(null != data.url){
                             domain = (d = data.url.replace(/http\:\/\/|https:\/\/|ftp:\/\//,'').replace(/^www\./i,'').match(/([^/\:]+)/ig)) ? d[0] : null;
                           }else{
                             continue;
                           }

                           TAGS += (typeof(data.tags) != 'undefined' && data.tags != '' && data.tags != null) ? data.tags + ',' :  '';
                           if(data.tags == null) { data.tags = ''}

                           TEXT += '<tr class="link" id="row_' + data.id + '">';
                           if(!(data.username != null)) TEXT += '<td><input type="checkbox"/></td>';
                           TEXT += '<td class="list-link">';
                           TEXT += '<div>';
                           //TEXT += (x+1) + ' ' + 
                           TEXT += '<a target="_blank" id="link_' + data.id + '" href="'+data.outUrl+'">' + ((data.name != '') ? data.name : data.url) + '</a>';
                           TEXT += '<div class="lists" id="tags_'+data.id+'">';
                           TEXT += '<span class="l_domain">'+ domain +'</span>';
                           TEXT += ((data.tags != '') ?  '<span>' + data.tags.replace(/,/ig,'</span><span>') + '</span>' : '');
                           if(data.sharedTags != null){
                             TEXT += ((data.sharedTags != '') ?  '<span class="l_shared">' + data.sharedTags.replace(/, ?/ig,'</span><span class="l_shared">') + '</span>' : '')
                           }
                           TEXT += '</div>';
                           TEXT += '</div>';
                           TEXT += '</td>';
                           TEXT += '</tr>';


                         }

                         BL.createActiveLists(TAGS,'#activelists ._viewport ul','<li class="activelists">x</li>',edit);
                         return TEXT;
                       },

showLinks: 
                       function(result,append){
                         $('#activelists ._viewport ul').html('');

                         $('#view-thumbnail').removeClass('disabled');
                         $('#view-list').removeClass('disabled');
                         $('#view-'+BL._viewType).addClass('active');

                         if(result != null){
                           if(result == '' || result.length == null || result == 'false'){
                             //$('#tableTopHeader').hide();
                             //$('.actions').hide();
                             if(BL.searchFocus != 'recomm'){
                               $('#content').html('<div class="_prompt"><h1>Move Along</h1><p>No links to see here.</p></div>');
                             }else{
                               $('#content').html('<div class="_prompt"><h1>Oops!</h1><p>Sorry, I am not sure what kind of sites to recommend to you. I can only recommend links after you have started saving more links into BlinkList. Please keep blinking more sites and check back later.</p></div>');
                             }
                           }else{
                             //$('#tableTopHeader').show();
                             //$('.actions').show();
                             switch(this._viewType){
                               case 'list':
                                 TEXT = BL.displayLinkAsListView(result);
                                 if(append != true) TEXT = '<table id="list-view" cellspacing="0" summary="List Name"><col width="32px"/><col />' + TEXT +  '</tbody></table>';
                                 className = 'list';
                                 $('#tableTopHeader').show();
                                 break;
                               case 'thumbnail':
                                 TEXT = '';
                                 TEXT += BL.displayLinkAsThumbView(result);
                                 className = 'thumbnail';
                                 $('#tableTopHeader').hide();
                                 break;
                             }

                             selParent = $('.selected:parent');
                             if(selParent.hasClass('sort') || selParent.hasClass('all')){
                               $('.actions').show();
                             }

                             if(append != true){
                               $('#content').html(TEXT).attr('class',className).animate({ scrollTop: 0 });
                             }else{
                               $('#content').append(TEXT);
                             }

                             //$('#view-folder').removeClass('active');

                             /*
                                viewType = ($.cookie('viewType') != null) ? $.cookie('viewType') : 'thumbnail';
                                $('#view-'+viewType).addClass('active');
                              */
                           }
                         }
                       },

createActiveLists: 
                       function(tags,intoId,whereToPut,edit){
                         if(edit !== false){
                           temp = '';
                           $(intoId + ' a').each(function(){
                               temp += $(this).text() + ',';
                               });
                           tags = temp + tags;
                         }

                         $(intoId).html('');
                         tags = tags.substring(0,tags.length - 1).split(',');
                         if(tags.length && tags != ''){
                           if(tags != 'null'){
                             suroudingHTML = whereToPut.split('x');

                             lists = getUniqueValues(tags).sort(
                                 function(a, b){ a = a.toLowerCase(); b = b.toLowerCase(); if (a>b) return 1; if (a <b) return -1; return 0;
                                 });

                             for(x = 0; x < lists.length; x++){
                               if(lists[x] != 'null'){
                                 $(intoId).append(suroudingHTML[0] + '<a href="#" onclick="return false">' + $.trim(lists[x]) + '</a>' + suroudingHTML[1]);
                               }
                             }

                             $(intoId+' a').click(function(){
                                 BL.getLinksOfTag($(this).html());
                                 return false;

                                 });

                             if(BL.searchFocus == null){
                               $(".activelists").draggable({ helper: 'clone', revert: true, delay:100, scroll:true, revert:'invalid'});
                             }

                             if(BL.hasGears){
                               if(BL.db.lastArguments[1] == 'tags'){
                                 token = BL.db.lastArguments[0].substr(1,BL.db.lastArguments[0].length-3);
                                 $('#activelists ._viewport .activelists:contains("'+token+'")').each(function(e,x){
                                     if($(x).text() == token){
                                     $(x).addClass('selected');
                                     }
                                     });
                               }
                             }
                             else{
                               if(BL._lastPagedQueryAction == "getLinksOfList"){
                                 $('#activelists ._viewport .activelists:contains("'+BL._lastPagedQueryData.token+'")').each(function(e,x){
                                     if($(x).text() == BL._lastPagedQueryData.token){
                                     $(x).addClass('selected');
                                     }
                                     });
                               }
                             }
                           }
                         }
                       },

showStartupPage:
                       function(folderName){
                         if(BL.hasGears){
                           BL.custructStarupPage(BL.db.getLinksOfFolder(folderName));
                           ui.displayFolderStuff(folderName);
                         }else{
                           BL.talkToServer('getLinksOfFolder',{folder:folderName},function(results){
                               BL.custructStarupPage(results)
                               ui.displayFolderStuff(folderName);
                               });
                         }
                       },

custructStarupPage:
                       function(results, withAvatar){
                         if(results != '0'){
                           TEXT = '';
                           for (list in results){
                             avatar = (withAvatar != null) ? '<img class="avatar" alt="'+list+'" src="/user/avatar/'+list+'">' : '';
                             TEXT += '<div class="list-container"><h2>' + avatar + ' <a href="#" class="startupTrigger" title="' + list + '">' + list + '</a></h2><div id="startup_'+list.replace(/[^0-9A-Za-z_]/g, '_')+'"><ul>';
                             for(t=0; t < results[list].length; t++ ){
                               TEXT += '<li>' + '<div><a href="'+results[list][t]['url']+'" target="_blank">'+results[list][t]['name']+'</a></div>' +'</li>';
                             }
                             if(results[list].length == 5){
                               TEXT += '<li>' + '<div><a href="#" class="startupTrigger" title="' + list + '">More&#8230;</a></div>' +'</li>';
                             }
                             TEXT += '</ul></div></div>';
                           }
                         }
                         else{
                           TEXT = '<div class="list-container"><h2>No results were found</h2></div>';
                         }

                         $('#content').html(TEXT).animate({ scrollTop: 0 });;

                         $('.startupTrigger').click(function(){
                             $('.selected:not(.open) .toggle').trigger('click');
                             $('.selected li a:contains("'+$(this).attr('title')+'")').trigger('click');
                             return false;
                             });
                       },

renderList:
                       function(result){
                         $('#myLinks').html('');

                         numberOfTagsToShow = result.length;

                         folders = new Array();
                         folders[BL.noFolderList] = "0";

                         for(x = 0; x < numberOfTagsToShow; x++){
                           if(result[x].name != ''){
                             if(result[x].folderName != '' && result[x].folderName != null){
                               fullName = result[x].folderName;
                               cleanName = fullName.replace(/[^0-9A-Za-z_]/g, '_');

                               if(!(folders[cleanName] != null)){
                                 BL.createFolder(fullName);
                                 folders[cleanName] = "0";
                               }
                               appendTo = (cleanName != BL.noFolderList) ? '#folder_'+cleanName : '#myLinks' ;
                               $(appendTo).append('<li class="sort"><a href="#" onclick="return false">' + result[x].name + '</a></li>');
                             }
                           }
                         }
                       },

createFolder:
function(folderName){
  $('#myLinks').prepend( 
    '<li class="folder"><a href="#" class="toggle"><span>+</span></a><a href="javaScript:void(0)" onclick="return false" class="folderName">'+folderName+'</a>'+
    '<ul class="listContainer" id="folder_'+folderName.replace(/[^0-9A-Za-z_]/g, '_')+'"></ul>'+
    '</li>');
  folderLi = $('#folder_'+folderName.replace(/[^0-9A-Za-z_]/g, '_')).parent();
  folderLi.find('a.toggle').click(function(){
    $(this).parent().toggleClass('open');
    $(this).parent().children('ul').slideToggle();
    return false;
  });
  folderLi.find('.folderName').click(function(){
    ui.highlightMe(this);
    BL.showStartupPage($(this).html());
    $('#view-list').addClass('disabled').removeClass('active');
    $('#view-thumbnail').addClass('disabled').removeClass('active');
    return false;
  });
  folderLi.droppable({
    accept: ".sort, .activelists",
    hoverClass: 'droppable-hover',
    greedy:true,
    drop: function(ev, me) {
      tagName = me.draggable.text();
      folderContainer = $('#'+$(this).find(".listContainer").attr('id'));
      iWasAt = me.draggable.parent().attr('id');
      nowAt = folderContainer.attr('id');
      if(nowAt != iWasAt){
        if(me.draggable.hasClass('activelists')){
          list = '';
          $('#myLinks .sort a').each(function(){ list += $(this).text() + ','; });
          if(list.search(eval('/' + tagName +'/i')) == -1){
            me.draggable.addClass('sort').removeClass('activelists');
          }else{
            ui.setSystemMessage('You have already added this list <b>'+tagName+'</b> into one of your folders.');
            return false;
          }
        }
        folderContainer.prepend(me.draggable);
        folderName = folderContainer.parent().find(".folderName").text();
        BL.tag(tagName).setFolder(folderName);
        if(!folderContainer.parent().hasClass('open')){
          folderContainer.parent().find('.toggle').trigger('click');
        }
        return true;
      }else{
        return false;
      }
    }
  });
},

showTagsFromResult:
function(result){
  BL.renderList(result);
  ui.renderListOptgroup(result);
  ui.bindListBehavior();
},

  // SQL & SQL Helpers

preparePagerLinks:
function(){
  if($('#rTo').text() >= $('#qResults').text()) {
    $('#rTo').text($('#qResults').text());
    $('#next').hide();
  }else{
    $('#next').show();
  }
},

setPageStats:
function(from){
  if($('#qResults').text() != 'false' && parseInt($('#qResults').text()) != 0){
    from = from * BL._resultsPerPage;
    $('#rFrom').html(from + 1);
    rto = from + BL._resultsPerPage;
    rto = rto > $('#qResults').text() ? $('#qResults').text() : rto;
    $('#rTo').html(rto);  
    if(from == 0) $('#back').hide(); else $('#back').show();
    if((from+BL._resultsPerPage) >= $('#qResults').text()) $('#next').hide(); else $('#next').show();
    if(parseInt($('#qResults').text()) > BL._resultsPerPage){
      $('#showingFrom').show();
    }
    else{
      $('#showingFrom').hide();
    }
    $('#pager').show();
  }else{
    $('#pager').hide();
  }
  ui.setAppHeight();
},

  // Actions
firstImport:
function(result){
  if(result != null){
    if(!(result == '' || result.length == null || result == 'false')){
      BL.callLinkWorker([BL.cookie,result]);
    }
  }
},

SyncNewUpdates:
function(result){

  doRefresh = false;
  if(result.deletes != null){
    if(result.deletes != ''){
      doRefresh = true;
      deletes = result.deletes.split(',');
      for(item = 0; item < deletes.length; item++){
        url = deletes[item];
        id = BL.db.getIdFromUrl(url);
        BL.db.deleteURL(id);
      }
    }
  }
  updates = result.updates;
  if(updates != null){
    if(!(updates == '' || updates.length == null || updates == 'false')){
      BL.callLinkWorker([BL.cookie,updates]);
      doRefresh = false;
    }
  }

  if(doRefresh){
    ui.setSystemMessage('You have new updates!');
    $('#allLinks').trigger('click');
  }

  BL.db.updateLastUpdate();

  BL.talkToServer('getUsertags',{withFoldersOnly:true},function(results){
      BL.firstImportTags(results);
      BL.showTagsFromResult(results);
      BL.talkToServer('getUserlinkCounts',{},function(result){
        if(BL.localLinks != parseInt(result)){ BL.talkToServer('firstImport',{begin:0,amount:BL._downloadPerWorker,firstCycle:true},BL.firstImport); }
        });
      });
},

firstImportTags:
function(result){
  BL.callTagWorker([BL.cookie,result]);
},

showListFromResult:
function(result,options){

  BL._lastPageResult = result;
  BL.showLinks(result);
  //if( BL._currentPage == 0){

  function countCallBack(count){
    BL.showRowCount(count);
    BL.setPageStats(BL._currentPage);
  };

  // no gears
  switch(options){
    case 'recomm':
      //BL.setPageStats(BL._currentPage);
      break;
    case 'sharedInbox':
      BL.talkToServer('getInboxLinksCount',{},countCallBack);
      break;
    case 'freindCount':
      BL.talkToServer('getLinksByFriendsCount',{'friendusername':BL._lastPagedQueryData.friendUsername},countCallBack);
      break;
    case 'popularCount':
      BL.talkToServer('getPopularLinksCount',{'token':BL.searchFocusParams},countCallBack);
      break;
    case 'listCount':
      if(BL.hasGearsAvtive){
        countCallBack(BL.db.getRowCount(BL.db.lastArguments[0],'tags'));
        BL._lastPagedQueryAction = null;
      }else{
        BL.talkToServer('getLinksOfListCount',{'token':BL._lastPagedQueryData.token,username:BL.searchFocusParams},countCallBack);
      }
      break;
    case 'fullTextCount':
      if(BL.hasGearsAvtive){
        countCallBack(BL.db.getRowCount(BL.db.lastArguments[0]));
        BL._lastPagedQueryAction = null;
      }else{
        BL.talkToServer('getFullTextSearchCount',{'token':BL._lastPagedQueryData.token,username:BL.searchFocusParams},countCallBack);
      }
      break;
    case 'sharedListCount':
      BL._currentPage = 0;
      BL.talkToServer('getSharedListLinksCount',{'sharedtagid':BL._lastPagedQueryData.sharedtagid},countCallBack);
      break;
    case 'noAskCount':
      BL.setPageStats(BL._currentPage);
      break;
    default:
      if(BL.hasGearsAvtive){
        BL.showRowCount(BL.db.getRowCount('*'));
        BL.setPageStats(BL._currentPage);       
        BL._lastPagedQueryAction = null;
      }else{
        BL.showRowCount();
      }
  }
  /*
     }else{
     if(result.length != null){
     BL.showRowCount(result.length);
     }else{
     BL.showRowCount(0);
     }
     BL.setPageStats(BL._currentPage);
     }
   */
  ui.bindListButtonsToFunctions();
  ui.makeAltDividers();
},

showRowCount:
function(count){
  if(count == null){
    if(BL.hasGears && BL.hasGearsAvtive){
      //$('#qResults').html(BL.db.getRowCount());
    }
    else{
      BL.talkToServer('getUserlinkCounts',{},function(result){
          BL.showRowCount(result);
          BL.setPageStats(BL._currentPage);
          if(BL._lastPagedQueryAction == 'initUser' && result == 0){
            $('#prompt_arrow').show();
            $('#footer').show();
            ui.setAppHeight();
          }
      });
    }
  }else{
    $('#qResults').html(count);
  }
},

taskAfterSwitchView:
function(){
  if(this._viewType == 'thumbnail'){
    $('#tableTopHeader').hide();
  }else{
    $('#tableTopHeader').show();
  }

  if(BL.changed){
    //TODO: MAKE SENCE OF THIS BL.showListFromResult(BL.db.showAll(BL._currentPage,BL._resultsPerPage));
    BL.talkToServer('initUser',{begin:BL._currentPage,amount:BL._resultsPerPage},BL.showListFromResult);
    BL.changed = false;
  }
  else{
    BL.showListFromResult(BL._lastPageResult,'noAskCount');
  }
},


talkToServer: 
function(actionType,data,callBack){
  //try{
  if(BL._registry == null){
    BL._registry = new Object();
    BL._registry.pendingRequests = 0;
    BL._registry.callQueue = new Array();
  }
  BL._registry.callQueue.push({actionType:actionType,data:data,callBack:callBack});
  BL._registry.pendingRequests++;
  if(BL._registry.pendingRequests == 1){
    BL.executeServerCommunications();
  }
  //}catch(e){
  //BL.error(e);
  //}
},

postTalkToServer: 
function(){
  BL._registry.pendingRequests--;
  if(BL._registry.callQueue.length > 0){
    BL.executeServerCommunications();
  }
  else{
    ui.hideMessage();
  }
},

error: 
function(e){
  BL.postTalkToServer();
  if(!BL.hasGears){
    ui.setSystemMessage('Opps! Action failed. Please try again.');
  }
  else{
    BL.db.addToCommands(BL._currentDataSent.action,BL._currentDataSent.data);
  }
},

syncOnline:
function(){
  if(BL.hasGears && BL.hasGearsAvtive){
    if(!BL.isOnline()){
      return false;
    }
  }
  return true;
},

executeServerCommunications: 
function(){
  callObject = BL._registry.callQueue.pop();  
  actionType  = callObject.actionType;
  data        = callObject.data;
  callBack    = callObject.callBack;
  data.hash = BL.hash;
  data.apiKey = BL.apiKey;

  BL._currentDataSent.data = data;
  BL._currentDataSent.action = actionType;

  if(actionType == 'getLinksByFriends'){
    //BL.xx.cancel();
  }
  if(BL.syncOnline()){
    if(BL.hasGears){
      if(BL.searchFocus != null){
        lMsg = 'Loading&#8230;';
      }else{
        lMsg = 'Updating&#8230;';
      }
    }
    else{
      lMsg = 'Loading&#8230;';
    }
    ui.setMessage(lMsg);
    switch(actionType){
      // special cases
      case 'firstImport':
        RPCCall('initUser',data,callBack);
        break;
      case 'getUsertagsThenInitUser':
        RPCCall('getUsertags',data,function(results){
            callBack(results);
            BL.talkToServer('initUser',{begin:0,amount:BL._resultsPerPage},function(results){
              BL.showListFromResult(results);
              $('#content').show();
              BL.talkToServer('getUsertagsArray',{begin:0,amount:500,type:'json'},function(results){
                ui.appendToSuggestList(results);
                });
              });
            BL.firstLoad = false;
            });
        break;
        // cases that has paging
      case 'initUser':
      case 'getuserlinks':
      case 'getPopularLinks':
      case 'getRecommendedLinks':
      case 'getSharedListLinks':
      case 'getFullTextSearch':
      case 'getLinksByFriends':
      case 'getFriendsLinks':
      case 'getLinksOfList':
        BL._lastPagedQueryAction = actionType;
        BL._lastPagedQueryData = data;
        eval('RPCCall("'+actionType+'",data,callBack)');
        break;
      default:
        eval('RPCCall("'+actionType+'",data,callBack)');
        break;
    }
    return true;
  }else{
    try{
      BL._registry.pendingRequests--;
      BL.db.addToCommands(actionType,data);
    }
    catch(e){
      alert(e);
    }
  }
},


  /* Generate the object to pass to http requests */

cleanNullProps: 
function(arrayOfProperties){
  temp = {};
  temp = jQuery.extend(temp, arrayOfProperties);
  return temp;
},

deleteUrl:
function(id){ 
  checked = (id != null) ? $('#row_'+id) : $('#content .selected');
  if(checked.length == 0){
    ui.setSystemMessage('Please select links to be deleted');
  }
  else{
    for(x = 0; x < checked.length; x++ ){
      id = checked[x].id.substr(4);
      BL.url(id).remove();
      ui.removeLinkUI(id);
    }
    if(checked.length > 1){
      ui.setSystemMessage(checked.length + ' links were deleted ');
    }
    else{
      ui.setSystemMessage('Link was deleted');
    }

    BL.createActiveLists('','#activelists ._viewport ul','<li class="activelists">x</li>','edit');
    ui.makeAltDividers();
    $('#qResults').text(parseInt($('#qResults').text())-checked.length);
    if($('#qResults').text() != '0'){
      if(parseInt($('#rTo').text()) > parseInt($('#qResults').text())){
        $('#rTo').text($('#qResults').text());
      }else{
        BL.getLinksAfterDelete(checked.length);
      }
    }
  }
},

getLinksAfterDelete: 
function(numOfLinks){
  //TODO: make work with GG
  getFrom = ((BL._currentPage * BL._resultsPerPage) + BL._resultsPerPage ) - numOfLinks;
  BL.talkToServer('initUser',{begin:getFrom,amount:numOfLinks},function(results){
      BL.showLinks(results,true);
      ui.makeAltDividers();
      });
},

editUrl: 
function(id){
  url = $('#f1').val();
  if(url.match(/^([a-z]+:\/{0,2})/ig) == null){
    url = 'http://' + url;
  }

  dataToSend = {
   id:id,
   userlinkid:id,
   originalUrl:$('#link_'+id).attr('href').replace('/link/view/?url=',''),
   link:url,
   url:url,
   name:$('#f3').val(),
   description:$('#f4').val(),
   private:$('#isPrivate').hasClass('checked'),
   tags:$('#f5').val().replace(/ +/ig,' ').replace(/, /ig,',').replace(/,+/ig,',').replace(/,$/i,''),
   comments:$('#comments_'+id).text().split(' ')[0],
   voteHTML:'<div class="vote">' + $('#row_'+id+' .vote').html() + '</div>'
  };

  if(BL.hasGears){
    dataToSend.votes = false;
  }

  BL.url(dataToSend.url).update(BL.cleanNullProps(dataToSend));
  displayLink = (BL._viewType == 'list') ? BL.displayLinkAsListView : BL.displayLinkAsThumbView;
  dataToSend.dateAdd = $('#row_'+id+' .u_blinked').text().substr(8);

  result = new Array();
  result[0] = dataToSend;

  $('#edit_' + id).remove();
  $('#row_' + id).html(displayLink(result,true));

  ui.bindListButtonsToFunctions(id);

  if($('#row_' + id).hasClass('selected')){
    $('#row_' + id + ' input:checkbox').attr('checked','checked');
  }

},

ChangePrivateSettings:
function(id){
  dataToSend = {};
  // dataToSend.link = $('#link_'+id).attr('href').replace('/link/view/?url=','');
  dataToSend.link = $('#link_'+id).attr('href');
  if(dataToSend.private = !$('#private_'+id).hasClass('public')){
    ui.setSystemMessage('Your link is now private');  
  }
  else{
    ui.setSystemMessage('Your link is now public'); 
  }
  BL.url(dataToSend.url).update(BL.cleanNullProps(dataToSend));
},

getLinksOfTag:
function(list){
  BL._currentPage = 0;
  BL._currentList = list;
  if(BL.searchFocus != null){
    switch(BL.searchFocus){
      case 'friends':
        BL.talkToServer('getLinksOfList',{begin:0,amount:BL._resultsPerPage,token:list,username:BL.searchFocusParams},function(results){
            BL.showListFromResult(results,'listCount');
            $('#mainTitle').html( $('#mainTitle').html().split(' | ')[0] + ' | ' + BL._currentList);
            $('#mainTitleUsername').click(ui.getUserLinks);
            $('#deleteFriend').hide();
            });
        break;
      case 'popular':
        BL.talkToServer('fullTextSearchPopular',{begin:0,amount:BL._resultsPerPage,token:list},function(results){
            BL.showListFromResult(results,'noAskCount'); //TODO: xxx
            $('#mainTitle').html( $('#mainTitle').html().split(' | ')[0] + ' | ' + BL._currentList);
            });
        break;
      case 'recomm':
        BL.talkToServer('getLinksOfList',{begin:0,amount:BL._resultsPerPage,token:list,scope:BL.searchFocus},function(results){
            BL.showListFromResult(results,'listCount');
            $('#mainTitle').html( $('#mainTitle').html().split(' | ')[0] + ' | ' + BL._currentList);
            });
        break;
      case 'shared':
        BL.talkToServer('getLinksOfList',{begin:0,amount:BL._resultsPerPage,token:list,scope:BL.searchFocus},function(results){
            BL.showListFromResult(results,'listCount');
            $('#mainTitle').html( $('#mainTitle').html().split(' | ')[0] + ' | ' + BL._currentList);
            $('#listOptions').hide();
            });
        break;
    }
  }else{
    myTitle = '<a href="#" id="staredList" class="toggle-star"> <span>*</span> </a>' + BL._currentList;
    if(BL.hasGears){
      $('#mainTitle').html(myTitle);
      ui.showOptions('showTags');
      ui.highlightMe()
        BL.showListFromResult(BL.db.query(list,'tags'),'listCount');
      ui.showTagSidebarOptions(list);
    }
    else{
      BL.talkToServer('getLinksOfList',{begin:0,amount:BL._resultsPerPage,token:list},function(results){
          $('#mainTitle').html(myTitle);
          ui.showOptions('showTags');
          ui.highlightMe()
          BL.showListFromResult(results,'listCount');
          ui.showTagSidebarOptions(list);
          });
    }
  }
},

isOnline:
function(){
  if(BL.status == 'online'){
    return true;
  }
  else{
    return false;
  }
},

slurp:
function(){
  localServer = google.gears.factory.create('beta.localserver','1.0');
  store = localServer.createManagedStore('blinklist');
  store.manifestUrl = '/js/manifest.json?user=khalid';
  store.checkForUpdate();
  var timerId = window.setInterval(function() {
      if (store.currentVersion) {
      window.clearInterval(timerId);
      } else if (store.updateStatus == 3) {
      }
      }, 500);  
}
}
var Firefox = {
pages: new Array(),
       init: function() {
         var db = google.gears.factory.create('beta.database');
         db.open('pages');
         lastCheck = BL.db.getLastFFSync();
         lastID = null;
         db.execute('CREATE TABLE IF NOT EXISTS pages (url STRING NOT NULL, path STRING NOT NULL, alive INTEGER DEFAULT 1, UNIQUE (url))');
         var rs = db.execute('select *,rowid from pages where rowid > ?',[lastCheck]);
         while (rs.isValidRow()) {
           lastID = rs.field(3);
           BL.db.updateCachedPages(rs.field(0),rs.field(1));
           rs.next();
         }
         if(lastID != null){
           BL.db.updateLastFFSync(lastID);
         }
         rs.close();
       }
}

/// ONLY GG + SQL
BL.url = 
function(url_id){
  return {
    postUpdate:
    function(){
      if(BL.hasGears){ BL.db.updateLastUpdate(); }
    },
    add: 
    function(data){
      BL.db.addURL(data);
      BL.talkToServer('saveLink',BL.cleanNullProps(data),this.postUpdate);
    },
    remove: 
    function(){
      re = new RegExp(/^\d+$/);
      if(re.exec(url_id) != null){
        id = url_id;
        url = $('#link_'+id).attr('href').replace('/link/view/?url=','');
      }
      else{
        //id = BL.db.getIdFromUrl(url_id);
      }

      if(BL.hasGears){
        BL.db.deleteURL(id);
      }
      BL.talkToServer('deleteLink',{link:url},this.postUpdate);
      BL.changed = true;
    },
    update: 
    function(data){
      BL.talkToServer('saveLink',data,this.postUpdate);
      if(BL.hasGears){
        BL.db.saveURLChanges(id,data);
      }
      data.private = (data.private) ? "1" : "0";
      BL.changed = true;
    }
  }
}

/* DATABASE - or links and tags that does not require to be set first */
BL.db = {
connection:null,
           // useage at queryAgainFrom
           lastArguments:['*'],
           // to make things shorter
           listFieldsToDisplay:'name,url,description,fulltextTable.rowid,dateAdd,private,tags,cached,location FROM fulltextTable,links',
           // execute the query
           execute:
             function(sql,params){
               if(params == null){
                 return this.connection.execute(sql);
               }else{
                 return this.connection.execute(sql,params);
               }
             },
getIdFromUrl:
           function(url){
             result = this.execute('select rowid from fulltextTable where url = "'+url+'" LIMIT 1');
             if(result.isValidRow()){
               val = result.fieldByName('rowid');
             }else{
               val = 0;
             }
             result.close();
             return val;
           },
open:
           function(dbName){
             this.connection = google.gears.factory.create('beta.database');
             this.connection.open(dbName);
             return this.createDb();
           },
addToCommands:
           function(name,data){
             this.execute('INSERT INTO commands VALUES (?,?)',[name,JSON.stringify(data)]);
             return false;
           },
syncCommands:
           function(){
             result = this.execute('select * from commands');
             while(result.isValidRow()){
               BL.talkToServer(result.field(0),JSON.parse(result.field(1)),null);
               result.next();
             }
             result.close();
             this.execute('DELETE FROM commands');
           },
           // create DB then return the number of records
createDb:
           function(){
             rows = 0;
             try{
               result = this.execute("select count(*) as num from links LIMIT 1");
               rows = result.fieldByName('num');
               result.close();
             }
             catch(e){
               this.execute('CREATE TABLE IF NOT EXISTS links (`dateAdd` DATE, `private` TEXT, `cached` BOOLIAN, `location` TEXT)');
               this.execute('CREATE INDEX date_add_index ON links (`dateAdd`)');
               this.execute('CREATE VIRTUAL TABLE fulltextTable USING fts2(`url` TEXT,`name` TEXT,`description` TEXT, `tags` TEXT)'); 
               this.execute('CREATE TABLE IF NOT EXISTS tags (`name` TEXT NOT NULL PRIMARY KEY, `folderName` TEXT, UNIQUE (`name`))');
               this.execute('CREATE TABLE IF NOT EXISTS commands (`name` TEXT, `data` TEXT)');
               this.execute('CREATE TABLE IF NOT EXISTS settings (`name` TEXT PRIMARY KEY, `value` TEXT)');
             }
             return rows;
           },
updateCachedPages:
           function(url,localFile){
             result = this.execute('SELECT rowid FROM fulltextTable WHERE url = ? LIMIT 1',[url]);
             if(result.isValidRow()){
               this.execute('UPDATE links SET cached = ?, location = ? WHERE rowid = ?',[true,localFile,result.fieldByName('rowid')]);
             }
             result.close();
           },
updateLastUpdate:
           function(){
             this.execute('INSERT OR REPLACE INTO settings VALUES("lastUpdate","'+BL.lastUpdate+'");');
           },
updateLastFFSync:
           function(id){
             this.execute('INSERT OR REPLACE INTO settings VALUES("lastFFSync","0");');
           },
getLastUpdate:
           function(){
             result = this.execute('select `value` from settings where `name` = "lastUpdate" LIMIT 1');
             if(result.isValidRow()){
               val = result.fieldByName('value');
             }else{
               val = 0;
             }
             result.close();
             return val;
           },
getLastFFSync:
           function(){
             result = this.execute('select `value` from settings where `name` = "lastFFSync" LIMIT 1');
             if(result.isValidRow()){
               val = result.fieldByName('value');
             }else{
               val = 0;
             }
             result.close();
             return val;
           },
cleanTags:
           function(_tags){
             returnVal = '';
             if(_tags != ''){
               zamp = _tags.split(',');
               for(t=0; t < zamp.length; t++){
                 temp = $.trim(zamp[t]).match(/^[^#]+$/i);
                 if(temp != null && temp != ''){
                   returnVal += temp + ',';
                 }
               }
             }
             //alert(returnVal)
             return returnVal.substring(0,returnVal.length - 1);
           },
addURL:
           function(data){
             this.execute('INSERT INTO links VALUES (datetime(?,"unixepoch","localtime"),?,?,?)',[this.getLastUpdate(),data.private,false,null]); //datetime("now")
             this.execute('INSERT INTO fulltextTable VALUES (?,?,?,?,last_insert_rowid())',[data.link, data.name, data.description, this.cleanTags(data.tags)]);
             return true;
           },
saveURLChanges:
           function(id,data){
             try{
               //TODO: Add Transactions
               sql2 = 'UPDATE links SET private = ? WHERE rowid = ?';
               this.execute(sql2,[data.private,id]);
               if(data.name != null){
                 sql1 = 'UPDATE fulltextTable SET url = ?, name = ?, description = ?, tags = ?  WHERE rowid = ?';
                 this.execute(sql1,[data.url, data.name, data.description, this.cleanTags(data.tags),id]);
               }
               return true;
             }catch(e){
               alert(e.message);
               return false;
             }
           },
deleteURL:
           function(id){
             this.execute("DELETE FROM links where rowid = ?", [id]);
             this.execute("DELETE FROM fulltextTable where rowid = ?", [id]);
           },
           // use the last query to go to another page, by increading the LIMIT values
queryAgainFrom:
           function(from,to){
             from = (from != null) ? from : 0;
             to = (to != null) ? to : BL._resultsPerPage;
             return this.query(this.lastArguments[0],this.lastArguments[1]);
           },
           // query the databse
query:
           function(text,field){
             this.lastArguments = arguments;
             if(text == '*'){
               sql = 'select '+ this.listFieldsToDisplay + ' WHERE fulltextTable.rowid = links.rowid ORDER BY links.dateAdd DESC';
               params = [];
             }else{
               if(field == null){
                 field = 'fulltextTable';
                 text = text + "*";
               }else{
                 if(field == 'tags'){
                   text = '"'+text+',"';
                 }
               }
               sql = 'select '+ this.listFieldsToDisplay + ' WHERE '+field+' MATCH ? and links.rowid = fulltextTable.rowid ORDER BY links.dateAdd DESC';

               params = [text];
             }
             sql = this.addLimits(sql);
             return this.convert(this.execute(sql,params),'links'); 
           },
           // get the row numbers of each query
getRowCount:
           function(text,field){
             if(text == '*'){
               sql = 'SELECT count(*) as num from links';
               params = [];
             }else{
               sql = 'SELECT count(*) as num from fulltextTable';
               if(field == null){
                 field = 'fulltextTable';
                 text = text + "*";
               }
               sql += ' WHERE '+field+' MATCH ?';
               params = [text];
             }

             result = this.execute(sql,params)
               num = result.fieldByName('num');
             result.close();
             return num;
           },
           // get the list of tags, these tags are the ones used in the bookmarked version
           // TODO: get the full list also
getTagList:
           function(){
             return this.convert(this.execute("select * from tags where folderName is not null order by name"),'tags');
           },
getAllTags: 
           function(){
             return this.convert(this.execute('select name from tags'),'group_concat');
           },  
getLinksOfFolder:
           function(folderName){
             foundTags = this.convert(this.execute('select * from tags where folderName = ?',[folderName]),'tags');
             compiledResults = new Array();
             foundStuff = false;
             for(current in foundTags){
               listOflinks = this.convert(
                   this.execute('select '+ this.listFieldsToDisplay + ' ' +
                     'WHERE tags MATCH ? and links.rowid = fulltextTable.rowid '+
                     'ORDER BY links.dateAdd DESC LIMIT 5',[foundTags[current].name]),'links');
               if(listOflinks.length != 0){
                 compiledResults[foundTags[current].name] = listOflinks;
                 foundStuff = true; 
               }
             }
             if(foundStuff){
               return compiledResults;
             }else{
               return '0';
             }

           },
           // google gears sends results as a resource ID like PHP, to make this work with JavaScript
           // you need to convert them to arrays
convert:
           function(result,_type){
             temp = new Array();
             switch(_type){
               case 'tags':
                 while (result.isValidRow()) {
                   temp.push({'name':result.field(0),'folderName':result.field(1)});
                   result.next();
                 }
                 break;
               case 'links':
                 while (result.isValidRow()) {
                   temp.push({
                       'name':result.field(0),
                       'url':result.field(1),
                       'description':result.field(2),
                       'rowid':result.field(3),
                       'dateAdd':result.field(4),
                       'private':(result.field(5) != 'false') ? 1 : 0,
                       'tags':result.field(6),
                       'cached':result.field(7),
                       'location':result.field(8)
                       });
                   result.next();
                 }
                 break;
               case 'group_concat':
                 while(result.isValidRow()){
                   temp.push(result.field(0));
                   result.next();
                 }
                 break;
             }
             result.close();
             return temp;
           },
addLimits:
           function(query){
             query += ' LIMIT ' + BL._currentPage * BL._resultsPerPage + ',' + BL._resultsPerPage;
             return query;
           }
}

BL.tag = function(tagName){
  return {
setFolder:
    function(folderName){
      BL.talkToServer('setFolder',{tag:tagName,folderName:folderName},null); 
      if(BL.hasGears){
        BL.db.execute('UPDATE tags SET folderName = ? where name = ?',[folderName,tagName]);
      }
      if(folderName != BL.noFolderList){
        ui.setSystemMessage('Moving list into folder');
      }
      else{
        ui.setSystemMessage('Adding list to sidebar');
      }
    },
removeFromSideBar:
      function(){
        BL.talkToServer('removeUserTagFromSideBar',{tag:tagName},function(){
            ui.setSystemMessage('List removed from sidebar');
            });
        if(BL.hasGears){
          BL.db.execute('UPDATE tags set folderNAme = null where name = ?',[tagName]);
        }
      },
remove:
      function(){
        BL.talkToServer('removeListCompletely',{tag:tagName},function(){
            ui.setSystemMessage('List removed');
            });
        if(BL.hasGears){
          BL.db.execute('DELETE FROM tags where name = ?',[tagName]);
          lists = BL.db.query(tagName,'tags');
          for(item in lists){
            replaced = lists[item].tags.replace(eval('/'+tagName+',?/gi'),'');
            BL.db.execute('UPDATE fulltextTable set tags = ? where rowid = ?',[replaced,lists[item].rowid]);
          }
        }
      },
renameFolder:
      function(oldName){
        BL.talkToServer('renameFolder',{'folder01':tagName,'folder02':oldName},function(){
            ui.setSystemMessage('folder renamed');
            });
        if(BL.hasGears){
          BL.db.execute('UPDATE tags SET folderName = ? where folderName = ?',[tagName,oldName]);
        }
      },
removeFolder:
      function(folderName){
        BL.talkToServer('deleteFolder',{'folder':folderName},function(){
            ui.setSystemMessage('folder deleted');
            $('#allLinks').trigger('click');
            });
        if(BL.hasGears){
          BL.db.execute('UPDATE tags set folderNAme = null where folderName = ?',[folderName]);
        }
      },
rename:
      function(newName){
        $('#myLinks .selected a:contains("'+tagName+'")').text(newName);
        $('#activelists .selected a:contains("'+tagName+'")').text(newName);
        BL._currentList = newName
          myTitle = '<a href="#" id="staredList" class="toggle-star"> <span>*</span> </a>' + newName;
        $('#mainTitle').html(myTitle);
        BL.talkToServer('renameUsertag',{'tag01':tagName,'tag02':newName},function(){
            ui.setSystemMessage('List renamed');
            });
        if(BL.hasGears){
          BL.db.execute('UPDATE tags set name = ? where name = ?',[newName,tagName]);
          lists = BL.db.query(tagName,'tags');
          for(item in lists){
            replaced = lists[item].tags.replace(eval('/'+tagName+'/gi'),newName);
            BL.db.execute('UPDATE fulltextTable set tags = ? where rowid = ?',[replaced,lists[item].rowid]);
          }
        }
      }
  }
}

/* GG WORKERPOOL */
BL.callLinkWorker = function(message){
  workerLinkPool = google.gears.factory.create('beta.workerpool','1.0');
  timer = google.gears.factory.create('beta.timer');
  workerLinkPool.onmessage = function(a, b, message) {
    if(message.text == BL._downloadPerWorker) {
      BL._downloadPerWorkerCycle++;
      BL.talkToServer('firstImport',{begin:(BL._downloadPerWorker * BL._downloadPerWorkerCycle)-1,amount:BL._downloadPerWorker},BL.firstImport);
    }
    else{
      BL.db.updateLastUpdate();
      if(BL.hasGearsAvtive){
        alertMessage = 'You have new updates!';
        $('#allLinks').trigger('click');
      }else{
        alertMessage = 'Done Importing Links';
      }
      ui.setSystemMessage(alertMessage);
      BL.hasGearsAvtive = true;
    }
  };

  childLinkWorkerId = workerLinkPool.createWorkerFromUrl('/js/worker_links.js');
  workerLinkPool.sendMessage(message,childLinkWorkerId);

}

BL.callTagWorker = function(message){
  workerTagPool = google.gears.factory.create('beta.workerpool');
  workerTagPool.onmessage = function(a, b, message) {};
  childTagWorkerId = workerTagPool.createWorkerFromUrl('/js/worker_tags.js');
  workerTagPool.sendMessage(message,childTagWorkerId);
}


BL.firstTimeImport = function(){
  BL.talkToServer('getUsertags',{withFoldersOnly:true},function(results){
    BL.firstImportTags(results);
    BL.talkToServer('firstImport',{begin:0,amount:BL._downloadPerWorker,firstCycle:true},BL.firstImport); 
  });
}

BL.startGearsVersion = function(){
  BL.status = 'offline';
  BL.hasGears = true;
  $(function(){
      BL.localLinks = BL.db.open('blinklist-'+BL.cookie);
      if(BL.localLinks == 0){
      // make the site work like online while we do they syc
      BL.statusCheck(function(){
        BL.talkToServer('getUsertagsThenInitUser',{withFoldersOnly:true},function(results){
          BL.showTagsFromResult(results);
          BL.firstTimeImport();
          //$('#system-sync').show();
          });
        });
      }else{
        Firefox.init();
        BL.hasGearsAvtive = true;
        BL.showTagsFromResult(BL.db.getTagList()); 
        BL.showListFromResult(BL.db.query('*'));
        $('#content').show();
        //ui.hideMessage();
        autoSuggest = BL.db.getAllTags();
        $('#shared .sharedTag').each(function(){ autoSuggest.push($(this).text()); });
        ui.appendToSuggestList(getUniqueValues(autoSuggest));
        BL.statusCheck(function(){
          BL.talkToServer('firstImport',{begin:0,amount:BL._downloadPerWorker,dateStart:BL.db.getLastUpdate(),firstCycle:true},BL.SyncNewUpdates);
        });
      }
      setInterval(BL.statusCheck,10000);
      if(BL.doSlurp) {
        BL.slurp();
      }

  });
}


BL.statusCheck = function(callback){
  jQuery.ajax({
    "type": "GET",
    'cache':false,
    "url": "/js/blank.txt",
    "success": function(){
      startSync = (BL.status == 'offline') ? true : false;
      BL.status = 'online';
      if(jQuery.isFunction(callback)){
        callback();
      }else{
        if(startSync){
          BL.db.syncCommands();
        }
      }
      if(startSync){
        $('#discovery').show();
        $('#shared').show();
        $('#sharedOptgroup').show();
        /* $('.addSharedTag').parent().show(); $('.friends-cp').parent().show(); $('.export-cp').parent().show(); $('.bookmarks-cp').parent().show();
           $('.delicious-cp').parent().show(); $('.language-cp').parent().show(); $('.profile-cp').parent().show(); */
        //ui.setSystemMessage('Google Gears online - synchronizing links');
      }
    },
    "error": function(){
      hide = (BL.status == 'online') ? true : false;
      if(hide){
        if($('#my-links .selected').length == 0){
          $('#allLinks').trigger('click');
        }
        $('#discovery').hide();
        $('#shared').hide(); 
        $('#sharedOptgroup').hide();
        BL.searchFocus = null;
        /* $('.addSharedTag').parent().hide(); $('.friends-cp').parent().hide(); $('.export-cp').parent().hide(); $('.bookmarks-cp').parent().hide();
           $('.delicious-cp').parent().hide(); $('.language-cp').parent().hide(); $('.profile-cp').parent().hide(); */
      }
      ui.setSystemMessage('Google Gears offline mode detected');
      BL.status = 'offline';
    }
  }); 
}

BL.normalStart = function(){
  BL.hasGears = false;
  BL.hasGearsAvtive = false;
}

/* WHAT IS BEEN CALLED BEFORE ANYTHING HAPPENS */
if (!window.google || !google.gears) {
  BL.normalStart();
}
else{
  if(google.gears.factory.hasPermission){
    if($.cookie('gears') != 'false'){
      BL.startGearsVersion();
    }else{
      BL.optionalGearsDisable = true;
      BL.normalStart();
    }
  }else{
    BL.hasGearsButNoPermition = true;
    BL.normalStart();
  }
}
