

var letters = {
	"b1":	{"url":'/i/letters/b1.png',"w":49,"h":67},
	"b1l":	{"url":'/i/letters/b1l.png',"w":67,"h":49},
	"b1r":	{"url":'/i/letters/b1r.png',"w":67,"h":49},
	"e":	{"url":'/i/letters/e.png',"w":43,"h":58},
	"u":	{"url":'/i/letters/u.png',"w":52,"h":48},
	"k":	{"url":'/i/letters/k.png',"w":46,"h":58},
	"kr":	{"url":'/i/letters/kr.png',"w":58,"h":46},
	"b2":	{"url":'/i/letters/b2.png',"w":47,"h":70},
	"b2l":	{"url":'/i/letters/b2l.png',"w":70,"h":47},
	"b2r":	{"url":'/i/letters/b2r.png',"w":70,"h":47},
	"b3":	{"url":'/i/letters/b3.png',"w":53,"h":61},
	"b3r":	{"url":'/i/letters/b3r.png',"w":61,"h":53},
	"b3l":	{"url":'/i/letters/b3l.png',"w":61,"h":53},
	"i":	{"url":'/i/letters/i.png',"w":56,"h":63},
	"il":	{"url":'/i/letters/il.png',"w":63,"h":56},
	"ir":	{"url":'/i/letters/ir.png',"w":63,"h":56},
	"l":	{"url":'/i/letters/l.png',"w":45,"h":67},
	"lr":	{"url":'/i/letters/lr.png',"w":67,"h":45},
	
	"smb1":		{"url":'/i/minletters/b1.png',"w":22,"h":30},
	"smb1l":	{"url":'/i/minletters/b1l.png',"w":30,"h":22},
	"smb1r":	{"url":'/i/minletters/b1r.png',"w":30,"h":22},
	"sme":		{"url":'/i/minletters/e.png',"w":22,"h":30},
	"smu":		{"url":'/i/minletters/u.png',"w":30,"h":28},
	"smk":		{"url":'/i/minletters/k.png',"w":24,"h":30},
	"smkr":		{"url":'/i/minletters/k.png',"w":30,"h":24},
	"smb2":		{"url":'/i/minletters/b2.png',"w":20,"h":30},
	"smb2l":	{"url":'/i/minletters/b2l.png',"w":30,"h":20},
	"smb2r":	{"url":'/i/minletters/b2r.png',"w":30,"h":20},
	"smb3":		{"url":'/i/minletters/b3.png',"w":26,"h":30},
	"smb3r":	{"url":'/i/minletters/b3r.png',"w":30,"h":26},
	"smb3l":	{"url":'/i/minletters/b3l.png',"w":30,"h":26},
	"smi":		{"url":'/i/minletters/il.png',"w":27,"h":30},
	"smir":		{"url":'/i/minletters/ir.png',"w":30,"h":27},
	"sml":		{"url":'/i/minletters/l.png',"w":20,"h":30},
	"smlr":		{"url":'/i/minletters/lr.png',"w":30,"h":20}	
};
var complex_letter = {
	"bottom" :["b1","k","u"],
	"top" :["b1","k","u","b2","b3","i","l"],
	"left" :["l","e","b3","b2l","b3l","il","u","b1l"],
	"right" :["e","b3","ir","b2r","b3r","b1r","lr","u"],
	"small_bottom" :["smb1","smk","smu"],
	"small_top" :["smb1","smk","smu","smb2","smb3","smi","sml"],
	"small_right" :["smb1","smk","smu","smb2","smb3","smi","sml"],
	"small_left" :["smb1","smk","smu","smb2","smb3","smi","sml"]
};	

