/* carousel vars */
var currItem = -1,
	itemsCount,
	timer,
	nextItem,
    carouselAnimating = false;
	
/* stylist vars */	
var	currSex,
	currType, 
	currQuestN,
	arQuestIndex = [],
	questions = [],
	alreadyLoad = false,
	submitBtn = '<a class="submit-btn" href="javascript:void(0)"><div class="r"><div class="submit">подобрать</div></div></a>';

/* fancy in contacts */	
var titleFancyContacts,
	videoContent = '';	
	
function carousel(number){
    if (carouselAnimating) {
        return;
    }
    carouselAnimating = true;
	number = number != undefined ? number : currItem + 1;
	currItem = number;

    if (!($.browser.msie && parseInt($.browser.version, 10) < 9)) {
        $("#carousel .carousel-item:visible").animate(
            {
                opacity: 0
            },
            {
                duration: 600,
                complete: function(){
                    $(this).css({'background':''}).hide().css({'opacity':1});
                
                    $("#carousel-pagination li.active").removeClass("active");		
                    nextItem = $("#carousel .carousel-item").eq(number);
                    nextItem.fadeIn(600);	

                    $("#carousel-pagination li").eq(number).addClass("active");
                    
                    if (currItem == itemsCount-1) {
                        currItem = -1;
                    }	
                    carouselAnimating = false;
                }
            }
        );
	} else {
        $("#carousel .carousel-item:visible").hide().css({'opacity':1});
        $("#carousel .carousel-item").eq(number).show().addClass("active").css({'opacity':1});
        $("#carousel-pagination li.active").removeClass("active");	
        $("#carousel-pagination li").eq(number).addClass("active");
        if (currItem == itemsCount-1) {
            currItem = -1;
        }
        carouselAnimating = false;
    }

}

