function Delete(id)
{
	return BmConfirm('Are you sure you want to delete this mark ?', 'DeleteMark('+id+')');
}

function DeleteMark(id)
{
	var myAjax = new Ajax.Request(
		BM_PATH + '/user/' + getCookie('user') + '/mark/' + id,
		{
			method: 'delete',
			requestHeaders: {'Accept': 'application/json'},
			onSuccess: function() { Effect.Fade('mark' + id) },
			onFailure: AjaxFailure
		}
	);
}

function AjaxFailure(xhr)
{
	alert('Error : ' + xhr.status + ' - ' + xhr.responseText);
}

function BmConfirm(message, action)
{
	if(BM_EFFECT && !Prototype.Browser.IE) {
		overlay = document.createElement('div'); // weirdness with IE6
		overlay.id = "overlay";
		overlay.innerHTML = "&nbsp;"; // must explain the reason
		lightbox = document.createElement('div'); // weirdness with IE6
		lightbox.id = "lightbox";
		lightbox.innerHTML  = ''
		+ '<p><strong>' + message + '</strong></p>'
		+ '<form onsubmit="return false" method="post">'
		+ '<input type="submit" value="ok" id="bmconfirm-ok" onclick="BmConfirmExit();' + action + '" />'
		+ '<input type="submit" value="cancel" onclick="BmConfirmExit()" />'
		+ '</form>'
		+ '';
		document.body.appendChild(overlay);
		document.body.appendChild(lightbox);
		$('bmconfirm-ok').focus();
		return false;
	} else {
		if(confirm(message)) { eval(action) }
		return false;	
	}
}

function BmConfirmExit()
{
	Element.remove('overlay');
	Element.remove('lightbox');
}



// Cookies

function getCookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function tags_jsontohtml(tags, path)
{
  if (tags.length == 0) return "no tag";
	tags = tags.sort(sort_tag_by_label);
	var maxPopularity = array_max_popularity(tags);
	var pas = (maxPopularity  - 1) / 5;
	var html = '';
	for(i=0;i<tags.length;i++) {
		if(tags[i].isprivate == 1) {
			var tmp_html = '<a class="tag private_tag" title="'+tags[i].popularity +' marks with this tag"'
				+' href="'+BM_PATH+'/my/private-tag/'+encodeURIComponent(encodeURIComponent(tags[i].label))+'">'+tags[i].label+'</a>';
		} else {
			var tmp_html = '<a class="tag public_tag" title="'+tags[i].popularity +' marks with this tag"'
				+' href="'+BM_PATH+'/'+path+'tag/'+encodeURIComponent(encodeURIComponent(tags[i].label))+'">'+tags[i].label+'</a>';
		}
		if (tags[i].popularity <= (maxPopularity - 4 * pas)) {
			tmp_html = '<small><small>' + tmp_html + '</small></small> ';
		} else if (tags[i].popularity <= (maxPopularity - 3 * pas)) {
			tmp_html = '<small>' + tmp_html + '</small> ';
		} else if (tags[i].popularity <= (maxPopularity - 2 * pas)) {
			tmp_html = '<span>' + tmp_html + '</span> ';
		} else if (tags[i].popularity <= (maxPopularity - 1 * pas)) {
			tmp_html = '<big>' + tmp_html + '</big> ';
		} else {
			tmp_html = '<big><big>' + tmp_html + '</big></big> ';
		}
		html += tmp_html + "\n &nbsp; \n";
	}
	return html;
}

function sort_tag_by_label(p1, p2)
{
	if (p1.label < p2.label) {
		return -1;
	} else {
		return 1;
	}
}

function array_max_popularity(array, popularity)
{
	var max = 0;
	for(i=0;i<array.length;i++) {
		popularity = parseInt(array[i].popularity);
		if(popularity > max) max = popularity;
	}
	return max;
}

function handleResize()
{
  var availableHeight = document.viewport.getHeight();
  ['top-bar', 'title-bar', 'footer'].each(function(elName) {
    el = $(elName);
    if (el && el.visible()) availableHeight -= el.getHeight();
  });
  
  var maxHeight = 0;
  ['left-bar', 'content', 'right-bar'].each(function(elName) {
    var el = $(elName);
    if (el && el.visible()) {
      el.style.height = 'auto';
      var height = el.getHeight();
      maxHeight = height > maxHeight ? height : maxHeight;
    } 
  });
  
  var resizeHeight = availableHeight > maxHeight ? availableHeight : maxHeight;
  if(resizeHeight != $('content').getHeight()) {
    $('content').style.height = resizeHeight + 'px';
  } 
  if ($('right-bar')) $('right-bar').style.height = resizeHeight + 'px';
  if ($('left-bar')) $('left-bar').style.height = (resizeHeight + 35) + 'px';
}