$(function() {
	
	$('html').removeClass('nojs');

	new mailto();
	


    var my_wink;
    setTimeout(function(){my_wink = new wink($('#header .td_menu'));},100);

	var my_happy = new happy('.happy_cover','body');

	var my_belka = new belka($('.td_wzrw'),30,50,'30%');
	
	//Функционал по центрированию выьранных фоток в галерее
	var my_gallery = new gallery($('.gallery_nav'),$('.gallery_picture'));
	
	//Инициализируем растягиваемые изображения
	var my_izoom = new izoom($('img.izoom'));

	$('.choser').find('.happy_cover').each(function(){
		new chooser($(this));
	});
	for(var i=0;i<chooserParent.length;i++){
		if(!chooserParent[i].jElement.hasClass('disable')){
				chooserParent[i].toggle();
			break;
		}
	}

    var iCurrentFeed = 1;
    $('#home_page .next-feedback').click(function(){
        iCurrentFeed++;
        var jParent = $(this).parents('.feedback');
        var jPseudo = jParent.find('.content_feedback p, .text_feedback p');
        var jCurrent = jParent.find('.feed_'+iCurrentFeed);

        if(jCurrent.length < 1){
            iCurrentFeed = 1;
            jCurrent = jParent.find('.feed_'+iCurrentFeed);
        }

        jPseudo.animate({'opacity':0},'fast',function(){
            jPseudo.html(jCurrent.html());
            jPseudo.animate({'opacity':1},'normal',function(){

            });
        })
    });

	/*
	$('.openclose').click(function(e){

			e.preventDefault();
			e.stopPropagation();
			
			if(!$(this).hasClass('active'))
			{
				var name = $(this).html();
				$(this).addClass('active');
				$(this).parent().find('.hidden').addClass('nohidden').removeClass('hidden');
				$(this).html($(this).attr('title'));
				$(this).attr('title',name);
			}
			else
			{
				var name = $(this).html();
				$(this).removeClass('active');
				$(this).parent().find('.nohidden').addClass('hidden').removeClass('nohidden');
				$(this).html($(this).attr('title'));
				$(this).attr('title',name);
			}
	});
	*/
});

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */
(function(jQuery){
    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if (typeof(fx.init) == 'undefined') {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
                //console.log('--- Получаем цвета',fx.start,fx.end,fx.state);
                fx.init = true;
            }
            //console.log(fx.state,fx.start,fx.end);
            if(typeof(fx) !='undefined' && typeof(fx.elem) !='undefined'){
            fx.elem.style[attr] = "rgb(" + [
                Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
            }
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Otherwise, we're most likely dealing with a named color
        //console.log('ЦВЕТ getRGB',colors[jQuery.trim(color).toLowerCase()]);
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        //console.log('НАЧАЛО ОПРЕДЕЛЕНИЯ ЦВЕТА')
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );  
        //console.log('КОНЕЦ ОПРЕДЕЛЕНИЯ ЦВЕТА',color,getRGB(color));
        return getRGB(color);
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        active:[233,90,27],
        winki:[211, 43, 15],
        link:[211, 43, 15],
        bg:[0,0,0]
    };

})(jQuery);

var mailto = function(){
    $('.mt').each(function(){
        var title = this.title.split(' ');
        if(title.length){
            $(this).wrapInner('<a href="mailto:' + title[0] + '@' + title[1] + '"/>');
        }
        $(this).find('.at').text('@');
    });
};


/* ХЕППИ БЛОКИ */
var happy = function(CoverName,GlobContainer){
	
	if($('body#home_page').length > 0)
		return false;
	
	this.CoverName = CoverName;
	this.GlobContainer = GlobContainer;
	this.jElements = $(this.CoverName);
	this.oElements = [];
	$('body').append('<div id="happy_sensors"></div>');
	
	//запускаем поиск хэппи элементов на странице. инициализация класса
	this.start();
};

happy.prototype.start = function() {
   
	var parent = this;
	var max = 4;
	var max_button = 2;
	var max_link = 1;
	
	//перебираем коверы
	var findNames = this.CoverName +".b:not(.button, .link_cover), "+this.CoverName +".r:not(.button, .link_cover), "+this.CoverName +".l:not(.button, .link_cover), "+this.CoverName +".t:not(.button, .link_cover)";
	this.create(this.random_elements(findNames,max));
	
	findNames = this.CoverName +".active.link_cover";
	this.create(this.random_elements(findNames,max_link));
	
	findNames = this.CoverName +".b.button, "+this.CoverName +".r.button, "+this.CoverName +".l.button, "+this.CoverName +".t.button";
	this.create(this.random_elements(findNames,max_button));
}

happy.prototype.create = function(jElements){
	var timer = 1000;
	var parent = this;
	var i=0;
	jElements.each(function(){
		var els = $(this);
		setTimeout(function(){
			parent.oElements.push(new happy_box(els,i,parent));
			i++;
		},timer);
		
		timer += 300;		
	});
}

happy.prototype.random_elements = function(Elements,max){
	var findsElement = $(this.GlobContainer).find(Elements);
	
	if(findsElement.length > max)
	{
		for(var i=0;findsElement.length > i;i++)
		{
			var rand1 = Math.round(Math.random()*(findsElement.length-1));
			var rand2 = Math.round(Math.random()*(findsElement.length-1));
			
			var temp = findsElement[rand1];
			findsElement[rand1] = findsElement[rand2];
			findsElement[rand2] = temp;
		}
		
		findsElement.splice(max-1,findsElement.length - max);
	}
	return findsElement;
}