function titleFormat(title, currentArray, currentIndex, currentOpts) {
	return '<div class="prev"></div><div class="pag">' 
			+ (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') 
			+ '</div><div class="next"></div><div class="close"></div><div class="clear"></div>';
}

function sendStylist(){
	//$(document).scrollTo($("#stylist .stylist-step:visible:last"), 500);
	$("#catalog .catalog").empty();
	alreadyLoad = false;
	$.ajax({
		data: $("#stylist form").serialize(),
		url: '/application/ajax/stylist.php',
		type: 'GET',
		success: function(data, mess){
			if ($(".stylist .buttons .submit-btn").length == 0){
					$(".stylist .buttons").append(submitBtn);
			}
				
			$(".stylist .buttons").show();
			$("#stylist-filter").html(data);
		}
	});

}

$(document).ready(function(){

    $(document).on('click','a.disabled',  function (e) { e.preventDefault(); });

	/* stylist handlers */
	$(".stylist .submit-btn, .stylist .btn a").live("click", function(){
		if (!alreadyLoad){
			$('#catalog').controller().loadPage('/application/ajax/stylist.php?' + $("#stylist form").serialize()+"&SHOW_ALL=Y", '', {onComplete: function(){
				$(document).scrollTo('#catalog', {duration: 500});
			}});
			
			alreadyLoad = true;	
		}
		else{
			$(document).scrollTo("#catalog", 500);
		}
		return false;	
	});
	
	$("#stylist .sex input").change(function(){
		var id = $(this).attr("id").split('-');
		currSex = id[1];
		
		$("#stylist input").val("");
		$(this).val(id[1]);
		
		$("#stylist .stylist-step").not(".sex, .type").hide()
													  .find("input").removeAttr("checked");
		$("#stylist .type").fadeIn();													
		$("#stylist .type .answer").hide()
								   .find("input").removeAttr("checked");
		$("#stylist .type .answer[rel*='"+id[1]+"']").show();	
		
		$("#stylist .togglers").hide();
		
		$(this).parents("form").find(".answer").hide();
		$(this).parents("form").next(".togglers").show();
		$(this).parent().show();			

		/*$("#stylist form").css({"height":"41px"});
		$("#stylist .togglers").html("Другие варианты ответов");
		
		var count = $("#stylist .type .answer[rel*='"+id[1]+"']").length;
		if (count < 3)
			$("#stylist .type .togglers").hide();
		else
			$("#stylist .type .togglers").show(); */
		sendStylist();	
	});
	
	$("#stylist .type input").change(function(){
		var id = $(this).attr("id").split('-');
		currType = id[1];
		questions = [];
		currQuestN = 4;
		arQuestIndex = [];
			
		$("#stylist .type input").val("");		
		$(this).val(id[1]);
		
		$(this).parents("form").find(".answer").hide();
		$(this).parents("form").next(".togglers").show();
		
		$(this).parent().show();		
		
		$("#stylist .question").each(function(){
			/*var count = $(this).find(".answer[rel*='"+currType+"']").length;
			if (count < 3)
				$(this).find(".togglers").hide();
			else
				$(this).find(".togglers").show();	
				//$(this).find(".togglers").html("Другие варианты ответов"); */
				$(this).find(".togglers").hide();
				$(this).hide()
					   //.find("form").css({"height":"41px"})	
					   .find(".answer").hide()	
						  			   .find("input").removeAttr("checked")
													 .val("");
						
		});

		$("#stylist .question[rel*='"+id[1]+"']").each(function(){
			questions.push(this);
		});	
		var first = questions.shift();
		$(first).fadeIn()
				.find(".answer[rel*='"+currType+"']").show();	
		sendStylist();			
	});
	
	$("#stylist .question input").change(function(){
		var id = $(this).attr("id").split('-');
		
		$(this).parents("form").find("input").val("");
		$(this).val(id[2]);
		
		$(this).parents("form").find(".answer").hide();
		$(this).parents("form").next(".togglers").show();
		
		$(this).parent().show();
						
		
		var thisQuestIndex = $(this).parents(".question").eq(0).index();
		if (questions.length != 0 && !in_array(thisQuestIndex, arQuestIndex)) {
			arQuestIndex.push(thisQuestIndex);
			var next = questions.shift();
			$(next).find(".number").html(currQuestN++);
			$(next).fadeIn()
					.find(".answer[rel*='"+currType+"']").show();	
			$(next).find(".togglers").hide();			
		}		
		sendStylist();
	});

	$("#stylist .togglers").click(function(){
		var hidden = $(this).attr('rel');

		if ($(this).parent().hasClass("type")) {
			$(hidden).find(".answer[rel*='"+currSex+"']").show();
		}
		else if ($(this).parent().hasClass("sex")){
			$(hidden).find(".answer").show();
		}
		else{
			$(hidden).find(".answer[rel*='"+currType+"']").show();
		}

		$(this).hide();
		return false;
	}); 
	
	$("#stylist-reset").click(function(){
		$("#stylist input").val("")
						   .removeAttr("checked");
						   
		$("#stylist .togglers").hide();	
		$("#catalog .catalog").empty();
		$("#stylist-filter ul").empty().append("<li>Здесь будут выводится рекомендованные товары. Пожалуйста, ответьте на вопросы Стилиста.</li>");
		
		$(".stylist .buttons, #stylist .question, #stylist .type").fadeOut(100);
		$("#stylist .sex .answer").show();
		alreadyLoad = false;	
	});
	/* end stylist handlers */	
	

	$('#main-menu').each(function () {
        var menu = $(this),
            lis = menu.children('li');
        menu.delegate('li>a, li>span', 'mouseover', function () {
            $(this).parent().addClass('hover');
        });
        menu.delegate('li', 'mouseleave', function () {
            $(this).removeClass('hover');
        });
        lis.each(function () {
            var li = $(this),
                a = li.children('a, span'),
                sub = li.find('.tall-menu');
            if (sub.length) {
                sub.css('left', a.position().left + 'px');
            }
        });
        //lis.find('li:last-child').addClass('last-item');
    });

	
	$("#fancybox-title .next").live('click', function(){
		$.fancybox.next();
	});	
	
	$("#fancybox-title .prev").live('click', function(){
		$.fancybox.prev();
	});	
	
	$("#fancybox-title .close").live('click', function(){
		$.fancybox.close();
	});	

	
	$(".contacts a.fancybox").fancybox({
		'titlePosition' 	: 'inside',
		'onStart'			: function (el){
			titleFancyContacts = el.next(".body").eq(0).html();
			$('#fancybox-wrap').addClass('contacts-section');
		},
		'titleFormat'		: function(){
			return  titleFancyContacts;
		}
	});		


	
	
	/*---- carousel init ----------*/
	itemsCount = $("#carousel .carousel-item").length;
	
	if (itemsCount > 0) {
		for (var i = 0; i < itemsCount; i++){
			$("#carousel-pagination").append("<li>"+(i+1).toString()+"</li>");
		}
		$("#carousel-pagination li").eq(0).addClass("active");
		currItem = 0;
	}
    
    var carouselTimeout = 7000;
    $("#carousel-pagination li").click(function (e){
        if (carouselAnimating) {
            return;
        }
        clearInterval(timer);
        carousel($("#carousel-pagination li").index(this));
        timer = setInterval("carousel()", carouselTimeout);
        return false;
    });

	//carousel();
	timer = setInterval("carousel()", carouselTimeout);
    $('#carousel').hover(
        function () {
            clearInterval(timer);
        },
        function () {
            timer = setInterval("carousel()", carouselTimeout);
        }
    );
    
	/*---- carousel init end ----------*/	
	
	$("select").selectBox();
	$("input:checkbox.nice").uniform();	
	
	$("#email").focus(function(){
		if ($(this).val() == "Укажите ваш email") {
			$(this).val("");
		}	
	})
	
	$("#email").blur(function(){
		if (($(this).val() == "" && $(this).hasClass("error")) || ($(this).val() == "")) {
			$(this).val("Укажите ваш email");
			$(this).removeClass("error")
		}	
	})	
	
    var onHashChange = function () {
        var hash = location.hash,
            id = '';
        
        if (!/#slide-to-(\d+)/.test(hash)) {
            return;
        }
        id = '#city' + Number(String(hash).replace(/#slide-to-(\d+)/, '$1'));
        $(document).scrollTo(id, {duration: 1000});
    };
    onHashChange();
        
    $('#selectNetForm select').each(function () {
        var select = $(this);
        select.bind('change', function () {
            if (select.val() != '') {
                location = '/contacts/#slide-to-' + select.val();
            }
        });
    });
    
    $(window).hashchange(function () {
        onHashChange();
    });
    
    (function () {
    
        $('.flash').each(function () {
            var counter = 5;
            
            function flashHL () {
                var continueFunc = flashUnHL;
                if (!counter) {
                    continueFunc = undefined;
                    
                } 
                counter--;
                $(this).animate({opacity: 0}, 400, continueFunc ? $.proxy(continueFunc, this) : undefined);
                
            }; 
            
            var flashUnHL = function () {
                var continueFunc = flashHL;
                if (!counter) {
                    continueFunc = undefined;
                }
                if (counter == 0) {
                    $(this).removeClass('flash');
                }
                counter--;
                $(this).animate({opacity: 1}, 400, continueFunc ? $.proxy(continueFunc, this) : undefined);
            };  
            flashHL.call(this);
        });
    })();
    
});


/* helpper */

function in_array(what, where) {
    for(var i=0; i<where.length; i++)
        if(what == where[i]) 
            return true;
    return false;
}

function in_array_keys(what, where) {
    for(var i=0; i<where.length; i++)
        if(where[what]) 
            return true;
    return false;
}


/* Каталог  */
(function ($) {
    
    window.APP = window.APP || {};

    // запускаем виджеты
    $(function () {
        $('#catalog').catalog();
        $('#ask-question a').contactForm();
        $('#catalog-top').catalogTop();
        $('.subscribe').subscribeForm();
        $('.vacancy-form').vacancyForm();
		$("#quiz").quiz();
		$("#video").videogalerry();
    });
    
    $.Controller('APP.VideoGallery', 
        {
            pluginName: 'videogalerry'
        },
        {
            init: function() {
				this.items = [];
                this.itemsCount = this.element.find(".video-item").length;
				this.element.find(".video-item").each(this.proxy(function(i, val){
					this.items[i] = $(val);
				}));
				
				this.currItemNum = -1;
				
				this.element.append('<div id="galerry-pagin" style="display: none"><div class="prev"></div> <div class="pag"></div><div class="next"></div><div class="close"></div><div class="clear"></div></div>');
				this.pagin = this.element.find('#galerry-pagin');
				this.current = this.pagin.find('.pag');
				this.videoContent = 'sss';
            },
			createPagin : function (number){
				this.current.html((number+1) + " / " + this.itemsCount);
				return this.pagin.html();
			},
			paginBind: function(){
				$('#fancybox-wrap').find('.close').bind('click', this.proxy(this.closeFancy));
				$('#fancybox-wrap').find('.prev').bind('click', this.proxy(this.prevFancy));
				$('#fancybox-wrap').find('.next').bind('click', this.proxy(this.nextFancy));			
			},
			onChangeContent: function(){
				this.paginBind();
				$("#fancybox-wrap").css({'width':'auto'});		
				$("#fancybox-content").css({'width':'auto'});
				$.fancybox.center();	
				setTimeout("$('#fancybox-wrap').css({'visibility':'visible'})",200);				
			},
			'.video-item a click' : function(el, ev){
				ev.preventDefault();
				var currItem = el.parents('.video-item').eq(0); 
				
				
				$.get(el.attr('href'), '', this.proxy(function(data){
					this.videoContent = data;
					this.videoContent += this.createPagin(currItem.index());
					$.fancybox({
						'scrolling'			: 'no',
						'overlayColor'		: '#000',
						'transitionIn'		: 'none',
						'transitionOut'		: 'none',
						'titlePosition' 	: 'inside',
						'padding'			: 0,
						'margin'			: 0,
						'showNavArrows'		: false,
						'showCloseButton'	: false,				
						'content'			: this.videoContent,
						onStart: function () {
							$('#fancybox-wrap').addClass('video-section');	
						},
						onComplete: this.proxy(function(){
							this.onChangeContent();		
						}) 
					});
					this.currItemNum = currItem.index();					
				}));

			},
			closeFancy : function(){
				$.fancybox.close();
			},
			prevFancy : function(){
				var nextItem = this.currItemNum-1;
				if (in_array_keys((nextItem), this.items)){
					$.get(this.items[nextItem].find('a.fancybox').eq(0).attr('href'), '', this.proxy(function(data){
						$('#fancybox-wrap #fancybox-content > div').hide();	
						$('#fancybox-wrap #fancybox-content').empty();	
						$('#fancybox-wrap #fancybox-content').html( data + this.createPagin(nextItem) );	
						this.currItemNum = nextItem;
						this.onChangeContent();					
					}));
				}
			},
			nextFancy : function(){
				var nextItem = this.currItemNum+1;
				if (in_array_keys((nextItem), this.items)){
					$.get(this.items[nextItem].find('a.fancybox').eq(0).attr('href'), '', this.proxy(function(data){
						$('#fancybox-wrap #fancybox-content > div').hide();	
						$('#fancybox-wrap #fancybox-content').empty();	
						$('#fancybox-wrap #fancybox-content').html( data + this.createPagin(nextItem) );	
						this.currItemNum = nextItem;
						this.onChangeContent();					
					}));
				}
			}
        }
    );	
    
    $.Controller('APP.FormTabber', 
        {
            pluginName: 'formTabber',
            defaults: {
                exclude: ['file'],
                parents: '.input',
                start: 1
            }
        },
        {
            init: function () {
                this.o = this.options;
                var tabindex = this.o.start + 1;
                this.inputs = this.find('input, select, textarea').not(':hidden');
                var self = this;
                this.inputs = this.inputs.filter(function (i) {
                    return !!($.inArray($(this).attr('type'),self.o.exclude) === -1);
                });
                
                this.first = this.o.start;
                var style = ' style="position: absolute; visibility: hidden: z-index: -10; width: 0; height: 0;" ';
                var firstEl = this.inputs.first();
                if (this.o.parents) {
                    firstEl = firstEl.closest(this.o.parents);
                }
                firstEl.before('<input type="text" tabindex="' + this.o.start + '"' + style + '/>');
                this.inputs.each(function () {
                    $(this).attr('tabindex', tabindex++);
                });
                this.last = tabindex;
                
                var lastEl = this.inputs.first();
                if (this.o.parents) {
                    lastEl = lastEl.closest(this.o.parents);
                }
                lastEl.after('<input type="text" tabindex="' + tabindex + '"' + style + '/>');
            }, 
           
            '* focus': function (el, ev) {
                this.checkAndJump(ev.target);
            },
            
            checkAndJump: function (el) {
                var index = $(el).attr('tabindex');
                
                if (index == this.first) {
                    this.find('[tabindex="' + (this.last - 1) + '"]').focus();
                } else if (index == this.last) {
                    this.find('[tabindex="' + (this.o.start + 1) + '"]').focus();
                }
            }
        }
    );
	
    (function () { 
        var inst = null;
        $.Controller('APP.AjaxLoader',
            {
                init: function () {
                    $(this.proxy(function () {
                        if (inst === null) {
                            var loader = $('<div id="ajaxLoader" />').appendTo('body');
                            
                            inst = new this(loader);
                        }
                    }));
                },
                
                show: function () {
                    if (inst) {
                        inst.show();
                    }
                }, 
                
                hide: function () {
                    if (inst) {
                        inst.hide();
                    }
                }
            },
            {
                init: function (el) {
                    el.append('<div class="inner" />');
                }, 
                
                show: function () {
                    this.element.show();
                }, 
                
                hide: function () {
                    this.element.hide();
                }
            }
        ); 
    })();
    var loader = APP.AjaxLoader;
    
    // уникализирует id и name при создании всплывашки с опциями камней для каталога
    $.fn.uniqify = function () {
        var parent = this,
            count = $.fn.uniqify.count++;
        this.find('*').andSelf().each(function (i, el) {
            var self = $(this),
                id = self.attr('id'),
                name = self.attr('name');
                
            if (id) {
                var newId = id + 'Clone' + count;
                self.attr('id', newId);
                parent.find('label[for="' + id + '"]').attr('for', newId);
            }
        });
        return this;
    };
    $.fn.uniqify.count = 0;
    
    $.goldFancybox = (function () {
        var o = {
            showCloseButton: true,
            centerOnScroll: true,
            padding: 0,
            overlayOpacity : 0.6,
            overlayColor : '#000',
            noOverflow: true,
            contentType: 'txt',
            onStart: function () {
                $('#fancybox-wrap').addClass('selector-window');
            },
            title: null,
            width: 400
        }
        return function (options) {
            options = options || {};
            var title = options.title;
            options.title = null;
            if ($.isFunction(options.onStart)) {
                options.onStart = (function () {
                    var onStart = options.onStart;
                    return function () {
                        o.onStart(arguments);
                        onStart(arguments);
                    }
                })();
            }
            
            options = $.extend({}, o, options, {
                content: $('#formTemplate').tmpl({
                        content: options.innerContent || '', 
                        title: title || 'Внимание',
                        width: options.width,
                        height: options.height,
                        contentType: options.contentType
                    }).html()
            });
            $.fancybox(options);
        };
    })();
    
    // различные утилиты
    $.Class('Utils',
        {
            wordForm: function (count, form1, form2_4, form5_0) {
                form1 = form1 || "";
                form2_4 = form2_4 || "а"; 
                form5_0 = form5_0 || "ов";
                
                var n100 = count % 100,
                    n10  = count % 10;
                if ((n100 > 10) && (n100 < 21)) {
                    return form5_0;
                } else if ((!n10) || (n10 >= 5)) {
                    return form5_0;
                } else if (n10 == 1) {
                    return form1;
                }
                return form2_4;
            }, 
            
            paramsToNames: function (params) {
                var strings = String($.param(params)).split(/&/);
                var decoded = {};
                $.each(strings, function (key, val) {
                    var splitted = String(decodeURIComponent(val)).split(/=/);
                    if (splitted.length < 2) {
                        return;
                    }
                    if (/\[\]$/.test(splitted[0])) {
                        if (!$.isArray(decoded[splitted[0]])) {
                            decoded[splitted[0]] = []; 
                        }
                        decoded[splitted[0]].push(splitted[1]);
                        
                    } else {
                        decoded[splitted[0]] = splitted[1];
                    }
                });
                return decoded;
            }
        },
        {}
    );
    
    // пейджер
    $.Controller('APP.Pager', 
        {
            pluginName: 'pager'
        },
        {
            init: function () {
                this.catalog = this.options.catalog;
            },
            'a click': function (el, ev) {
                ev.preventDefault();
                this.element.trigger('pagerchanged', {url: el.attr('href')});
            }
        }
    );
    
    // управляет контентом окна с полным набором опций
    $.Controller('APP.SelectorWindowContent',
        {
            pluginName: 'selectorWindowContent',
            defaults: {
                parent: null    // контроллер объекта окна
            }
        },
        {   
            init: function (el) {
                this.parent = this.options.parent;
            },
            
            'input[type="checkbox"] click': function (el, ev) {
                if (this.parent !== null) {
                    this.updateParent();
                }
            },
            
            '.submit click': function (el, ev) {
                ev.preventDefault();
                if (this.parent !== null) {
                    this.updateParent(true);
                }
                $.fancybox.close();
            },
            
            '.reset click': function (el, ev) {
                ev.preventDefault();
                this.find('input[type="checkbox"]').removeAttr('checked');
                if (this.parent !== null) {
                    this.updateParent();
                }
            },
            
            updateParent: function (submit) {
                submit = typeof submit === 'undefined' ? false : !!submit;
                
                this.parent.find('input[type="checkbox"]').removeAttr('checked');
                var parent = this.parent,
                    otherVariants = 0;
                    
                this.find('input[type="checkbox"]').filter(':checked').each(function (i, el) {
                    var input = $(this);
                    parent.find('input[name="' + input.attr('name') + '"][value="' + input.val() + '"]').attr('checked', 'checked');
                    
                    if ($.inArray(parseInt(input.attr('value'), 10), parent.shortVariants) === -1) {
                        otherVariants++;
                    }
                });
                var other = this.parent.find('.other');
                if (otherVariants) {
                    this.parent.selectorLink.html('И еще ' + otherVariants + ' ' + Utils.wordForm(otherVariants, "элемент", "элемента", "элементов"));
                } else {
                    this.parent.selectorLink.html('Показать все')
                }
                if (submit) {
                    this.parent && this.parent.parent && this.parent.parent.notifyFilter();     
                }
            }
        }
    );
    
    // управляет координацией взаимоотношений между блоком чекбоксов в фильтре, и всплывающим окном с полным списком опций, содержит всплывающее окно
    $.Controller('APP.SelectorWindow',
        {
            pluginName: 'selectorWindow',
            defaults: {
                source: '.all-variants',
                windowLink: '.selector-link',
                parent: null
            },
            count: 0
        },
        {
            init: function (el) {
                this.o = this.options;
                this.c = this.constructor;
                this.parent = this.o.parent;
                this.source = this.find(this.o.source);
                this.selectorLink = this.find(this.o.windowLink);
                this.allVariants = this.find(this.o.source);
                this.shortVariants = $.parseJSON(this.find('.kinds-variants').attr('data-short') || '[]');
            },
            '.selector-link click': function (el, ev) {
                ev.preventDefault();
                var content = this.allVariants.clone().wrapInner('<form action="#" />').uniqify();
                if ($.browser.msie) {
                    this.cloneInputsToPopup(content);
                }

                $.fancybox({
                    content: content.html(),
                    //modal: true,
                    showCloseButton: true,
                    centerOnScroll: true,
                    padding: 0,
                    width: this.allVariants.width(),
                    height: this.allVariants.height(),
                    overlayOpacity : 0.6,
                    overlayColor : '#000',
                    noOverflow: true,
                    onStart: this.proxy(function () {
                        $('#fancybox-wrap').addClass('selector-window');
                    }),
                    onComplete: this.proxy(function () {
                        $('#fancybox-wrap form').selectorWindowContent({parent: this});
                    })
                });
            },
            
            cloneInputsToPopup: function (popup) {
                if (!(popup instanceof jQuery)) {
                    return;
                }
                
                this.find('input[type="checkbox"]').filter(':checked').each(function (i, el) {
                    var input = $(this);
                    popup.find('input[name="' + input.attr('name') + '"][value="' + input.val() + '"]').attr('checked', 'checked');
                });
            }
        }
    );
    
    // управляет блоками сеелктбоксов в фильтре
    $.Controller('APP.SelectorBlock',
        {
            pluginName: 'selectorBlock',
            defaults: {
                hiddens: '.all-variants',
                shortVariants: '.kinds-variants'
            } 
        },
        {
            init: function (el) {
                this.o = this.options;
                this.hiddens = this.find(this.o.hiddens);
                this.short = this.find(this.o.shortVariants);
                if (this.hiddens.length) {
                    this.element.selectorWindow({parent: this});
                }
            },
            '.kinds-variants input[type="checkbox"] click': function (el, ev) {
                
                var selector = 'input[name="' + el.attr('name') + '"][value="' + el.val() + '"]',
                    doubler = this.hiddens.find(selector);

                if (el.is(':checked')) {
                    doubler.attr('checked', 'checked');
                } else {
                    doubler.removeAttr('checked');
                }
            },
            
            notifyFilter: function () {
                this.element.trigger('blockfilterchanged');
            }
        }
    );
    
    // контроллирует всю панель фильтра, также является скользящим виджетом
    $.Controller('APP.FloatingWidget',
        {
            pluginName: 'floatingWidget',
            defaults: {
                parent: '#catalog',
                minTop: 24,
                backLink: '.back-to-top'
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.startClasses = this.element.attr('class');
                this.startPosition = this.element.position();
                this.parent = $(this.options.parent);
                this.backLink = $(this.o.backLink);
                
                this.element.addClass('floating-window')
                    .width(this.element.width());
                
                this.marginFix = 0; //parseInt(this.find('.sidebar-title').css('margin-top'), 10);

                if (this.parent.height() == this.element.height() && $(window).height() <= $(document).height()) {
                    
                    
                }
                this.placeholder = $('<div />').attr('class', this.startClasses).addClass('floating-window-placeholder').html('&nbsp;')
                    .width(this.element.width())
                    .height(this.element.height());
                    
                this.placeholder.insertBefore(this.element);
                
                this.setSizes();
                this.repositionate();
                var shift = this.start - this.parent.offset().top + this.parent.css('margin-top');
                this.element.css({top: shift + 'px'});
                
                $(this.o.backLink).localScroll({duration:600});
                
                // запускаем позиционирование по таймеру, чтобы обновлять позицию панельки при скролле с помощью ползунков
                //this.repositionateCycle();
            },
            
            '{window} resize': function () {
                this.setSizes();
                this.repositionate();
            },
            
            '{document} resize': function () {
                this.setSizes();
                this.repositionate();
            },
            
            // Определяем новые рамки для виджета
            setSizes: function () {
                this.parentOffset = this.parent.offset();
                this.placeholderOffset = this.placeholder.offset();
                //this.placeholderPosition = this.placeholder.position();
                this.parentHeight = this.parent.height();
                this.start = this.parentOffset.top;
                this.end = this.start + this.parentHeight;
                this.windowHeight = $(window).height();
            },
            
            // располагаем виджет в нужном месте в рамках разрешенного пространства
            repositionate: function () {
                var top = $(window).scrollTop(),
                    outerHeight = this.element.outerHeight(),
                    widgetHeight = this.element.height(),
                    diff = outerHeight - widgetHeight,      // учет паддингов и маргинов
                    newTop = this.start - top,
                    state = this.state;
                    newLeft = this.placeholderOffset.left;

                 // устанавливаем максимальное смещение сверху
                 
                if (newTop < this.o.minTop && outerHeight + this.o.minTop < this.windowHeight && this.parentHeight > outerHeight) {
                    if (top + outerHeight <= this.end) {
                        this.element.css('position', 'fixed');
                        if (top + outerHeight < this.end - this.o.minTop - diff ) {
                            newTop = this.o.minTop;
                            
                        } else {
                            newTop = this.end - widgetHeight - top - this.o.minTop;
                        }
                        
                    } else {
                        this.element.css('position', 'absolute');
                        if (outerHeight >= this.parentHeight) {
                            newTop = this.start - this.parentOffset.top + this.o.minTop;
                            
                        } else {
                            newTop = this.end - widgetHeight - this.parentOffset.top;
                        }
                        newLeft -= this.parentOffset.left;
                    }
                    state = 'active';
                    
                } else {
                    this.element.css('position', 'absolute');
                    newTop = this.start - this.parentOffset.top + this.o.minTop;
                    if (top > this.start + outerHeight + this.o.minTop) {
                        if (!this.backLink.is(':visible')) {
                            this.backLink.stop(false, true).fadeIn('fast');
                        }
                    } else {
                        if (this.backLink.is(':visible')) {
                            this.backLink.stop(false, true).fadeOut('fast');
                        }
                    }  
                    newLeft -= this.parentOffset.left;                    
                    
                    state = 'passive';
                }                
                
                if (state != this.state) {
                    var oldState = this.state;
                    this.state = state;
                    this.onStateChange(this.state, oldState);
                    this.element.trigger('fwstatechange', {newState: this.state, oldState: oldState});
                }
                
                this.element.css({
                    left: newLeft + 'px', 
                    top: newTop + 'px'
                });                
            },
            
            repositionateCycle: function () {
                setTimeout(this.proxy(function () {
                    this.repositionate();
                    this.repositionateCycle();
                }), 30);
            },
            
            onStateChange: function (oldState) {
                
            },
            
            '{window} scroll': function (el, ev) {
                this.repositionate();
            }
        }
    );
    
    // контроллер фильтра
    APP.FloatingWidget('APP.Filter', 
        {
            pluginName: 'catalogFilter',
            listenTo: ['blockfilterchanged']
        },
        {
            init: function (el) {
                this._super();
                this.find('a.submit-btn').removeAttr('onclick');
                this.form = this.find('form');
                this.find('.filter-kind').selectorBlock();
            },
            
            'a.submit-btn click': function (el, ev) {
                ev.preventDefault();
                this.submitForm();
            },
            
            'input[type="checkbox"] click': function (el, ev) {
                setTimeout(this.proxy(function () { 
                    this.submitForm();
                }), 0);
            },
            
            submitForm: function () {
                var parts = /(.*?)\?/im.exec(this.form.get(0).action),
                    url = '';
                
                if (!$.isArray(parts) || !parts[1] || (parts[1] && parts[1].length === 0)) {
                    url = this.form.get(0).action;

                } else {
                    url = parts[1];
                }
                if (!url) {
                    return;
                }
                var params = this.form.formParams();
                delete params.PAGEN_1;
                this.element.trigger('filterchanged', {
                    url: url,
                    params: params
                });
            },
            
            '.filter-kind blockfilterchanged': function (el, ev) {
                this.submitForm();
            },
            
            'form submit': function (el, ev) {
                ev.preventDefault();
            }, 
            
            updateParamsFromState: function (params) {
                if (!(params instanceof Object)) {
                    return;
                }
                
                this.find('input[type="checkbox"]').removeAttr('checked');
                var names = Utils.paramsToNames(params);
                
                $.each(names, this.proxy(function (key, val) {
                    if ($.isArray(val)) {
                        for (var i = 0; i < val.length; i++) {
                            this.find('input[type="checkbox"][name="' + key + '"][value="' + val[i] + '"]').attr('checked', 'checked');
                        }
                    } else {
                        this.find('input[type="checkbox"][name="' + key + '"][value="' + val + '"]').attr('checked', 'checked');
                    }
                })); 
            }
        }
    );
    
    $.Controller('APP.CatalogDetail',
        {
            pluginName: 'catalogDetail',
            defaults: {
                jqZoomOptions: {  
                    zoomType: 'standard',  
                    lens:true,  
                    preloadImages: true,  
                    alwaysOn:false,  
                    zoomWidth: 366,  
                    zoomHeight: 284,  
                    //xOffset:90,  
                    //yOffset:30,  
                    //position:'right',
                    preloadText: 'Загрузка...'
                }
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.img = this.find('.left-block .image img');
                
                if ($.browser.msie && this.img.length) {
                    this.img[0].onload  = this.proxy(this.attachZoom);
                    this.img[0].src = this.img[0].src;
                } else {
                    this.img.on('load', this.proxy(this.attachZoom));
                }
            },
            
            '.video-link a click': function (el, ev) {
                ev.preventDefault();
                
                $.fancybox({
                    href: el.attr('href'),
                    //modal: true,
                    showCloseButton: true,
                    centerOnScroll: true,
                    overlayOpacity : 0.6,
                    overlayColor : '#000',
                    onStart: this.proxy(function () {
                        $('#fancybox-wrap').addClass('detail-video-window');
                    })
                });
            },
            
            attachZoom: function () {
                var pos = this.img.position();
                this.find('.left-block .image a').jqzoom($.extend({}, this.o.jqZoomOptions, {
                    yOffset: -1 * pos.top,
                    xOffset: pos.left + 10
                }));
            }
        }    
    );
    
    // основной контроллер каталога, управляет координацией своих компонентов и загружает страницы списка
    $.Controller('APP.Catalog',
        {
            pluginName: 'catalog',
            listenTo: ['pagerchanged', 'filterchanged', 'popstate'],
            defaults: {
                paging: '.pagination',
                list: '.catalog',
                detail: '.catalog-detail',
                filter: '.filter',
                history: true,
                infiniteList: true
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.loadedPages = [1];
            },
            
            '{document} ready': function () {
                this.attachPager();
                this.window = $(window);
                this.list = this.find(this.o.list);
                this.wrapper = $();
                this.infiniteLast = false;
                if (this.o.infiniteList) {
                    this.wrapper = this.list.wrapInner('<div id="catalogListWrapper" />').children();
                }
                this.detail = this.find(this.o.detail).catalogDetail();
                this.originalTitle = document.title;
                this.filter = this.find(this.o.filter).catalogFilter({parent: '#catalog', backLink: '#catalog ' + this.o.filter + ' + .back-to-top'});
                this.find('.category-nav').floatingWidget({parent: '#catalog', backLink: '#catalog .sidebar-block + .back-to-top'});
                this.setLoading(false);
               
                if (this.o.history && History.enabled ) {
                    History.Adapter.bind(window, 'statechange', this.proxy(function(ev) {
                        if (!this.isLoading) {
                            this.loadPage(location.href); 
                        }
                        var data = History.getState().data,
                            stateParams = data && data.params;

                        if (stateParams && this.filter.length) {
                            this.filter.controller().updateParamsFromState(stateParams);
                        }
                        
                    }));
                }
                
                $.ajaxSetup({
                    timeout: 10000,
                    error: this.proxy(function () {
                        this.setLoading(false);
                    })
                });
            },
            
            '.pager pagerchanged': function (el, ev, data) {
                this.infiniteLast = false;
                if (data && data.url) {
                    this.loadPage(data.url);
                    if (this.o.history) {
                        this.pushCatalogUrl(data.url);
                    }
                    this.scrollToUp();
                }
            },
            
            '.filter filterchanged': function (el, ev, data) {
                this.infiniteLast = false;
                if (data instanceof Object && data.url) {
                    this.loadPage(data.url, data.params);
                    if (this.o.history) {
                        this.pushCatalogUrl(data.url, data.params);
                    }
                    this.scrollToUp();
                }
            },
            
            '{window} scroll': function (el, ev) {
                if (this.infiniteLast || this.find('.catalog-section').length == 0) {
                    return;
                }
            
                var lastItem = this.list.find('.catalog-item:last'),
                    lastHeight = lastItem.length > 0 ? lastItem.height : 200;
                
                if (this.isLoading) {
                    this.waitingParams = null; //[location, {PAGEN_1: lastPage + 1}];
                    return;
                }
                
                // если есть хоть один элемент и окно проскроллено до него, подгружаем еще
                if (lastItem.length && this.window.scrollTop() + this.window.height() > lastItem.offset().top) {
                    this.loadPage();
                }                
            },
            
            scrollToUp: function () {
                var scrollTop = $(window).scrollTop(),
                    top = this.element.offset().top;
                
                if (scrollTop > top) {
                    $(document).scrollTo('#workarea', {duration: 500});
                }
            },
            
            scrollToPageEnd: function () {
                var top = this.list.offset().top + this.list.height() - $(window).height();
                top = top < 0 ? 0 : top;

                $(document).scrollTo(top, {duration: 600});
            },
            
            loadPage: function (page, params, options) {
                defaults = {
                    changeUrl: true,
                    PAGEN_1: '1'
                };
                options = $.extend({}, defaults, options);
                
                if (this.isLoading) {
                    this.waitingParams = arguments;
                    return;
                }
                var infinite = !!(this.o.infiniteList && arguments.length == 0);
                
                this.setLoading(true, infinite);

                if (options.changeUrl) {
                    //this.pushUrl($.trim(page) + (typeof params === 'undefined' ? '' : '?' + $.param(params)), {params: params, pageNum: options.pageNum});
                }
                
                if (arguments.length === 0 && this.o.infiniteList) {
                    page = String(location).replace(/&?PAGEN_\d+=\d+/i, '');
                    var next = parseInt(this.list.find('.catalog-section:last').attr('data-page'), 10) + 1;
                    
                    if ($.inArray(this.loadedPages, next) !== -1) {
                        return;
                    } 
                    params = $.extend({}, params, {PAGEN_1: next});
                } else {
                    this.loadedPages = [1];
                    this.infiniteLast = false;
                }  
                
                var afterLoad;
                if (this.o.infiniteList && arguments.length == 0) {
                    this.list.find('.catalog-section:last').after('<div class="ajax-load-box"></div>');
                    //this.scrollToPageEnd();
                    afterLoad = this.afterPageLoadedInfinite;
                    
                } else {
                    afterLoad = this.afterPageLoaded;
                }

				if (typeof options.onComplete == "function"){
					this.onComplete = options.onComplete;
				};
				
                if (params instanceof Object) {
                    $.get(page, params, this.proxy(afterLoad));
                } else {
                    $.get(page, this.proxy(afterLoad));
                }
            },
            
            setLoading: function (loading, infinite) {
                loading = typeof loading == 'undefined' ? true : loading;
                infinite = typeof infinite == 'undefined' ? false : infinite;
                
                this.isLoading = loading;
                if (this.isLoading) {
                    if (!this.o.infiniteList) {
                        this.list.stop(false, false).animate({opacity: 0.6}, 300);
                    } 
                    this.list.addClass('catalog-loading');
                    //this.list.find('.load-screen .inner').css({opacity:0}).animate({opacity: 0.5}, 400);
                    if (!infinite) {
                        loader.show();
                    }
                    
                } else {
                    this.list.removeClass('catalog-loading');
                    if (!this.o.infiniteList) {
                        this.list.stop(false, false).animate({opacity: 1}, 300);
                    }
                    //this.list.children('.load-screen').animate({opacity: 0}, 200);
                    if (!infinite) {
                        loader.hide();
                    }
                }
            },
            
            afterPageLoaded: function (answer) {
                var tmp = this.list.wrapInner('<div id="catalogListWrapper" />').children().eq(0);
                // фиксируем высоту
                this.list.height(this.list.height());
                // вставляем контунт во враппер                
                tmp.html(answer);
                //this.list.find('.load-screen .inner').css({opacity:0.5}).animate({opacity: 0}, 400);
                this.list.animate({height: tmp.height()}, 400, this.proxy(function () {
                    this.attachPager();
                    this.setLoading(false);
                    
                    if (this.waitingParams) {
                        var newParams = this.waitingParams;
                        this.waitingParams = null;
                        this.loadPage.apply(this, newParams);
                        if (this.o.history) {
                            this.pushCatalogUrl.apply(this, Array.prototype.slice.call(newParams, 0, 2));
                        }
                    }
                    
                }));
				
				if (this.onComplete) {
					this.onComplete();
				}
                
            },
            
            afterPageLoadedInfinite: function (answer) {
                var last = this.list.find('.catalog-section:last'),
                    newPage = null,
                    oldHeight = this.wrapper.height();
                
                this.list.find('.ajax-load-box').remove();
                
                // фиксируем высоту
                this.list.height('auto');
                this.wrapper.height(oldHeight);
                // вставляем контунт во враппер                
                newPage = $(answer).filter('.catalog-section').insertAfter(last);
 
                if (parseInt(newPage.attr('data-count'), 10) === 0) {
                    newPage.remove();
                    this.infiniteLast = true;
                    this.setLoading(false, true);
                    this.repositionateChildren();
                    return;
                }
                
                //this.list.find('.load-screen .inner').css({opacity:0.5}).animate({opacity: 0}, 400);

                this.wrapper.animate({height: oldHeight + newPage.height()}, 400, this.proxy(function () {
                    this.setLoading(false);
                    this.repositionateChildren();
                }));
                
            },
            
            repositionateChildren: function () {
                this.find('.floatingWidget:last, #catalogFilter').each(function () {
                    var controller = $(this).controller();
                    controller.setSizes();
                    controller.repositionate();
                });
            },
            
            attachPager: function () {
                this.pager = this.find(this.o.paging).pager({catalog: this});
            },
            
            pushCatalogUrl: function (page, params, pageNum) {
                this.pushUrl($.trim(page) + (typeof params === 'undefined' ? '' : '?' + $.param(params)), {params: params, pageNum: pageNum || 1});
            },
            
            pushUrl: function (url, params) {
                params = params || {};
                if (typeof params.page !== 'undefined' && params.page != 1) {
                    document.title = this.originalTitle + ' &mdash; страница ' + params.page;
                }
                this.pushState(params, document.title, url); 
            },
            
            pushState: function (state, title, url) {
                if ( !History.enabled ) {
                    return false;
                }

                History.pushState(state, title, url);
                /* History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2"
                History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3"
                History.back(); // logs {}, "Home Page", "?"
                History.go(2); // logs {state:3}, "State 3", "?state=3" */
            },
            
            update: function () {
                this._super();
            }
        }
    );
    
    (function () {
        $.Controller('APP.ContactFormContent', 
            {
                pluginName: 'contactFormContent',
                defaults: {
                    formID: '#contactForm',
                    validation: {
                        errorPlacement: function (error, element) {},
                        highlight: function (element, errorClass) {
                            $(element).closest('.input').addClass(errorClass);
                        },
                        unhighlight: function (element, errorClass) {
                            $(element).closest('.input').removeClass(errorClass);
                        }     
                    }
                }
            },
            {
                init: function (el) {
                    this.o = this.options;
                    this.element.validate(this.o.validation);
                    this.element.formTabber({start: 1000});
                    this.find('input[type="text"]').first().focus();
                },
                
                'submit': function (el, ev) {
                    ev.preventDefault();
                    if (this.element.valid()) {
                        $.post(this.element[0].action, this.element.formParams(), this.proxy(this.successSubmit));
                    }
                },
                
                '.submit click': function (el, ev) {
                    ev.preventDefault();
                    this.element.submit(); 
                },
                
                '.ok click': function (el, ev) {
                    ev.preventDefault();
                    $.fancybox.close();
                },
                
                successSubmit: function (response) {
                    if (response.status == 'success') {
                        this.element.html('').append($('#contactFormThankYou').tmpl());
                        setTimeout(function () {
                            $.fancybox.close();
                        }, 5000);
                        
                    } else {
                        $.each(response.errors, this.proxy(function (name, val) {
                            this.find('[name="Contact[' + name + ']"]').closest('.row').addClass('error');
                        }));
                    }
                },
                
                'input[type="text"], textarea focusin': function (el, ev) {
                    el = $(ev.target);
                    el.parent().addClass('focus');
                },
                
                'input[type="text"], textarea focusout': function (el, ev) {
                    el = $(ev.target);
                    el.parent().removeClass('focus');
                }
            }
        );
        
        var instance = null;
        
        $.Controller('APP.ContactFormWindow', 
            {
                pluginName: 'contactFormWindow',
                defaults: {
                    formID: '#contactForm'
                },
                
                init: function () {
                    if (instance === null) {
                        var el = $(this.defaults.formID);
                        if (!el.length) {
                            el = $('<div id="' + this.defaults.formID + '" />')
                        }
                        instance = el.contactFormWindow().controller();
                    }
                },
                
                show: function () {
                    instance && instance.show();
                },
                
                close: function () {
                    instance && instance.close();
                }
            },
            {
                init: function (el) {
                    this.o = this.options;
                },
                
                show: function () { 
                    $.goldFancybox({
                        innerContent: $('#contactFormTemplate').tmpl().html(),
                        contentType: 'html',
                        title: 'Форма обратной связи',
                        width: 360,
                        height: 270,
                        autoDimensions: false,
                        onStart: function () {
                            $('#fancybox-wrap').addClass('contact-form-window');
                        },
                        onComplete: function () {
                            $('#fancybox-content form').contactFormContent();
                        }
                    });
                },
                
                close: function () {
                    $.fancybox.close();
                }
            }
        );
    })();
    
    
    $.Controller('APP.ContactForm', 
        {
            pluginName: 'contactForm',
            defaults: {
                linksClass: '.contact-link'
            },
            
            init: function () {
                $(this.defaults.linksClass).contactForm();
            }
        },
        {
            'click': function (el, ev) {
                ev.preventDefault();
                APP.ContactFormWindow.show();
            }
        }
    );
    
    $.Controller('APP.CatalogTop',
        {
            pluginName: "catalogTop"
        },
        {
            init: function (el) {
                this.wrapper = this.find('.catalog-wrapper');
                this.wrapperOuter = this.find('.catalog-outer-wrapper');
                this.wrapperOuter.height($('.catalog-wrapper .catalog:not(.hidden)').outerHeight());
            },
            
            '.switcher a click': function (el, ev) {        
                ev.preventDefault();
                var tab = el.closest('.tab'),
                    id = tab.attr('data-id'),
                    otherTabs = this.find('.switcher .tab').not('[data-id=' + id + ']'),
                    oldTab = this.find('.catalog:not(.hidden)');

                 var tabs = this.find('.catalog-wrapper .catalog'),
                    curTab = tabs.eq(id - 1),
                    maxHeight = curTab;
                if(curTab.length == 0) {
                     return;
                }
                
                tab.addClass('hidden');
                this.find('.switcher .tab-active-state[data-id=' + id + ']').removeClass('hidden');
                otherTabs.filter('.tab-active-state').addClass('hidden');
                otherTabs.filter('.tab-passive-state').removeClass('hidden');
                
               
                
                
                this.wrapper.height(curTab.outerHeight());
                this.wrapperOuter.height(oldTab.outerHeight());
                oldTab.addClass('switching');
                curTab.addClass('switching');
                
                oldTab.stop(false, true).animate({opacity: 0}, 300);
                curTab.stop(false, true).animate({opacity: 1}, 300, this.proxy(function () {
                    
                    
                    oldTab.removeClass('switching');
                    curTab.removeClass('switching');
                    this.wrapper.css('height', 'auto');
                    tabs.not(curTab).addClass('hidden');
                    curTab.removeClass('hidden');
                    
                }));
                this.wrapperOuter.stop(false, true).animate({height: curTab.outerHeight()}, 300);
            }
        }
    );
    
    
    $.Controller('APP.SubscribeForm',
        {
            pluginName: "subscribeForm",
            defaults: {
                validation: {
                    errorPlacement: function (error, element) {},
                    highlight: function (element, errorClass) {
                        $(element).parent().andSelf().addClass(errorClass);
                    },
                    unhighlight: function (element, errorClass) {
                        $(element).parent().andSelf().removeClass(errorClass);
                    }     
                }
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.form = this.find('form');
                this.form.validate(this.o.validation);
                
            },
            
            'submit': function (el, ev) {
                
            },
            
            '.submit-btn .submit click': function (el, ev) {
                ev.preventDefault();
                this.form.submit(); 
            }
        }
    );
    
    $.Controller('APP.VacancyForm',
        {
            pluginName: "vacancyForm",
            defaults: {
                validation: {
                    errorPlacement: function (error, element) {},
                    highlight: function (element, errorClass) {
                        $(element).closest('.input').addClass(errorClass);
                    },
                    unhighlight: function (element, errorClass) {
                        $(element).closest('.input').removeClass(errorClass);
                    }     
                }
            }
        },
        {
            init: function (el) {
                this.o = this.options;
                this.form = this.find('form');
                this.form.validate(this.o.validation);
                this.form.formTabber();
                this.find('input[type="file"]').customFileInput();	
                
            },
            
            '.submit click': function (el, ev) {
                ev.preventDefault();
                this.form.submit(); 
            },
            
            'input[type="text"], textarea focusin': function (el, ev) {
                el = $(ev.target);
                el.parent().addClass('focus');
            },
            
            'input[type="text"], textarea focusout': function (el, ev) {
                el = $(ev.target);
                el.parent().removeClass('focus');
            }
        }
    );
    
	
	$.Controller('APP.QuizForm',
		{
			pluginName: 'quiz'
		},
		{
			init: function(){
				this.findForm();
			},
			findForm: function(){
				this.form = this.find('form');
			},				
            '.submit-btn click': function (el, ev) {
                ev.preventDefault();
                this.element.load(this.form.attr('action'), this.form.serialize(), this.proxy(function(){
					this.findForm();	
				})); 
            },
            
            '.js-get-results click': function (el, ev) {
                ev.preventDefault();
                this.element.load(this.form.attr('action'), $.extend(this.form.serialize(), {show_results: 'Y'}), this.proxy(function(){
					this.findForm();	
				})); 
            },
            '.js-get-quiz click': function (el, ev) {
                ev.preventDefault();
                this.element.load(this.form.attr('action'), this.proxy(function(){
					this.findForm();	
				})); 
            }
		}
	);
})(jQuery);
