/* common function */
function toggleBlock(id, link, animate, t_class, animate_param){
	if(!animate_param){
		animate_param = 'height';
	}
	//alert(animate_param);
	var res = 1;
	if(t_class){
		$(link).parent().toggleClass(t_class);
	}
	if($('#'+id).css('display') == 'none'){
		if(animate){
			if(animate_param == 'height')
				$('#'+id).animate({'height': 'show'}, 'fast');
			else
				$('#'+id).animate({'width': 'show'}, 'fast');
		}else
			$('#'+id).show();
	}else{
		if(animate){
			if(animate_param == 'height')
				$('#'+id).animate({'height': 'hide'}, 'fast');
			else
				$('#'+id).animate({'width': 'hide'}, 'fast');
		}else
			$('#'+id).hide();
	}
	if(link)
		link.blur();
	return false;
}

/* popups */
function showPopup(id, link){
	hideAllPopups();
	if(link)
		link.blur();
	showSandBox();
	var t = ($(window).width()-$('#' + id).width())/2;
	$('#' + id).show();//animate({height: 'show'}, 200);
	$('#' + id).css({'left': t});
	$('#' + id).css({'top': $(document).scrollTop() + 50});
	//$(document).scrollTop(0);
}

function hidePopup(id){
	hideSandBox();
	var t = document.getElementById(id);
	if(t){
		t.style.display = 'none';
	}
}

function hideAllPopups(){
	hideSandBox();
	$('div.login_popup').hide();
}

function showSandBox(){
	var s = document.getElementById('sandbox');
	if(!s){
		s = document.createElement('div');
		s.setAttribute('id', 'sandbox');
		$(s).click(function(){hideAllPopups();});
		document.body.appendChild(s);
	}
	s.style.height = $(document).height() + 'px';
	$(s).show();
}

function hideSandBox(){
	var s = document.getElementById('sandbox');
	if(s){
		s.style.display = 'none';
	}
}
			
/* init images actions */
$(document).ready(
	function(){
		/* thumb events */
		var t = $('#thumbs > a');
		if(t.length){
			$(t[0]).children().addClass('active');
			$(t).click(
				function(){
					changeCatalogPhoto(this.href, this.rel, $(this).children());
					return false;
				}
			);
		}
		/* opeing lightbox by clicking on middle size picture */
		$('#big_photo > a').click(
			function(){
				tb_show('', this.href, '');
				return false;
			}
		);
	}
);

function showFirstPhoto(){
	var t = $('#thumbs > a');
	if(t.length)
		$(t[0]).click();
}

function changeCatalogPhoto(src, src2, thumb){
	$('#big_photo > a > img').attr('src', src);
	$('#big_photo > a').attr('href', src2);
	$('#thumbs > a > img.active').removeClass('active');
	if(thumb){
		$(thumb).addClass('active');
	}
}

/* login */
function doLogin(link, form_name){
	var sch = false;
	if(!form_name){
		form_name = 'login_form';
		sch = true;
	}
	link.blur();
	var email = document.forms[form_name].elements['login'];
	var password = document.forms[form_name].elements['password'];
	var remember = document.forms[form_name].elements['remember'];
	var ok = sch ? simpleFormCheck(form_name) : true;
	if(ok){
		var s_data = {'login': email.value, 'password': password.value, '_save': 1}
		if(remember.checked){
			s_data.remember=1;
		}
		$.post('/login/', s_data, onLoginDone);
	}
}

function onLoginDone(text){	
	if(text != ''){
		document.getElementById('login_errors').style.display = 'block';
		document.getElementById('login_errors').innerHTML = text;
	}else{
		window.location.reload();
	}
}

function clearLoginForm(){
	var form_name = 'login_form';
	document.getElementById('login_errors').style.display = 'none';
	document.getElementById('login_errors').innerHTML = '';
	for(var i=0; i<document.forms[form_name].elements.length; i++){
		if(document.forms[form_name].elements[i].className != 'but' && document.forms[form_name].elements[i].className != 'chb'){
			document.forms[form_name].elements[i].value = '';
			$(document.forms[form_name].elements[i]).removeClass('error');
		}
	}
}

