var just_opened, open_this_id, is_opened=0;	// make var for checking if we have opened lists

this.tooltip = function(){	
	/* CONFIG */		
		var xOffset = -16;
		var yOffset = 16;
    var tTitle  = '';
    var obj     =	"a,h3#commentsTitle,td"
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$(obj).hover(function(e){											  
      tTitle = this.title; //over
      this.title = "";	
      if (tTitle.length>3) {								  
         $("body").append("<div id='tooltip'>"+ tTitle +"</div>");
      }
    	$("#tooltip")
    		.css("top",(e.pageY - xOffset) + "px")
    		.css("left",(e.pageX + yOffset) + "px")
    		.fadeIn("fast");		
    },
  	function(){ //out
      this.title = tTitle;
      tTitle = '';
  		$("#tooltip").fadeOut("fast");
  		$("#tooltip").remove();
    });
    	
	$(obj).mousemove(function(e){
  	$("#tooltip")
  		.css("top",(e.pageY - xOffset) + "px")
  		.css("left",(e.pageX + yOffset) + "px");
    });			
};

Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++) {
		for(var x = 0, y = r.length; x < y; x++) {
			if(r[x]==this[i]) {
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

$(document).ready(function(){

	// toggle menu with subcategories
	$(".menu div.hoverTrigger:contains('Половые инфекции')").hover(
		function () {
			$("#topHoverMenu").css("left",$(this).position().left) //set position of over menu to the left point of element which triggers menu
						  	.slideDown(500);
		}, 
      		function () {
			$("#topHoverMenu").slideUp(500);
      		}
	);
    
	// add titles to links in the menu
	$(".menu a:contains('Женские')")
		.attr("title","Какие распознать <b>женские половые инфекции</b> и как избавиться от них? Все в этом разделе!");
	$(".menu a:contains('Мужские')")
		.attr("title","Описание самых распостраненных <b>мужских половых инфекций</b> и лечение от них!");
	$(".menu a:contains('Народная медицина')")
		.attr("title","Статьи о лечении простатита без дорогих лекраств - травами, грязями, массажем.");	
	$(".menu a:contains('простатит')")
		.attr("title","Что такое простатит? Как его вовремя обнаружить и вылечить? ");		
	$(".menu a:contains('урологические болезни')")
		.text('болезни')
		.attr("title","Какие <b>урологические болезни</b> подстерегают в этой важной области? Все о них!");
	$(".menu a:contains('урологические процедуры')")
		.text('лечение')
		.attr("title","Как лечат простатит? Как происходит операция на простате? Статьи о том, как обнаружить и вылечить болезни.");
	$(".menu a:contains('Словарь')")
		.attr("title","Более 600 определений урологических терминов, которые можно встретить на сайте.");
	$(".menu a:contains('Видео')")
		.attr("title","Видео-раздел: видео операций, репортажи, лекции урологов.");
	$(".menu a:contains('Вопрос')")
		.attr("title","Новый раздел: Задайте свой вопрос квалифицированному врачу.");
	$(".menu a:contains('Тесты')")
		.attr("title","НОВИНКА! Пройдите тест и узнайте состояние своего здоровья. БЕСПЛАТНО!");

	// add title to add_clinic_link
	$(".metro a:contains('Добавить клинику')")
		.attr("title","Добавьте информацию о клинике в наш каталог БЕСПЛАТНО!");	
	
	// starting the script of tooltip on page load
	tooltip();

	// toggle visibility of block with comments
	$("h3#commentsTitle")
		.click(function() {
			if (location.href.indexOf('vopros-otvet') == -1) { // hide comments only for not FAQ pages
				$("div#comments").slideToggle("slow"); 
			}
		})
		.css("cursor","pointer");

	// check if we have to open any list - if true read value from cookie
    	if ($.cookie('counter')) {
    		open_this_id=parseInt($.cookie('counter'));
			$("li > span").eq(open_this_id).next("ul").slideDown();
			just_opened=open_this_id;
			is_opened = 1;		// 
    	}

	$("li > span").css("cursor","pointer");
	$("li > span").attr("title","Открыть список метро");
	$("li > span").click(function () {

		// check if we haven't opened list yet. if false - close previously opened
		if (is_opened == 1) {
		
			// if all lists are collapsed - delete cookie
			if (just_opened==$("li > span").index(this)) {
				$(this).next("ul").slideUp("slow");
				is_opened=0;
				$.cookie('counter',null);
			} else {
				$(this).next("ul").slideToggle("slow");			// toggling required list
				$("li > span").eq(just_opened).next("ul").slideToggle(500);	// closing previously opened list
				just_opened=$("li > span").index(this);			// refreshing index of opened list
			}
		
		} else {
			$(this).next("ul").slideToggle("slow");			// toggling required list
			just_opened=$("li > span").index(this);			// index of opened list
			is_opened=1;						// mark that we have opened
   		}

		$.cookie('counter', just_opened, {expires: 0.001, path: '/category/'}); 
    }); //$("li > span").click(function () {
    	
    	//$.cookie('counter') ? open_this_id=$.cookie('counter') : '';
    	
	$("div.searchHead").css("display","block");	//show search div after page loaded
	$("input#q").css("width","115px");			//reset width to normal after page loaded

	// Test scripts
	// get all checked radio buttons, read their value and summerize them. 
	if ($("#run_test").length = 1) {
		// check button on clicking on span
		$("input[name^=uromax_]").next("span").css('cursor','default').click(function(){
			$(this).prev().attr("checked", "checked");
		});
		
		$("#run_test").click(function(){
			$("#test_results li.error").slideUp(500,function(){$(this).remove();});
			$("#test_results li").slideUp(500);
			$("#test_results ul").slideUp(500);

			// count how many questions wasn't answered
			// HOW WORKS: Creat array of elements' name attrs, check all elements of one name
			// if no one of elements with one name is checked - sum_not_checked++. 
			// In the end count - if sum_not_checked>0, then there were unanswered elements.
			var x=new Array(); i=0; checked=0; sum_not_checked=0;
			$("input[name^=uromax_test]").each(function(){ // create array of all name attributes
				x[i++]=$(this).attr('name');
			})
			elements=x.unique() //leave only unique name attrs
			for (k=0;k<elements.length;k++) { // iterate through all elemets with one name
				$("input[name="+elements[k]+"]").each(function(){
					$(this).is(":checked") == true ? checked=1 : checked=0;
					//console.log(elements[k] + ": " +checked);
					if (checked==1) { return false; }
				})
				checked==0 ? sum_not_checked++ : '';
			}
			//console.log('not: '+sum_not_checked);
			if (sum_not_checked > 0) {
				$("#test_results li:last").after("<li class='error'>Пожалуйста, ответьте на все вопросы. Надо ответить еще на <b>"+sum_not_checked+"</b> вопросов.</li>")
				$("#test_results").slideDown(500);			// show parent ul
				$("#test_results li.error").slideDown(500)	// show li.error
			} else {
				total=0;
				$("input[name^=uromax_test]:checked").each(function(){
					total += parseInt( $(this).val() );
				});

				$("#test_results li").each(function() {
					range=$(this).attr('title');
					range=range.split('-');
					if (total >= range[0] && total <= range[1]) {
						$(this).parent("ul").slideDown(500);
						$(this).slideDown(500);
					}
				});
			} //if (sum_not_checked > 0) {
			try { //run custom test function
  				custom_test(total);
  			} catch(err) {}
		}); //button.click()
	} //  if ($("#run_test").length = 1) 

	// TABS
	if ($(".tabs").length > 0) {
		// child tab div should start with "tab.." - don't work with YandexMap's divs
		var tabContainers = $('div.tabs > div'); 
		tabContainers.css('display','none').filter(':first').css('display','block');
		
		$('div.tabs ul.tabNavigation a').click(function () {
			tabContainers.css('display','none');
			tabContainers.filter(this.hash).css('display','block');
			$('div.tabs ul.tabNavigation a').removeClass('selected');
			$(this).addClass('selected');
			// get current tab clicked
			active_tab=1+$("div.tabs ul.tabNavigation li").index( $(this).parent("li") );
			// refresh placemark
			placemark[active_tab].update();
			
			return false;
		}).filter(':first').click();

	} //	if ($(".tabs").length > 0) {

	$("#search_comment_q").keyup(function(event){		
		if (event.keyCode==32) { // 32 = " " (space)
			ajax_comment_search();
			return false;
		}
	});

	// SEARCH COMMENTS AJAX
	$("#search_comment").click(function() {
		query 		= $("#search_comment_q").val();
		article_id	= $("#article_id").val();
		ajax_comment_search();
	});
	
	// add extra PAGINATOR

	if (location.href.indexOf('vopros-otvet') == -1) { // show extra pagination not on faq pages
		$('<div class="paginator" id="paginator"></div>').insertBefore(".pagination");
		$(".pagination").hide();
	
		var pagesTotal  = $(".total_pages").text();
		var pageCurrent = $(".pagination li.current").text();
		
		
		//console.log(pagesTotal + ' ' + pageCurrent);
		
		$('#paginator').paginator({
			pagesTotal: 	parseInt(pagesTotal), 
			pagesSpan: 		7, 
			pageCurrent: 	parseInt(pageCurrent), 
			baseUrl: 		'?pg=',
		});
	} // if (location.href.indexOf('vopros-otvet') == -1) {




}); // document.ready

// SEARCH COMMENTS AJAX
function ajax_comment_search() {
	$.ajax({
		type: 'POST',
		dataType: 'json',
		url: '/ajax/',
		data: { q: query, parent_id: article_id},
		beforeSend: function() {
			$('#search_result').slideUp(600);
			$('#loading').animate({width: "32px", height: "32px", opacity: 1}, 500)
		},
		success: function($data) {
			$('#loading').slideUp(600);
			if ($data.total) {
				$('#search_result').html($data.html);
			} else {
				$('#search_result').html('Не найдено. Попробуйте поискать другое слово.');
			}
			$('#search_result').slideDown(600);
		}
	});
}



/******************************************************************************
AJAX FILE UPLOAD
******************************************************************************/
var path_to_file='http://uromax.ru/files/';

function ajaxFileUpload()
{
	$("#loading")
	.ajaxStart(function(){
		$(this).show();
		$("div.result_message").fadeOut();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
		{
			url:'/fileupload/doajaxfileupload.php',
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{ 
					if(data.error == '')
					{
						//alert(data.error);
						//$("#file_razrez").attr("value",''+path_to_file+data.filepath);
						//$("div.uploadform").hide();
						$("div.result_message,h3.uploadedImgs").fadeIn();
						$("#fileToUpload").val(''); // clear input string
						$("#buttonUpload").text('Добавить еще одну картинку'); // clear input string
						$("<a href='"+path_to_file+data.img_full+"'><img src='"+path_to_file+data.img_thumb+"' alt='" + data.img_full + "'/></a>").appendTo("div.result_imgs"); // add img's thumb to preview it before uploading
						//console.log("<img src='"+path_to_file+data.img_thumb+"' />");
					} 
					else
					{					
						//$("#file_razrez").attr("value",'' + path_to_file + data.filepath);
						$("div.result_message").text('Ошибка: '+data.error).fadeIn();
					}
				}
			},
			error: function (data, status, e)
			{ 
				// alert(e);
				$("div.result_message").text('Ошибка: '+data.error).fadeIn();
			}
		}
	)
	return false;
}

/******************************************************************************
 START ADSENSE CLICKS COUNTER
******************************************************************************/
function as_click () {
	urchinTracker ('/asclick');
}

// incredibly funky onload add-event scripting, for all browsers

		 if(typeof window.addEventListener != 'undefined')
		 {
		 	//.. gecko, safari, konqueror and standard
		 	window.addEventListener('load', adsense_init, false);
		 }
		 else if(typeof document.addEventListener != 'undefined')
		 {
		 	//.. opera 7
		 	document.addEventListener('load', adsense_init, false);
		 }
		 else if(typeof window.attachEvent != 'undefined')
		 {
		 	//.. win/ie
		 	window.attachEvent('onload', adsense_init);
		 }

		 //** remove this condition to degrade older browsers
		 else
		 {
		 	//.. mac/ie5 and anything else that gets this far

		 	//if there's an existing onload function
		 	if(typeof window.onload == 'function')
		 	{
		 		//store it
		 		var existing = onload;

		 		//add new onload handler
		 		window.onload = function()
		 		{
		 			//call existing onload function
		 			existing();

		 			//call adsense_init onload function
		 			adsense_init();
		 		};
		 	}
		 	else
		 	{
		 		//setup onload function
		 		window.onload = adsense_init;
		 	}
		 }
function adsense_init () {

	if (document.all) {  //ie

		var el = document.getElementsByTagName("iframe");
	
		for(var i = 0; i < el.length; i++) {
			if(el[i].src.indexOf('googlesyndication.com') > -1) {
				el[i].onfocus =  as_click;
			}
		}
	} else {   // firefox
		window.addEventListener('beforeunload', doPageExit, false);
		window.addEventListener('mousemove', getMouse, true);	
	}
		
}
//for firefox
var px;
var py;

function getMouse(e) {
	px=e.pageX;
	py=e.clientY;
}
function findY(obj) {
	var y = 0;
	while (obj) {
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return(y);
}
function findX(obj) {
	var x = 0;
	while (obj) {
		x += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return(x);
}
function doPageExit(e) {
	ad = document.getElementsByTagName("iframe");
	for (i=0; i<ad.length; i++) {
		var adLeft = findX(ad[i]);
		var adTop = findY(ad[i]);
		var inFrameX = (px > (adLeft - 10) && px < (parseInt(adLeft) + parseInt(ad[i].width) + 15));
		var inFrameY = (py > (adTop - 10) && py < (parseInt(adTop) + parseInt(ad[i].height) + 10));
		
		if (inFrameY && inFrameX) {
			urchinTracker('/asclick');
		}
	}
}
//end for firefox
/******************************************************************************
  END ADSENSE CLICKS COUNTER
******************************************************************************/

/* EXTRA PAGINATOR FUNCTION ~9kB */
;(function($){
	$.fn.paginator = function (s){
		var options = {
			pagesTotal  : 1, //бщее количество страниц
		 	pagesSpan   : 10,  //количество показываемых страниц
		 	pageCurrent : 50,  //текущая страница
			baseUrl     : './page/', //ссылка или функция function (page){}
		 	returnOrder : false,
		 	lang        : { next  : "Следующая",
							last  : "Последняя",
							prior : "Предыдущая",
							first : "Первая",
							arrowRight : String.fromCharCode(8594),
							arrowLeft  : String.fromCharCode(8592)}
     };
	 
	 
	 $.extend(options, s);
	 
	 options.pagesSpan = options.pagesSpan < options.pagesTotal ? options.pagesSpan : options.pagesTotal;
	 options.pageCurrent = options.pagesTotal < options.pageCurrent ? options.pagesTotal : options.pageCurrent;
	 if (!$.isFunction(options.baseUrl) && !options.baseUrl.match(/%page%/i)) options.baseUrl += '%page%';
	 
	 
	 var html = {
	       holder: null,
		   table: null,
		   trPages: null, 
		   trScrollBar: null,
		   tdsPages: null,
		   scrollBar: null,
		   scrollThumb: null,
		   pageCurrentMark: null
         };
	 
	 function prepareHtml(el){
	   html.holder = el;
	   $(html.holder).html(makePagesTableHtml());
	   html.table = $(html.holder).find('table:last');
	   html.trPages = $(html.table).find('tr:first');
	   html.tdsPages = $(html.trPages).find('td');
	   html.scrollBar = $(html.holder).find('div.scroll_bar');
	   html.scrollThumb = $(html.holder).find('div.scroll_thumb');
	   html.pageCurrentMark = $(html.holder).find('div.current_page_mark');
	   if (options.pagesTotal == options.pagesSpan) {
	     $(html.holder).addClass('fulsize');
	   };
     };
     
     function makePagesTableHtml(){
	   var tdWidth = (100 / (options.pagesSpan + 2)) + '%';
     
	   var isFunc = $.isFunction(options.baseUrl); 	
		
	   var next_page = (parseInt(options.pageCurrent)< parseInt(options.pagesTotal)) ? parseInt(options.pageCurrent) + 1 : options.pagesTotal;
			 
	   var next  = '<a href="';
	       next+= isFunc ? 'javascript:void(0)' : options.baseUrl.replace(/%page%/i, next_page);
	       next += '" rel="' + next_page + '">%next%</a>';
	   var last  = '<a href="';
	       last +=  isFunc ? 'javascript:void(0)' : options.baseUrl.replace(/%page%/i, options.pagesTotal);
		   last += '" rel="' + options.pagesTotal + '">%last%</a>';
	   
	   var prior_page = (parseInt(options.pageCurrent) > 1) ? parseInt(options.pageCurrent) - 1 : 1;
	   
	   var prior = '<a href="';
	       prior += isFunc ? 'javascript:void(0)' : options.baseUrl.replace(/%page%/i, prior_page);
		   prior += '" rel="' + prior_page + '">%prior%</a>';
	   var first = '<a href="';
	       first += isFunc ? 'javascript:void(0)' : options.baseUrl.replace(/%page%/i, 1);
		   first += '" rel="' + 1 + '">%first%</a>';
	 
	 
	   if (options.returnOrder){
	     var top_left       = options.lang.arrowLeft + ' ' + options.lang.next;
		 var bottom_left    = options.lang.last;
		 var top_right      = options.lang.prior + ' ' + options.lang.arrowRight;
		 var bottom_right   = options.lang.first;
		 
		 if (options.pageCurrent !== options.pagesTotal){
		   var top_left     = next.replace(/%next%/, top_left);
		   var bottom_left  = last.replace(/%last%/, bottom_left);
		 };
		 
		 if (options.pageCurrent !== 1){
    	   var top_right    = prior.replace(/%prior%/, top_right);
		   var bottom_right = first.replace(/%first%/, bottom_right);
		 };
		 
	   } else {
		 var bottom_right   = options.lang.last;
		 var top_right      = options.lang.next + ' ' + options.lang.arrowRight;
		 var top_left       = options.lang.arrowLeft + ' ' + options.lang.prior;
		 var bottom_left    = options.lang.first;
		 
		 if (options.pageCurrent !== options.pagesTotal){
		   var top_right    = next.replace(/%next%/, top_right);
		   var bottom_right = last.replace(/%last%/, bottom_right);
		 };
		 
		 if (options.pageCurrent !== 1){
		   var top_left     = prior.replace(/%prior%/, top_left);
		   var bottom_left  = first.replace(/%first%/, bottom_left);
		 };
	   };
	 
	   var html = '' +
	   '<table width="100%">'+
	     '<tr>' +
		   '<td class="left top">' + top_left + '</td>' +
		   '<td class="spaser"></td>' +
		   '<td rowspan="2" align="center">' +
	         '<table>' +
	 	       '<tr>'
			     for (var i=1; i<=options.pagesSpan; i++){
				   html += '<td width="' + tdWidth + '"></td>';
			     }
			     html += '' +
		       '</tr>' +
		       '<tr>' +
			     '<td colspan="' + options.pagesSpan + '">' +
				   '<div class="scroll_bar">' + 
				     '<div class="scroll_trough"></div>' + 
					 '<div class="scroll_thumb">' + 
						'<div class="scroll_knob"></div>' + 
					 '</div>' + 
					 '<div class="current_page_mark"></div>' + 
				   '</div>' +
			     '</td>' +
		       '</tr>' +
	         '</table>' +
		   '</td>' + 
		   '<td class="spaser"></td>' +
		   '<td class="right top">' + top_right + '</td>' +
		'</tr>' + 
        '<tr>' +
		  '<td class="left bottom">' + bottom_left + '</td>' + 
		  '<td class="spaser"></td>' +
		  '<td class="spaser"></td>' +
		  '<td class="right bottom">' + bottom_right + '</td>' +
		'</tr>' +
	  '</table>';
	 
	   return html;
    };
     
    function initScrollThumb(){
	  html.scrollThumb.widthMin = '8';
	  html.scrollThumb.widthPercent = options.pagesSpan/options.pagesTotal * 100;
	  html.scrollThumb.xPosPageCurrent = (options.pageCurrent - Math.round(options.pagesSpan/2))/options.pagesTotal * $(html.table).width();
	  if (options.returnOrder) {
		 html.scrollThumb.xPosPageCurrent = $(html.table).width() - (html.scrollThumb.xPosPageCurrent + Math.round(options.pagesSpan/2)/options.pagesTotal * $(html.table).width());
	  }; 
	  html.scrollThumb.xPos = html.scrollThumb.xPosPageCurrent;
	  html.scrollThumb.xPosMin = 0;
	  html.scrollThumb.xPosMax;
	  html.scrollThumb.widthActual;
	  setScrollThumbWidth();  
    };
   
    function setScrollThumbWidth(){
	  $(html.scrollThumb).css({width : html.scrollThumb.widthPercent + "%"});
	  html.scrollThumb.widthActual = $(html.scrollThumb).width();

	  if (html.scrollThumb.widthActual < html.scrollThumb.widthMin)
		$(html.scrollThumb).css('width', html.scrollThumb.widthMin + 'px');

	  html.scrollThumb.xPosMax = $(html.table).width - html.scrollThumb.widthActual;   
    };

    function moveScrollThumb(){
	  $(html.scrollThumb).css({left : html.scrollThumb.xPos + "px"});
    }

    function initPageCurrentMark(){
	  html.pageCurrentMark.widthMin = '3';
	  html.pageCurrentMark.widthPercent = 100 / options.pagesTotal;
	  html.pageCurrentMark.widthActual;
	  setPageCurrentPointWidth();
	  movePageCurrentPoint();
    };
  
    function setPageCurrentPointWidth(){
	  $(html.pageCurrentMark).css({width : html.pageCurrentMark.widthPercent + '%'});

	  html.pageCurrentMark.widthActual = $(html.pageCurrentMark).width();

	  if(html.pageCurrentMark.widthActual < html.pageCurrentMark.widthMin)
		$(html.pageCurrentMark).css("width", html.pageCurrentMark.widthMin + 'px');
    };
  
    function movePageCurrentPoint(){
	  var pos = 0;
	  if(html.pageCurrentMark.widthActual < $(html.pageCurrentMark).width()){
	    pos = (options.pageCurrent - 1) / options.pagesTotal * $(html.table).width() - $(html.pageCurrentMark).width() / 2;
	  } else {
	    pos = (options.pageCurrent - 1)/options.pagesTotal * $(html.table).width();
	  };
	  
	  if (options.returnOrder) pos = $(html.table).width() - pos - $(html.pageCurrentMark).width(); 
	  
	  $(html.pageCurrentMark).css({left: pos + 'px'}); 	
    };

    function initEvents (){
	  moveScrollThumb();
	  options.returnOrder ? drawReturn() : drawPages();
	
	  $(html.scrollThumb).bind('mousedown', function(e){										   
		var dx = e.pageX - html.scrollThumb.xPos;		
	
		$(document).bind('mousemove', function(e){
			html.scrollThumb.xPos = e.pageX - dx;
			
			moveScrollThumb();
			options.returnOrder ? drawReturn() : drawPages();
		});
		
		$(document).bind('mouseup', function(){
			$(document).unbind('mousemove');
			enableSelection();
		});
		
		disableSelection();
	  }); 
	
	  if ($.isFunction(options.baseUrl)){
	    $(html.holder).find('a[rel!=""]').bind('click', function (e){
			var n = parseInt($(this).attr('rel'));
			options.baseUrl(n);
		});
	  };	
	  
	  $(window).resize(function (){
	     setPageCurrentPointWidth();
	     movePageCurrentPoint();
         setScrollThumbWidth();
	  });
	  
    };  

    function drawPages(){  
	  var percentFromLeft = html.scrollThumb.xPos / $(html.table).width();
	  var cellFirstValue = Math.round(percentFromLeft * options.pagesTotal);
	 
	  var data = "";

	  if (cellFirstValue < 1){
	    cellFirstValue = 1;
	    html.scrollThumb.xPos = 0;
	    moveScrollThumb();
	  } else if (cellFirstValue >= options.pagesTotal - options.pagesSpan) {
	    cellFirstValue = options.pagesTotal - options.pagesSpan + 1;
	    html.scrollThumb.xPos = $(html.table).width() - $(html.scrollThumb).width();
  	    moveScrollThumb();
	  };  
	
	  var isFunc = $.isFunction(options.baseUrl);
	
	  for(var i=0; i < html.tdsPages.length; i++){	
	    var cellCurrentValue = cellFirstValue + i;
	    if(cellCurrentValue == options.pageCurrent){
		  data = '<span> <strong>' + cellCurrentValue + '</strong> </span>';
	    } else {
		  data = '<span> <a href="'; 
		  data += isFunc ? 'javascript:void(0)' : options.baseUrl.replace(/%page%/i, cellCurrentValue);       
		  data += '">' + cellCurrentValue + '</a> </span>';
	    };
	    $(html.tdsPages[i]).html(data);
	    if (isFunc){
		  $(html.tdsPages[i]).find('a').bind('click', function (){
														options.baseUrl($(this).text());	  
													  });  
	    }
	  };
    };

    function drawReturn(){  
	  var percentFromLeft = html.scrollThumb.xPos / $(html.table).width();
	  var cellFirstValue = options.pagesTotal - Math.round(percentFromLeft * options.pagesTotal);
	  
	  var data = "";
	  if (cellFirstValue < options.pagesSpan){
	    cellFirstValue = options.pagesSpan;
	    html.scrollThumb.xPos = $(html.table).width() - $(html.scrollThumb).width();
	    moveScrollThumb();
	  } else if (cellFirstValue >= options.pagesTotal) {
	    cellFirstValue = options.pagesTotal;
	    html.scrollThumb.xPos = 0;
	    moveScrollThumb();
	  }; 	 
	
	  var isFunc = $.isFunction(options.baseUrl);
	
	  for(var i=0; i < html.tdsPages.length; i++){	
	    var cellCurrentValue = cellFirstValue - i;
	    if(cellCurrentValue == options.pageCurrent){
		  data = '<span> <strong>' + cellCurrentValue + '</strong> </span>';
	    } else {
		  data = '<span> <a href="'; 
		  data += isFunc ? 'javascript:void(0)' : options.baseUrl.replace(/%page%/i, cellCurrentValue);       
		  data += '">' + cellCurrentValue + '</a> </span>';
	    };
	    $(html.tdsPages[i]).html(data);
	    if (isFunc){
		  $(html.tdsPages[i]).find('a').bind('click', function (){
		  												options.baseUrl($(this).text());	  
		 											  });  
	    }
	  };
    };

    function enableSelection(){
	  document.onselectstart = function(){
		return true;
	  };
    };

    function disableSelection (){
	  document.onselectstart = function(){
		return false;
	  };  
	  $(html.scrollThumb).focus();	
    };
	 
	 
	 prepareHtml(this);	 
	 initScrollThumb();
	 initPageCurrentMark();
	 initEvents();	 
   };
})(jQuery);
