﻿function change_sub_menu(id, div) {
	if ($("#"+id).attr("class")!="activ") {
		span = $("span", $("#"+div));
		for (i=0;i<span.length;i++) {
			if ($(span[i]).attr("class")=="activ") {
				id_activ = $(span[i]).attr("id");
				$("#"+id_activ).html($("#"+id_activ).text());
				$("#"+id_activ+"_text").hide();
			}
			$(span[i]).attr("class", "");
		}
		
		$("#"+id).html('<img src="./images/bleft.gif" align="absmiddle"/>' + $("#"+id).text() + '<img src="./images/bright.gif" align="absmiddle"/>')
		$("#"+id).attr("class", "activ");
		$("#"+id+"_text").show();
	}
}

function change_vkl(id, div) {
	if ($("#"+id).attr("class")!="activ") {
		li = $("LI", $("#"+div));
		for (i=0;i<li.length;i++) {
			if ($(li[i]).attr("class")=="activ") {
				id_activ = $(li[i]).attr("id");
				$("#"+id_activ+"_text").hide();
			}
			$(li[i]).attr("class", "");
		}
		$("#"+id).attr("class", "activ");
		$("#"+id+"_text").show()
	}
}

function chanage_focus(id, text) {
	if ($("#"+id).val() == text) {
		$("#"+id).attr("value", "");
	} else if ($("#"+id).val() == ''){
		$("#"+id).attr("value", text);
	}
}

old_link = '';
function change_menu_over(id) {
	if ($("#"+id).attr("class")!="activ") {
		$("#change_img").hide();
		$("#"+id).attr("class", "activ");
		$("#change_img_"+id).show();
	} else {
		$("#change_img").show();
		$("#change_img_"+id).hide();
		$("#"+id).attr("class", "");
	}
}

$(document).ready(function() {
    
    
    
	// Инициализация SWF'ки в первой комнате.
	var swfFile = $('#div_tour_file').text();
	//alert(swfFile)
	swfobject.embedSWF('/swf/vtour/' + swfFile, 'div_tour', '968', '531', '9.0.0');
	
	// Распознание якоря в брендах
	var sHash = window.location.hash;
	var aHash = sHash.split("/");
	var jHashSender = false;
	var categoryKey = false;
	//'div.fl100.brends_bottom.mt30.link span div.key'
	if (aHash[1] == 'category') {
		$('div.fl100.brends_bottom.link span div.mcu').each(function () {
			if ($(this).text() == aHash[2]) {
				jHashSender = $(this).parent();
				categoryKey = $(this).parent().find('div.key').text();
				return false;
			}
		});
		if (!jHashSender) {
			$('div.fl100.brends_bottom.link span div.key').each(function () {
				if ($(this).text() == aHash[2]) {
					jHashSender = $(this).parent();
					categoryKey = aHash[2];
					return false;
				}
			});
		}
		brandSelectCategory(jHashSender, '/' + aHash[1] + '/' + aHash[2], categoryKey);
	}
	
	// Переключака по комнатам.
	// 08.07.10: закомментировал на всякий пожарный,
	//	на данный момент не нужно поскольку есть постоянные ссылки
	/*
	$('.vtour_room').bind('click', function() {
		// Меняем HTML текущего активного.
		$('.vtour_room.activ').html('<a href="#">' + $('.vtour_room.activ').text() + '</a>');
		
		// Меняем классы между ними.
		$('.vtour_room.activ').removeClass('activ');
		$(this).addClass('activ');
		
		// Меняем HTML нового активного.
		$('.vtour_room.activ').html(
			'<img src="/images/bleft.gif" align="absmiddle"/>' +
			$('.vtour_room.activ').text() +
			'<img src="/images/bright.gif" align="absmiddle"/>'
		);
		
		// Подгружаем новую SWF'ку.
		swfobject.embedSWF('/swf/vtour/' + $(this).attr('id') + '.swf', 'div_tour', '968', '531', '9.0.0');
	});
	*/
	
	// Анимация навигационного меню
	animateNavigationMenu();
	
	// Привязывание некоторых событий
	// Наведения на пункт меню
	$('li.jq-slide').hover(
		function() {
			$(this).find('div.submenu').fadeIn(200);
		},
		function() {
			$(this).find('div.submenu').fadeOut(200);
		}
	);
	
	// Проверка для переключателей
	$('table.jq-gallery-table').each( function() {
		var jGTable = $(this);
		var iReadyImagesCount = 0;

                var i = 0;

                jGTable.find('img').each( function() {
                        if ( $(this).parent().parent().css('display') != 'none' ) {
                                i++;
                        }
                });
		var iImagesCount = i;
		
		// Проверка готовности изображений
		jGTable.find('img').one('load', function() {
			if ( $(this).parent().parent().css('display') != 'none' ) {
                                gtImagesLoaded(); 
                        }
		}).each(function() {
			if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
				$(this).trigger('load');
		});
		
		function gtImagesLoaded() {
		
			iReadyImagesCount++;
			
			if (iReadyImagesCount == iImagesCount) {
//                                checkSwitchers(jGTable);
				
			}
		}
	});
	
	// Перелистывание фотографий в галерее
	$('.jq-gallery-left').click(function () {
		gallerySlide(this, "left");
	});
	
	$('.jq-gallery-right').click(function () {
		gallerySlide(this, "right");
	});
	

});