/* registration */
function doRegister(link, auto, no_reload){
	if(link)
		link.blur();
	var ok = false;
	if(auto){
		ok = true;		
	}else{
		var email = document.forms['registration_form'].elements['login'];
		var password = document.forms['registration_form'].elements['password'];
		var password_r = document.forms['registration_form'].elements['password_repeat'];
		var cpt = document.forms['registration_form'].elements['captcha_word'];
		var ok = simpleFormCheck('registration_form');
	}
	if(ok){
		var p = new Object();
		if(auto)
			p = {'auto': 1}
		else
			p = {'_save': 1, 'login': email.value, 'password': password.value, 'password_repeat': password_r.value, 'captcha_word': cpt.value}

		$.post('/registration/', p, function(rsp){onRegisterDone(rsp, no_reload)});
	}
}

function onRegisterDone(text, no_reload){
	//alert($('errors', text).text());
	if($('errors', text).text() != ''){
		document.getElementById('registration_errors').style.display = 'block';
		document.getElementById('registration_errors').innerHTML = $('errors', text).text();
	}else{
		if(!no_reload){
			window.location.reload();
		}else{
			$('#login_linkslogin_links').html($('userlinks', text).text());
			addToCart(add_item_id, null, add_item_var, add_item_num);
		}
	}
}

/* common form functions */
function onFieldFocus(el){
	$(el).removeClass('error');
}

function simpleFormCheck(form_name){
	var isok = true;
	for(var i=0; i<document.forms[form_name].elements.length; i++){
		if(document.forms[form_name].elements[i].value == ''){
			document.forms[form_name].elements[i].className = document.forms[form_name].elements[i].className == '' ? 'error' : document.forms[form_name].elements[i].className + ' error';
			isok = false;
		}
	}
	return isok;
}

/* WISHLIST */
var item_variant = 0;
var toadd_item = 0;
var cur_wl_link = null;

function addToWishlist(id, link){
	
	if(false && !user_authorized){
		showPopup('login_form');
		return false;
	}
	
	/* set default values */
	$('input:checkbox', document.forms['tocart_form']).attr('checked', false);
	document.forms['tocart_form'].elements['num'].value = 1;
	document.forms['tocart_form'].elements['name'].value = '';
	$('#new_wl_name_cnt').hide();
	$('select', document.forms['tocart_form']).attr('disabled', false);
	
	cur_wl_link = link;
	link.blur();
	toadd_item = id;
	var offs = $(link).offset();	
	var h = $('#tocart_popup').height();
	var left = offs.left - 17;
	var top = offs.top;
	//alert($(window).height());
	if(top+h-$(document).scrollTop() > $(window).height())
		top = top - h;
	$('#tocart_popup').css({'left': left, 'top': top});
	$('#tocart_popup').show();
}

function doAddToWishlist(){
	var params = {'id': toadd_item, 'item_variant': item_variant, 'action': 'add_item'};
	if($('input:checkbox', document.forms['tocart_form']).attr('checked')){
		var nwl = $('#new_wl_name').attr('value');
		if(nwl == ''){
			alert('Необходимо ввести название нового списка покупок');
			return false;
		}else{			
			params.new_wishlist = nwl;
		}
	}else{
		if(false && $('select[@name="wishlist_id"]').attr('value') == ''){
			alert('Необходимо выбрать список покупок');
			return false;
		}else{
			params.wishlist_id = document.forms['tocart_form'].elements['wishlist_id'].value;
		}
	}
	var num = document.forms['tocart_form'].elements['num'].value;
	if(num == '' || !parseInt(num) || parseInt(num) < 1){
		alert('Укажите правильное кол-во товара');
		return false;
	}else{
		params.num = num;
	}
	$.get('/wishlist/', params, function(response){onAfterAddedToWishlist(response);});
	return false;
}

function onAfterAddedToWishlist(response){
	if(!user_authorized){
		location.reload();
	}
	link = cur_wl_link;
	closeWLPopup();
	if(response){		
		$(link).attr('href','/wishlist/');
		link.removeAttribute('onclick');
		$(link).html('добавлено');
		$(link).parent().addClass('added');
		setWishlistInfo(response);
	}else{
		showPopup('login_form');
	}	
}

function closeWLPopup(){
	$('#tocart_popup').hide();
}

