/* This JS generated by /root/js/makefile. Don't edit this. For edit style, please use: jquery/jquery-regru.js messages.js common.js keyboard.js jquery/jquery.tooltip.js  */

/* BEGIN jquery/jquery-regru.js */

/* browser detection */
var browser_info = new function(ie)
{
   var d = document, w = window, qsel = !!d.querySelectorAll,
   csel = !!d.getElementsByClassName;
   this.ff = !!w.Iterator && !!d.addEventListener && /a/[-1] == 'a';
   this.ff2 = this.ff && (function x(){})[-6] == 'x';
   this.ff3 = csel && this.ff && (function x(){})[-5] == 'x';
   this.ff35 = qsel && this.ff;
   this.ie = (ie && '\v' == 'v');
   this.ie5 = this.ie && ie == 5;
   this.ie6 = this.ie && (ie == 6 || (d.compatMode && d.all && !!d.readyState));
   this.ie7 = this.ie && (ie == 7 && d.documentElement && typeof d.documentElement.style.maxHeight != "undefined");
   this.ie8 = this.ie && (ie == 8 && qsel);
   this.safari = /a/.__proto__ == '//';
   this.chrome = /source/.test((/a/.toString + ''));
   this.opera = (!ie && !!w.opera && w.opera.toString() === "[object Opera]");
}(0/*@cc_on + (@_jscript_version * 10 % 10) @*/);
/* / browser detection */

var $ = jQuery;

$(function(){

    /*** buttons ***/
    
    /* эмуляция text-shadow на кнопках для FF 3.0 */
    if (browser_info.ff && browser_info.ff3 && !browser_info.ff35)
        $('head').append('<link type="text/css" rel="stylesheet" href="/css/buttons-ff3.css" />');
        
    /* правые закругления и css фиксы для FF 2.0*/
    if (browser_info.ff && browser_info.ff2) {
    	$('head').append('<link type="text/css" rel="stylesheet" href="/css/buttons-ff2.css" />');
    	$('.button-18, .button-20, .button-24, .button-40').append('<span class="after"></span>').prepend('<span class="before"></span>');
    }

    /* anti-google-translate */
    buttons_antiGoogleTranslate();

    /* отмена клика для ссылок rel="disabled" */
    $('a[rel~=disabled]').live('click', function(){
	return false;
    });
    
    /* ie6, не понимающий сдвоенные селекторы */
    if (browser_info.ie6) {
	$('.button-20, .button-24, .button-40').each(function() {
	    var classname = 'button-';
	    var disabled  = 'button-';
	    if ($(this).hasClass('button-20')) {
		classname += '20-';
		disabled  += '20-';
	    } else if ($(this).hasClass('button-24')) {
		classname += '24-';
		disabled  += '24-';
	    } else if ($(this).hasClass('button-40')) {
		classname += '40-';
		disabled  += '40-';
	    }
	    disabled += 'disabled';
	    if ($(this).hasClass('button-green')) {
	    	classname += 'green';
	    } else if ($(this).hasClass('button-green-forward')) {
	    	classname += 'green-forward';
	    	disabled  += '-forward'; 
	    } else if ($(this).hasClass('button-orange')) {
	    	classname += 'orange';
	    } else if ($(this).hasClass('button-orange-back')) {
	    	classname += 'orange-back';
	    	disabled  += '-back';
	    } else if ($(this).hasClass('button-red')) {
	    	classname += 'red';
	    } else if ($(this).hasClass('button-blue')) {
	    	classname += 'blue';
	    }
	    $(this).addClass(classname);
	    if ($(this).is('[disabled]') || $(this).is('[rel~=disabled]'))
	    	$(this).addClass(disabled);
	});
    }
    
    /* смещение кнопки по клику в IE */
    if (browser_info.ie) {
        $('.button-20, .button-24, .button-40').live('mousedown', function(){
	    if ($(this).not('[disabled], [rel~=disabled]').length)
	        $(this).addClass('button-active');
	}).live('mouseup', function(){
	    $(this).removeClass('button-active');
	});
    }
    /*** / buttons ***/
    
    /*****
    new js
    *****/
    
    /* fix bug with overflow in opera */
    if (browser_info.opera && $.browser.version < 10)
        $('#wrapper').css({
	       overflow: 'visible',
	       'float': 'left'
        });

    /* header_top menu */
    $('.menu', '#header_top').hover(function(){
        if (!$('div.submenu_wrap', this).is(":animated")) {
            $('div.submenu_wrap', this).show(200);
        }
    }, function(){
        $('div.submenu_wrap', this).hide(400);
    });

    /* header #regru-description scroller */
    var $description = $('#regru-description');
    var description_line_height = parseInt($('li', $description).css('lineHeight'));
    var description_count = parseInt($('ul', $description).height()) / description_line_height;
    var div_lines_count = parseInt($description.height()) / description_line_height;
    var description_index = 0;

    var prev_next_click =  function() {
        if($('.prev', $description).attr('clicked') == 'true' || $('.next', $description).attr('clicked') == 'true') return false;

        var $original = $('ul', $description);
        var top = $original.position().top;

        if ($(this).is('.prev')) {
            $(this).attr('clicked', true);
            $('.next', $description).show();

            top += description_line_height;

            description_index--;

            if (top >= 0) {
                $('.prev', $description).hide();
                top = 0;
            }
        } else {
            $(this).attr('clicked', true);
            $('.prev', $description).show();

            description_index++;

            if (description_index + div_lines_count >= description_count) {
                $('.next', $description).hide();
            }

            top -= description_line_height;
        }

        $original.css({top: $original.position().top + 'px'}).animate({
            top: ''+top+'px'
        }, 150, function() {
            var fix_position = $original.position().top;
            $original.css({top: ''+fix_position}).removeClass('clone');
            $('.prev, .next', $description).attr('clicked', false);
        });

        return false;
    }

    $('.prev', $description).hide();
    $('.prev, .next', $description).css({visibility: 'visible'}).click(prev_next_click);


    /* header login form */
    $('#header-login', '#header').focus(function(){
	$(this).parent().removeClass('login-tip-ru login-tip-en');
    }).blur(function(){
	if ($(this).parents('#personal').hasClass('.ru'))
	    var cl = 'login-tip-ru';
	else
	    var cl = 'login-tip-en';
	if ($(this).val() == '')
	    $(this).parent().addClass(cl);
    }).keyup(function(){
	if ($('#header-password', '#header').val() != '')
	    $('#header-password', '#header').parent().removeClass('password-tip-ru password-tip-en');
    }).blur();

    $('#header-password', '#header').focus(function(){
	$(this).parent().removeClass('password-tip-ru password-tip-en');
    }).blur(function(){
	if ($(this).parents('#personal').hasClass('.ru'))
	    var cl = 'password-tip-ru';
	else
	    var cl = 'password-tip-en';
	if ($(this).val() == '')
	    $(this).parent().addClass(cl);
    }).blur();
    
    $('form#personal', '#header').submit(function(){
    	if ($('#header-password', '#header').val() != '')
    	    $('#header-password', '#header').parent().removeClass('password-tip-ru password-tip-en');
    	if ($('#header-login', '#header').val() != '')
    	    $('#header-login', '#header').parent().removeClass('login-tip-ru login-tip-en');
    	return true;
    });

    /* sidebar uslugi - ie6 fix */
    if (browser_info.ie6) {
        $('a', '#sidebar #uslugi').hover(function(){
            $('span', this).css({textDecoration: 'underline'});
        }, function(){
            $('span', this).css({textDecoration: 'none'});
        });
    }

    /* sidebar info menu */
    $('span.toggle', '#sidebar #info').css({cursor: 'pointer'}).click(function(){
        var $li = $(this).parents('li');
        if ($li.hasClass('collapsed')) {
            $li.removeClass('collapsed').addClass('expanded');
            $('ul', $li).show();
        }
        else {
            $li.removeClass('expanded').addClass('collapsed');
            $('ul', $li).hide();
        }

    });

    $('a.foo', '#sidebar #info').css({cursor: 'pointer'}).click(function(){
	$(this).prev('span').click();

	return false;
    });

    // fixing ie6 positioning bug
    if (browser_info.ie6) {
        $(window).resize(function(){
            $('#wrapper-lb, #wrapper-rb').css({bottom: '1px'}).css({bottom: '0px'});
        });
    }

    /*******************
    old js, From Dima
    *******************/

    $('table tr td:last-child .item span').css('border', 'none');
    // unload
    $("#more_domens a").click(function() {
	$("#all_domens").css("display", "block");
	// $('#all_domens').show();
	// $("#pop_up_iframe").css("display","block");
	$("iframe").css("display", "block");

	return false;
    });

    $("#all_domens #close a").click(function(){
	$("#all_domens").css("display", "none");
	// $('@all_domens').hide();

	return false
    });

    $("#all_domens #top_close a").click(function(){
	$("#all_domens").css("display", "none");

	return false;
    });

    /* -- */
    $("#pp_wm_child").hide();

    $("#org_wm_child").hide();

    $("#pp_wm a").click(function(){
	    now = $("#pp_wm_child").css("display");
	    if (now == "block") {
	       $("#pp_wm_child").css("display", "none");
	    } else {
	       $("#pp_wm_child").css("display", "block");
	    }
    });
    $("#org_wm a").click(function(){
	    now = $("#org_wm_child").css("display");
	    if (now == "block") {
	       $("#org_wm_child").css("display", "none");
	    } else {
	       $("#org_wm_child").css("display", "block");
	    }
    });


    //partners
    $("table.sales tr.more_p").hide();
    $("table.sales tr.less_p").show();
    $("#content #partners table.sales td.links a#table_close_link").hide();
    $("#partners table.sales tr:first td:last div").append("<div style='position:absolute;right:-1px;top:-19px;'><a href='javascript://' id='table_close_link'><img src='/i/style/second/widget-part/pop_up_top_close.gif'></a></test>");
    $("table.sales tr:first td:last div div").hide();

    //show close
    $(".zones .more_zones a").click(function(){
	    $("table.sales tr.more_p").show();
	    $("table.sales tr.less_p").hide();
	    $("#content #partners table.sales td.links a#table_close_link").show();
	    $("table.sales tr:first td:last div div").show();
    });
    $(".zones .full_table a").click(function(){
	    $("table.sales tr.more_p").show();
	    $("table.sales tr.less_p").hide();
	    $("#content #partners table.sales td.links a#table_close_link").show();
	    $("table.sales tr:first td:last div div").show();
    });

    //hide close
    $("#content #partners table.sales td.links a#table_close_link").click(function(){
	    $("table.sales tr.more_p").hide();
	    $("table.sales tr.less_p").show();
	    $("#content #partners table.sales td.links a#table_close_link").hide();
	    $("table.sales tr:first td:last div div").hide();
    });
    $("#content #partners table.sales a#table_close_link").click(function(){
	    $("table.sales tr.more_p").hide();
	    $("table.sales tr.less_p").show();
	    $("#content #partners table.sales td.links a#table_close_link").hide();
	    $("table.sales tr:first td:last div div").hide();
    });

    /* clients */
    $("table.sales tr.more_p").hide();
    $("#clients table.sales tr:first td:last div").append("<div style='position:absolute;right:-1px;top:-25px;'><a href='javascript://' id='table_close_link'><img src='/i/style/second/widget-part/pop_up_top_close.gif'></a></test>");
    $("table.sales tr:first td:last div div").hide();

    $(".zones #client_table_o").click(function(){
	    $("table.sales tr.more_p").show();
	    $("#clients table.sales tr:first td:last div div").show();
    });

    $("#content #clients table.sales a#table_close_link").click(function(){
	    $("table.sales tr.more_p").hide();
	    $("table.sales tr.less_p").show();
	    $("#content #partners table.sales td.links a#table_close_link").hide();
	    $("table.sales tr:first td:last div div").hide();
    });

    // docs download menu
    $('#docs_download li div').hide();
    $('.docs_ltitle').click(function(){
	var div = $(this).parent().children('div');
	if ( div.attr("class") == 'active' ) {
	    div.removeClass("active");
	    div.hide();
	}
	else {
	    div.addClass("active");
	    div.show();
	}
    });


    $("#content #partners h3:first").css("border-top", "none");
    $("#content #partners .partners_title:first").css("border-top", "none");
    $("#content #clients h3:first").css("border-top", "none");


   // tooltip
    if (typeof $('.tooltip').Tooltip != 'undefined') {
        $('.tooltip').Tooltip({
            show_delay: 250,
            hide_delay: 500,
            fade: 200,
            top: 5,
            left: 5
        });
    }
    // /tooltip

// new default js functions
    //target blank
    $("a[rel*=blank]").click(function(){
	    window.open(this.href);
	    return false;
    });
    //block menu show\hide, activiti status
    $("#domain_list-filter .dfilter_block:not(.active)").hide();

    $("#domain_list-filter .dfilter_link").click(function(){
	if($(this).parent().next().hasClass("active")) {
	    filter_id = "domain_list__"+$(this).attr("id");
	    $.ajax({
	      url: "/user/set_session_value?group_name=filter_groups&name="+filter_id+"&value=0",
	      cache: false,
	      success: function(status) {
		if ( status == 'Ok' ) {}
		else {
		    //alert ('Error');
		};}
	    });
	    $(this).parent().next().removeClass("active").slideUp(150);
	}
	else {
	    filter_id="domain_list__"+$(this).attr("id");
	    $.ajax({
		url: "/user/set_session_value?group_name=filter_groups&name="+filter_id+"&value=1",
		cache: false,
		success: function(status) {
		    if ( status == 'Ok' ) {}
		    else {
			//alert ('Error');
		    };}
		});
	    $(this).parent().next().slideDown(150).addClass("active");
	}
	return false;
    });

    // Ссылки в newdomain/checkmany на занятый домен/ХУИЗ домена
    // В полной версии сайта - открываются в новом окне, в мобильной - в текущем
    $(".extPopUp").click(function(){
	extPopUpIE($(this).attr("href"));
	return false;
    });

    // вставки в retail+reseller/documents
        $('.document_links .expanded')
        .removeClass('expanded')
        .addClass('collapsed');

       $('.document_links h4').bind('click', function(){
            var td = $(this).parents('td');

            if ($(td).is('.collapsed')) {
                $(td)
                 .removeClass('collapsed')
                 .addClass('expanded');
            }
            else {
                $(td)
                 .removeClass('expanded')
                 .addClass('collapsed');
            }
       });

       $('.document_links h4 a').bind('click', function(){
            $(this).parents('h4').click();
            return false;
       });

});