var happy_box = function(jCover,id,happy) {
	
	var oThis = this;
	this.start = {};
	this.happy = happy;
	
	this.is_click=false;
	
	this.jCover = jCover;
	this.id = id;
	this.type_letters = "bottom";
	this.letter = {};
	this.disable = true;
	this.corner_size = 40;
	this.small_corner_size = 20;
	
	this.width = jCover.width();
	this.height = jCover.height();
	this.top = jCover.offset().top;
	this.left = jCover.offset().left;
	
	this.sensor;
	this.type;
	this.horizontal;
	this.new_horizontal;
	this.vertical;
	this.new_vertical;
	
	if(typeof(letters) == "undefined")
		return false;
		
	if(jCover.width() == 0)
		return false;
	
	//если изображние должно появляться снизу объекта. Определяется наличием класса b (bottom)
	if(jCover.hasClass('sm'))	
		this.corner_size = this.small_corner_size;	
		
	if(jCover.hasClass('b'))
	{
		this.type_letters = "bottom";
		if(jCover.hasClass('sm'))
			this.type_letters = "small_bottom";
		
		this.letter = this.random_letter();
		
		this.hdiapazon(this.width,this.height);
		
		this.horizontal = this.get_horizontal();
		this.new_horizontal = this.horizontal;

		this.vertical = (100 - parseInt((this.letter.h)))+'%';
		this.new_vertical = '100%';
		
		this.start.x = this.horizontal; 
		this.start.y = (100 - parseInt((100/this.height)*(this.letter.h)))+"%";
		/*
		if(!jCover.hasClass('button') && !jCover.hasClass('link_cover') && !jCover.hasClass('hidden'))
		{
			this.sensor = this.add_sensor();
			this.position_bottom_sensor();
			this.sensor.click(function(){oThis.bottom_click()});
			$(window).resize(function(){
				oThis.disabled();
				oThis.bottom_click();
			});
		}    */
	}

	else if(jCover.hasClass('l'))
	{
		this.type_letters = "left";
		if(jCover.hasClass('sm'))
			this.type_letters = "small_left";		
		
		this.letter = this.random_letter();
		
		this.vdiapazon(this.width,this.height);
		
		this.horizontal = parseInt((100/this.width)*(this.letter.w))+'%';
		this.new_horizontal = '0%';

		this.vertical = this.get_vertical();
		this.new_vertical = this.vertical;
		
		this.start.x = parseInt((100/this.width)*(this.letter.w))+"%";
		this.start.y = this.vertical;

		/*
		if(!jCover.hasClass('button') && !jCover.hasClass('link_cover') && !jCover.hasClass('hidden'))
		{
			this.sensor = this.add_sensor();
			this.position_left_sensor();
			this.sensor.click(function(){oThis.left_click()});
			$(window).resize(function(){oThis.disabled();oThis.left_click()});
		}     */
	}
	else if(jCover.hasClass('r'))
	{
		this.type_letters = "right";
		if(jCover.hasClass('sm'))
			this.type_letters = "small_right";		
		this.letter = this.random_letter();
		
		this.vdiapazon(this.width,this.height);
		
		this.horizontal = (100 - parseInt((100/this.width)*(this.letter.w)))+'%';
		this.new_horizontal = '100%';

		this.vertical = this.get_vertical();
		this.new_vertical = this.vertical;
		
		this.start.x = (80)+"%";
		this.start.y = this.vertical;
		 /*
		if(!jCover.hasClass('button') && !jCover.hasClass('link_cover') && !jCover.hasClass('hidden'))
		{
			this.sensor = this.add_sensor();
			this.position_right_sensor();
			this.sensor.click(function(){oThis.right_click()});
			$(window).resize(function(){oThis.disabled();oThis.right_click()});
		}    */
	}
/*
	else if(jCover.hasClass('t'))
	{
		this.type_letters = "top";
		if(jCover.hasClass('sm'))
			this.type_letters = "small_top";		
		this.letter = this.random_letter();
		
		this.hdiapazon(this.width,this.height);

		this.horizontal = this.get_horizontal();
		this.new_horizontal = this.horizontal;

		this.vertical = parseInt((100/this.height)*(this.letter.h/3))+"%";
		this.new_vertical = '0%';
		
		this.start.x = this.horizontal; 
		this.start.y = parseInt((100/this.height)*(this.letter.h))+'%';
		          /*
		if(!jCover.hasClass('button') && !jCover.hasClass('link_cover') && !jCover.hasClass('hidden'))
		{
			this.sensor = this.add_sensor();
			this.position_top_sensor();
			this.sensor.click(function(){oThis.top_click()});
			$(window).resize(function(){oThis.disabled();oThis.top_click});
		}
	}
*/
	else return this;		

	this.set_image(this.start);
	
	if(jCover.width() != 0)
	jCover.animate({backgroundPosition: this.get_position(this.horizontal,this.vertical)},3000);
		
	//jCover.children().hover(function(){if(!oThis.is_click)oThis.on_hover()},function(){if(!oThis.is_click)oThis.off_hover()});

	$('.td_wzrw a').hover(function(){if(!oThis.is_click)oThis.on_hover()},function(){if(!oThis.is_click)oThis.off_hover()});

	/*
	if(typeof(this.sensor) == "object")
		this.sensor.hover(function(){if(!oThis.is_click)oThis.on_hover()},function(){if(!oThis.is_click)oThis.off_hover()});
	*/
	return this;
}