function setWishlistInfo(xml, in_list){	
	
	var new_cnt = '';
	var lnk = '';
	var items = $('items > item', xml);
	
	if(!$('#wishlist_short').length){
		if(in_list && !items.length){
			$('#wishlist_order_form').remove();
			$('#wishlist_items_list').html('<div class="space sm"></div><div class="cnt_pad">Список пуст</div>');
		}
		return false;
	}
	
	var sum = $('totalSum', xml).text();
	
	var sel = new Array();
	sel[0] = document.forms['cur_list'].elements['wishlist'];
	sel[1] = document.forms['tocart_form'].elements['wishlist_id'];
	
	var new_wishlist = $('newWishlist', xml);
	if(new_wishlist.length){
		var new_name = $('newWishlist > name', xml);
		var new_id = $('newWishlist > id', xml);
		for(var i=0; i<sel.length; i++){
			sel[i].options[sel[i].options.length] = new Option(new_name.text(), new_id.text());
		}
	}
	
	var default_list = $('defaultList', xml).text();
	for(var i=0; i<sel.length; i++){
		for(var j=0; j<sel[i].options.length; j++){
			if(sel[i].options[j].value == default_list)
				$(sel[i].options[j]).attr('selected', true);
		}
	}
	
	if(items.length){
		$('#wishlist_price_info').show();
		for(var i=0; i<items.length; i++){
			lnk = '<a href="/catalog/?id=' + $('id', items[i]).text() + '">';
			//new_cnt += '<div class="item_photo">' + lnk + '<img src="' + $('photo', items[i]).text() + '"/></a></div>';
			new_cnt += '<div class="item">';
			new_cnt += '<div class="item_name">' + lnk + $('name', items[i]).text() + '</a></div>';
			new_cnt += '<div class="items_num">' + $('num', items[i]).text() + 'шт</div>';
			new_cnt += '<div class="clearer"></div>';
			new_cnt += '</div>';
		}
		$('#cur_wishlist_sum').text($('totalSum', xml).text() + ' ' + $('currency', xml).text());
		$('#wishlist_info').show();
	}else{
		$('#wishlist_info').hide();
		new_cnt = '<div class="item">Нет покупок</div>';
	}
	
	new_cnt += '<div class="ug"></div>';
	$('#wishlist_short').html(new_cnt);
	
	if(in_list){
		if(!items.length){
			$('#wishlist_order_form').remove();
			$('#wishlist_items_list').html('Список пуст');
			//$('#wishlist_total_sum').remove();
		}else{
			$('#totalSum').html($('totalSum', xml).text());
		}
	}
}

function deleteWishlistItem(wishlist, item, variant, link){
	if(confirm('Вы уверены?')){
		$('#wl_item'+item).addClass('loading');
		$.get('/wishlist/', {'action': 'delete_item', 'item': item, 'item_variant': variant, 'wishlist': wishlist}, function(response){onAfterItemDeleted(response, item, variant);});
	}
	link.blur();
}

function onAfterItemDeleted(response, id, variant){	
	$('#wl_item'+id+'_'+variant).remove();
	setWishlistInfo(response, true);
}

function onWLCreateSubmit(form){
	if(form.elements['name'].value.replace(' ','') == ''){
		alert('Введите название списка');
		return false;
	}
	return true;
}

var curMoveItem = 0;
var curMoveVariant = 0;

function showMoveItemPopup(id, variant, link, ev){
	if(link)
		link.blur();
	var e = (window.event) ? window.event : ev;
	if($('div#moveitem_popup').css('display') == 'none' || curMoveItem != id){
		$('div#moveitem_popup').css('display', 'block');
		var l = e.clientX;
		var t = e.clientY + $(document).scrollTop();
		$('div#moveitem_popup').css('left', l);
		$('div#moveitem_popup').css('top', t);
	}else{
		if(curMoveItem == id)
			$('div#moveitem_popup').css('display', 'none');
	}
	curMoveItem = id;	
	curMoveVariant = variant;	
}

function closeMoveItemPopup(){
	curMoveItem = 0;
	curMoveVariant = 0;
	$('div#moveitem_popup').css('display', 'none');
	$('div#wishlist_items_list > div').removeClass('hover');
}

function moveItemToList(from_list, to_list){
	if(curMoveItem){
		$('#wl_item'+curMoveItem).addClass('loading');			
		var item = curMoveItem;
		var variant = curMoveVariant;
		closeMoveItemPopup();
		$.get('/wishlist/', {'action': 'move_item', 'id': item, 'item_variant': variant, 'from': from_list, 'to': to_list}, function(response){onAfterItemMoved(response, item, variant);});		
	}
}

function onAfterItemMoved(response, item, variant){
	$('#wl_item'+item+'_'+variant).remove();
	setWishlistInfo(response, true);
}