//

/**
 * Анимация переключения галереи
 */
function gallerySlide(sender, direction) {
 	var galleryTable = $(sender).parent().parent().find('table.jq-gallery-table');
        var galleryTableParent = galleryTable.parent();
        var galleryTableParentWidth = galleryTableParent.width();
        var galleryTableParentOffset = galleryTableParent.offset();

        var tdToMove;
        var tdGtpInterval;
        galleryTable.stop();

        var gtpRight = galleryTableParentOffset.left + galleryTableParentWidth;
        var gtpLeft = galleryTableParentOffset.left;

        galleryTable.find('td').each(function () {
                if ($(this).css('display') != 'none') {
                        var tdRight = $(this).offset().left + $(this).outerWidth();
                        var tdLeft = $(this).offset().left;

                        if (direction == "right") {
                                if ((tdRight > gtpRight) && (tdLeft >= gtpRight)) {
                                        tdToMove = $(this);
                                        tdGtpInterval = tdRight - gtpRight;
                                        return false;
                                } else if ((tdRight > gtpRight) && (tdLeft < gtpRight)) {
                                        var nextAllTds = $(this).nextAll();
                                        var nextAllTdsInvisible = true;
                                        nextAllTds.each( function() {
                                                if ($(this).css('display') != 'none') {
                                                        nextAllTdsInvisible = false;
                                                        return false;
                                                }
                                        });
                                        if (($(this).next().size() == 0) || (nextAllTdsInvisible)) {
                                                tdToMove = $(this);
                                                tdGtpInterval = tdRight - gtpRight;
                                                return false;
                                        }
                                }
                        } else {
                                if ((tdLeft < gtpLeft) && (tdRight <= gtpLeft)) {
                                        tdToMove = $(this);
                                        tdGtpInterval = gtpLeft - tdLeft;
                                } else if ((tdLeft < gtpLeft) && (tdRight > gtpLeft)) {
                                        var prevAllTds = $(this).prevAll();
                                        var prevAllTdsInvisible = true;
                                        prevAllTds.each( function() {
                                                if ($(this).css('display') != 'none') {
                                                        prevAllTdsInvisible = false;
                                                        return false;
                                                }
                                        });
                                        if (($(this).prev().size() == 0) || (prevAllTdsInvisible)) {
                                                tdToMove = $(this);
                                                tdGtpInterval = gtpLeft - tdLeft;
                                        }
                                } else {
                                        return false;
                                }
                        }
                }
        });

        var lastTdRight; //= galleryTable.find('td').last().offset().left + galleryTable.find('td').last().outerWidth();
        var firstTdLeft; //= galleryTable.find('td').first().offset().left;
        var galleryTableTdsReverse = galleryTable.find('td').get().reverse();


        $(galleryTableTdsReverse).each( function() {
                if ( $(this).css('display') != 'none' ) {
                        lastTdRight = $(this).offset().left + $(this).outerWidth();
                        return false;
                }
        });

        galleryTable.find('td').each( function() {
                if ( $(this).css('display') != 'none' ) {
                        firstTdLeft = $(this).offset().left;
                        return false;
                }
        });

        if ( lastTdRight - tdGtpInterval > gtpRight ) {
                //alert(galleryTableParent.parent().html());
                galleryTableParent.parent().find('.jq-gallery-right').css('visibility', 'visible');
        } else {
                galleryTableParent.parent().find('.jq-gallery-right').css('visibility', 'hidden');
        }

        if ( firstTdLeft + tdGtpInterval < gtpLeft ) {
                galleryTableParent.parent().find('.jq-gallery-left').css('visibility', 'visible');
        } else {
                galleryTableParent.parent().find('.jq-gallery-left').css('visibility', 'hidden');
        }

        if ( direction == "right" ) {
                if ( firstTdLeft - tdGtpInterval <= gtpLeft ) {
                        galleryTableParent.parent().find('.jq-gallery-left').css('visibility', 'visible');
                }
        } else {
                if ( lastTdRight + tdGtpInterval >= gtpRight ) {
                        galleryTableParent.parent().find('.jq-gallery-right').css('visibility', 'visible');
                }
        }
        //checkSwitchers(galleryTable);

        //galleryTable.animate({"left": "+=" + tdGtpInterval + "px"}, 150);
        galleryTable.animate({"left": (direction == "right" ? "-" : "+") + "=" + tdGtpInterval + "px"}, 150);
		
}