happy_box.prototype.set_sensors = function(){
	
	if(typeof(this.sensor) != "object")
	{
		var oThis = this;
		this.sensor = this.add_sensor();
		this.sensor.click(function(){oThis.bottom_click()});
	}
		
	if(this.jCover.hasClass('hidden'))
	{	
		this.disabled();
		return false;
	}
	else if(this.disable)
		this.enabled();	
	
	if(this.jCover.hasClass('t'))
	{
		this.position_top_sensor();
	}
	else if(this.jCover.hasClass('b'))
	{
		this.position_bottom_sensor();
	}
	else if(this.jCover.hasClass('l'))
	{
		this.position_left_sensor();
	}
	else if(this.jCover.hasClass('r'))
	{
		this.position_right_sensor();
	}	
}

happy_box.prototype.hdiapazon = function(w,h){
	if(w < this.letter.w*2 || h < this.letter.h*1.5)
		this.disabled();
	else if(this.disable)
		this.enabled();
}

happy_box.prototype.vdiapazon = function(w,h){
	if(h < this.letter.h*2 || w < this.letter.w*1.5)
		this.disabled();
	else if(this.disable)
		this.enabled();
}

happy_box.prototype.position_bottom_sensor = function() {
	
	var width = this.jCover.width();
	var height = this.jCover.height();
	
	this.hdiapazon(width,height);
	
	var t = this.jCover.height()+this.jCover.offset().top-5;
	var l = this.new_horizontal+this.jCover.offset().left;
	var w = this.letter.w;
	var h = this.jCover.outerHeight()+this.jCover.offset().top - t;
	
	//Ставим сенсор
	this.position_sensor(t,l,w,h);
}

happy_box.prototype.position_top_sensor = function() {

	var width = this.jCover.width();
	var height = this.jCover.height();
	
	this.hdiapazon(width,height);
	
	var t = this.jCover.offset().top;
	var l = this.new_horizontal+this.jCover.offset().left;
	var w = this.letter.w;
	var h = this.jCover.outerHeight()-this.jCover.height();
	
	//Ставим сенсор
	this.position_sensor(t,l,w,h);
}

happy_box.prototype.position_left_sensor = function() {
	
	var width = this.jCover.width();
	var height = this.jCover.height();
	
	this.vdiapazon(width,height);

	var t = parseInt(this.new_vertical+this.jCover.offset().top);
	var l = parseInt(this.jCover.offset().left);
	var w = this.jCover.outerWidth()-this.jCover.width()+2;
	var h = this.letter.h;
	
	//Ставим сенсор
	this.position_sensor(t,l,w,h);
}

happy_box.prototype.position_right_sensor = function() {
	
	var width = this.jCover.width();
	var height = this.jCover.height();
	
	this.vdiapazon(width,height);
	
	var t = parseInt(this.new_vertical+this.jCover.offset().top);
	var l = this.jCover.offset().left+width;
	var w = this.jCover.outerWidth()-this.jCover.width()+2;
	var h = this.letter.h;
	
	//Ставим сенсор
	this.position_sensor(t,l,w,h);
}

happy_box.prototype.on_hover = function() {
	this.jCover.stop().animate({backgroundPosition: this.get_position(this.new_horizontal,this.new_vertical)},300);
}

happy_box.prototype.off_hover = function() {
	this.jCover.stop().animate({backgroundPosition: this.get_position(this.horizontal,this.vertical)},300);
}

happy_box.prototype.set_image = function(start) {
	//Устанавливаем изображение
	if(!this.disable)
		this.jCover.css({"background-image":"url("+ this.letter.url +")"});

	this.jCover.css({
		"background-position":this.get_position(start.x,start.y),
		"background-repeat":"no-repeat"
	});
}

happy_box.prototype.new_image = function() {
	this.jCover.css({
		"background-image":"url("+ this.letter.url +")"
	});	
}

happy_box.prototype.position_sensor = function(t,l,w,h) {
	
	t= t+"px";l= l+"px";w= w+"px";h= h+"px";

	this.sensor.css({
		'top':t,
		"left":l,
		"width":w,
		"height":h
	});
}