/*** buttons ***/
/* переключить состояние disabled .button-20 | .button-24 */
function button_toggle($button)
{
    if (!$button.hasClass('button-20') && !$button.hasClass('button-24'))
	return;
            
    if ($button.attr('disabled') || $button.attr('rel') == 'disabled') {
	button_enable($button);         
    } else if ($button.is('a') || $button.is('button')) {
	button_disable($button);
    }
}
/* disable .button-20 | .button-24 */
function button_disable($button)
{
    if (!$button.hasClass('button-20') && !$button.hasClass('button-24'))
	return;
            
    var $clone = $button.clone();
    if ($clone.is('button'))
	$clone.attr('disabled', 'disabled');
    else if ($clone.is('a'))
	$clone.attr('rel', 'disabled');

    if (browser_info.ie6) {
	if ($clone.hasClass('button-20-green-forward'))
	    $clone.addClass('button-20-disabled-forward');
	else if ($clone.hasClass('button-24-green-forward'))
	    $clone.addClass('button-24-disabled-forward');
	else if ($clone.hasClass('button-20-orange-back'))
	    $clone.addClass('button-20-disabled-back');
	else if ($clone.hasClass('button-24-orange-back'))
	    $clone.addClass('button-24-disabled-back');
	else if ($clone.hasClass('button-20'))
	    $clone.addClass('button-20-disabled');
	else if ($clone.hasClass('button-24'))
	    $clone.addClass('button-24-disabled');
    }            
            
    $button.replaceWith($clone);
}
/* enable .button-20 | .button-24 */
function button_enable($button)
{
    if (!$button.hasClass('button-20') && !$button.hasClass('button-24'))
	return;
            
    var $clone = $button.clone();
    if ($clone.is('button'))
	$clone.removeAttr('disabled');
    else if ($clone.is('a'))
	$clone.removeAttr('rel');
	
    if (browser_info.ie6)
	$clone.removeClass('button-20-disabled button-20-disabled-forward button-20-disabled-back button-24-disabled button-24-disabled-forward button-24-disabled-back');
	                
    $button.replaceWith($clone);
}
/* google translate очень вольно обращается с dom, для кнопок это критично */
function buttons_antiGoogleTranslate()
{
    if (!$('.google-src-text').length)
    	return; // no google detected

    $('.button-18, .button-20, .button-24, .button-40').each(function(){
    	var label = $(this).text();
    	$(this).html('<b title="' + label + '">' + label + '</b>');
    });
}
/*** / buttons ***/


/* stop event */
function stopEvent(e){if(e.preventDefault){e.preventDefault();e.stopPropagation();}else{e.returnValue=false;e.cancelBubble=true;}return false;}