/**
 * Функция проверки переключателей галереи
 */
function checkSwitchers(jGTable) {
        var jGTableParent = jGTable.parent();
        var jGTableGrandParent = jGTableParent.parent();
        var jGTableTdsReverse = jGTable.find('td').get().reverse();
        
        //var jGTableTdLast = jGTable.find('td').last();
        //var jGTableTdFirst = jGTable.find('td').first();
        var jGTableTdLast;
        var jGTableTdFirst;

        var jGTableTdCount = jGTable.find('td').size();

        $(jGTableTdsReverse).each( function() {
                if ( $(this).css('display') != 'none' ) {
                        jGTableTdLast = $(this);
                        return false;
                }
        });

        jGTable.find('td').each( function() {
                if ( $(this).css('display') != 'none' ) {
                        jGTableTdFirst = $(this);
                        return false;
                }
        });
        
        var jGSwitcherRight = jGTableGrandParent.find('.jq-gallery-right');
        var jGSwitcherLeft = jGTableGrandParent.find('.jq-gallery-left');

        //alert(jGTableTdLast.offset().left + jGTableTdLast.width());
        //alert(jGTableParent.offset().left + jGTableParent.width());
        if (jGTableTdLast.offset().left + jGTableTdLast.outerWidth() > jGTableParent.offset().left + jGTableParent.width()) {
                jGSwitcherRight.css('visibility', 'visible');
        } else {
                jGSwitcherRight.css('visibility', 'hidden');
        }

        if (jGTableTdFirst.offset().left < jGTableParent.offset().left) {
                jGSwitcherLeft.css('visibility', 'visible');
        } else {
                jGSwitcherLeft.css('visibility', 'hidden');
        }
}

/** 
 * Анимация навигационного меню
 */
