function Delete(id)
{
	return BmConfirm('Are you sure you want to delete this mark ?', 'DeleteMark('+id+')');
}

function DeleteMark(id)
{
	
	if(Browser.isOpera || Browser.isIE) { // method delete and auth http, not working in opera 8.5/9.*
		var headers = ['x-method', 'DELETE'];
	} else {
		//var headers = ['authorization', 'Basic ' + getCookie('hash')];
	}
	var myAjax = new Ajax.Request(
		BM_API_BASE_URL + '/user/' + getCookie('user') + '/mark/' + id,
		{
			method: 'delete',
			requestHeaders: headers,
			onSuccess: function(xhr) { Effect.Fade('mark' + id) },
			onFailure: AjaxFailure
		}
	);
}

function AjaxFailure(xhr)
{
	alert('Error : ' + xhr.status + ' - ' + xhr.responseText);
}

function BmConfirm(message, action)
{
	if(BM_EFFECT && !Browser.isIE) {
		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');
}

function Rename()
{
	if ( rename = document.getElementById('new-tag-name') ) {
		if ( rename.value == '' )
			var agree = confirm ( 'Are you sure you want to delete this tag ?' );	
		else
			var agree = confirm ( 'Are you sure you want to rename this tag ?' );
	}
	return agree;
}


// Enable Js In Tags

function enableJsInTags()
{
	links = $('taglist').getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
	  if ( links[i].className == 'tag public_tag' ) {
		  links[i].onclick = function()
      {
        if($F('new-publictags').length != 0) var token = ', '; else var token = '';
			  $('new-publictags').value += token + this.innerHTML;
				$('new-publictags').focus();
        this.style.background = '#ff9';
				return false;
		  }
	  } else if ( links[i].className == 'tag private_tag' ) {
		  links[i].onclick = function()
      {
        if($F('new-privatetags').length != 0) var token = ', '; else var token = '';
			  $('new-privatetags').value += token + this.innerHTML;
				$('new-privatetags').focus();
        this.style.background = '#ff9';
				return false;
		  }
	  }
	}
}


// 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 ) );
}


// Tags Live Filter

/*
function liveGetTagsStart()
{
	if (t) { window.clearTimeout(t); }
	t = window.setTimeout("liveGetTagsSearch()", 500);
}
*/

liveGetTagsSearch = function()
//function liveGetTagsSearch()
{
	if(BM_EFFECT) {
		Effect.Fade('taglist', { duration: 0.1 });
		$('tags').style.height = '250px';
		$('tags').style.background = 'url('+BM_BASE_DIR+'img/snake_transparent.gif) center 220px no-repeat';
	}

	var myAjax = new Ajax.Request(
		BM_API_BASE_URL + '/tags',
		{
			method: 'get',
			//parameters: Form.serialize($("liveFilter")) + '&out=json',
      parameters: Form.serialize('liveFilter') + '&format=json', // '&format=json',
			//requestHeaders: ['Authorization', 'Basic ' + getCookie('hash')],
			onComplete: liveGetTagsShow
			//,onFailure: AjaxFailure
		}
	);
}

function liveGetTagsShow(xhr) 
{
  //alert(xhr.responseText);
	if(BM_EFFECT) {
		$('tags').style.height = 'auto';
		$('tags').style.background = 'none';
	}
	eval("var tags = " + xhr.responseText);
	if($("liveFilter").includePrivates && $("liveFilter").includePrivates.value == 1) {
    path = 'my/';
  } else if($("liveFilter").user && $("liveFilter").user.value.length > 0 ) {
    path = 'user/' + $("liveFilter").user.value + '/';
  } else {
    path = '';
  }
	$("taglist").innerHTML = tags_jsontohtml(tags, path);
	if(BM_EFFECT) Effect.Appear('taglist', { duration: 0.25 });
	if($("liveFilter").enableJsInTags && $("liveFilter").enableJsInTags.value==1) enableJsInTags();
  if (t) { window.clearTimeout(t); } t = window.setTimeout(handleResize, 150);
}

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_BASE_DIR+'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_BASE_DIR+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 prepareSimpleTagArray(json)
{
    var TagArray = [];
    eval("var tags = " + json);
    for(i=0;i<tags.length;i++) {
        /*
        label = tags[i].label;
        if( label.search(" ") != -1 ) {
            TagArray.push('"' + label + '" ')
        } else {
            TagArray.push(label + ' ')
        }
        */
        TagArray.push(tags[i].label + '')
    }
    return TagArray;
}

