var lastfetch = 0;
var fetchid = 0;
var highestfetch = 0;

// jquery ready
$(document).ready(function () {
  
  // initialize
  $('.onReadyShow').show();
  stripeTable();
  bindRemoveLinks();
  bindLabel();
  
  // bindings
  $('.connectionupdatebutton').bind("click", function(event) {; document.connectionform.submit();});
  $('.connectionaddbutton').bind("click", function(event) {
    document.connectionaddform.submit();
    $('.connectionaddbutton').attr('disabled', 'disabled');
    $('.connectionForm .loading').show();
  });
  $('#connectionform').bind("submit", function(event){ event.preventDefault(); return false; });
  $('#connectionaddform').bind("submit", function(event){ event.preventDefault(); return false; });
  bindKeyPress();
  bindPrettyName();
  
  // table drag n drop
  $("#connection_account_table").tableDnD({
      onDragClass: "dragClass", 
      onDrop: function(table, row) { 
        stripeTable();
        saveOrder();
      }
    });
    
  $("#connection_feed_table").tableDnD({
      onDragClass: "dragClass", 
      onDrop: function(table, row) { 
        stripeTable();
        saveOrder();
      }
    });
    
  $("#connection_foaf_table").tableDnD({
      onDragClass: "dragClass", 
      onDrop: function(table, row) { 
        stripeTable();
        saveOrder();
      }
    });
  saveOrder();

});

function bindLabel() {
  // bind the export_u dropdown
  $('.export_u').bind('change', function(e) {
    var v = $(this).attr('value');
    if (v == '1') {
      $(this).next().show();
    }
    else {
      $(this).next().hide();
    }
  });
  // bind the label itself
  $('.export_u_label').bind('focus', function(e) {
    if ($(this).attr('value') == 'label...') {
      $(this).attr('value', '');
      $(this).css('color', '#000000');
    }
  });
  $('.export_u_label').bind('blur', function(e) {
    if ($(this).attr('value') == '' || !$(this).attr('value')) {
      $(this).attr('value', 'label...');
      $(this).css('color', '#dddddd');
    }
  });
  $('.export_u_label').bind('keyup', function(e) {
    var val = $(this).attr('value');
    var val2 = check_label(val);
    if (val != val2)
      $(this).attr('value', val2);
  });
  
  $('.export_u_label').focus().blur();
}

function check_label(str) {
  if (str.match(/^[a-z\d\-_,]{1,250}$/i)) {
    return str;
  }
  var ret = '';
  for (var item in str) {
    if (str[item].match(/^[a-z\d\-_,]{1,250}$/i)) {
      ret += str[item];
      if (str[item] == ',')
        ret += ' ';
    }
  }
  return ret;
}

// stripe the table
function stripeTable() {
  $('.editForm tr:odd').removeClass('alt');
  $('.editForm tr:even').addClass('alt');
}

// save the table order
function saveOrder() {
  $('.connectionweight').each(function(intIndex) { $(this).attr('value', intIndex);});
}

// bind the remove links
function bindRemoveLinks() {
  // overwrite remove links with ajax
  $('.removeConnectionaccount').bind('click', function(event) { 
    event.preventDefault(); 
    var str = $(this).attr('alt'); 
    removeConnection(parseInt(str.substr(18,70)), 'account'); 
    stripeTable();
  });
  $('.removeConnectionfeed').bind('click', function(event) { 
    event.preventDefault(); 
    var str = $(this).attr('alt'); 
    removeConnection(parseInt(str.substr(18,70)), 'feed'); 
    stripeTable();
  });
  $('.removeConnectionfoaf').bind('click', function(event) { 
    event.preventDefault(); 
    var str = $(this).attr('alt'); 
    removeConnection(parseInt(str.substr(18,70)), 'foaf'); 
    stripeTable();
  });
}

// bind pretty name click
function bindPrettyName() {
  $('.prettyNameClass').unbind("click").bind("click", function(event) {
    var old = $(this).clone();
    var p = $(this).parent();
    $(this).replaceWith('<input type="text" maxlength="40" name="'+$(this).attr('id')+'" value="'+$(this).text()+'"/> <span style="cursor:default" title="Cancel Title Change">x</span>');
    $('span', p).bind("click", function(e) {
      $(this).prev().remove();
      $(this).replaceWith(old);
      bindPrettyName();
    }); 
  });
}

// remove a profile field with id
function removeConnection(id, table) {
  var ajaxurl = $('#ajax_url').text();
  $.getJSON(ajaxurl, 
    { ajaxcallid: 'removeconnection', 
      id: id,
      table: table,
      sid: $('#session_id').text() }, 
    function (json) {
      // assume everything went well
    }
  );
  
  // remove row
  $('#tr_'+table+'_'+id).remove();
  $("#connection_"+table+"_table").tableDnD({
    onDragClass: "dragClass", 
    onDrop: function(table, row) { 
      stripeTable();
      saveOrder();
    }
  });
  saveOrder();
}

