$j(document).ready(function() {
	
	var flashing;
	var notHover = true;
	var whiteColor = $j("html").attr("id") == "js-color_color_white" ? true : false;
	function setIntval() {
		if(whiteColor) {
			flashing = window.setInterval(function() {
				$j(".js-colorchange").animate({"background-color":"#ffffff"}, 300, function() {
					setTimeout(function() {if(notHover) {$j(".js-colorchange").animate({"background-color":"#000000"}, 300)}}, 500);
				});
			}, 1100);
		} else {
			flashing = window.setInterval(function() {
				$j(".js-colorchange").animate({"background-color":"#ffffff"}, 300, function() {
					setTimeout(function() {if(notHover){$j(".js-colorchange").animate({"background-color":"#000000"}, 300)}}, 500);
				});
			}, 1100);		
		}
	};


	//alert(document.cookie);
    /* Слайды на главной */
    $indexcontent = $j(".js-indexcontent");
    $header = $j(".js-header-row-brace");
    $footer = $j(".js-footer-row-brace");
    $j(".js-teaser").click(function() {
		clearInterval(indexSlides);
        $this = $j(this);
        if($this.hasClass("pseudolink")) {		
            nextTeaserClass = $this.attr("class");
            nextTeaserName = nextTeaserClass.substring(nextTeaserClass.lastIndexOf("-")+1, nextTeaserClass.lastIndexOf(" "));
			
            $currentTeaserLink = $j(".js-teaser:not([class*='pseudolink'])");
            currentTeaserClass = $currentTeaserLink.attr("class");
            currentTeaserName = currentTeaserClass.substring(currentTeaserClass.lastIndexOf("-")+1, currentTeaserClass.length);
			
            /* Переключение слайдов */
            $indexcontent.fadeOut(400, function() {
                if (currentTeaserName == "models") {
                    $j(".js-indexcontent_type_models").show();
                }
                $indexcontent.removeClass("b-indexcontent_show_"+currentTeaserName).addClass("b-indexcontent_show_"+nextTeaserName);
                $this.removeClass("pseudolink");
                $currentTeaserLink.addClass("pseudolink");
				$j(".b-indexcontent-block_type_teaser").css({"background":"rgba(244,244,244,0.3)"});
                $indexcontent.fadeIn(400);
            });		
        }
    });
	
	(function() {
		indexSlides = window.setInterval(function() {
			if($indexcontent.hasClass("b-indexcontent_show_models")) {
				$indexcontent.fadeOut(400, function() {
					$indexcontent.removeClass("b-indexcontent_show_models").addClass("b-indexcontent_show_whycrown");
					$j(".js-teaser-whycrown").removeClass("pseudolink");
					//$j(".js-teaser-models").addClass("pseudolink");
					$j(".b-indexcontent-block_type_teaser").css({"background":"rgba(244,244,244,0.5)"});
					$indexcontent.fadeIn(400);
				});
			} else if($indexcontent.hasClass("b-indexcontent_show_whycrown")) {
				$indexcontent.fadeOut(400, function() {
					$indexcontent.removeClass("b-indexcontent_show_whycrown").addClass("b-indexcontent_show_bemodel");
					$j(".js-teaser-bemodel").removeClass("pseudolink");
					$j(".js-teaser-whycrown").addClass("pseudolink");
					$j(".b-indexcontent-block_type_teaser").css({"background":"rgba(244,244,244,0.5)"});
					$indexcontent.fadeIn(400);
				});			
			} else {
				$indexcontent.fadeOut(400, function() {
					$indexcontent.removeClass("b-indexcontent_show_bemodel").addClass("b-indexcontent_show_models");
					//$j(".js-teaser-models").removeClass("pseudolink");
					$j(".js-teaser-bemodel").addClass("pseudolink");
					$j(".b-indexcontent-block_type_teaser").css({"background":"rgba(244,244,244,1)"});
					$indexcontent.fadeIn(400);
				});			
			}
		}, 8000);
	})();
	
    /* Резкое изменение ширины блоков + позиционирование по вертикальному центру */
    $wrap = $j(".js-wrap");
    function resizedBlock() {
        windowWidth = $j(window).width();
        if(windowWidth > 940 && windowWidth <= 1350) {
            wrapWidth = windowWidth - 40;
            resizedBlockWidth = Math.floor(wrapWidth/150)*150;
            $wrap.css({
                "width":resizedBlockWidth
            });
			if(resizedBlockWidth==900) {
				$wrap.addClass("js-wrap-width900");
			} else {
				$wrap.removeClass("js-wrap-width900");
			}
        } else if(windowWidth < 940) {
            $wrap.css({
                "width":"900px"
            }).addClass("js-wrap-width900");
        } else if(windowWidth > 1350) {
            $wrap.css({
                "width":"1350px"
            }).removeClass("js-wrap-width900");
        }
        windowHeight = $j(window).height();
        wrapHeight = $wrap.height();
        if(windowHeight > wrapHeight) {
            wrapTop = (windowHeight-wrapHeight)/2;
            $wrap.css({
                "padding-top":wrapTop
            });
        }
    };
    resizedBlock();
	$wrap.fadeOut(1, function() { $wrap.css({"visibility":"visible"}); $wrap.fadeIn(200); });
	
	
    /* «Показать еще» в каталоге */
    photosInCatalog = $j(".js-catalog .b-catalog-item").size();
    $catalog = $j(".js-catalog");
    $j(".js-catalog-footer__link").click(function() {
		wrapWidth = $j(".js-wrap").width();
        catalogHeight = $catalog.height();
		rowOpenedCount = catalogHeight / 205;
		photosOnRow = Math.floor(wrapWidth / 150);
		photosHiddenCount = photosInCatalog - rowOpenedCount * photosOnRow;
		//needRowsCount = Math.floor(photosHiddenCount / photosOnRow) + 1;
		needRowsCount = Math.ceil(photosHiddenCount / photosOnRow);
		if (needRowsCount > 0 && needRowsCount <= 3) {
			$catalog.animate({
				"height": catalogHeight+205*needRowsCount
			}, needRowsCount*200);
			$j(".js-catalog-footer__link").hide();
		}else {
			return;
		}
    });
	
	
    /* Карусель */
    photoSize = 270;
    carouselPosition = 0;
    weAreOnRightEdge = false;
    $j(".js-modelpage-arrow").click(function() {
        lastPhotoPosition = $j(".js-modelpage-photo:last-child").position().left;
        rightEdge = lastPhotoPosition + $j(".js-modelpage-photo:last-child").width();
        wrapWidth = $j(".js-wrap").width();
        photosOnScreen = Math.floor(wrapWidth / photoSize) * photoSize;
        prevCarouselPosition = carouselPosition;
		
        goodShift = rightEdge - wrapWidth;		
        if($j(this).hasClass("js-modelpage-arrow-left")) {
            carouselShift = "+=" + photosOnScreen;
            carouselPosition -= photosOnScreen;
            if(carouselPosition<=0) {
                if(prevCarouselPosition==0) {
                    //console.log("Мы у левого края, командир!");
                    $j(".js-modelpage-gallery").animate({
                        left:"5px"
                    }, 50, function() {
                        $j(".js-modelpage-gallery").animate({
                            left:"0px"
                        }, 50);
                    });
                    carouselPosition = 0;
                } else {
                    $j(".js-modelpage-gallery").animate({
                        left:"10px"
                    }, photosOnScreen*0.6, function() {
                        $j(".js-modelpage-gallery").animate({
                            left:"0px"
                        }, 50);
                    });
                    carouselPosition = 0;
                }
            } else {
                $j(".js-modelpage-gallery").animate({
                    left:carouselShift
                }, photosOnScreen*0.6);
            }
            weAreOnRightEdge = false;
        }
        if($j(this).hasClass("js-modelpage-arrow-right")) {
            carouselShift = "-=" + photosOnScreen;
            carouselPosition += photosOnScreen;
            if(prevCarouselPosition + photosOnScreen >= goodShift) {
                if(prevCarouselPosition == goodShift) {
                    console.log("Мы у правого края, командир!");
                    $j(".js-modelpage-gallery").animate({
                        left:"-=5"
                    }, 50, function() {
                        $j(".js-modelpage-gallery").animate({
                            left:"+=5"
                        }, 50);
                    });
                    carouselPosition = goodShift;
                    weAreOnRightEdge = true;
                } else {
                    edgeShift = goodShift - prevCarouselPosition + 10;
                    console.log("Сейчас левый край в точке -" + prevCarouselPosition + ".");
                    console.log("Мы хотим, чтобы левый край был в точке -" + (prevCarouselPosition + photosOnScreen) + ", но нельзя: левый край должен быть не меньше чем -" + goodShift + ".");
                    console.log("Сдвинем на " + edgeShift + "? +10 пикселей для красоты ;)");
                    $j(".js-modelpage-gallery").animate({
                        left:"-="+edgeShift
                        }, photosOnScreen*0.6, function() {
                        $j(".js-modelpage-gallery").animate({
                            left:"+=10"
                        },50);
                    });
                    carouselPosition = goodShift;
                    weAreOnRightEdge = true;
                }
            } else {
                $j(".js-modelpage-gallery").animate({
                    left:carouselShift
                }, photosOnScreen*0.6);
            }
        }
    });
	
	
	/* Карусель мышиная
	$window = $j(window);
	$j(".js-modelpage-gallery")
		.mousemove(function(e) {
			wrapWidth = $wrap.width();
			galleryCenter = wrapWidth / 2;
			windowWidth = $j(window).width();
			cursorPosition = e.clientX + $window.scrollLeft();
			cursorAberration = galleryCenter - cursorPosition;
			$j(".js-modelpage-gallery").stop();
			if(cursorAberration>0) {
				$j(".js-modelpage-gallery").animate({ left: 0}, cursorAberration*10);
			} else {
				$j(".js-modelpage-gallery").animate({ left: "-900px"}, cursorAberration*(-10));
			}
		});
	 */
	
    function shiftCarousel() {
        if(weAreOnRightEdge) {
            resizedShift = ($j(".js-modelpage-photo").length * photoSize - $wrap.width()) * -1;
            $j(".js-modelpage-gallery").animate({
                left:resizedShift
            }, 400);
            carouselPosition = resizedShift*-1;
        }
    }
	
	
    /* Window resizing */
    $j(window).resize(function() {
        resizedBlock();
        shiftCarousel();
		showNeededRowCount();
    });
	
	
	var colorChangeHover = false;
	$j(".js-colorchange")
		.mouseenter(function() {
			colorChangeHover = true;
			notHover = false;
			clearInterval(flashing);
			whiteColor = $j("html").attr("id") == "js-color_color_white" ? true : false;
			if(whiteColor) { $j(".js-colorchange").css({"background":"#000000"}); } else { $j(".js-colorchange").css({"background":"#ffffff"}); };
			setTimeout(function() {if(colorChangeHover) {$j(".js-colorchange-hint").fadeIn(300);}}, 70);
		})
		.mouseleave(function() {
			colorChangeHover = false;
			notHover = true;
			setTimeout(function() {if(!colorChangeHover) {$j(".js-colorchange-hint").fadeOut(300);}}, 70);
			setIntval();
		});
	/* Color change */
	$j(".js-colorchange").click(function() {
	
		//if(getCookie('blackColor')=='1') {document.cookie="blackColor=";}
		if(getCookie("blackColor")) {deleteCookie("blackColor","/");}
		else if(!getCookie("blackColor")) {document.cookie="blackColor=1;path=/";}
		//else {document.cookie="blackColor=1";}
		
		whiteColor = $j("html").attr("id") == "js-color_color_white" ? true : false;	
		if(whiteColor) {
			$j("html, body").animate({backgroundColor: "#000"}, 400, function() {
				$j("html").attr("id","js-color_color_black");
			});
			$j(".js-colorchange").animate({backgroundColor: "#fff"}, 400);
			$j(".js-colorchange-hint").animate({color: "#fff"}, 400);
			$j(".b-menu-item a").animate({color: "#fff"}, 400);
			$j(".b-footer").animate({color: "#fff"}, 400);
			$j(".js-logo__logo_bg_black").fadeIn(400);
			$j(".b-catalog-head").animate({backgroundColor: "#000"}, 400);
			$j(".b-catalog-head .b-pageheader").animate({color: "#fff"}, 400);
			$j(".b-catalog-head a").animate({color: "#fff"}, 400);
			$j(".b-catalog-footer").css({"background-image":"none"}).animate({backgroundColor: "#000"}, 400);
			$j(".b-catalog-footer .js-catalog-footer__link").animate({color: "#fff"}, 400);
			$j(".b-model-footer").css({"background-image":"none"}).animate({backgroundColor: "#000", color: "#fff"}, 400);
			$j(".b-model-footer a").animate({color: "#fff"}, 400);
			$j(".b-catalog-choice").animate({color: "#fff", backgroundColor: "#000"}, 400);
		} else {
			$j("html, body").animate({backgroundColor: "#fff"}, 400, function() {
				$j("html").attr("id","js-color_color_white");
			});
			$j(".js-colorchange").animate({backgroundColor: "#000"}, 400);
			$j(".js-colorchange-hint").animate({color: "#000"}, 400);
			$j(".b-menu-item a").animate({color: "#000"}, 400);
			$j(".b-footer").animate({color: "#000"}, 400);
			$j(".js-logo__logo_bg_black").fadeOut(400);
			$j(".b-catalog-head").animate({backgroundColor: "#E7E6E2"}, 400);
			$j(".b-catalog-head .b-pageheader").animate({color: "#000"}, 400);
			$j(".b-catalog-head a").animate({color: "#000"}, 400);
			$j(".b-catalog-footer").animate({backgroundColor: "#E7E6E2"}, 400, function() {$j(".b-catalog-footer").css({"background-image":"url('/i/b-innercontent__bg.png')"})});
			$j(".b-catalog-footer .js-catalog-footer__link").animate({color: "#000"}, 400);
			$j(".b-model-footer").animate({backgroundColor: "#E7E6E2", color: "#000"}, 400, function() {$j(".b-model-footer").css({"background-image":"url('/i/b-innercontent__bg.png')"})});
			$j(".b-model-footer a").animate({color: "#000"}, 400);
			$j(".b-catalog-choice").animate({color: "#000", backgroundColor: "#e7e6e2"}, 400);
		}
	});
	
	
	/* Model choice */
	$j(".js-modelchoice-button").click(function() {
		$j(".js-catalog-choice").slideToggle(400);
	});
	
	$j(".js-modelform-span").click(function() {
		$j(".js-modelform").slideToggle(200);
	});
	
	
	function getCookie(name) {
			var prefix = name + "="
			var cookieStartIndex = document.cookie.indexOf(prefix)
			if (cookieStartIndex == -1)
					return null
			var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
			if (cookieEndIndex == -1)
					cookieEndIndex = document.cookie.length
			return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
	}

	function deleteCookie(name, path, domain) {
			if (getCookie(name)) {
					document.cookie = name + "=" + 
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					"; expires=Thu, 01-Jan-70 00:00:01 GMT"
			}
	}

	function sumb(){
		$j('#interface_search').submit();
	}


	showNeededRowCount();
	setIntval();
});
	/* What's this? */
	function showModels(recs) {
		$j("#catalog").empty();
		$j("#nulltext").empty();
		
		for (var i in recs) {
				crown='';
				if((recs[i]['crown']) && (recs[i]['crown']!=0)) crown='b-catalog-item-name_crown_show';
				$j("#catalog").append('<div class="inlineBlock b-catalog-item" style="background: url('+recs[i]['img']+') no-repeat;"><span class="b-catalog-item-name '+crown+'"><a class="inlineBlock b-catalog-item-link" href="'+recs[i]['url']+'"><span class="inlineBlock b-catalog-item-link-text"><span class="b-catalog-item-link-text__shadow">'+recs[i]['title']+'</span><span class="b-catalog-item-link-text__main">'+recs[i]['title']+'</span></a></span></div>');
		}
		if(!recs) $j("#nulltext").html('<strong>Моделей, подходящих под ваши критерии, не найдено.</strong>');
		showNeededRowCount();
	}
	
	function showNeededRowCount(){
		if($j(".js-catalog").is(":visible")) {
			wrapWidth = $j(".js-wrap").width();
			photosInCatalog = $j(".js-catalog .b-catalog-item").size();
			$catalog = $j(".js-catalog"); 
			photosOnRow = Math.floor(wrapWidth / 150);
			rowCount=Math.ceil(photosInCatalog / photosOnRow);		

			if (rowCount < 3) {
				$catalog.height(rowCount*205);
			} else {
				$catalog.height(615);
			}
			
			catalogHeight = $catalog.height();
			rowOpenedCount = catalogHeight / 205;
			photosHiddenCount = photosInCatalog - rowOpenedCount * photosOnRow;
			if (photosHiddenCount<=0) {
				$j(".js-catalog-footer__link").hide();
			} else {
				$j(".js-catalog-footer__link").show();
			}
		}		
	}