happy_box.prototype.add_sensor = function() {
	var name = "happy_sensor_"+this.id;
	
	$('#happy_sensors').append("<div id='"+name+"' class='opacity0'></div>");
	
	var jSensor = $('#'+name);
	jSensor.css({
		"position":"absolute",
		"background":"purple",
		"cursor":"pointer"
	});	
	return jSensor;
}

happy_box.prototype.get_horizontal = function() {
	var min = this.corner_size;
	var max = this.jCover.width()-(this.corner_size*2+this.letter.w);
	
	if(max < 0) {this.disabled();return parseInt(this.jCover.width()/2 - this.letter.w/2)}
	else if(this.disable) this.enabled();

	return min + (Math.round(Math.random() * max));
}

happy_box.prototype.get_vertical = function() {	
	var min = this.corner_size;
	var max = this.jCover.height() - (this.corner_size*2+this.letter.h);
	
	if(max < 0) {this.disabled();return parseInt(this.jCover.height()/2 - this.letter.w/2)}
	else if(this.disable) this.enabled();

	return min + (Math.round(Math.random() * max));
}

happy_box.prototype.get_position = function(x,y) {
	var res = "";
	if(typeof(x) == "number") res = x + "px "; else res = x+" ";		
	if(typeof(y) == "number") res += y+"px"; else res += y;
	return res;
}

happy_box.prototype.disabled = function() {
	
	this.jCover.css("background-image","");

	if(typeof(this.sensor) == "object")
		this.sensor.addClass('hidden');
	this.disable = true;
}

happy_box.prototype.enabled = function() {
	this.jCover.css("background-image","url("+this.letter.url+")");
	
	if(typeof(this.sensor) == "object")
		this.sensor.removeClass('hidden');
	this.disable = false;
}

happy_box.prototype.random_letter = function() {
	if(typeof(complex_letter[this.type_letters]) != "object")
		alert("Данной категории букв нет");
	
	var num = complex_letter[this.type_letters][Math.round(Math.random() * (complex_letter[this.type_letters].length-1))];		
	return letters[num];
}

happy_box.prototype.bottom_click = function(e) {
	
	if(this.is_click)
		return false;
	
	var oThis = this;
	this.is_click = true;
	this.sensor.css('cursor',"default");
		
	var hr = this.get_horizontal();		
	this.jCover.animate({backgroundPosition: this.get_position(this.new_horizontal,oThis.start.y)},300,function(){
		
		setTimeout(function(){
		
			oThis.jCover.css('background-position',oThis.get_position(hr,oThis.start.y));
			oThis.letter = oThis.random_letter();
			oThis.new_image();
			oThis.position_bottom_sensor();

			setTimeout(function(){
			
				if(oThis.disable) oThis.enabled();
				oThis.is_click = false;oThis.sensor.css('cursor',"pointer");oThis.off_hover()
			
			},200);
		
		},1500)
		
		
	});		
		
	this.horizontal = hr;
	this.new_horizontal = hr;
	
	

	return false;
}

happy_box.prototype.top_click = function() {
	
	if(this.is_click)
		return false;
	
	var oThis = this;
	this.is_click = true;
	this.sensor.css('cursor',"default");
		
	var hr = this.get_horizontal();		

	this.jCover.animate({backgroundPosition: this.get_position(this.new_horizontal,oThis.start.y)},300,function(){
		
		setTimeout(function(){
		
			oThis.jCover.css('background-position',oThis.get_position(hr,oThis.start.y));
			oThis.letter = oThis.random_letter();
			oThis.new_image();
			oThis.position_top_sensor();

			setTimeout(function(){oThis.is_click = false;oThis.sensor.css('cursor',"pointer");oThis.off_hover()},200);
		
		},1500)
		
		
	});		
		
	this.horizontal = hr;
	this.new_horizontal = hr;


	return false;
}

happy_box.prototype.left_click = function(e) {
	
	if(this.is_click)
		return false;
	
	var oThis = this;
	this.is_click = true;
	this.sensor.css('cursor',"default");
		
	var hr = this.get_vertical();	
	this.jCover.animate({backgroundPosition: this.get_position(this.start.x,this.vertical)},300,function(){
		
		setTimeout(function(){
		
			oThis.jCover.css('background-position',oThis.get_position(oThis.start.x,hr));
			oThis.letter = oThis.random_letter();
			oThis.new_image();
			oThis.position_left_sensor();

			setTimeout(function(){oThis.is_click = false;oThis.sensor.css('cursor',"pointer");oThis.off_hover()},200);
		},1500)
	});		
		
	this.vertical = hr;
	this.new_vertical = hr;
	
	

	return false;
}