if (typeof BM == 'undefined') BM = {};

BM.initLiveFilter = function()
{
  $$('#liveFilter input').each(function(el) {
    switch(el.type) {
      case 'radio':
        Event.observe(el, 'click', BM.liveGetTagsSearch);
        break;
      case 'text':
        new Form.Element.DelayedObserver(el, 0.35, BM.liveGetTagsSearch);
        break;
    }
  });
}

BM.liveGetTagsSearch = function()
{
  if(BM_EFFECT) {
    Effect.Fade('taglist', { duration: 0.1 });
    $('tags').style.height = '250px';
    $('tags').style.background = 'url('+BM_PATH+'/img/snake_transparent.gif) center 220px no-repeat';
  }
  new Ajax.Request(BM_PATH + '/tags', {
    method: 'get',
    parameters: Form.serialize('liveFilter') + '&format=json',
    onComplete: BM.liveGetTagsShow
  });
}

BM.liveGetTagsShow = function(xhr) 
{
  var tags = xhr.responseText.evalJSON(), path = '';
  if (BM_EFFECT) {
    $('tags').setStyle({'height': 'auto', 'background': 'none'});
  }
  if ($("liveFilter").includePrivates && $("liveFilter").includePrivates.value == 1) {
    path = 'my/marks/';
  } else if($("liveFilter").user && $("liveFilter").user.value.length > 0 ) {
    path = 'user/' + $("liveFilter").user.value + '/marks/';
  }
  $("taglist").innerHTML = tags_jsontohtml(tags, path);
  if (BM_EFFECT) {
    Effect.Appear('taglist', { duration: 0.25 });
  }
  if ($("liveFilter").enableJsInTags && $("liveFilter").enableJsInTags.value == 1) {
    BM.enableJsInTags();
  } 
  if (t) {
    clearTimeout(t);
  }
  t = setTimeout(handleResize, 150);
}

BM.enableJsInTags = function()
{
  $$('#taglist a').each(function(el) {
    el.observe('click', function(e) {
      var input = this.hasClassName('private_tag') ? 'new-privatetags' : 'new-publictags';
      var token = $F(input).length > 0 ? ', ' : '';
      $(input).value += token + this.innerHTML;
      $(input).focus();
      e.stop();
    });
  });
}

BM.onResize = function()
{
  if(t) {
    clearTimeout(t);
  }
  if(!Prototype.Browser.IE) {
    t = setTimeout(handleResize, 150);
  }
}

BM.initTagAutocomplete = function()
{
  var configuration = {tokens: [',',';'], minChars: 1, fullSearch: true, choices: 5};
  
  var init = [
    {'includePrivates': 0, 'container': 'new-publictags', 'ac': 'publictags-ac'},
    {'includePrivates': 2, 'container': 'new-privatetags', 'ac': 'privatetags-ac'}
  ];
  
  init.each(function(conf) {
    new Ajax.Request(BM_PATH + '/tags', {
        method: 'get',
        parameters: {
          'user' : getCookie('user'),
          'last' : -1,
          'includePrivates': conf.includePrivates,
          'format': 'json'
        },
        onSuccess: function(xhr)
        {
            configuration.afterUpdateElement = function() { $(conf.container).value += ', ' };
            var tags = BM.prepareSimpleTagArray(xhr.responseText);
            new Autocompleter.Local(conf.container, conf.ac, tags, configuration)
        }
      }
    );
  });
}

BM.prepareSimpleTagArray = function(json)
{
    var tagArray = [];
    eval("var tags = " + json);
    for(var i = 0; i < tags.length; i++) {
        tagArray.push(tags[i].label)
    }
    return tagArray;
}

BM.handleMarkDelete = function()
{
  $$('.mark .action-bar .delete').each(function(el) {
    el.observe('click', function(e) {
      var id = Event.element(e).getAttribute('href').replace('/my/marks/', '').replace(',delete', '');
      Delete(id);
      e.stop();
    });
  });
}

BM.rename = function()
{
  if ($('new-tag-name')) {
    if ($F('new-tag-name') == '') {
      return confirm('Are you sure you want to delete this tag ?');
    } else {
      return confirm('Are you sure you want to rename this tag ?');
    }
  }
}

BM.formBeautify = function()
{
  if ($F('new-via') != '') {
    $('new-via').setStyle('width', '75%');
    if ( $('new-via-empty') == null ) {
      var empty = new Element('a', { 'id': 'new-via-empty', 'href': '#' });
      empty.setStyle('vertical-align', 'middle').update("empty");
      empty.onclick = function() { $('new-via').value = ''; return false; };
      Element.insert('new-via', {'after': empty});
      Element.insert('new-via', {'after': ' &nbsp; '});
    }
  }
}