function fetchdropdown(recheck) {
  if (!$("#connectiontext").is(":hidden")) {
	  var mindelay = 300; // wait at least 300 ms between fetches
	  var ajaxurl = $('#ajax_url').text();
	  var url = $('#connectiontext').attr('value');
	  var d = new Date();
	  var millis = d.valueOf() - lastfetch;
	  
	  if (recheck) {
      setTimeout("fetchdropdown(false);", mindelay);
    }
	  else if (millis >= mindelay) {
	    lastfetch = d.valueOf();
	    fetchid++;
	    $.getJSON(ajaxurl, 
		    { ajaxcallid: 'fetchdropdown', 
		      url: url,
		      fetchid: fetchid, 
		      sid: $('#session_id').text() }, 
		    function (json) {
		      // handle result
		      if (json !== undefined) {
		        var fid = parseInt(json['fetchid']);
		        if (fid > highestfetch) { 
		          highestfetch = fid;
			        $('#idconnectiondropdown').text('');
			        var i = 0;
			        var base = $('#base_url').text();
			        var json_res = json['result']
			        for (var item in json_res) {
			          i++;
			          var value = json_res[item];
			          // write dropdown
			          if (value['icon'] == '') {
			            var img = '<img src="'+base+'img/blank.gif" width="16" height="16" alt=""/>';
			          }
			          else {
			            var img = '<img src="'+base+value['icon']+'" width="16" height="16" alt=""/>';
			          };
			          $('#idconnectiondropdown').append('<a href="javascript:void(0);" onclick="clickservice($(this));">'+img+' '+value['name']+'<span class="acc_type_id" style="display:none">'+value['id']+'</span><span class="profile_page" style="display:none">'+value['profile_page']+'</span><span class="profile_url" style="display:none">'+value['url']+'</span><span class="profile_icon" style="display:none">'+value['icon']+'</span><span class="profile_user_type" style="display:none">'+value['user_type']+'</span><span class="profile_help" style="display:none">'+value['help']+'</span></a>');
			        }
			        $('#idconnectiondropdown').append('<a href="javascript:void(0);" onclick="clickservice($(this));"><img src="'+base+'img/blank.gif" width="16" height="16" alt=""/> - none - <span class="acc_type_id" style="display:none">0</span><span class="profile_page" style="display:none"></span><span class="profile_url" style="display:none"></span><span class="profile_icon" style="display:none"></span></a>');
			        if ($("#idconnectiondropdown").is(":hidden")) {
			          $("#idconnectiondropdown").show();
		            $("#idconnectiondropdown").slideDown("fast");
		          }
		          else if (i == 0) {
		            // $("#idconnectiondropdown").slideUp("fast");
		          }
		        }
		      }
		    }
		  );
	  }
	}
}

// service link was clicked
function clickservice(t) {
  // clean up connectionform
  $('.connectionForm .connectionFormHelp').remove();

  $('#account_type').attr('value', $('.acc_type_id', t).html());
  var icon = $('.profile_icon', t).html();
  var base = $('#base_url').text();
  var profile_url = $('.profile_url', t).html();
  var profile_page = $('.profile_page', t).html();
  var user_type = $('.profile_user_type', t).html();
  user_type = (user_type == '')?'username':user_type;
  var help = $('.profile_help', t).html();
  
  // clear the dropdown again
  $("#idconnectiondropdown").hide().text('');
  if (icon != '') {
    var img = base+icon;
  }
  else {
    var img = base+'img/blank.gif';
  }
  
  var s = profile_page.split('***');
  if (profile_page == '' || s == profile_page) {
    // there is no profile url
	  $('#connectiontext').css('background-image', 'url('+img+')');
	  if (profile_url != '')
	    $('#connectiontext').attr('value', profile_url);
  }
  else {
    // we have a profile page add text input text for the profile url
    var str = '<img src="'+img+'" style="width:16px; height:16px;" alt=""/> <span class="showurltext">'+s[0]+'</span>';
    str += '<input type="text" name="profile_username" id="profile_username" value="'+user_type+'"/>';
    if (s.length <= 1)
      s[1] = '';
    str += '<span class="showurltext">'+s[1]+'</span>';
    $('#connectiontext').hide(); 
    $('#profile_page_alt').html(str); 
    $('#connectiontext').attr('value', '');
    $('#profile_page_alt').show();
    $('#profile_username').focus().select();
    // set the account type
    document.getElementById('conn_type').selectedIndex = 0;
    $('#connectiontext').next().attr('disabled', 'disabled');
    
    // add binding for viewing normal url field again
    $('.showurltext').bind("click", function(event) {
	    $(this).unbind("click");
	    $('#profile_page_alt').hide();
	    var name = ($('#profile_username').attr('value') == null)?'':$('#profile_username').attr('value');
	    $('#profile_username').attr('value', '');
	    $('#connectiontext').attr('value', s[0]+name+s[1]);
	    $('#connectiontext').css('background-image', 'url('+img+')');
	    $('#connectiontext').show();
	    $('#connectiontext').next().attr('disabled', '');
	  });
  }
  
  // add help, if it exists
  if (help != '' && help != null) {
    $('.connectionForm tbody').append('<tr class="connectionFormHelp"><td>&nbsp;</td><td><span class="smallurl">'+help+'</span></td></tr>');
  }
}

function bindKeyPress() {
  $("#connectiontext").keyup(function(e){
    if (e.keyCode == 38) {
      // up pressed
      if ($('#idconnectiondropdown .connectiondropdownSelected').length == 0) {
        $('#idconnectiondropdown a :last').parent().addClass('connectiondropdownSelected');
      }
      else {
        $('#idconnectiondropdown .connectiondropdownSelected').removeClass('connectiondropdownSelected').prev().addClass('connectiondropdownSelected');
      }
    }
    else if (e.keyCode == 40) {
      // down pressed
      if ($('#idconnectiondropdown .connectiondropdownSelected').length == 0) {
        $('#idconnectiondropdown :first').addClass('connectiondropdownSelected');
      }
      else {
        $('#idconnectiondropdown .connectiondropdownSelected').removeClass('connectiondropdownSelected').next().addClass('connectiondropdownSelected');
      }
    }
    else if (e.keyCode == 13) {
      // enter pressed
      if ($('#idconnectiondropdown .connectiondropdownSelected').length == 0)
        fetchdropdown(true);
      else {
        clickservice($('#idconnectiondropdown .connectiondropdownSelected'));
      }
    }
    else {
      fetchdropdown(true);
    }
  });
}