// Auto Refresh
// @todo : rewrite ajax part with prototype.js

function refreshContent()
{
	xhr.open("GET", BM_API_BASE_URL + '/search?last=10&offset=0&out=json', true);
	xhr.onreadystatechange = function() {
		if (xhr.readyState==4 && xhr.status!=404) {
			eval("var marks = " + xhr.responseText);
			marks = marks.sort(sort_marks_by_id_asc);
			html = '<div style="display:none" id="new-marks'+ marks[0].id+'">';
			count = 0;
			for(i=0;i<marks.length;i++) {
				id = marks[i].id;
				if(!$('mark'+id)) {
					html += mark_jsontohtml(marks[i]);
					count ++;
				}
			}
			html += '</div>';
			if(count > 0) {
				$('contentb').innerHTML = html + $('contentb').innerHTML;
				Effect.Appear('new-marks'+ marks[0].id);
				//window.focus();
			}
		}
	}
	//xhr.setRequestHeader('Authorization', 'Basic ' + getCookie('hash'));
	xhr.send(null);
	return false;
}

function sort_marks_by_id_asc(p1, p2)
{
	if (parseInt(p1.id) < parseInt(p2.id)) {
    return -1;
  } else {
    return 1;
  }
}

function mark_jsontohtml(mark)
{

	html  = '<div class="mark" id="mark'+mark.id+'">';
	html +=	'<a href="'+mark.href+'"><img class="screenshot gold" src="'+mark.image+'" alt="" /></a>';
	html += '<div class="markB">';
	html += '<h4><a href="'+mark.href+'">'+mark.title+'</a></h4>';
	html += '<a href="'+BM_BASE_DIR+'user/'+mark.author.id+'"><img style="vertical-align:-40%" alt="" width="20" height="20" src="'+mark.author.image+'" /></a>';
	html += ' by <a class="user" href="'+BM_BASE_DIR+'user/'+mark.author.id+'">'+mark.author.name+'</a>';
	html += '<div class="description">'+mark.content+'</div>';
	if(mark.author.id == getCookie('user')) {
		html += '<a class="my" href="'+BM_BASE_DIR+'my/new-edit.php?id='+mark.id+'">Edit</a> &nbsp; ';
		html += '<a class="my" href="'+BM_BASE_DIR+'my/delete.php?id='+mark.id+'" onclick="return Delete(\''+mark.id+'\');">Delete</a>';
	} else {
		html += '<a class="public" href="'+BM_BASE_DIR+'my/new-new.php?id='+mark.id+'">Copy</a> &nbsp; ';
	}
	html += '</div>';
	html += '</div>';

	return html;
}

function sortDivs()
{
	var currDivs = [];
	allElements = document.getElementsByClassName('mark');
	for(var i = 0; i < allElements.length; i++) {
		currDivs.push(allElements[i].id.replace('mark', ''));
	}
	currDivs.sort(sort_marks_by_id_desc);
	var index = 0;
	for(var i = 0; i < currDivs.length; i++) {
		oldNode = $('mark'+currDivs[i]).parentNode;
		oldNodeHtml = oldNode.innerHTML;
		$('mark'+currDivs[i]).id = 'old' + $('mark'+currDivs[i]).id;
		newNode = document.createElement('div');
		newNode.innerHTML = oldNodeHtml;
		$('contentb').appendChild(newNode);
		$('contentb').removeChild($('oldmark' + currDivs[i]).parentNode);
	}
}

function sort_marks_by_id_desc(p1, p2)
{
	if (parseInt(p1) > parseInt(p2)) { return -1; }
	else {return 1; }
}