happy_box.prototype.right_click = function(e) {
	
	if(this.is_click)
		return false;
	
	var oThis = this;
	this.is_click = true;
	this.sensor.css('cursor',"default");
		
	var hr = this.get_vertical();	
	this.jCover.animate({backgroundPosition: this.get_position(this.start.x,this.vertical)},300,function(){
		
		setTimeout(function(){
		
			oThis.jCover.css('background-position',oThis.get_position(oThis.start.x,hr));
			oThis.letter = oThis.random_letter();
			oThis.new_image();
			oThis.position_right_sensor();

			setTimeout(function(){oThis.is_click = false;oThis.sensor.css('cursor',"pointer");oThis.off_hover()},200);
		
		},1500)
	});		
		
	this.vertical = hr;
	this.new_vertical = hr;

	return false;
}


//Кликабельные лейблы около чекбоксов и радиобатонов
var clickLabel = function(jParent)
{	
	//Клик по лейблу и включение соседнего радиобаттона или чекбокса
	jParent.find('label.clickable').click(function(e){
		var input = $(this).parent().find('input[type=checkbox],input[type=radio]');
		if(input.attr('checked'))
			input.attr('checked',false);
		else
			input.attr('checked',true);
	});
	
	jParent.find('label').disableTextSelect();
	
	jParent.find('.close').hover(function(e){$(this).addClass('hovered')},function(){$(this).removeClass('hovered')});
}

var wink = function(jMenu)
{
    //если есть двойной баннер.
    //Подмигиваем активным элементом
    if(jMenu.find('.double_banner').length > 0 && jMenu.find('.root .current').length > 0){
        this.winkCurrent(jMenu.find('.root .current'));
    }
    //Если есть меню второго уровня
    else if(jMenu.find('.root .current').length > 0 && jMenu.find('.two_menu .current').length == 0){
        this.winkCurrent(jMenu.find('.root .current,.root .parent'),jMenu.find('.two_menu'));
    }

    else if(jMenu.find('.root .current').length > 0 && jMenu.find('.two_menu .current').length > 0){
        this.winkCurrent(jMenu.find('.two_menu .current'));
    }

    else if(jMenu.find('.two_menu .current').length > 0 && jMenu.find('.two_menu .current.parent').length == 0){
	    this.winkCurrent(jMenu.find('.two_menu .current'));
    }
    /*
    else if(jMenu.find('.three.last').length > 0){
        this.winkCurrent(jMenu.find('.two_menu .current,.two_menu .parent'),jMenu.find('.three'));
    }

    else if(jMenu.find('.three').length > 0){
        this.winkCurrent(jMenu.find('.three .current'));
    }
    */
}

wink.prototype.winkCurrent = function(jElement,jBlock){
    var oThis = this;
    var jSpan = jElement.find('span');

    jSpan.css('background-color','#E3DFD7');
    jSpan.stop().animate({backgroundColor:'winki'},'fast','linear',function(){
        //console.log('Плашка загорелась')
        $(this).animate({backgroundColor:'active'},'fast','linear',function(){
            //console.log('Плашка активировалась')
            if(typeof(jBlock) != 'undefined' && jBlock.length > 0){
                setTimeout(function(){oThis.winkMenu(jBlock);},250);
            }
        })
        
    })
}

wink.prototype.winkMenu = function(jElement){
    var oThis = this;
    var jA = jElement.find('a,b');
    var jSpan = jA.find('span');

    jA.css({'color':'#fff'});
    jA.each(function(){
        var thA = $(this);
        thA.animate({color:'active'},'fast','linear',function(){
            thA.animate({color:'link'},'fast','linear',function(){
                jElement.removeClass('last');
                thA.removeAttr('style');
                jSpan.css('background-color','#E3DFD7');
            })
        })
    })
}



var chooserParent = [];
var chooser = function(jElement,happy){
	
	var oThis = this;
	//this.happy = happy;
	this.jElement = jElement;
	this.jBlocks = $('.'+jElement.attr('id'));
	this.jLink = jElement.find('a');
  this.init = false;
	
	this.jElement.addClass('ready');
	
	chooserParent.push(this);
	this.jLink.click(function(e){oThis.click(e);});
	 /*
  if(this.jElement.hasClass('active'))
	{
        oThis.toggle();
	}
	*/
}

chooser.prototype.toggle = function(){
	//var height = this.jBlocks.parent().height();
	//this.jBlocks.parent().css({'height':height+'px'});

  for(var i=0;i<chooserParent.length;i++)
	{
		chooserParent[i].close();
		chooserParent[i].jElement.removeClass('active');
	}

  this.open();
	this.jElement.addClass('active');
}

chooser.prototype.close = function(){
	this.jBlocks.addClass('hidden');
}
	