function changeDefaultList(sel){
	$.get('/wishlist/', {'action': 'set_default_list', 'id': sel.value}, onAfterListChanged);
}

function onAfterListChanged(response){
	window.location.reload();
}

function showConfigElements(el, link){
	
	$('#'+el).toggle('fast',
		function(){
			var t = $(link).parent();
			var p = t[0];
			if(document.getElementById(el).style.display == 'none'){
				$(p).removeClass('opened');
				$(p).addClass('closed');
			}else{
				$(p).removeClass('closed');
				$(p).addClass('opened');
			}
		}
	);
	link.blur();	
	
}

/* menu functions */
function menuItemHover(el){
	
	if(this.className != 'active')
		$(this).addClass('hover');
	
}

function menuItemOut(el){

	$(this).removeClass('hover');
	
}

/* init hor menu */
/*
$(document).ready(
	function(){
		stretchMenu('hor_menu');
		// hover effects
		var t = $('table.hor_menu > tbody > tr > td');
		$(t).mouseover(menuItemHover);
		$(t).mouseout(menuItemOut);
	}
);
*/

var menu_types = new Array('catalog_sections', 'brand_list');//, 'lib_links');
function showMenu(bid, lnk){
	bid = '#' + bid;
	if($(bid).css('display') != 'block'){
		/* hide opened */
		for(var i = 0; i < menu_types.length; i++)
			if(bid != '#' + menu_types[i] && $('#' + menu_types[i]).css('display') == 'block'){
				var tt = $('div.menu_section_name.opened');
				var cur_opened = false;
				if(tt.length && tt[0].className != 'menu_section_name opened stat')
					cur_opened = tt[0];
				$('#' + menu_types[i]).animate({height: "hide"}, 300, 
					function(){
						if(cur_opened)
							$(cur_opened).removeClass('opened');
					}
				);
				//$('#' + menu_types[i]).hide();
			}
		$(bid).animate({height: "show"}, 300);
		if(lnk)
			$(lnk).addClass('opened');
	}else{
		$(bid).animate({height: "hide"}, 300, function(){if(lnk) $(lnk).removeClass('opened')});
	}
}

/* top banner functions */
var curBan = 1;

function changeBan(dir){
	var cur = document.getElementById('top_ban'+curBan);
	if(cur){
		if(dir == 0)
			curBan--;
		else
			curBan++;
		var toshow = document.getElementById('top_ban'+curBan);
		if(toshow){
			cur.style.display = 'none';
			toshow.style.display = 'block';
		}else{
			if(dir == 0)
				curBan++;
			else
				curBan--;
		}
	}
	checkControls();
}

function checkControls(){
	var t = curBan+1;
	var next = document.getElementById('ban_control_next');
	var prev = document.getElementById('ban_control_prev');
	if(document.getElementById('top_ban'+t))
		next.style.visibility = 'visible';
	else
		next.style.visibility = 'hidden';
	t = curBan-1;
	if(document.getElementById('top_ban'+t))
		prev.style.visibility = 'visible';
	else
		prev.style.visibility = 'hidden';		
}

/* init top news behavior */
$(document).ready(
	function(){
		$('div#top_news > a.news_entry').mouseover(topNewsOver);
	}
);

function topNewsOver(){
	$('div#top_news > a.news_entry.n_opened').removeClass('n_opened');
	$(this).addClass('n_opened');
}

/* news line functions */
function showNextNews(dir){
	
	var cur = $('#cur_news');
	$(cur).removeAttr('id');
	$(cur).hide();
	var new_el = dir == 1 ? $(cur).next() : $(cur).prev();
	if(!new_el.length){
		/* get first or last */
		var t = $('#news_line_items > div');
		new_el = dir == 1 ? t[0] : t[t.length-1];
	}
	$(new_el).fadeIn('fast');
	$(new_el).attr('id', 'cur_news');
	
}

/* product details */
/*
$(document).ready(
	function(){
		$('table#product_menu > tbody > tr > td > div > a').click(
			function(){
				showProductInfo(this.href, this);
				return false;
			}
		);
	}
);
*/

function showProductInfo(url, it){
	$(it).parent().parent().siblings('.active').removeClass('active');
	$(it).parent().parent().addClass('active');
	$(it).blur();
	ajaxLoadContent(url, 'product_detail_info');
}