;(function($) {

    // cleartype fix for IE
    $.fn.clearTypeFix = function() {
        return $.browser.msie ? this.each(function() {
            if (this.style.filter != 'undefined' &&
                this.style.removeAttribute)
                this.style.removeAttribute('filter');
        }) : undefined;
    };

// popup hiding on outer click 
// example: $('a').click(function(e){
// 	$('#popup').show().hideOnOuterClick(e, {
//		hide: function(){ $(this).slideUp(300); }
//	});
// });
; (function($) {
    $.fn.hideOnOuterClick = function(event, callback) {
	if (typeof event !== 'undefined' && event !== null)
    		stopEvent(event);
	
	var Hider = function(popup) {    		
		var self = this;
		
		this.ignore = '.ui-datepicker';
		
		this.settings = {
			callback: function(){ }, // функция, вызываемая перед закрытием. this == $popup
			ignore: '',              // селекторы элементов, клик по которым не должен скрывать попап, через запятую
			hide: function(){ $(this).hide(); } // анимация скрытия. this == $popup    
		}
		
		this.$popup = $(popup);
		
		this.hide = function() {
			self.settings.callback.apply(self.$popup);
                	self.$popup.hasClass('wpopup')
				? self.close_wpopup()
				: self.settings.hide.apply(self.$popup);
                	self.off();
            	};
		
		this.check = function(e) {
			var $target = e.target;
			var $ignore = self.$popup.find('*').andSelf();
			
			if (self.ignore.length)
				$ignore = $ignore.add($(self.ignore).find('*').andSelf());
			
			if (self.settings.ignore.length)
				$ignore = $ignore.add($(self.settings.ignore).find('*').andSelf());
			
			if ($.inArray($target, $ignore) < 0) {
				self.hide();
			}
		};
		
		this.blur = function(e) {
			self.check(e);
		};

		this.on = function() {
			$(document).bind('click', self.blur);
		};

		this.off = function() {
			$(document).unbind('click', self.blur);
		};
			
		this.close_wpopup = function(){
			self.$popup.css({
				left: -10000,
				top: -10000
			}).removeClass('wpopup-visible');
		};
		
		if (typeof callback == 'function')
                    this.settings.callback = callback;	
	    };
	        
	return this.each(function() {
	    var hider = new Hider(this);
	    
	    if (typeof callback == 'object')
	    	hider.settings = $.extend(hider.settings, callback);
    	     	
	    if (!$(this).is(':visible')) {
		hider.off();
		return;
	    }
	
	    hider.on();
        });
    };
})(jQuery);

    // Based off of the plugin by Clint Helfers, with permission.
    // http://blindsignals.com/index.php/2009/07/jquery-delay/
    if(!$.fn.delay)
    $.fn.delay = function( time, type ) {
        time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
        type = type || "fx";
      
        return this.queue( type, function() {
          var elem = this;
          setTimeout(function() {
            jQuery.dequeue( elem, type );
          }, time );
        });
    };

    /**
    * hoverIntent is similar to jQuery's built-in "hover" function except that
    * instead of firing the onMouseOver event immediately, hoverIntent checks
    * to see if the user's mouse has slowed down (beneath the sensitivity
    * threshold) before firing the onMouseOver event.
    * 
    * hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
    * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
    * 
    * hoverIntent is currently available for use in all personal or commercial 
    * projects under both MIT and GPL licenses. This means that you can choose 
    * the license that best suits your project, and use it accordingly.
    * 
    * // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
    * $("ul li").hoverIntent( showNav , hideNav );
    * 
    * // advanced usage receives configuration object only
    * $("ul li").hoverIntent({
    *   sensitivity: 7,  // number = sensitivity threshold (must be 1 or higher)
    *   interval: 100,   // number = milliseconds of polling interval
    *   over: showNav,   // function = onMouseOver callback (required)
    *   timeout: 0,      // number = milliseconds delay before onMouseOut function call
    *   out: hideNav     // function = onMouseOut callback (required)
    * });
    * 
    * @param  f  onMouseOver function || An object with configuration options
    * @param  g  onMouseOut function  || Nothing (use configuration options object)
    * @author    Brian Cherne brian(at)cherne(dot)net
    */
    $.fn.hoverIntent = function(f,g) {
        // default configuration options
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        // override configuration options with user supplied object
        cfg = $.extend(cfg, g ? { over: f, out: g } : f );

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev,ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
                $(ob).unbind("mousemove",track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob,[ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
                return undefined;
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev,ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob,[ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = jQuery.extend({},e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // if e.type == "mouseenter"
            if (e.type == "mouseenter") {
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $(ob).bind("mousemove",track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

            // else e.type == "mouseleave"
            } else {
                // unbind expensive mousemove event
                $(ob).unbind("mousemove",track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
            }
        };

        // bind the function to the two event listeners
        return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
    };
})(jQuery);

// <select> to .double_border dropdown 
;(function($) {
	$.fn.dropdowns = function() {
		return this.each(function(){
			if (!$(this).is('select'))
				return;
			var select = '<div class="dropdown double_border"><div class="current"></div><ul>';
			var current = '';
			$('option', this).each(function(){
				if ($(this).attr('selected'))
					current = $(this).text();
				select += '<li class="'+$(this).attr('value')+'">'+$(this).text()+'</li>';
			});
			select += '</ul></div>';
			$(this).before(select).hide();
			var $select = $(this);
			var $dropdown    = $(this).prev('.dropdown');
			var $dropdown_ul =  $('ul', $dropdown); 
			var dropdown_width = $dropdown_ul.width();
			$dropdown_ul.addClass('set').show(2).hide(1).clearTypeFix(); // oh ie
	
			$dropdown.width(dropdown_width).find('.current').text(current).end()
			.click(function(e){
				stopEvent(e);
				$dropdown_ul.toggle().hideOnOuterClick();
				
				if (typeof promo_stop == 'function')
					promo_stop();
					
			}).find('li').click(function(){
				$('.current', $dropdown).text($(this).text());	
				$select.val($(this).attr('class'));
			});
		});
	};
	
	$.fn.undropdowns = function() {
		return this.each(function(){
			$(this).prev('.dropdown').click().remove();
			$(this).show();
		});
	};
})(jQuery);

// fixing font size, so "zoom text only" doesnt break layout
var fix_interval = null;
var widefont = false;
var EM = 12;

$(function(){
    fix_fontsize_init('12px/12px Tahoma, "DejaVu Sans", Geneva, sans-serif', 12);
    check_fontname();
});

function fix_fontsize_init(font, expectedSize, $fix)
{
    if (typeof font == 'undefined' || font == '')
        font = 'normal 16px/16px Arial, sans-serif';
    if (typeof expectedSize == 'undefined' || expectedSize == 0)
        expectedSize = 16;
    if (typeof $fix == 'undefined' || !$fix.length)
        $fix = $('body');

    $fix.prepend('<div id="fontsize_tester">A</div>');

    var $tester = $('#fontsize_tester');
    var $topmenu = $('#header_top .submenu div').eq(0);

    $tester.css({
        font:        font,
        position:   'absolute',
        left:       '-999em'
    });

    _fix_fontsize(expectedSize, $fix, $tester, $topmenu);

    fix_interval = setInterval(function(){
        _fix_fontsize(expectedSize, $fix, $tester, $topmenu);
    }, 1000);
}

function _fix_fontsize(expectedSize, $fix, $tester, $topmenu)
{
    if (!$.browser.opera && !$.browser.safari && !$.browser.msie) {
	var size = Math.round(expectedSize * expectedSize / $tester.height());
	$fix.css({ fontSize: size + 'px' });
    }

    EM = $tester.height();
}

function check_fontname()
{
    var testsize = '4em';
    var tstr = 'абвгдеёжзийклмнопрстуфхцчшщъыьэяю';

    $('body').append('<div id="__fonttable_tester__"></div>');
    var $tester = $('#__fonttable_tester__');

    $tester.css({
        position: 'absolute',
        top: 0,
        left: '-9999em',
        visibility: 'hidden',
        whiteSpace: 'nowrap',
        fontSize: testsize,
        lineHeight: testsize,
        letterSpacing: 'normal',
        fontWeight: 'normal',
        fontStyle: 'normal',
        height: testsize
    });

    $tester.text(tstr);

    var koeff = $tester.width() / tstr.length / $tester.height();

    $tester.remove();

    if ( koeff >= 0.15 ) {
	widefont = true;

        //if ( $('#header_top #lang').hasClass('ru') ) {
		    $('body').addClass('widefont');
		   /* $('.sidebar-banner #supporten')
				.attr('src','/i/intinfo/supportw_en.jpg');
		    $('.sidebar-banner #supportru')
				.attr('src','/i/intinfo/supportw_ru.jpg');*/
		    $('.sidebar-banner #nitiken')
				.attr('src','/i/intinfo/nitik_bookw_en.jpg');
		    $('.sidebar-banner #nitikru')
				.attr('src','/i/intinfo/nitik_bookw_ru.jpg');
		    $('.sidebar-banner #office_b')
				.attr('src','/i/intinfo/company_contacts.jpg');
		//}
    }

    /*if (widefont)
	   $.cookie('widefont', koeff, {expires: 365, path: '/'}); // 1 year
	else
	   $.cookie('widefont', null, {path: '/'}); // delete cookie*/
}

/*
 * Cookie plugin
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses.
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toGMTString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toGMTString();}var path=options.path?'; path='+options.path:'';var domain=options.domain?'; domain='+options.domain:'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};



// index promo block
var promo_changing = false;
var promo_slide_timing = 300;

$(function(){
	// ie6 pngfix init
	if ($.ifixpng) {
		$.ifixpng('/i/blank.gif');
		$('img[src$=.png]', '#promo .selector').ifixpng();
		$('.promo', '#promo').css({zoom: 1});
	}

	$('.promo-dname select').dropdowns();
	$('.promo-dname-2 select').dropdowns();

	$('a', '#promo .selector').click(function(){
		if (promo_changing)
			return false;

		var $li = $(this).parents('li');
		if ($li.hasClass('active'))
			return false;

		promo_slide($li);

		return false;
	});

	$('input, select', '#promo').focus(function(){
		$(this).addClass('focus');
	}).blur(function(){
		$(this).removeClass('focus');
	});

        if ($.cookie('promo_slide')) {
                $('a[href="' + $.cookie('promo_slide') + '"]', '#promo .selector').click();
        }
});

function promo_slide($li)
{
	if (promo_changing)
		return false;

	if (!$li.length)
		return false;

	var id = $('a', $li).attr('href');

	var $prev = $('.promo.active', '#promo');
	if ($prev.attr('id') == id)
		return false;

	var $cur = $(id, '#promo');
	if (!$cur.length)
		return false;

	promo_changing = true;

	var $active = $('li.active', '#promo .selector');

        $active.removeClass('active');
	$li.addClass('active');

        $.cookie('promo_slide', id);

	$cur.css({
		left: 0,
		opacity: 0,
		display: 'block'
	}).animate({
		opacity: 1
	}, promo_slide_timing, function(){
		$(this).clearTypeFix();
	});

	$prev.animate({
		opacity: 0
	}, promo_slide_timing, function(){
		$prev.removeClass('active').hide();
		$cur.addClass('active');
		promo_changing = false;
	});
}

// Возвращает позицию курсора в поле ввода
new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var input = $(this).get(0);
        // IE Support
        if (document.selection) {
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            pos = sel.text.length - selLen;
        }
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionStart;

        return pos || 0;
    }
} (jQuery);

// Возвращает favicon после изменения url hash
function reset_favicon() {
    var link = $('link[rel="shortcut icon"]').remove().attr("href");
    $('<link href="'+ link +'" rel="shortcut icon" type="image/ico" />').appendTo('head');
}

// Привязываем к текстовому полю autocomplete по премиум-доменам (использует jquery ui autocomplete)
function bind_autocomplete_in_premiums(input_obj, zones_obj) {
    // включаем локальное кеширование запросов
    var ac_cache = {};
    
    function split( val ) {
	return val.split( /\s+/ );
    }

    // Возвращает слово из указанной строки, в котором в данный момент находится курсор, либо последнее слово
    function extract_current( term ) {
	var pos = input_obj.getCursorPosition();

	if ( pos ) {
	    // Обрезаем строку по правой границе слова на котором стоит курсор
	    var space_pos = term.indexOf(' ', pos);
	    var ret_pos = term.indexOf("\n", pos); // перенос строки тоже разделитель
	    if (ret_pos != -1 && ( space_pos == -1 || ret_pos < space_pos ))
		space_pos = ret_pos;	    
	    
	    if ( space_pos != -1 )
		term = term.substring(0, space_pos);
	}
	    
	return split( term ).pop();
    }

    input_obj.autocomplete({
	delay : 500,
	source: function( request, response ) {
	    var term = extract_current(request.term);
	    if ( term in ac_cache ) {
		response( ac_cache[term] );
		return;
	    }
	    
	    // если указан элемент выбора зоны, берем зону из него, иначе определяем автоматически на сервере
	    var tld = zones_obj && zones_obj.size() ? zones_obj.val() : '';
	    
	    if ( tld ) {
		switch(tld) {
		    case 'tld_ru':
			tld = 'ru';
			break;
		    case 'tld_su':
			tld = 'su';
			break;
		    case 'tld_рф':
			tld = 'рф';
			break;
		    default:
			tld = '';
		}
	    }

	    // запускаем быстрый поиск по префиксу - быстро показать пользователю варианты
	    $.getJSON( '/api/regru2/domain/get_premium_variants', {
		    search : term,
		    tld : tld
		}, function( data, status ) {
		    ac_cache[term] = data.list;
		    if ( extract_current(input_obj.val()) == term ) // проверяем соответствие запроса и ответа
			response( data.list );
		}
	    );

	    // параллельно запускаем долгий поиск по подстроке (включает варианты по префиксу)
	    $.getJSON( '/api/regru2/domain/get_premium_variants', {
		    search : term,
		    search_substring : 1,
		    tld : tld
		}, function( data, status ) {
		    ac_cache[term] = data.list;
		    if ( extract_current(input_obj.val()) == term ) // проверяем соответствие запроса и ответа
			response( data.list );
		}
	    );
	},
	focus: function() {
	    // prevent value inserted on focus
	    return false;
	},
	search: function() {
	    // custom minLength
	    var term = extract_current( this.value );
	    if ( term.length < 3 ) {
		return false;
	    }
	}
    })    
    // перекрываем дефолтный рендерер меню (чтобы показать заголовки в меню и html разметку)
    .data( 'autocomplete' )._renderMenu = function( ul, items ) {
	var self = this;

	$('<a id="ac_premiums_close" href="#" title="Закрыть список вариантов">Скрыть</a>')
	 .click(function () {
	    input_obj.autocomplete('close');
	    return false;
	 })
	 .appendTo(ul);
	
	$('<li id="ac_premiums_h"><h1>Автоматические варианты</h1></li>').appendTo(ul);
	 
	$('<div id="ac_premiums_show_all"><a href="/newdomain/suggest-variants#search=' + extract_current(input_obj.val()) + '">Посмотреть все...</a></div>').appendTo( ul );
	
	$.each( items, function( index, item ) {
	    return $( '<li></li>' )
	     .data( 'item.autocomplete', item )
	     .append( '<a>' + item.label + '</a>' )
	     .appendTo( ul );
	});
    };   
    
    // в textarea выбранный вариант добавляем в конец списка
    if (input_obj.is('textarea')) {
	input_obj.bind( 'autocompleteselect', function( event, ui ) {
	    var curr = extract_current( this.value );
	    var terms = split( this.value );

	    var new_terms = [];
	    for (i in terms) {
		if (terms[i] == curr)
		    // remove the current input
		    // add the selected item
		    new_terms.push(ui.item.value);
		else
		    new_terms.push(terms[i]);
	    }
	    
	    this.value = new_terms.join( ' ' ) + ' ';
	    return false;
	});
    }
}

// Вычисляет ширину блока
$.fn.calculate_width = function(){
    var sensor = $('<div />').css({margin: 0, padding: 0});
    $(this).append(sensor);
    var width = sensor.width();
    sensor.remove();
    return width;
};

// Окно MessageBox 
function message_box(message, options) {

    if(!$.message_box) {
        $.message_box = {
            visibled_count: 0
        };
    }

    this.buttons = [];
    var self = this;

    var default_options = {
        button_class: "button-20 button-green"
    };

    this.on_keypress_handler = function(event) {
        
    };

    var Button = function(options) {
        $.extend(this, options);
        var $text = $("<b>").text(this.text || "Button");
        if(this.width) $text.css("width", this.width);
        this.$button = $("<button>").append($text).appendTo('<td style="padding: 0 3px 0 3px">');
        this.container = this.$button.parent();
        if(this.classes) this.$button.addClass(this.classes);
        if(this.click) this.$button.bind('click', { window: self }, this.click );
        if(this.id) this.$button.attr("id", this.id);
        self.buttons.push(this);
    };

    var Expander = function(options) {
        $.extend(this, options);
        var width = this.width ? this.width : "100%";
        this.container = $('<td>').css('width', width);
    };

    this.options = $.extend(default_options, options);

    if (!$.message_box.overlay) {
        $.message_box.overlay = $('<div id="message_box_overlay" class="message_box_block_bg" style="display: none;">').appendTo(document.body);
    }

    var $window = $('<div class="message_box_to_hide" style="display: none;">').jqoteapp('#message_block_template', {
        title: this.options.title || "",
        content: message
    }).attr( {
        id: 'hide_message_box'
    }).appendTo(document.body);

    var $table = $('<table border="0" cellspacing="0" cellpadding="0" width="100%"></table>');
    var $buttons_container = $('<tr></tr>').appendTo($table);
    $(".message_box-btn", $window).append($table);

    if(this.options.buttons) {
        $.each(this.options.buttons, function(index) {
            var button;
            if(this.type === "expander") {
                button = new Expander(this);
            }
            else {
                button = new Button(this);
                if (button) button.$button.focus();
            }
            if (button) $buttons_container.append( button.container );
        });
    }
    else {
        $buttons_container.append( new Expander(this).container );
        $buttons_container.append( new Button({
            text: "OK",
            width: "50px",
            classes: this.options.button_class,
            default_button: 1,
            click: function() {
                self.hide();
            }
        }).container);
    }

    this.show = function() {
        $.message_box.visibled_count++;
        $.message_box.overlay.show();
        $window.show();
        $buttons_container.find('button:first').focus();
    };
    
    this.hide = function() {
        $('body').unbind('keypress');
        $window.remove();

        $.message_box.visibled_count--;
        if ( $.message_box.visibled_count <= 0 ) {
            $.message_box.visibled_count = 0;
            $.message_box.overlay.hide();
        }
    };
}

window.glamor_alert = function(message, callback) {
    if(!message) return;

    this.callback = $.extend({
        ok : function(event) {
            event.data.window.hide();
        }
    }, callback);

    new message_box(message, {
        title: "ВНИМАНИЕ",
        buttons: [
            {
              type: "expander"
            },
            {
              text: "OK",
              width: "50px",
              classes: "button-20 button-green",
              default_button: true,
              click: this.callback.ok
            }
        ]
    }).show();
}

window.glamor_confirm = function(message, callback) {
    if(!message) return;

    this.callback = $.extend({
        ok : function(event) {
            event.data.window.hide();
        },
        cancel : function(event) {
            event.data.window.hide();
        }
    }, callback);

    new message_box(message, {
        title: "ПОДТВЕРЖДЕНИЕ",
        buttons: [
            {
              type: "expander"
            },
            {
              text: "OK",
              width: "50px",
              classes: "button-20 button-green",
              default_button: true,
              click: this.callback.ok
            },
            {
              text: "Отмена",
              classes: "button-20 button-red",
              cancel_button: true,
              click: this.callback.cancel
            }
        ]
    }).show();
}


/* .wpopup */
$(function(){
        var wpopup_zindex = 800;
        $('.wpopup-toggle').click(function(){
				var reg = /^#/;
				if(reg.test($(this).attr('href'))){
					var $popup = $($(this).attr('href'));
				} else {
					var $popup = $($(this).attr('rel'));
				}

                $popup.hideOnOuterClick();
                
                if ($popup.hasClass('wpopup-visible')) {
                        $popup.css({
                                left: -10000,
                                top: -10000
                        }).removeClass('wpopup-visible');
                        wpopup_zindex--;
                } else {
                    wpopup_zindex++;
                    
                    if ($(this).hasClass('wpopup-show-single')) {
                        $('.wpopup-visible').each(function(){
                                wpopup_zindex--;
                                $(this).css({
                                        left: -10000,
                                        top: -10000
                                }).removeClass('wpopup-visible');
                        });
                    }
                    
                    $popup.css({
                            left: '50%',
                            top: Math.max(0, $(window).scrollTop() + Math.max(0, (($(window).height() - $popup.outerHeight()) / 2))) - $('#wrapper-content').offset().top,
                            margin: '0 0 0 -' + Math.round($popup.outerWidth() / 2) + 'px',
                            zIndex: wpopup_zindex
                    }).addClass('wpopup-visible');
                }
                return false;
        });
        
        $('.wpopup a.close').click(function(){
                $(this).parent('.wpopup-visible').removeClass('wpopup-visible').css({
                        left: -10000,
                        top: -10000
                });
                return false;
        });
});

// zone_manager
$(document).ready(function(){
		$('table.rrs_table tr:even').addClass('color_cell');
		$('ul.service_list h4').bind('click', function(){
				if ($(this).parent().children('div.glamor_block_content').is(':visible')) {
					$(this).removeClass('show_icon').addClass('hide_icon').parent().children('div.glamor_block_content').hide();
				} else {
					$(this).removeClass('hide_icon').addClass('show_icon').parent().children('div.glamor_block_content').show();
				}
				return false;
		});

		$('#domen_operations a').click(function(){
				var name = $(this).attr('href');
				name = 'a[name = ' + name.slice(1) + ']';
				$('ul.service_list').find(name).next('h4').removeClass('hide_icon').addClass('show_icon').parent().children('div').show();
		});

		$('div.rrs_wrap a.edit_but').click(function(){
				var value_list = [];
				var $tr = $(this).parents('tr');
				var address = $.trim($tr.find('td.address').attr('abbr')).split(' ');
				$tr.find('td').slice(0,3).each(function(){
					if ($(this).hasClass('prio')){
						if ($(this).text().length > 0) value_list.push($.trim($(this).attr('abbr')))
					} else {value_list.push($.trim($(this).attr('abbr')));}
				});
				if (value_list[1] == 'TXT') address = $tr.find('td.address').attr('abbr'); 
				value_list = value_list.concat(address);
								
				var filter = 'a[name = ' + value_list[1]+ ']';
				$form = $('ul.service_list').find(filter.toLowerCase()).nextAll().find('div.add_record_form').clone();
				
				if (value_list[1] == 'SRV') {
					$form.find('tr').slice(3).remove().end().end().find('strong').remove();
				} else {
					$form.find('tr').slice(2).remove().end().end().find('strong').remove();
				};
				$('#edit_RRs_record').find('div.add_record_form').remove().end().find('h3.rust').after($form);
				if (value_list[1] == 'MX') {
					$('#edit_RRs_record').find('div.add_record_form select').val(value_list[2]).end().find('h3.rust span').text(value_list[1]);
					value_list.splice(1,2);
					$('input:text','#edit_RRs_record').each(function(i,a){
						$(this).val(value_list[i]);
					})				
				} else if(value_list[1] == 'NS'){
					$('#edit_RRs_record').find('h3.rust span').text(value_list[1]);
					value_list.splice(1,1);
					$('input:text','#edit_RRs_record').eq(0).val(value_list[0])
						.end().eq(1).val(value_list[2])
						.end().eq(2).val(value_list[1]);
				} else {
					$('#edit_RRs_record').find('h3.rust span').text(value_list[1]);
					value_list.splice(1,1);
					$('input:text','#edit_RRs_record').each(function(i,a){
						$(this).val(value_list[i]);
					})				
				};
				$('#edit_RRs_record').find('input[name = action]').filter('[value != editrr]').remove();
				var reg = /(.*)_(\d+)/;
				$form.find('table').find('input, select').each(function(){
					var name = $(this).attr('name');
					name = name.replace(reg, "$1");
					name = name.replace('rr_','');
					$(this).attr('name',name).after('<input type="hidden" name="old_rr_' + name + '" value="' + $(this).val() + '">');
				})
				$(document).one('keydown', function(e) {
					if (e.which == 27) {
						$('#edit_RRs_record a.close').click();
					}
				});								
		});
		
		$('div.add_record_form .add_field').click(function(){
			var reg = /(.*)_(\d+)/;
			var index = $(this).parents('tr').prev().find('input, select').eq(0).attr('name');
			index = parseInt(index.replace(reg, "$2"))+1;
			if ($(this).attr('name') == 'add_srv') {
				var $new_fields = $(this).parents('table').find('tr').slice(-4, -1).clone();
			} else {
				var $new_fields = $(this).parents('tr').prev().clone();
			}
			$new_fields.find('input, select').each(function(){
			    var name = $(this).attr('name');
				name = name.replace(reg, "$1") +"_" + index;
                $(this).attr('name',name);
			});
			$new_fields.find('input').val('');
			$(this).parents('tr').before($new_fields);
			return false;
		});	
});

//поиск в top line
$(function(){
	var $search = $('#header_top .search'),
	search_blur = function(e){
		var curElements = $search.find('*').andSelf();
		if ($.inArray(e.target, curElements) < 0) {
			$search.removeClass('search-focused');
			$(document).unbind('click', search_blur);
		}
	};
	$('#header_top .search .query input').focus(function(){
		$search.addClass('search-focused');
		$(document).bind('click', search_blur);
		if ($(this).val() == $(this).attr('title'))
			$(this).val('');
	}).blur(function(){
		
		if ($(this).val().replace(/\s/g, '') == '')
			$(this).val($(this).attr('title'));
	}).blur();

	$('#top_search_form').submit( function() {
	    var categories_str = '';
	    $('#top_search_form input.search_categories').each(function() {
		if ( $(this).is(':checked') ) {
		    categories_str += $(this).val() + ';';
		}
	    });
	    $('#top_search_form #categories_for_yasearch').val(categories_str);
	    return true;
	});

	$('div.bg input.search_categories').click(function() {
	    if ( $(this).val() == 'all' ) {
		$('div.bg input.search_categories').removeAttr('checked');
		$('#cat_all').attr('checked', 'checked');
	    }
	    else {
		$('#cat_all').removeAttr('checked');
	    }
	});
});

// OpenID
function openOpenidPopup(name, ident, text, img) {
    var $popup = $('#openid-popup');

    if ( name == 'Mail.ru' )
       $popup.find('.what-enter').text('Вашу почту'); 
    else if ( name == 'OpenID' )
       $popup.find('.what-enter').text('Ваш'); 
    else
       $popup.find('.what-enter').text('Ваш логин');


    $popup.find('input[name=openid_ident]').val(ident);
    $popup.find('#openid-popup-text').text(text);

    $popup.find('input[name=username]').val('');

    $popup.find('#openid-popup-icon').attr('src', img);
    $popup.find('#openid-popup-provider-name').text(name);

    $('#more_providers').hide();
    $popup.show();
}
$(function(){
    $('#show_login_openID').click(function(){
        var $link = $(this);
        var pos = $link.offset();
        var x = pos.left;
        var y = pos.top + 22;
        $('#login_openID').css({
            left: x,
            top: y
        });
    });
    $('#openid-popup form').submit(function() {
        var ident = $(this).find('input[name=openid_ident]').val();
        var username = $(this).find('input[name=username]').val();
        var name = $(this).find('#openid-popup-provider-name').text();
        if ( name == 'Mail.ru' ) {
            var parts = username.split('@');
            ident = ident.replace(/USERNAME/, parts[0]);
            ident = ident.replace(/DOMAIN/, parts[1]);
        }
        else if ( name == 'OpenID' ) {
            ident = username;
        }
        else {
            ident = ident.replace(/USERNAME/, username);
        }
        $(this).find('input[name=openid_ident]').val(ident);
        console.debug(ident);
    });
});

function otrs_open() {
    open("/user/support", "displayWindow", "width=800,height=600,scrollbars=yes");
}

/* END jquery/jquery-regru.js */


/* BEGIN messages.js */

function jq_hide (element_id) {
    var $jq = jQuery;
    $jq(element_id).hide();
}

function toggle_checkbox_messages (messages_div_id) {
    var $jq = jQuery;

    $jq(document).ready(function() {
        //alert('DIV ID=' + messages_div_id);
        var new_attr = $jq(messages_div_id).find('#multi_checkbox').attr("checked") ? "checked" : "";
	//alert('XXX new attr=' + new_attr);
        $jq(messages_div_id).find('#multi_checkbox').attr("checked", new_attr);
        
        $jq(messages_div_id + ' input:enabled[type=checkbox]:not(#multi_checkbox)').each(function() {
            $jq(this).attr("checked", new_attr);
        });
    });
    
}

function set_force_refresh_page() {
    $('#new_messages_refresh_form input[name="force_refresh"]').attr('value', 1);
    
    return true;
}

function submit_message( messages_div_id, status, process_result, hide_layer_name, hide_layer_number, skip_checkbox_check, on_success_show_div, message_id ) {
    var $jq = jQuery;
    
    $jq(document).ready(function() {

	var message_processed = 0;
	var message_debug = false;

	if (message_debug) {
	    console.log('messages_div_id: '+messages_div_id);
	}

	if (!message_id) {
	    var checkbox = $jq("#terms_accepted_" + hide_layer_number);
	    
	    if ( (! checkbox.attr("checked") && process_result == 'accepted') && !skip_checkbox_check )  {
			alert( 'Вы должны согласится с условиями Договора-Оферты!' );
		return false;
	    }
	    
	    var all_checkbox_number = $jq(messages_div_id + ' input[type=checkbox]:not(#multi_checkbox)').length;
	    if (message_debug) {
			console.log( 'ALL CHECKBOX NUM:' + all_checkbox_number );
	    }
	    
	    var checked_service_ids = $jq(messages_div_id + ' input[type=checkbox]:checked:not(#multi_checkbox)');
	    if (message_debug) {
			console.log( 'all cheked_num: ' + checked_service_ids.length );
	    }
	    
	    var checked_enabled_service_ids = $jq(messages_div_id + ' input:enabled[type=checkbox]:checked:not(#multi_checkbox)');
	    if (message_debug) {
			console.log( 'enabled cheked_num: ' + checked_enabled_service_ids.length );
	    }

	    if (!checked_enabled_service_ids.length && status != 'delayed') {
			alert ('Вы должны выбрать как минимум 1 домен!');
			return false;
	    }
	    
	    var message_ids = [];

        if ( status != 'delayed' ) {
			checked_enabled_service_ids.each(function() {
				$jq(this).attr("disabled","disabled");
        	    var message_id = $jq(this).attr("name");
	
				if (message_id) message_ids.push( message_id );
        	});
		}
		else {
			// Ищем все отложенные сообщения
            var delayed_service_ids = $jq(messages_div_id + ' input[type=checkbox]:enabled:not(#multi_checkbox)');
			delayed_service_ids.each(function() {
				var message_id = $jq(this).attr("name");
        
                if (message_id) message_ids.push( message_id );

			});

			message_processed = 1;
		}


		if( message_ids.length > 0 ) $jq.ajax({
			url: '/user/process_messages?ids=' + message_ids.join(' ') + '&status=' + status + '&process_result=' + process_result,
			async: false,
			success: function(msg) {
				if ( msg == 'ok' ) {}
				else {
					alert ('Ошибка при обращении к  БД'); return false;
				};
			}
	    });

	    // WHY??? message_processed = 1;

	    var disabled_service_ids = $jq(messages_div_id + ' input[type=checkbox]:disabled:not(#multi_checkbox)');
	    if (message_debug) {
			alert ('disabled: ' + disabled_service_ids.length);
	    }
	}
	else {
	    $jq.ajax({
		url: '/user/process_message?id=' + message_id + '&status=' + status + '&process_result=' + process_result,
		async: false,
		success: function(msg) {
		    if ( msg == 'ok' ) {}
		    else {
				alert ('Ошибка при обращении к  БД'); return false;
		    };
		}
	    });
	    message_processed = 1;
	}
	
	if ( message_processed || (checked_service_ids.length == disabled_service_ids.length &&
	    disabled_service_ids.length == all_checkbox_number) ) {
	    // Типа по всеми сервисами разобрались
	    // Показываем следующее новое сообщение
	    //alert('ALL PROCESSED!');
	    $jq(hide_layer_name + hide_layer_number).remove();
	    show_layer_number = hide_layer_number - 1;
	    
	    if (show_layer_number < 1) { // нет больше сообщений
		if (on_success_show_div) { // временно запретил в темплейте, т.к. не перегружается страничка
		    $jq(on_success_show_div).show();
		} else {
            // В форме есть флаг force_refresh который указывает, делать рефреш страницы или нет. 
            if ( $jq('#new_messages_refresh_form input[name="force_refresh"]').attr('value') == 1 ) {
                document.refresh_page.submit(); // обновляем страницу
            }
		}
	    //window.location = '/user/domain_list?nocache=[% rand %]'; // обновляем страницу
	    } else {
			$jq(hide_layer_name + show_layer_number).show();
			message_box_block_bg_stretch();
	    }
	}
    });
    
    return true;
}

function jq_toggle_checkbox(selector1, selector2) {
    var $ = jQuery;
    
    $(document).ready(function() {

        //alert('curr attr=' + $(selector1).find(selector2).attr("checked"));
        
        $(selector1).find(selector2).attr("checked") ?
            $(selector1).find(selector2).attr("checked", "") :
            $(selector1).find(selector2).attr("checked", "checked");

        var new_attr = $(selector1).find(selector2).attr("checked") ? "checked" : "";
	//alert('new attr=' + new_attr);
        
        $(selector1 + ' input:enabled[type=checkbox]:not(#multi_checkbox)').each(function() {
            $(this).attr("checked", new_attr);
        });
        
    });

    
}

// stretching all .message_box_block_bg
function message_box_block_bg_stretch()
{
    var $bgs = $('.message_box_block_bg:visible');
    
    if (!$bgs.length) {
        $(window).unbind('resize', message_box_block_bg_stretch);
        return;
    } 
    
    $bgs.css({
        width: $('#wrapper').width(),
        height: $('#wrapper').height() 
    });

    var h = window.innerHeight - 250;
    if( isNaN(h) ) {
        // IE
        h = document.documentElement.clientHeight - 250;
    }

    var item_div = $('.message_box-item', $bgs)[0];
    var $item_div_container = $('.message_box-item-container', $bgs);

    $item_div_container.css('height', h);

    if(item_div.scrollHeight < h)
        h = item_div.scrollHeight;
    $item_div_container.css('max-height', h);
}

$(function(){
    var $bgs = $('.message_box_block_bg');
    if ($bgs.length) {
        message_box_block_bg_stretch();
        $(window).resize(message_box_block_bg_stretch);
    }
});

function mark_all_delayed () {
    $('div.message_box_to_hide input[name=message_id]').each(function(){
    
	if (/^\d+$/.test($(this).val())) {
	    message_id = $(this).val();

	    $.ajax({
		url: '/user/process_message?id=' + message_id + '&status=delayed&process_result=',
		async: false,
		success: function(msg) {
		    if ( msg == 'ok' ) {}
		    else {
			alert ('Ошибка при обращении к  БД'); return false;
		    };
		}
	    });
	}
    
    });
    
    $('div.message_box_to_hide').hide();
    document.refresh_page.submit(); // обновляем страницу
}


/* END messages.js */


/* BEGIN common.js */

function checkwhois( frm ) {
  dname = frm.domain_name.value;
  if (! dname)
    return false;

  return true;
}
function month( offset, lang ) {
    var month = new Array(12);
    if (lang == '/en') {
	month[-1+ offset] = "December";
	month[0+ offset] = "January";
	month[1+ offset] = "February";
	month[2+ offset] = "March";
	month[3+ offset] = "April";
	month[4+ offset] = "May";
	month[5+ offset] = "June";
	month[6+ offset] = "July";
	month[7+ offset] = "August";
	month[8+ offset] = "September";
	month[9+ offset] = "October";
	month[10+ offset] = "November";
	month[11+ offset] = "December";
    }
    else {
	month[-1+ offset] = "Декабрь";
	month[0+ offset] = "Январь";
	month[1+ offset] = "Февраль";
	month[2+ offset] = "Март";
	month[3+ offset] = "Апрель";
	month[4+ offset] = "Май";
	month[5+ offset] = "Июнь";
	month[6+ offset] = "Июль";
	month[7+ offset] = "Август";
	month[8+ offset] = "Сентябрь";
	month[9+ offset] = "Октябрь";
	month[10+ offset] = "Ноябрь";
	month[11+ offset] = "Декабрь";
    }
    return month;
}


function extPopUp( Url, Width, Height) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(Url, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=Width,height=Height');");
}

function extPopUpNoBars( Url, Width, Height) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(Url, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=Width,height=Height');");
}


function extPopUpIE(Url) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(Url, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1');");
}

function openwin( winname ) {
    window.open("/tlds_help/"+winname+".pl","littlehelp","toolbar=no,scrollbars=yes,width=360,height=450");
}

function openwin2( winname ) {
    window.alert('Регистрация в зоне "'+winname+'" ещё не начата на нашем сайте');
}

function openwin3( winname ) {
    window.alert('Регистрация в зоне "'+winname+'" приостановлена');
}

// Преобразует строку зон в список Input'ов со значениями
function generate_check_zones() {
    var zones = $('#zones_select').val();
    
    var zone = zones.split(' ');
    
    i = 0;
    while (i <= zone.length) {
	if (zone[i] && !zone[i].match(/_/)) {
	    $('#registration').prepend('<input type="hidden" name="group_code" value="'+zone[i]+'" />');
	}
	else {
	    if ( zone[i] != 'tld_рф') 
		$('#registration').prepend('<input type="hidden" name="'+zone[i]+'" checked="checked" value="" />');
	}
	i++;
    }
}

function change_check_zones(obj) {
    var state = $(obj).attr('checked');
    var name = $(obj).attr('name');
    //ставим или убираем галочки
    switch (name) {
	case 'sng_tlds':
	    changesng(state);
	    break;
	case 'popular_tlds':
	    changepopular(state);
	    break;
	case 'all_tlds':
	    changeall_page(state);
	    break;
    };
    //если галочку убрали, проставляем галочки, которые ещё стоят
    if (!state) {
	switch (name) {
	    case 'sng_tlds':
		if( $('#popular_tlds_').attr('checked') ) changepopular( true );
		if( $('#all_tlds_').attr('checked') ) changeall_page( true );
		break;
	    case 'popular_tlds':
		if( $('#sng_tlds_').attr('checked') ) changesng( true );
		if( $('#all_tlds_').attr('checked') ) changeall_page( true );
		break;
	    case 'all_tlds':
		if( $('#sng_tlds_').attr('checked') ) changesng( true );
		if( $('#popular_tlds_').attr('checked') ) changepopular( true );
		break;
	}
    }
}

function changesng( state ) {
    $('input.sng_tld').add('.sng_tlds').each( function() {
          $(this).attr('checked', state);
    });
}

function changepopular( state ) {
    $('input.main_tld').add('.popular_tlds').each( function() {
          $(this).attr('checked', state);//state.attr('checked'));
    });
}

function changeall_page( state ) {
    $('input[name^=tld_]:checkbox:enabled').add('.all_tlds').each( function() {
          $(this).attr('checked', state);
    });
}

function popUp_and_fill() {
    $("#all_domens").css("display", "block");
    $("iframe").css("display", "block");
    $('input[name=dname]').each( function() {
          $(this).attr('value',
          $('input#domain_name').attr('value'));
    });
}

function addEngine() {
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
    alert('Добавляем REG.Бар');
        window.sidebar.addSearchEngine(
            "http://www.reg.ru/docs/searchplugins/reg.ru.domain.src",
            "http://www.reg.ru/docs/searchplugins/reg.ru.domain.png",
            "REG.RU Whois",
            "Web");
    } else {
        alert("Sorry, you need a Mozilla-based browser (such as Firefox) to install a search plugin.");
    }
}

function checkall_disabled_availform( frm ) {
  for (var i = 0; i < frm.elements.length; i++) {
    var elem = frm.elements[i];
    var s4 = elem.name.substring(0, 4);
    if ( s4 == 'tld_' && !elem.disabled && elem.checked) {
      return false;
    }
  }
  return true;
}

function changeall_selections( frm, prefix, limit ) {
  //var frm = document.forms[2];
  var count = 0;
  var prefix_length = prefix.length;
  for (var i = 0; i < frm.elements.length; i++) {
    var elem = frm.elements[i];
    var start = elem.name.substring(0, prefix_length);
    if ( start == prefix && !elem.disabled ) {
      count++;
      if (count <= limit || !frm.select_all.checked) {
        elem.checked = frm.select_all.checked;
      } else if (count == limit + 1) {
        alert('Выделено только '+limit+' позиций! Массовая операция невозможна для более чем '+limit+' элементов.');
	return;
      }
    }
  }
}

function changeall_domainlist( frm ) {
  return changeall_selections( frm, 'service_', 1500);
}

function changeall_folderlist( frm ) {
  return changeall_selections( frm, 'folder_', 200);
}

function gotoifconf( question, url ) {
    if (confirm(question)) {
        location.href=url
    }
}

function gotoifconf_glamor( question, url ) {
    if(window.glamor_confirm) {
        glamor_confirm(question, {
            ok: function() {
                location.href=url;
            }
        });
    } else {
        gotoifconf( question, url );
    }
}

function gElByID ( id ) {
    return document.getElementById( id );
}

function validate_whois( frmname ) {
    var submitOK = true;

    frm = document.getElementById( frmname );

    if (frm.dname.value.length == 0) {
        submitOK = false;
    }

    if (submitOK) {
	var el = document.getElementById( 'progress' );
	el.style.display = 'block';
    }

    return submitOK;
}

// Проверить корректность указания объёкта RIPN
function validate_ripn_object( frmname ) {
    var frm = document.getElementById( frmname );
    var val = frm.registrar.value;

    if (val.length == null || val.length == 0) {
	frm.blur();
	frm.registrar.blur();
	document.getElementById('btn4').blur();
	alert( 'Не введено имя!' );
	return false;
    }
    else if ( ! val.match( /^\s*[-A-Z0-9]+(?:-[A-Z0-9]+)?-[A-Z0-9]+\s*$/i ) ) {
	frm.blur();
	frm.registrar.blur();
	document.getElementById('btn4').blur();
	alert( 'Неверное имя!' );
	return false;
    }

    var el = document.getElementById( 'progress' );
    el.style.display = 'block';

    return true;
}

function validate_regform( dname ) {
    var error_name = false;
    var submitOK = true;
    var dname = $('#' + dname).val();
    if (dname.length == 0) {
        submitOK = false;
    }

    //~ if (checkall_disabled_availform( frm ) && dname.search(/\./) == -1) {
	//~ error_name = true;
        //~ submitOK = false;
    //~ }
/*
    if (submitOK) {
	var el = document.getElementById( 'progress' );
	el.style.display = 'block';
    } else {
	if (error_name) {
	    alert('Пожалуйста, отметьте хотя бы одну доменную зону или укажите ее напрямую внутри имени (например: yourdomain.com).');
	} else {
	    alert('Пожалуйста, введите имя домена.');
	}
    }
*/

    if (!submitOK) {
	if (error_name) {
	    alert('Пожалуйста, отметьте хотя бы одну доменную зону или укажите ее напрямую внутри имени (например: yourdomain.com).');
	} else {
	    alert('Пожалуйста, введите имя домена.');
	}
    }

    return submitOK;
}

function validate_regform_domains_count( field_id, max_limit ) {
    var error_name = false;
    var submitOK = true;
    var domains = $('#' + field_id).val();

    var error_message = '';
    if (domains.replace(/[ ,;]/g, '').length == 0) {
        error_message = 'Пожалуйста, введите хотя бы одно имя домена для проверки.';
    }
    else if (domains.split(/[\s;,]+/).length > max_limit) {
        error_message = 'С помощью этой формы можно проверить не более ' + max_limit + ' доменов одновременно.';
    }

    if (error_message != '') {
        alert(error_message);
        return false;
    }
    else {
        return true;
    }
}

function hide_progress() {
    var progress = document.getElementById( 'progress' );
    progress.style.display = 'hidden';
}

function addZero(vNumber){
    return ((vNumber < 10) ? "0" : "") + vNumber
}

function formatDate(vDate, vFormat){
    var vDay              = addZero(vDate.getDate());
    var vMonth            = addZero(vDate.getMonth()+1);
    var vYearLong         = addZero(vDate.getFullYear());
    var vYearShort        = addZero(vDate.getFullYear().toString().substring(3,4));
    var vYear             = (vFormat.indexOf("yyyy")>-1?vYearLong:vYearShort)
    var vHour             = addZero(vDate.getHours());
    var vMinute           = addZero(vDate.getMinutes());
    var vSecond           = addZero(vDate.getSeconds());
    var vDateString       = vFormat.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear)
    vDateString           = vDateString.replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond)
    return vDateString
}

function nowdate( addmonths ) {
    var date = new Date;
    if (addmonths && addmonths != 0) {
	date.setMonth( date.getMonth() + addmonths );
    }
    return formatDate( date, 'yyyy-MM-dd' );
}

function nowdate_mstart() {
    return formatDate( new Date, 'yyyy-MM-01' );
}

function nowdate_mend() {
    return formatDate( new Date, 'yyyy-MM-31' );
}


// My Domains

function toggle_folders_for_all() {
    var sign = $('#folders_toggle_sign');
    var signs = $('a.folders_toggle_sign');

    if (sign.html() == '&gt;&gt;&gt;') {
      sign.html('&lt;&lt;&lt;');
      signs.html('&lt;&lt;&lt;');
      signs.hide();
      $('div.folders_for_service').show();
    }
    else {
      $('div.folders_for_service').hide();
      sign.html('&gt;&gt;&gt;');
      signs.html('&gt;&gt;&gt;');
      signs.show();
    }
}

function toggle_folders( service_id ) {
    var id = 'folders_for_'+service_id;

    var obj = $('#'+id);
    var sign = $('.folders_toggle_sign', obj);

    $('div.folders_for_service', obj).toggle();

    if (sign.html() == '&gt;&gt;&gt;') {
      sign.html('&lt;&lt;&lt;');
    }
    else {
      sign.html('&gt;&gt;&gt;');
    }
}

function toggle_nss_for_all() {
    var sign = $('#nss_toggle_sign');
    var signs = $('a.nss_toggle_sign');

    if (sign.html() == '&gt;&gt;&gt;') {
      sign.html('&lt;&lt;&lt;');
      signs.html('&lt;&lt;&lt;');
      signs.hide();
      $('div.nss_for_service').show();
    }
    else {
      $('div.nss_for_service').hide();
      sign.html('&gt;&gt;&gt;');
      signs.html('&gt;&gt;&gt;');
      signs.show();
    }
}

function toggle_nss( service_id ) {
    var id = 'nss_for_'+service_id;

    var obj = $('#'+id);
    var sign = $('.nss_toggle_sign', obj);

    $('div.nss_for_service', obj).toggle();

    if (sign.html() == '&gt;&gt;&gt;') {
      sign.html('&lt;&lt;&lt;');
    }
    else {
      sign.html('&gt;&gt;&gt;');
    }
}

function check_right_action() {
    var frm = document.domainlist;
    if ( frm.multi_action.options[ frm.multi_action.selectedIndex ].value == '' ) {
      alert('Действие не выбрано')
      return false;
    }

    var checked = $('input[name=service_ids]:checked', '#domainlist').length;

    if ( checked > 2000 ) {
      alert('Массовые действия невозможны для > 2000 доменов единовременно');
      return false;
    }

    if ( checked == 0 ) {
      alert('Домены не выбраны');
      return false;
    }

    var $multi_action_select = $('select[name="multi_action"]');
    if ( $multi_action_select.length == 1 ) {
        var action = $multi_action_select.val();
        if ( action == "private_flag_set" ) {
            $('#private_person_flag').attr('value', 1);
        }
        else if ( action == "private_flag_unset" ) {
            $('#private_person_flag').attr('value', 0);
        }
        else if ( action == "total_private_set" ) {
            $('#total_private_flag').attr('value', 1);
        }
        else if ( action == "total_private_unset" ) {
            $('#total_private_flag').attr('value', 0);
        }
        else if ( action == "parking_yandex_order" ) {
            $('#servtype').val('srv_parking_yandex');
        }
    }

    return true;
}

function toggle_date_filter() {
    var date_filter = $('#toggle_date_filter');
    date_filter.toggle();

    if (date_filter.css("display") == 'none') {
      //alert('hidden!');
      $('#toggle_date_filter input').attr('disabled', 'disabled');
    } else {
      $('#toggle_date_filter input').removeAttr('disabled');
    }
}

// jQuery based function to toggle block
function toggle_div_block(selector) {
    var obj = $(selector);
    obj.toggle();
}

// jQuery based function to show block
function jq_show_block(selector) {
    var obj = $(selector);
    obj.show();
}

// jQuery based function to hide block
function jq_hide_block(selector) {
    var obj = $(selector);
    obj.hide();
}

function disable_exp_or_cre_input_filter(filter_name, self) {
    var obj = "#" + filter_name + " input";

    if ( self.value == '') {
      $(obj).removeAttr('disabled');
    }
    else {
      $(obj).attr('disabled', 'disabled');
    }
}

function check_search_details( obj ) {
    if ( $('#misc_functions_id').css("display") == 'none' ) {
	$('#misc_functions_id > span > input').attr('disabled', 'disabled');
    }
    prepare_userpref_names( obj );
    return true;
}

function prepare_userpref_names( obj ) {
    var already_filtered_re = /^filters_/;

    $(".session_prefs input").
    add(".session_prefs textarea").
    add(".session_prefs select").each(
	function (i) {
	    var name = $(this).attr('name');
	    if (!already_filtered_re.test( name ) ) {
		$(this).attr('name', 'filters_' + name );
	    }
	    // alert( $(this).attr('name') );
	}
    );
}

function wish_toggle_anonymous() {
    $("#wish input:not(:radio, :checkbox, #valid, :image)").each(
	function( i ) {
	    if ( $(this).attr("disabled") == 1 ) {
	      $(this).attr("disabled", 0);
	    } else {
	      $(this).attr("disabled", 1);
	    }
	}
    );
}

function bind_default_value_for_input(elem_selector, default_value) {
    $(document).ready(function() {
        if (!default_value) {
            default_value = $(elem_selector).val(); // start value
	}

	$(elem_selector).focus(function () {
            $(this).click();
	});

        $(elem_selector).click(function () {
            if ( $(this).val() == default_value ) {
                $(this).val('');
            }
        });

        $(elem_selector).blur(function () {
            if($(this).val() == "") {
                $(this).val(default_value);
            }
        });

    });
}

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox')
            this.checked = false;
        else if (t == 'radio' && this.value == '')
            this.checked = true;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

function check_required( field ) {
    if (!field.checked) {
	window.alert('Услуга не может быть отменена!');
	field.checked = 1;
    }
}

String.prototype.space1k = function() {
    var reversed = '', nums = 1;
    var string = this.toString().replace(/[^0-9]/g, '');
    for (var i = string.length - 1; i >= 0; i--) {
        if (nums == 4) {
            reversed = ' ' + reversed;
            nums = 1;
        }
        reversed = string.substr(i, 1) + reversed;
        nums++;
    }
    return reversed;
}
Number.prototype.space1k = function() {
    return this.toString().space1k();
}


// проверка email на валидность
function check_email( value ) {
    return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,6}$/i).test( value );
}