chooser.prototype.open = function(){
	var oThis = this;
		oThis.jBlocks.each(function(i){
	    $(this).eq(0).removeClass('hidden');
	    //$(this)[0].className('toddler');
	    $(this).parent().removeAttr('style');
    });
}

chooser.prototype.click = function(e){
	if(this.jElement.hasClass('active'))
		return false;
	
	e.preventDefault();
	e.stopPropagation();
	
	this.toggle();
}



var belka = function(jContainer,startx,finishx,starty){

	var position;
	var jaContainer = jContainer.find('a');
	
	var w = $(window).width();
	
	w = 11+((w-1000)/100);
	
	//jContainer.css({'width':w+'%'},1000);	

	jContainer.append('<a class="sensor" href="/wzrv/"></a>')
	var jSense = jContainer.find('.sensor')

	jSense.css({'top':'145px','width':'30px'});
	setTimeout(function(){jContainer.css({'background-position':(jContainer.width()-startx)+"px "+starty})},300);
	
	jaContainer.hover(function(){

		position = (jContainer.width()-finishx)+'px '+starty;
		jContainer.stop().animate({backgroundPosition:position},200);
		jSense.css({'top':'145px','width':'50px'});
	
	},function(){
	
		position = (jContainer.width()-startx)+'px '+starty;
		jContainer.stop().animate({backgroundPosition:position},200);
	  jSense.css({'top':'145px','width':'30px'});

	});

	jSense.hover(function(){

		position = (jContainer.width()-finishx)+'px '+starty;
		jContainer.stop().animate({backgroundPosition:position},200);
		jSense.css({'top':'145px','width':'50px'});

	},function(){

		position = (jContainer.width()-startx)+'px '+starty;
		jContainer.stop().animate({backgroundPosition:position},200);
	  jSense.css({'top':'145px','width':'30px'});

	});
	
	$(window).resize(function(){
	
		if($(window).width() > 1000)
		{
			var w = $(window).width();
			
			w = 11+((w-1000)/100);
			
			//jContainer.css({'width':w+'%'});
		}
		else
		{
			//jContainer.css({'width':10+'%'});
		}
		
		position = (jContainer.width()-startx)+'px '+starty;
		jContainer.stop().animate({backgroundPosition:position},500);

	});
	
}











/*Функция вывода отладочной инфы в консоль, если она включена*/
function debug(string){
	
	return false;
	
	if(typeof(console) == "object")
		console.log(string);
	return false;
}
					
/**
 * Enables/Disables text selection, saves selected text
 *   
 * @example jQuery('p').enableTextSelect(); / jQuery('#selectable-area').disableTextSelec();
 * @cat plugin
 * @type jQuery 
 *
 */
jQuery.fn.disableTextSelect = function() {
  return this.each(function() {
    $(this).css({
      'MozUserSelect' : 'none'
    }).bind('selectstart', function() {
      return false;
    }).mousedown(function() {
      return false;
    });
  });
};

jQuery.fn.enableTextSelect = function() {
  return this.each(function() {
    $(this).css({
      'MozUserSelect':''
    }).unbind('selectstart').mousedown(function() {
      return true;
    });
  });
};


var gallery = function(jNav,jPic) {
	
	if(jNav.length < 1)
		return false;
	
	var oThis = this;
	oThis.jScrollBox = jNav.children().eq(0);
	oThis.jSelectPic = jNav.find('.selected');
	
	//Движение скрола
	oThis.jScrollBox.animate({ scrollLeft: getPosition() }, 50)

	function getPosition()
	{
		if(oThis.jSelectPic.length !== 0){
			return oThis.jSelectPic.offset().left - parseInt(jNav.width()/2) + parseInt(oThis.jSelectPic.width() / 2);
		}
	}
}



//Увеличиваем фотку
var izoom = function(jPic) {
	
	if(jPic.length < 1)
		return false;

	var oThis = this;
	debug(this);
	
	this.count = 0;		
	this.jPic =[];

    $('body').append('<div id="izoom_close" class="hidden">x</div>');
    $('body').append('<div id="izoom_background" class="hidden opacity05"></div>');
    this.jClose = $('#izoom_close');
    this.jFade = $('#izoom_background');
    this.jFade.css({'height':$('#layout').height()});
	
	jPic.each(function(obj){
	
		var parent = $(this).parent();
		oThis.jPic[oThis.count]             = $(this);
		oThis.jPic[oThis.count].parent      = parent;
		oThis.jPic[oThis.count].imgId       = 'pic_now_'+oThis.count;
		oThis.jPic[oThis.count].status      = 'close';
        oThis.jPic[oThis.count].jLoader     = parent.find('.imgLoad');
        oThis.jPic[oThis.count].pos         = 0;
		
		var mH = parseInt(parent.find('.imgHeight').html());
		var mW = parseInt(parent.find('.imgWidth').html());
		var mA = parseInt(parent.find('.imgAlt').html());
		var mS = parent.find('.imgSrc').html();
		var i = oThis.count;
		
		if(mH == '' || mW == '')
			return true;
		
		$(this).click(function(e){oThis.clicks(e,i,mH,mW,mA,mS)});
			
		oThis.count ++;	
	});
	
	$(window).resize(function(){oThis.resize()});
}