function animateNavigationMenu() {
	
	var bAnimateWave = false;	/* Условная переменная выбора анимации:
					 * true - появление волной
					 * false - появление по-очереди
					 */
	
	var iShowTime = 500;		// Время разворота блока навигации (миллисекунды)
	var iFadeTime = 600;		// Время появления элемента
	var iFadeDelay = 200;		// Прирост ко времени появления	(для волны)
	var iNextStartDelay = 300;	// Интервал между запуском последующих элементов (для поочередной анимации)
	var iStartDelay = 0;		// Отсрочка запуска первого элемента

	var iReadyImagesCount = 0;	// Количество загруженных изображений	
	var iImagesCount = $('.main_prod > div > a > img').size();	// Количество изображений вообще

	// Подготовка стилей элементов - все скрываем
	//$('.main_prod').css('height', $('.main_prod > div').outerHeight(true) + 'px');
	var divHeight;

        /*
        switch (location.pathname) {
		case '/':
		case '/ru':
		case '/ru/':
		case '/en':
		case '/en/':
			divHeight = '216px'; 
			break;
		
		default:
			divHeight = '127px';
			break;
	}
        */

        // Если строка = /, /ru, /en, /ru/, /en/, /index.php, /index.php?переменные
        var uriPattern = /^\/(((ru|en)\/?)|(index\.php([^.]*)))?$/gi
        if (uriPattern.test(location.pathname)) {
               divHeight = '216px';
        } else {
               divHeight = '127px';
        }

	//$('.main_prod').css('height', (location.pathname == '/' ? '216px' : '127px'));
	$('.main_prod').css('height', divHeight);
	$('.main_prod > div').css('height', divHeight);
	//$('.main_prod').css('display', 'none');
	//$('.main_prod > div').css('display', 'none');

	// Проверка готовности изображений
	$('.main_prod').find('img').one('load', function() {
		imagesLoaded();
	}).each(function() {
		if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
			$(this).trigger('load');
	});

        // Фикс для оперы
        if (jQuery.browser.opera) window.load = operaWindowLoaded();
        if (jQuery.browser.opera && window.load) operaWindowLoaded();
        function operaWindowLoaded() {
                iReadyImagesCount = iImagesCount - 1;
                imagesLoaded();
        }

	// Функция появления изображений
	function imagesLoaded() {
		
		// Счетчик загруженных изображений
		iReadyImagesCount++;
		
		if (iReadyImagesCount == iImagesCount) {
			// Разворот блока навигации
			$('.main_prod').show(iShowTime);
			
			// Добавление эффекта появления элементам с последовательным приростом
			$('.main_prod > div').each(function(index) {
				$(this).delay(iStartDelay).fadeIn(iFadeTime);
				bAnimateWave ? iFadeTime += iFadeDelay : iStartDelay += iNextStartDelay;
			});
		}
	}
}

/**
 * Перенаправление на категории в брендах
 */
function brandSelectCategoryRedirect(sender, url, key, backUrl) {
	location.href = backUrl + "#" + url;
}

/**
 * Переключение категорий в брендах
 */
function brandSelectCategory(sender, url, key) {
	if (!$(sender).hasClass('activ')) {
		window.location.hash = url;
		var jDivParent = $('body');
		var arrBrandsToShow = new Array();
		var arrBrandsToHide = new Array();
                var jGTable;
		$('.brands div.key').each(function () {
			if ($(this).parent().html() != jDivParent.html()) {
				if ($(this).text() == key) {
					//$(this).parent().show();
					//$(this).parent().fadeIn(150);
					arrBrandsToShow.push($(this).parent());
					jDivParent = $(this).parent();
				} else {
					//$(this).parent().hide();
					//$(this).parent().fadeOut(150);
				}
				arrBrandsToHide.push($(this).parent());
			}
		});
		$('.div_pr div.key').each(function () {
			if ($(this).parent().html() != jDivParent.html()) {
				if ($(this).text() == key) {
                                        //jGTable = $(this).parents('table.jq-gallery.table');
					//$(this).parent().show();
					//$(this).parent().fadeIn(150);
					arrBrandsToShow.push($(this).parent());
					jDivParent = $(this).parent();
				} else {
					//$(this).parent().hide();
					//$(this).parent().fadeOut(150);
				}
				arrBrandsToHide.push($(this).parent());
			}
		});
		
		//jDivParent.parent().parent().parent().height(jDivParent.parent().parent().parent().height());
		//jDivParent.parent().parent().parent().css('min-height', jDivParent.parent().parent().parent().height() + 'px');
		var i;
		for (i in arrBrandsToHide) {
			var jBrand = arrBrandsToHide[i];
            //console.info(jBrand);
			//jBrand.hide();
            //jBrand.css({'visibility':'hidden'});
            jBrand.css('width','0px');
            jBrand.css('height','0px');
            jBrand.css({"display":"none"});
		}
		
		window.setTimeout(function () {
			var tmpHeight = 0;
                        jGTable = arrBrandsToShow[0].parents('table.jq-gallery-table');
                        //jGTable.position({left: 0});
			for (i in arrBrandsToShow) {
				var jBrand = arrBrandsToShow[i];
				if (jBrand.height() > tmpHeight) {
					tmpHeight = jBrand.height();
				}
				//jBrand.fadeIn(150);
                //jBrand.css({'visibility':'visible'});
                //jBrand.show();
                if($.browser.msie )//&& $.browser.version<8) 
                {
                    jBrand.css('width','298px');
                    jBrand.css('height','140px');
                }
                else
                {
                    jBrand.css('width','300px');
                    jBrand.css('height','140px');
                }
                jBrand.css({'display':'block'});
			}
			if ($('.brands').size() < 1) {
				//jDivParent.css('height', '51px');
				setTimeout(function () {
					//jDivParent.parent().parent().parent().animate({'height': tmpHeight + 'px'}, 150);
					//jDivParent.parent().parent().parent().css('min-height', tmpHeight + 'px');	
				}, 150);
			}
                        setTimeout(function () {
                               //checkSwitchers(jGTable);
                        }, 200);
		}, 200);
		
		var jOldSender = $('div.fl100.brends_bottom.link span.activ');
		jOldSender.find("img").hide();
                jOldSender.find(".jq-space").hide();
		jOldSender.removeClass('activ');
		$(sender).find("img").show();
                $(sender).find(".jq-space").show();
		$(sender).addClass('activ');
	}
	
}