function ajaxLoadContent(url, content_id){
	$('#' + content_id).html('<div class="ajax_loader"><img src="/img/ajax-loader.gif"/></div>');
	$.get(url, null, 
		function(response){
			onAjaxContentLoaded(response, content_id);
		}
	);
}

function onAjaxContentLoaded(text, content_id){
	$('#' + content_id).html(text);
}

/* filter functions */
function showFilter(filter, link){
	link.blur();
	if(!$(link).parent().hasClass('cur')){
		$(link).parent().siblings('.cur').removeClass('cur');
		$(link).parent().addClass('cur');
		$('#filter_contents > div').hide();
		$('#' + filter).fadeIn('fast');
	}	
}

function showSpecialProducts(sid, link){
	link.blur();
	var par = $(link);
	if(!$(par).hasClass('act')){
		//$(par).siblings('.act').addClass('lnk');
		$(par).siblings('.act').removeClass('act');
		$(par).addClass('act');
		//$(par).removeClass('lnk');
		$('#special_products > div').hide();
		$('#catalog_special' + sid).show();
	}
}

/* some other */

function changeProductVariant(){
	
	var p_var = document.forms['product_variants'].elements['product_variants'].value;
	if(p_var == ''){
		document.getElementById('product_price').innerHTML = base_price;
		//showFirstPhoto();
	}
	
	/*
	DESCRIPTIONS
	$('#product_descriptions div.short_desc').hide();
	$('#product_description_v' + p_var).show();
	
	if(p_var != '' && $('#product_description_v' + p_var).html() == ''){
		$('#product_description_v' + p_var).hide();
		$('#product_description_v').show();
	}
	*/
	
	item_variant = p_var;
	if(item_variant == '')
		item_variant = 0;
		
	for(var i=0; i<product_variants.length; i++){
		if(product_variants[i]['id'] == p_var){
			if(product_variants[i]['pict1'] != ''){
				changeCatalogPhoto(product_variants[i]['pict1'], product_variants[i]['pict2']);
			}else{
				showFirstPhoto();
			}
			document.getElementById('product_price').innerHTML = product_variants[i]['price'];
		}
	}	
}

/* init purpose filter behaviour */
/*
$(document).ready(
	function(){
		var t = $('#purpose_filter > div > table > tbody > tr > td');
		//alert(t.length);
		$('#purpose_filter > div > table > tbody > tr > td > a').mouseover(
			function(){				
				$(this).parent().addClass('hover');
			}
		).mouseout(
			function(){
				$(this).parent().removeClass('hover');
			}
		);
	}
);
*/

function stretchMenu(cnt_id){
	
	var container = document.getElementById(cnt_id);
	if(container){
		var e_width = 0;
		var items = $('table > tbody > tr >td a span', container);
		var items_num = 0;
		
		/* calculate width */
		for(var i=0; i<items.length; i++){
			e_width += items[i].offsetWidth;
			items_num++;
		}
		
		if(items_num){		
			var padding = (container.offsetWidth-e_width)/(items_num*2);
			$('table > tbody > tr >td a', container).css('padding-left', padding+'px').css('padding-right', padding+'px');
		}	
	}
	
}

$(document).ready(
	function(){
		stretchMenu('purpose_items');
		moveFilterMarker();
	}
);

/* purpose filter */
function changeCatalogPurpose(id, lnk, index){	
	$('#sections_content_rel').addClass('loading');
	lnk.blur();
	$(lnk).parent().siblings().removeClass('active');
	$(lnk).parent().addClass('active');
	var req = {'purpose': id}
	if(index)
		req.no_sub = '1';
	$.get('/catalog/', req, onFilterApplied);
	moveFilterMarker();
	$('#clear_filter').show();	
}

function onFilterApplied(text){
	var c = document.getElementById('sections_content')
	if(c){
		$(c).html(text);
	}else{
		location.href = '/catalog/';
	}
	$('#sections_content_rel').removeClass('loading');
}

function clearPurposeFilter(lnk, index){
	$('#sections_content_rel').addClass('loading');
	$(lnk).parent().hide();
	var pf = $('#purpose_items');
	$('td.active', pf).removeClass('active');
	moveFilterMarker();
	var req = {'purpose': 'all'}
	if(index)
		req.no_sub = '1';
	$.get('/catalog/', req, onFilterApplied);
}

function moveFilterMarker(){
	if(document.getElementById('filter_marker')){
		var t = $('#purpose_filter > div > table > tbody > tr > td.active');
		if(t.length){
			offs = $(t).position();
			l = offs.left + (($(t[0]).width()-$('#filter_marker').width())/2);
			$('#filter_marker').css({'left': l + 'px'}).show();
		}else{
			$('#filter_marker').hide();
		}
	}
}