izoom.prototype.clicks = function(jObj,i,mH,mW,mA,mS){
	
	var oThis = this.jPic[i];
	var oZoom = this;
	
	if(typeof(oThis.newImg) != 'object')
	{
		var newId = oThis.imgId;
        this.startLoad(oThis);

        $('body').append('<img class="photo opacity0" id="'+newId+'" src="'+mS+'" width="'+oThis.width()+'" height="'+oThis.height()+'" />')

        oThis.newImg = $('body').find('#pic_now_'+i);

        oThis.newImg.css({	'position':'absolute',
                        'top':oThis.offset().top+'px',
                        'left':oThis.offset().left+'px',
                        'width':oThis.width()+'px',
                        'height':oThis.height()+'px'
            });

        oThis.newImg.click(function(){if(oThis.status == 'open'){oZoom.close();}else{oThis.newImg.removeClass('opacity0');oZoom.open(i,mH,mW,mA,mS);}});
        oZoom.jFade.click(function(){oZoom.close();})
        oZoom.jClose.click(function(){oZoom.close();})

        oThis.newImg.load(function(){
            setTimeout(function(){
                oZoom.stopLoad(oThis);
                oZoom.open(i,mH,mW,mA,mS);
            },300);
        });
	}
}

izoom.prototype.startLoad = function(jObj){
    jObj.jLoader.removeClass('hidden');

    jObj.pos = setInterval(function(){
        jObj.jLoader.html(jObj.jLoader.html()+'.');
        var len = jObj.jLoader.html().length;
        if(len > 3) jObj.jLoader.html('.');
    },300);
}

izoom.prototype.stopLoad = function(jObj){
    clearInterval(jObj.pos);
    jObj.jLoader.html('');
    jObj.jLoader.addClass('hidden');
    jObj.newImg.removeClass('opacity0');
}

izoom.prototype.open = function(i,mH,mW,mA,mS){

	var oThis = this;
	
	var winH = $(window).height() - 100;
	var winW = $(window).width() - 100;

	if(mH > winH || mW > winW)
	{
		var del;
		if(winW / mW < winH / mH) del= winW / mW;
		else del= winH / mH;
		
		mW = mW*del;
		mH = mH*del;
	}
	
	var mL = oThis.jPic[i].offset().left + oThis.jPic[i].width() - mW;
	var mT = oThis.jPic[i].offset().top -(mH - oThis.jPic[i].height());
	
	if(mL < 16) mL = 16;
	if(mT < $(window).scrollTop()) mT = $(window).scrollTop() + 16;
	
	this.close(i);

    oThis.jFade.removeClass('hidden');

    oThis.jPic[i].newImg.css('z-index','1001').stop().animate({width:mW+'px',height:mH+'px',left:mL,top:mT},500,function(){
        oThis.jClose.removeClass('hidden').css({top:(mT+10)+'px',left:(mL+mW-15)+'px','z-index':'10000'});
	});
	oThis.jPic[i].status = 'open';
}

izoom.prototype.close = function(){
	
	var oThis = this;

	oThis.jFade.addClass('hidden');
    oThis.jClose.addClass('hidden');

    for(var i=0; i<this.count;i++)
	{
		if(typeof(oThis.jPic[i].newImg) == 'object' && oThis.jPic[i].status == 'open'){
		    oThis.jPic[i].newImg.css('z-index','1000').stop().animate({width:oThis.jPic[i].width()+'px',height:oThis.jPic[i].height()+'px',left:oThis.jPic[i].offset().left,top:oThis.jPic[i].offset().top},500,function(){
                $(this).addClass('opacity0');
            });
		    oThis.jPic[i].status = 'close';
		}
	}
}

izoom.prototype.resize = function(){
	
	var oThis = this;
	
	oThis.close();
	
	for(var i=0; i<this.count;i++)
	{
		if(typeof(oThis.jPic[i].newImg) == 'object'){
            oThis.jPic[i].newImg.addClass('opacity0');
            oThis.jPic[i].newImg.css({
			    top:oThis.jPic[i].offset().top+'px',
			    left:oThis.jPic[i].offset().left+'px'
		    });
        }
	}
}