// Ajaxian Take Screenshot

function takeScreenshot(id) 
{
		var screenshot = document.getElementsByClassName("screenshot", $('mark'+id))[0];
		var oldscreenshotsrc = screenshot.src;
		screenshot.src = BM_BASE_DIR + 'screenshots/loading.gif';
		new Ajax.Request(
		  BM_BASE_DIR + 'my/marks/' + id + ',takeScreenshot',
      {
        method: 'get',
        //requestHeaders: ['Authorization', 'Basic ' + getCookie('hash')],
        onSuccess: function(xhr)
        {
          screenshot.src = xhr.responseText + '?nocache=' + Math.floor(Math.random() * 9999);
        },
        onFailure: function(xhr)
        {
          alert('Error : ' + xhr.status + ' - ' + xhr.responseText);
          screenshot.src = oldscreenshotsrc;
        }
      }
		);
    return false;
}


// Browser Detection

var Browser = new Object();
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);
Browser.isIE = (navigator.userAgent.toLowerCase().indexOf("msie")!=-1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari")!=-1);


handleResize = function()
{

	// Width
  
  /*
	totalWidth = getTotalWidth();
	availableWidth = totalWidth - 125;

	$('left-bar').style.width = '125px';
	$('title-bar').style.width = availableWidth + 'px';

	contentWidth = Math.round(availableWidth * 65 / 100);
	$('content').style.width = contentWidth + 'px';

	rightBarwidth = availableWidth - contentWidth;
	$('right-bar').style.width = rightBarwidth + 'px';
  */

  // Height

  $('left-bar').style.height = 'auto';
  $('content').style.height = 'auto';
  if($('right-bar')) $('right-bar').style.height = 'auto';

	var occupedHeight = Element.getHeight('top-bar') + Element.getHeight('title-bar') + Element.getHeight('footer');
	var newContentHeight = getTotalHeight() - occupedHeight;
	
	if(newContentHeight < Element.getHeight('content')) {
		newContentHeight = Element.getHeight('content');
	}

	$('content').style.height = newContentHeight + 'px';

  if($('left-bar') && Element.getHeight('left-bar') < newContentHeight) {
    $('left-bar').style.height = (newContentHeight + 35 ) + 'px';
  }
  
  if($('right-bar') && Element.getHeight('right-bar') < newContentHeight) {
    $('right-bar').style.height = (newContentHeight ) + 'px';
  } else if($('right-bar')) {
    $('content').style.height = Element.getHeight('right-bar') + 'px';
  }

  if($('left-bar') && Element.getHeight('left-bar') > Element.getHeight('content')) {
    $('content').style.height = ( Element.getHeight('left-bar') - 35 ) + 'px';
    $('right-bar').style.height = ( Element.getHeight('left-bar') - 35 ) + 'px';
  }
  
  if(Element.getHeight('left-bar') < Element.getHeight('right-bar')) {
    $('left-bar').style.height = ( Element.getHeight('right-bar') + 33 ) + 'px';
  } else if(Element.getHeight('left-bar') < Element.getHeight('content')) {
    $('left-bar').style.height = ( Element.getHeight('content') + 33 ) + 'px';
  }

  /*
	if(newContentHeight + occupedHeight > totalHeight ) {
		$('title-bar').style.width = parseInt(availableWidth - 16) + 'px';
		$('content').style.width = parseInt(contentWidth - 16) + 'px';
	}
  */

}

function getTotalWidth()
{
	if (self.innerWidth) {
		return parseInt(self.innerWidth);
	} else if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	} else if (document.body) {
		return document.body.clientWidth;

	}
}

function getTotalHeight()
{
	if (self.innerHeight) {
		return parseInt(self.innerHeight);
	} else if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	} else if (document.body) {
		return document.body.clientHeight;
	}
}

//Event.onDOMReady(handleResize);
addDOMLoadEvent(handleResize);

window.onresize = function()
{
  if(t) {
    window.clearTimeout(t);
  }
  if(!Browser.isIE) {
    t = window.setTimeout(handleResize, 150);
  }
}