function copyPreviousElement(lnk){
	lnk.blur();
	var new_el = $(lnk).prev().clone();
	$(new_el).insertBefore(lnk);
	/* clear inputs */
	$(':input', new_el).attr('value', '');
}

function showSectionChildren(field){
	field.blur();
	var section_id = field.value;
	if(section_id){
		$.get('/catalog/', {'a': 'sub_sections', 'parent': section_id}, function(text){onChildrenLoaded(text, field)});
	}else{
		removeNextSections(field);
	}
}

function onChildrenLoaded(text, field){
	var options = $('option',text);
	removeNextSections(field);
	if(options.length){
		var sel = document.createElement('select');
		$(sel).attr('name', 'section[]');
		$(sel).change(function(){showSectionChildren(this)});
		$(sel).insertAfter(field);
		sel.options[0] = new Option('--', '')
		for(var i=0; i<options.length; i++){
			sel.options[sel.options.length] = new Option($('name', options[i]).text(), $('value', options[i]).text());
		}
	}
}

function removeNextSections(field){
	$(field).nextAll('select').remove();
}

function checkSectionSelected(form){
	var s = $('select', form);
	var check = s[s.length-1].value != '';
	if(!check){
		alert('Необходимо выбрать категорию');
		return false;
	}
	return true;
}

function changePriceType(sel){
	var val = sel.value;
	if(val == 2){
		$('#mlt_prices').show();
	}else{
		$('#mlt_prices').hide();
	}
	if(val == 0){
		$('#discount_price').show();
	}else{
		$('#discount_price').hide();
	}
}

/* add to cart functions */
function checkCreateNew(el){
	$('#new_wl_name_cnt').toggle();
	if(el.checked)
		$('select', document.forms['tocart_form']).attr('disabled', true);
	else
		$('select', document.forms['toart_form']).removeAttr('disabled');
}

/* sections list */
function toggleSectionsList(list, link){
	link.blur();
	$('#sections_content > div').hide();
	$('#' + list).show();
	$('#sections_switcher > div').removeClass('active');
	$(link).parent().parent().addClass('active');
}

function toggleAllSections(link){
	link.blur();
	$('#all_sections').slideToggle('fast', function(){$(link).parent().toggleClass('opened');});	
}

function checkAll(formname, but, el, exclude){
	//var but_ob = document.forms[formname].elements[but];
	var but_ob = $('input[@name="' + but + '"]:checkbox', document.forms[formname]);
	var elements = $('input:checkbox', document.forms[formname]);
	for(var i=0; i < elements.length; i++){
		if((!el || elements[i].getAttribute('name') == el) && (!exclude || !elements[i].getAttribute(exclude))){			
			//alert($(but_ob).attr('checked'));
			if($(but_ob).attr('checked'))
				elements[i].checked = true;
			else
				elements[i].checked = false;
		}
	}	
}

function initCheckboxes(formname, but, el, exclude){
	$(document.forms[formname].elements[but]).click(
		function(){
			checkAll(formname, but, el, exclude);
		}
	);

	$(document.forms[formname].elements[el]).click(
		function(){
			if((!exclude || !this.getAttribute('exclude')) && !$(this).attr('checked')){
				$('input[@name="' + but + '"]:checkbox', document.forms[formname]).attr('checked', false);
			}
		}
	);

}

/* tooltips */

function showTooltip(id, lnk){
	var offs = $(lnk).offset();
	if(document.getElementById(id)){
		var h = $('#' + id).height();
		var w = $('#' + id).width();
		
		var left = offs.left + lnk.offsetWidth + 4;
		var top = offs.top - ((h/2)-10);
		
		if(top <= 0){
			top = offs.top + $(lnk).height() + 0;
		}
		
		if(left + w <= $(document.width)){
			left = offs_left - w;
		}
		
		$('#' + id).css({'top': top + 'px', 'left': left + 'px'}).show();
	}
}

function hideTooltip(id){
	$('#' + id).hide();
}

// init tooltip
$(document).ready(
	function(){
		$('a.tooltip_control').mouseover(
			function(){
				showTooltip($(this).attr('rel'), this);
			}
		).mouseout(
			function(){
				hideTooltip($(this).attr('rel'));
			}
		);
	}
);