//
function showPhoto(url, aId) {

	
	$('#div_win img.jq-photo').hide();
	$('#div_win img.jq-photo').css('height', 'auto');
	$('#div_win img.jq-loader').show()
	$('#div_shadow').fadeIn(150);
	$('#div_win').fadeIn(150);
	//$('#div_win > div.jq-photo-close').delay(200).slideDown(200);
	var jA = $('#' + aId);
	
	try {
		window.captureEvents(Event.KeyPress);
	}
	catch(e) {
	}
	window.onkeypress = key_pressed;
	function key_pressed(e) {
		key = e.keyCode || e.which;
		//alert(key);
	}
	
	function photo_show_close() {
		//$('#div_win > div.jq-photo-close').stop();
		//$('#div_win img.jq-photo').stop();
		//$('#div_win > div.jq-photo-container').stop();
		//$('#div_shadow').stop();
		//$('#div_win').stop();
		
		//$('#div_win > div.jq-photo-close').slideUp(200);
		//$('#div_win img.jq-photo').fadeOut(200);
		//$('#div_win > div.jq-photo-container').delay(200).animate({'width': $('#div_win img.jq-loader').width() + 'px', 'height': $('#div_win img.jq-loader').height() + 'px'}, 150);
		//setTimeout( function () {
			$('#div_win img.jq-photo').css('display', 'none');
			$('#div_win img.jq-loader').css('display', 'block');
			$('#div_win > div.jq-photo-container').width($('#div_win img.jq-loader').width());
			$('#div_win > div.jq-photo-container').height($('#div_win img.jq-loader').height());
			$('#div_shadow').fadeOut(150);
			$('#div_win').fadeOut(150);
		//}, 450);
	}
	
	$('#div_win a img').css('border', 'solid 2px transparent');
	$('#div_win a#' + aId + ' img').css('border', 'solid 2px white');
	
	if ($('#div_win table.jq-gallery-table td').last().offset().left >= ($('#div_win div.div_pr').offset().left + $('#div_win div.div_pr').width())) {
		$('#div_win .jq-gallery-right').css('visibility', 'visible');
		//$('#div_win .jq-gallery-left').css('visibility', 'visible');
	} else {
		$('#div_win .jq-gallery-right').css('visibility', 'hidden');
		//$('#div_win .jq-gallery-left').css('visibility', 'hidden');
	}
	
	if ($('#div_win table.jq-gallery-table td').first().offset().left + $('#div_win table.jq-gallery-table td').first().width() <= ($('#div_win div.div_pr').offset().left)) {
		//$('#div_win .jq-gallery-right').css('visibility', 'visible');
		$('#div_win .jq-gallery-left').css('visibility', 'visible');
	} else {
		//$('#div_win .jq-gallery-right').css('visibility', 'hidden');
		$('#div_win .jq-gallery-left').css('visibility', 'hidden');
	}
	
	$('#div_win').bind('click', function (e) {
		if ($('#div_win img.jq-loader').css('display') == 'none') {
		var mouseX = e.pageX - $('body').scrollLeft();
		var mouseY = e.pageY - $('body').scrollTop();
		
		var headBottom = $('#div_win > div.jq-photo-close').height();
		var footTop = $('#div_win > div.jq-photo-switch').position().top;
		
		var photoTop = $('#div_win > div.jq-photo-container').position().top;
		var photoLeft = $('#div_win > div.jq-photo-container').position().left;
		var photoRight = photoLeft + $('#div_win > div.jq-photo-container').outerWidth();
		var photoBottom = photoTop + $('#div_win > div.jq-photo-container').outerHeight();
		
		/*
		var debugText = "mouseX: " + mouseX + "\n\
		mouseY: " + mouseY + "\n\
		headHeight: " + headHeight + "\n\
		footHeight: " + footHeight + "\n\
		photoTop: " + photoTop + "\n\
		photoLeft: " + photoLeft + "\n\
		photoRight: " + photoRight + "\n\
		photoBottom: " + photoBottom + "\n";
		
		alert(debugText);
		*/
			
		if ( (mouseY > headBottom) && (mouseY < footTop) ) {
			if ( !( (mouseX > photoLeft && mouseX < photoRight) && (mouseY > photoTop && mouseY < photoBottom) ) ) {
				photo_show_close();
				$(this).unbind('click');
			}
		}
		}
	});
	
	$('#div_win > div.jq-photo-close').one('click', function () {
		photo_show_close();
	});
	
	$('#div_win > div.jq-photo-container').width($('#div_win img.jq-loader').width());
	$('#div_win > div.jq-photo-container').height($('#div_win img.jq-loader').height());
	
	$('#div_win img.jq-photo').attr('src', '/up_photo_gallery/' + url);
	$('#div_win img.jq-photo').one('load', function() {
		var jImage = this;
		setTimeout(function() {
			var headHeight = $('#div_win > div.jq-photo-close').outerHeight();
			var footHeight = $('#div_win > div.jq-photo-switch').outerHeight();
			
			if ( $(jImage).height() > Math.floor($('body').height() - headHeight - footHeight - 60)  ) {
				//$(jImage).css('height', Math.floor(((70 * $('body').height()) / 100)) + 'px');
				$(jImage).css('height', Math.floor($('body').height() - headHeight - footHeight - 60) + 'px');
			}
			
			$('#div_win img.jq-loader').css('display', 'none');
			$('#div_win > div.jq-photo-container').animate({"width": $(jImage).width() + 'px', "height": $(jImage).height() + 'px'}, 400);
			//$('#div_win img.jq-photo').css('display', 'block');
			$(jImage).delay(400).fadeIn('400');
			var thisTd = jA.parent();
			var nextTd = thisTd.next();
			if (nextTd.html() != null) {
				$(jImage).css('cursor', 'pointer');
				
				var nextAId = nextTd.find('a').attr('id');
				var nextSrc = nextTd.find('a > img').attr('src');
				var nextSrcArr = nextSrc.split('/');
				var nextUrl = nextSrcArr[2];
				var nextUrlArr = nextUrl.split('_');
				var nextUrlFinished = "large";
				
				for (i in nextUrlArr) {
					if (i > 0) {
						nextUrlFinished += "_" + nextUrlArr[i];
					}
				}
				
				$(jImage).one('click', function () {
					showPhoto(nextUrlFinished, nextAId);
				});
			} else {
				$(jImage).unbind('click');
				$(jImage).css('cursor', 'default');
			}
		}, 500);
	}).each(function() {
		if (jImage.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
			$(jImage).trigger('load');
	});
}