// Эскейпим селекторы jQuery
function jq_id(id) { return '#' + jq_selector(id); }
function jq_selector(selector) { return selector.replace(/(:|\.)/g,'\\$1'); }

function align_popup_vertical(popup_id) {
  var wh = $(window).height();
  var rh = $('#'+popup_id).height();
  var top = (Math.floor((wh - rh) / 2) + $(window).scrollTop() - 110);
  if ( top < 5 ) { top = 10; }
  $('#'+popup_id).css('top', top + 'px');
}

// запрет загрузки сайта REG.RU во фрейме на стороннем сайте
if (top.location != location) top.location.href = location.href;

/* END common.js */


/* BEGIN keyboard.js */

function buildKeyboardInputs(){var self=this;this.VKI_version="1.4";this.VKI_target=this.VKI_visible="";this.VKI_shift=this.VKI_capslock=this.VKI_alternate=this.VKI_dead=false;this.VKI_deadkeysOn=false;this.VKI_kt="US";this.VKI_range=false;this.VKI_keyCenter=3;this.VKI_layout=new Object();this.VKI_layoutDDK=new Object();this.VKI_layout.Russian=[[["\u0451","\u0401"],["1","!"],["2",'"'],["3","\u2116"],["4",";"],["5","%"],["6",":"],["7","?"],["8","*"],["9","("],["0",")"],["-","_"],["=","+"],["Bksp","Bksp"]],[["Tab","Tab"],["\u0439","\u0419"],["\u0446","\u0426"],["\u0443","\u0423"],["\u043A","\u041A"],["\u0435","\u0415"],["\u043D","\u041D"],["\u0433","\u0413"],["\u0448","\u0428"],["\u0449","\u0429"],["\u0437","\u0417"],["\u0445","\u0425"],["\u044A","\u042A"],["Enter","Enter"]],[["Caps","Caps"],["\u0444","\u0424"],["\u044B","\u042B"],["\u0432","\u0412"],["\u0430","\u0410"],["\u043F","\u041F"],["\u0440","\u0420"],["\u043E","\u041E"],["\u043B","\u041B"],["\u0434","\u0414"],["\u0436","\u0416"],["\u044D","\u042D"],["\\","/"]],[["Shift","Shift"],["/","|"],["\u044F","\u042F"],["\u0447","\u0427"],["\u0441","\u0421"],["\u043C","\u041C"],["\u0438","\u0418"],["\u0442","\u0422"],["\u044C","\u042C"],["\u0431","\u0411"],["\u044E","\u042E"],[".",","],["Shift","Shift"]],[[" "," "]]];this.VKI_layout.US=[[["`","~"],["1","!"],["2","@"],["3","#"],["4","$"],["5","%"],["6","^"],["7","&"],["8","*"],["9","("],["0",")"],["-","_"],["=","+"],["Bksp","Bksp"]],[["Tab","Tab"],["q","Q"],["w","W"],["e","E"],["r","R"],["t","T"],["y","Y"],["u","U"],["i","I"],["o","O"],["p","P"],["[","{"],["]","}"],["\\","|"]],[["Caps","Caps"],["a","A"],["s","S"],["d","D"],["f","F"],["g","G"],["h","H"],["j","J"],["k","K"],["l","L"],[";",":"],["'",'"'],["Enter","Enter"]],[["Shift","Shift"],["z","Z"],["x","X"],["c","C"],["v","V"],["b","B"],["n","N"],["m","M"],[",","<"],[".",">"],["/","?"],["Shift","Shift"]],[[" "," "]]];this.VKI_deadkey=new Object();this.VKI_deadkey['"']=this.VKI_deadkey['\u00a8']=[["a","\u00e4"],["e","\u00eb"],["i","\u00ef"],["o","\u00f6"],["u","\u00fc"],["y","\u00ff"],["\u03b9","\u03ca"],["\u03c5","\u03cb"],["A","\u00c4"],["E","\u00cb"],["I","\u00cf"],["O","\u00d6"],["U","\u00dc"],["Y","\u0178"],["\u0399","\u03aa"],["\u03a5","\u03ab"]];this.VKI_deadkey['~']=[["a","\u00e3"],["o","\u00f5"],["n","\u00f1"],["A","\u00c3"],["O","\u00d5"],["N","\u00d1"]];this.VKI_deadkey['^']=[["a","\u00e2"],["e","\u00ea"],["i","\u00ee"],["o","\u00f4"],["u","\u00fb"],["w","\u0175"],["y","\u0177"],["A","\u00c2"],["E","\u00ca"],["I","\u00ce"],["O","\u00d4"],["U","\u00db"],["W","\u0174"],["Y","\u0176"]];this.VKI_deadkey['`']=[["a","\u00e0"],["e","\u00e8"],["i","\u00ec"],["o","\u00f2"],["u","\u00f9"],["A","\u00c0"],["E","\u00c8"],["I","\u00cc"],["O","\u00d2"],["U","\u00d9"]];this.VKI_deadkey["'"]=this.VKI_deadkey['\u00b4']=this.VKI_deadkey['\u0384']=[["a","\u00e1"],["e","\u00e9"],["i","\u00ed"],["o","\u00f3"],["u","\u00fa"],["\u03b1","\u03ac"],["\u03b5","\u03ad"],["\u03b7","\u03ae"],["\u03b9","\u03af"],["\u03bf","\u03cc"],["\u03c5","\u03cd"],["\u03c9","\u03ce"],["A","\u00c1"],["E","\u00c9"],["I","\u00cd"],["O","\u00d3"],["U","\u00da"],["\u0391","\u0386"],["\u0395","\u0388"],["\u0397","\u0389"],["\u0399","\u038a"],["\u039f","\u038c"],["\u03a5","\u038e"],["\u03a9","\u038f"]];this.VKI_deadkey["\u0385"]=[["\u03b9","\u0390"],["\u03c5","\u03b0"]];this.VKI_deadkey['\u00b0']=this.VKI_deadkey['\u00ba']=[["a","\u00e5"],["A","\u00c5"]];var inputElems=[document.getElementsByTagName('input'),document.getElementsByTagName('textarea'),]
for(var y=0,inputCount=0;y<inputElems.length;y++){if(inputElems[y]){for(var x=0;x<inputElems[y].length;x++){if((inputElems[y][x].nodeName=="TEXTAREA"||inputElems[y][x].type=="text"||inputElems[y][x].type=="password")&&inputElems[y][x].className.indexOf("keyboardInput")>-1){var keyid="";if(!inputElems[y][x].id){do{keyid='keyboardInputInitiator'+inputCount++;}while(document.getElementById(keyid));}else keyid=inputElems[y][x].id;var keybut=document.createElement('img');keybut.src="/i/keyboard.png";keybut.alt="Keyboard interface";keybut.className="keyboardInputInitiator";keybut.title="Display graphical keyboard interface";keybut.onclick=(function(a){return function(){self.VKI_show(a);};})(keyid);inputElems[y][x].id=keyid;inputElems[y][x].parentNode.insertBefore(keybut,inputElems[y][x].nextSibling);inputElems[y][x].onclick=inputElems[y][x].onkeypress=inputElems[y][x].onselect=function(){if(self.VKI_target.createTextRange)self.VKI_range=document.selection.createRange();}}}}}
this.VKI_keyboard=document.createElement('table');this.VKI_keyboard.id="keyboardInputMaster";this.VKI_keyboard.cellSpacing=this.VKI_keyboard.cellPadding=this.VKI_keyboard.border="0";var layouts=0;for(ktype in this.VKI_layout)if(typeof this.VKI_layout[ktype]=="object")layouts++;var thead=document.createElement('thead');var tr=document.createElement('tr');var th=document.createElement('th');if(layouts>1){var kblist=document.createElement('select');for(ktype in this.VKI_layout){if(typeof this.VKI_layout[ktype]=="object"){var opt=document.createElement('option');opt.value=ktype;opt.appendChild(document.createTextNode(ktype));kblist.appendChild(opt);}}
kblist.value=this.VKI_kt;kblist.onchange=function(){self.VKI_kt=this.value;self.VKI_buildKeys();self.VKI_position();}
th.appendChild(kblist);}
var label=document.createElement('label');var checkbox=document.createElement('input');checkbox.type="checkbox";checkbox.checked=this.VKI_deadkeysOn;checkbox.title="Toggle dead key input";checkbox.onclick=function(){self.VKI_deadkeysOn=this.checked;this.nextSibling.nodeValue=" Dead keys: "+((this.checked)?"On":"Off");self.VKI_modify("");return true;}
label.appendChild(checkbox);label.appendChild(document.createTextNode(" Dead keys: "+((checkbox.checked)?"On":"Off")))
th.appendChild(label);tr.appendChild(th);var td=document.createElement('td');var clearer=document.createElement('span');clearer.id="keyboardInputClear";clearer.appendChild(document.createTextNode("Clear"));clearer.title="Clear this input";clearer.onmousedown=function(){this.className="pressed";}
clearer.onmouseup=function(){this.className="";}
clearer.onclick=function(){self.VKI_target.value="";self.VKI_target.focus();return false;}
td.appendChild(clearer);var closer=document.createElement('span');closer.id="keyboardInputClose";closer.appendChild(document.createTextNode('X'));closer.title="Close this window";closer.onmousedown=function(){this.className="pressed";}
closer.onmouseup=function(){this.className="";}
closer.onclick=function(e){self.VKI_close();}
td.appendChild(closer);tr.appendChild(td);thead.appendChild(tr);this.VKI_keyboard.appendChild(thead);var tbody=document.createElement('tbody');var tr=document.createElement('tr');var td=document.createElement('td');td.colSpan="2";var div=document.createElement('div');div.id="keyboardInputLayout";td.appendChild(div);var div=document.createElement('div');var ver=document.createElement('var');ver.appendChild(document.createTextNode("v"+this.VKI_version));div.appendChild(ver);td.appendChild(div);tr.appendChild(td);tbody.appendChild(tr);this.VKI_keyboard.appendChild(tbody);this.VKI_buildKeys=function(){this.VKI_shift=this.VKI_capslock=this.VKI_alternate=this.VKI_dead=false;this.VKI_deadkeysOn=(this.VKI_layoutDDK[this.VKI_kt])?false:this.VKI_keyboard.getElementsByTagName('label')[0].getElementsByTagName('input')[0].checked;var container=this.VKI_keyboard.tBodies[0].getElementsByTagName('div')[0];while(container.firstChild)container.removeChild(container.firstChild);for(var x=0,hasDeadKey=false;x<this.VKI_layout[this.VKI_kt].length;x++){var table=document.createElement('table');table.cellSpacing=table.cellPadding=table.border="0";if(this.VKI_layout[this.VKI_kt][x].length<=this.VKI_keyCenter)table.className="keyboardInputCenter";var tbody=document.createElement('tbody');var tr=document.createElement('tr');for(var y=0;y<this.VKI_layout[this.VKI_kt][x].length;y++){if(!this.VKI_layoutDDK[this.VKI_kt]&&!hasDeadKey)
for(var z=0;z<this.VKI_layout[this.VKI_kt][x][y].length;z++)
if(this.VKI_deadkey[this.VKI_layout[this.VKI_kt][x][y][z]])hasDeadKey=true;var td=document.createElement('td');td.appendChild(document.createTextNode(this.VKI_layout[this.VKI_kt][x][y][0]));var alive=false;if(this.VKI_deadkeysOn)for(key in this.VKI_deadkey)if(key===this.VKI_layout[this.VKI_kt][x][y][0])alive=true;td.className=(alive)?"alive":"";if(this.VKI_layout[this.VKI_kt][x].length>this.VKI_keyCenter&&y==this.VKI_layout[this.VKI_kt][x].length-1)
td.className+=" last";if(this.VKI_layout[this.VKI_kt][x][y][0]==" ")
td.style.paddingLeft=td.style.paddingRight="50px";td.onmouseover=function(e){if(this.className!="dead"&&this.firstChild.nodeValue!="\xa0")this.className+=" hover";}
td.onmouseout=function(e){if(this.className!="dead")this.className=this.className.replace(/ ?(hover|pressed)/g,"");}
td.onmousedown=function(e){if(this.className!="dead"&&this.firstChild.nodeValue!="\xa0")this.className+=" pressed";}
td.onmouseup=function(e){if(this.className!="dead")this.className=this.className.replace(/ ?pressed/g,"");}
td.ondblclick=function(){return false;}
switch(this.VKI_layout[this.VKI_kt][x][y][1]){case"Caps":case"Shift":case"Alt":case"AltGr":td.onclick=(function(type){return function(){self.VKI_modify(type);return false;}})(this.VKI_layout[this.VKI_kt][x][y][1]);break;case"Tab":td.onclick=function(){self.VKI_insert("\t");return false;}
break;case"Bksp":td.onclick=function(){self.VKI_target.focus();if(self.VKI_target.setSelectionRange){var srt=self.VKI_target.selectionStart;var len=self.VKI_target.selectionEnd;if(srt<len)srt++;self.VKI_target.value=self.VKI_target.value.substr(0,srt-1)+self.VKI_target.value.substr(len);self.VKI_target.setSelectionRange(srt-1,srt-1);}else if(self.VKI_target.createTextRange){try{self.VKI_range.select();}catch(e){}
self.VKI_range=document.selection.createRange();if(!self.VKI_range.text.length)self.VKI_range.moveStart('character',-1);self.VKI_range.text="";}else self.VKI_target.value=self.VKI_target.value.substr(0,self.VKI_target.value.length-1);if(self.VKI_shift)self.VKI_modify("Shift");if(self.VKI_alternate)self.VKI_modify("AltGr");return true;}
break;case"Enter":td.onclick=function(){if(self.VKI_target.nodeName=="TEXTAREA"){self.VKI_insert("\n");}else self.VKI_close();return true;}
break;default:td.onclick=function(){if(self.VKI_deadkeysOn&&self.VKI_dead){if(self.VKI_dead!=this.firstChild.nodeValue){for(key in self.VKI_deadkey){if(key==self.VKI_dead){if(this.firstChild.nodeValue!=" "){for(var z=0,rezzed=false;z<self.VKI_deadkey[key].length;z++){if(self.VKI_deadkey[key][z][0]==this.firstChild.nodeValue){self.VKI_insert(self.VKI_deadkey[key][z][1]);rezzed=true;break;}}}else{self.VKI_insert(self.VKI_dead);rezzed=true;}
break;}}}else rezzed=true;}
self.VKI_dead=false;if(!rezzed&&this.firstChild.nodeValue!="\xa0"){if(self.VKI_deadkeysOn){for(key in self.VKI_deadkey){if(key==this.firstChild.nodeValue){self.VKI_dead=key;this.className="dead";if(self.VKI_shift)self.VKI_modify("Shift");if(self.VKI_alternate)self.VKI_modify("AltGr");break;}}
if(!self.VKI_dead)self.VKI_insert(this.firstChild.nodeValue);}else self.VKI_insert(this.firstChild.nodeValue);}
self.VKI_modify("");return false;}
for(var z=this.VKI_layout[this.VKI_kt][x][y].length;z<4;z++)
this.VKI_layout[this.VKI_kt][x][y][z]="\xa0";}
tr.appendChild(td);tbody.appendChild(tr);table.appendChild(tbody);}
container.appendChild(table);}
this.VKI_keyboard.getElementsByTagName('label')[0].style.display=(hasDeadKey)?"inline":"none";}
this.VKI_buildKeys();if(window.sidebar||window.opera){this.VKI_keyboard.onmousedown=function(){return false;}
this.VKI_keyboard.onclick=function(){return true;}}else this.VKI_keyboard.onselectstart=function(){return false;}
this.VKI_keyboard.style.display="none";document.body.appendChild(this.VKI_keyboard);this.VKI_modify=function(type){switch(type){case"Alt":case"AltGr":this.VKI_alternate=!this.VKI_alternate;break;case"Caps":this.VKI_capslock=!this.VKI_capslock;break;case"Shift":this.VKI_shift=!this.VKI_shift;break;}
var vchar=0;if(!this.VKI_shift!=!this.VKI_capslock)vchar+=1;var tables=this.VKI_keyboard.getElementsByTagName('table');for(var x=0;x<tables.length;x++){var tds=tables[x].getElementsByTagName('td');for(var y=0;y<tds.length;y++){var dead=alive=target=false;switch(this.VKI_layout[this.VKI_kt][x][y][1]){case"Alt":case"AltGr":if(this.VKI_alternate)dead=true;break;case"Shift":if(this.VKI_shift)dead=true;break;case"Caps":if(this.VKI_capslock)dead=true;break;case"Tab":case"Enter":case"Bksp":break;default:if(type)tds[y].firstChild.nodeValue=this.VKI_layout[this.VKI_kt][x][y][vchar+((this.VKI_alternate&&this.VKI_layout[this.VKI_kt][x][y].length==4)?2:0)];if(this.VKI_deadkeysOn){var char=tds[y].firstChild.nodeValue;if(this.VKI_dead){if(char==this.VKI_dead)dead=true;for(var z=0;z<this.VKI_deadkey[this.VKI_dead].length;z++)
if(char==this.VKI_deadkey[this.VKI_dead][z][0]){target=true;break;}}
for(key in this.VKI_deadkey)if(key===char){alive=true;break;}}}
tds[y].className=(dead)?"dead":((target)?"target":((alive)?"alive":""));if(y==tds.length-1&&tds.length>this.VKI_keyCenter)tds[y].className+=" last";}}
this.VKI_target.focus();}
this.VKI_insert=function(text){this.VKI_target.focus();if(this.VKI_target.setSelectionRange){var srt=this.VKI_target.selectionStart;var len=this.VKI_target.selectionEnd;this.VKI_target.value=this.VKI_target.value.substr(0,srt)+text+this.VKI_target.value.substr(len);if(text=="\n"&&window.opera)srt++;this.VKI_target.setSelectionRange(srt+text.length,srt+text.length);}else if(this.VKI_target.createTextRange){try{this.VKI_range.select();}catch(e){}
this.VKI_range=document.selection.createRange();this.VKI_range.text=text;this.VKI_range.collapse(true);this.VKI_range.select();}else this.VKI_target.value+=text;if(this.VKI_shift)this.VKI_modify("Shift");if(this.VKI_alternate)this.VKI_modify("AltGr");this.VKI_target.focus();}
this.VKI_show=function(id){if(this.VKI_target=document.getElementById(id)){if(this.VKI_visible!=id){this.VKI_range="";this.VKI_keyboard.style.display="none";var elem=this.VKI_target;this.VKI_target.keyboardPosition="absolute";do{if(VKI_getStyle(elem,"position")=="fixed"){this.VKI_target.keyboardPosition="fixed";break;}}while(elem=elem.offsetParent);this.VKI_keyboard.style.top=this.VKI_keyboard.style.right=this.VKI_keyboard.style.bottom=this.VKI_keyboard.style.left="auto";this.VKI_keyboard.style.position=this.VKI_target.keyboardPosition;try{this.VKI_keyboard.style.display="table";}catch(e){this.VKI_keyboard.style.display="block";}
this.VKI_visible=this.VKI_target.id;this.VKI_position();this.VKI_target.focus();}else this.VKI_close();}}
this.VKI_position=function(){if(self.VKI_visible!=""){var inputElemPos=VKI_findPos(self.VKI_target);self.VKI_keyboard.style.top=inputElemPos[1]-((self.VKI_target.keyboardPosition=="fixed")?document.body.scrollTop:0)+self.VKI_target.offsetHeight+3+"px";self.VKI_keyboard.style.left=Math.min(VKI_innerDimensions()[0]-self.VKI_keyboard.offsetWidth-15,inputElemPos[0])+"px";}}
if(window.addEventListener){window.addEventListener('resize',this.VKI_position,false);}else if(window.attachEvent)
window.attachEvent('onresize',this.VKI_position);this.VKI_close=function(){this.VKI_keyboard.style.display="none";this.VKI_visible="";this.VKI_target.focus();this.VKI_target="";}}
if(window.addEventListener){window.addEventListener('load',buildKeyboardInputs,false);}else if(window.attachEvent)
window.attachEvent('onload',buildKeyboardInputs);function VKI_findPos(obj){var curleft=curtop=0;do{curleft+=obj.offsetLeft;curtop+=obj.offsetTop;}while(obj=obj.offsetParent);return[curleft,curtop];}
function VKI_innerDimensions(){if(self.innerHeight){return[self.innerWidth,self.innerHeight];}else if(document.documentElement&&document.documentElement.clientHeight){return[document.documentElement.clientWidth,document.documentElement.clientHeight];}else if(document.body)
return[document.body.clientWidth,document.body.clientHeight];return[0,0];}
function VKI_getStyle(obj,styleProp){if(obj.currentStyle){var y=obj.currentStyle[styleProp];}else if(window.getComputedStyle)
var y=window.getComputedStyle(obj,null)[styleProp];return y;}

/* END keyboard.js */


/* BEGIN jquery/jquery.tooltip.js */

/*
 * jQuery Tooltip plugin 1.3 полностью regrurized by akahan
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 J?rn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
    // the tooltip element
    var helper = {},
        // the current tooltipped element
        current_element,
        // the title of the current element, used for restoring
        tooltip_body,
        // timeout id for tooltips show delayed 
        show_timeout_id,
        // timeout id for tooltips hide delayed 
        hide_timeout_id,
        // IE 5.5 or 6
        IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
    
    $.tooltip = {
        blocked: false,
        defaults: {
            show_delay: 0,
            hide_delay: 0,
            fade: true,
            extra_class: "",
            top: 0,
            left: 0,
            id: "tooltip"
        },
        block: function() {
            $.tooltip.blocked = !$.tooltip.blocked;
        }
    };

    $.fn.extend({
        tooltip: function(settings) {
            settings = $.extend({}, $.tooltip.defaults, settings);
            createHelper(settings);

            return this.each(function() {
                this.settings = settings;
                this.tOpacity = helper.tooltip.css("opacity");
                // copy tooltip into its own expando and remove the title
                this.tooltip_body = this.title;
                $(this).removeAttr("title");
                // also remove alt attribute to prevent default tooltip in IE
                this.alt = "";

                this._popup_state = function(show) {
                    var t_settings = this.settings;
                    var self = this;

                    function complete() {
                        helper.tooltip.hide().css({ opacity: "", width: '' });
                        helper.tooltip_body.html('');
                    }

                    if ((!IE || !$.fn.bgiframe) && t_settings.fade) {
                        if(show) {
                            if (helper.tooltip.is(":animated"))
                                helper.tooltip.stop().show().fadeTo(t_settings.fade, this.tOpacity);
                            else
                                helper.tooltip.is(':visible') ? helper.tooltip.fadeTo(t_settings.fade, this.tOpacity) : helper.tooltip.fadeIn(t_settings.fade);
                        }
                        else {
                            if (helper.tooltip.is(':animated'))
                                helper.tooltip.stop().fadeTo(t_settings.fade, 0, complete);
                            else
                                helper.tooltip.stop().fadeOut(t_settings.fade, complete);
                        }
                    }
                    else {
                        if(show)
                            helper.tooltip.show();
                        else
                            complete();
                    }
                };

                this.hide_popup = function(event) {
                    // hide helper, either with timeout or on instant
                    if( this.settings.hide_delay && !show_timeout_id) {
                        if (!hide_timeout_id)
                            hide_timeout_id = setTimeout(this._hide_popup_private, this.settings.hide_delay);
                    }
                    else
                        this._hide_popup_private();
                };

                this.show_popup = function(event) {
                    // show helper, either with timeout or on instant
                    if( this.settings.show_delay )
                        show_timeout_id = setTimeout(this._show_popup_private, this.settings.show_delay);
                    else
                        this._show_popup_private();

                    update(event);
                };

                // delete timeout and show helper
                this._show_popup_private = function() {
                    show_timeout_id = null;
                    current_element._popup_state(1);
                    update();
                };

                // hide helper and restore added classes and the title
                this._hide_popup_private = function() {
                    if($.tooltip.blocked)
                        return;

                    // clear timeouts if possible
                    _clear_show_timeout();
                    _clear_hide_timeout();

                    $(this).unbind('mouseleave').unbind('click');
                    helper.tooltip_body.unbind('mouseenter').unbind('mouseleave');
                    current_element._popup_state(0);
                    // no more current element
                    current_element = null;
                }
            }).mouseenter(save);
        }
    });

    function createHelper(settings) {
        // there can be only one tooltip helper
        if( helper.tooltip )
            return;
        // create the helper
        helper.tooltip = $('<div id="' + settings.id + '"><table class="tooltip-square-popup"><tr><td class="sp-lt" style="line-height: 0px;">&nbsp;</td><td class="sp-t" style="line-height: 0px;">&nbsp;</td><td class="sp-rt" style="line-height: 0px;">&nbsp;</td></tr><tr><td class="sp-l">&nbsp;</td><td class="sp-c"><div class="body"></div></td><td class="sp-r">&nbsp;</td></tr><tr><td class="sp-lb">&nbsp;</td><td class="sp-b">&nbsp;</td><td class="sp-rb">&nbsp;</td></tr></table></div>')
            // add to document
            .appendTo(document.body)
            // hide it at first
            .hide();

        // apply bgiframe if available
        if ( $.fn.bgiframe )
            helper.tooltip.bgiframe();

        helper.tooltip_body = $('div.body', helper.tooltip);
    }
    
    function viewport() {
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
    }

    function _clear_show_timeout() {
        show_timeout_id = show_timeout_id ? clearTimeout(show_timeout_id) : null;
    }

    function _clear_hide_timeout() {
        hide_timeout_id = hide_timeout_id ? clearTimeout(hide_timeout_id) : null;
    }

    function _hide_private(event) {
        if(current_element) current_element.hide_popup(event);
    }

    // save elements title before the tooltip is displayed
    function save(event) {
        _clear_hide_timeout();

        // if this is the current source, or it has no title (occurs with click event), stop
        if ( this == current_element || $.tooltip.blocked || helper.tooltip.is(":animated") || !this.tooltip_body )
            return;

        // save current
        current_element = this;
        $(this).mouseleave(_hide_private).click(_hide_private);

        if( helper.tooltip.is(":visible") ) helper.tooltip.hide();

        helper.tooltip.mouseenter(_clear_hide_timeout).mouseleave(_hide_private);

        helper.tooltip_body.html(this.tooltip_body);

        // add an optional class for this tip
        helper.tooltip.removeClass();
        helper.tooltip.css({ opacity: "", width: this.settings.width });
        helper.tooltip.addClass(this.settings.extra_class);
        if(this.getAttribute('tooltip_extra_classes'))
            helper.tooltip.addClass( this.getAttribute('tooltip_extra_classes') );
        if(this.getAttribute('tooltip_width'))
            helper.tooltip.css({ width: this.getAttribute('tooltip_width')});

        this.show_popup(event);
    }
    
    /**
     * updates the helper position
     * removes itself when no current element
     */
    function update(event)  {
        if ( (event && event.target.tagName == "OPTION") || $.tooltip.blocked || helper.tooltip.is(":animated") )
            return;

        // remove position helper classes
        helper.tooltip.removeClass("viewport-right").removeClass("viewport-bottom");

        var t_settings = current_element.settings;
        var v = viewport(), $tooltip = helper.tooltip;
        var left = $tooltip.offset().left;
        var top = $tooltip.offset().top;
        if (event) {
            // position the helper 15 pixel to bottom right, starting from mouse position
            left = event.pageX + t_settings.left;
            top = event.pageY + t_settings.top;
            var right='auto';
            if (t_settings.positionLeft) {
                right = $(window).width() - left;
                left = 'auto';
            }
            helper.tooltip.css({
                left: left,
                right: right,
                top: top
            });
        }

        var tooltip_width = $tooltip.width();
        var tooltip_height = $tooltip.height();
        // check horizontal position
        if (v.x + v.cx < left + tooltip_width) {
            left -= tooltip_width + 10 + t_settings.left;
            helper.tooltip.css({left: left + 'px'}).addClass("viewport-right");
        }
        // check vertical position
        if (v.y + v.cy < top + tooltip_height) {
            top -= tooltip_height + 10 + t_settings.top;
            helper.tooltip.css({top: top + 'px'}).addClass("viewport-bottom");
        }
    }

    $.fn.Tooltip = $.fn.tooltip;

})(jQuery);

/* END jquery/jquery.tooltip.js */


