document.documentElement.id = 'js';

var appointmentTab = 2;
var massiv = new Array;

// Popup stuff
function setCenter(item) {
	var windowHeight = document.documentElement.clientHeight;
	var currentOffset = document.documentElement.scrollTop || document.body.scrollTop;
	currentOffset = currentOffset + parseInt((windowHeight - $(item).outerHeight()) / 2);
	currentOffset = (currentOffset < 10) ? 10 : currentOffset;
	var pLeft = parseInt($(item).outerWidth() / 2);
	$(item).css({
		top : currentOffset,
		marginLeft : -pLeft
	});
}
function showPopup(popup) {
	popup = $('#'+popup);
	setCenter(popup);
	createBlind(popup);
	popup.show();
	popup.find('.popup-close').click(function(){
		closePopup(popup);
		return false;
	});
}
function createBlind(popup) {
	var blind = $('<div class="blind"></div>');
	var pageHeight = $(document).height();
	blind.height(pageHeight).appendTo('body');
	blind.click(function(){
		closePopup(popup);
	});
}
function closePopup(popup) {
	$('div.blind').remove();
    popup.hide();
    return false;
}

// Pain shop
function preload(arrayOfImages) {
	$(arrayOfImages).each(function(){
		$('<img/>')[0].src = this;
	});
}
function painTabInit(shopName) {

	var preloadImages = [],
		currentStep = 0,
		currentShop = this[shopName + 'Array'],
		shopLength = currentShop.length,
		$shopContext = $('#' + shopName + 'Tab'),
		$prevStep = $('.psArrowPrev', $shopContext),
		$nextStep = $('.psArrowNext', $shopContext);

	$prevStep.click(psPrev);
	$nextStep.hide().click(psNext);

	for( var i = 0; i < shopLength; i++ ) {
		preloadImages.push( currentShop[i].sImg );
		preloadImages.push( currentShop[i].lImg );
	}

	preload(preloadImages);
    fillShop(currentStep);

	$($shopContext).delegate('.psSmallLink', 'mouseover', function() {

		var linkCount = $('.psSmallLink', $shopContext).index($(this)),
			itemCount = linkCount + currentStep,
			$parentHolder = $(this).parent();

		if( $parentHolder.not('.psActive') ) {

			$('.psActive' ,$shopContext).removeClass('psActive psSmallImg-1_hover psSmallImg-2_hover psSmallImg-3_hover psSmallImg-4_hover psSmallImg-5_hover');
            
			$parentHolder.addClass('psActive psSmallImg-' + (linkCount + 1) + '_hover');

			$('.psBigImgCover', $shopContext).attr('style' , 'background-image: url(' + currentShop[itemCount].lImg + ')');

			if( currentShop[itemCount].lText != '' && currentShop[itemCount].lText != undefined ) {
				$('.psBigImgCaption', $shopContext).text( currentShop[itemCount].lText ).show();
			} else {
				$('.psBigImgCaption', $shopContext).hide();
			}
		}
	});

	$('.psSmallLink:eq(0)', $shopContext).trigger('mouseover');

    function fillShop(startPosition) {

        for( var j = startPosition, k = 1 ; j < startPosition + 5 ; j++, k++ ) {

            var _sText = currentShop[j].sText,
                    _psSmallLink = '<a href="'+ currentShop[j].iLink +'" class="psSmallLink" style="background-image:url(' + currentShop[j].sImg + ')">' + '<div class="ttl ttlWhite">';

            if (_sText.length > 14 && _sText.search(' ') != -1) {
                _psSmallLink += '<span class="word wordFirst"><ins>' + _sText.slice(0, _sText.indexOf(' ')) + '</ins><em></em></span><span class="word"><ins>' + _sText.slice(_sText.indexOf(' ') + 1) + '</ins><em></em></span></div></a>';
            } else {
                _psSmallLink += '<span class="word"><ins>' + _sText + '</ins><em></em></span></div></a>';
            }

            $('.psSmallImg-' + k, $shopContext).html(_psSmallLink);

        }

    }

	function psPrev() {
		currentStep++;
		$('div[class*=hover] a.psSmallLink', $shopContext).trigger('mouseover');

		if( currentStep == 1) $nextStep.show();
		shopLength == currentStep + 5 ? $prevStep.hide() : $prevStep.show();

		fillShop(currentStep);
		return false;

	}

	function psNext() {
		currentStep--;
		$('div[class*=hover] a.psSmallLink', $shopContext).trigger('mouseover');

		if (shopLength == currentStep + 6) $prevStep.show();
		currentStep == 0 ? $nextStep.hide() : $nextStep.show();

		fillShop(currentStep);
		return false;
	}
}

$(function() {

    // Всплывающее окно логитипа
	$('.logo').hover(function() {
		$('#logoHint').fadeIn();
	}, function() {
		$('#logoHint').fadeOut();
	});

    // Попап экспресс-теста
	$('#expressTestLink').click(function() {
		showPopup('expressTestPopup');
		return false;
	});

    $('#expressTestPopup').delegate('.nextPage', 'click', function() {
        var $etPopup = $('#expressTestPopup'),
            $etPage = $('.etPage', $etPopup),
            $ajaxLoader = $('.etAJAXLoader', $etPopup),
            linkTarget = $(this).attr('href');
			nameTarget = $(this).text();
			idTarget = $(this).attr('id');
			if($(this).attr('id') == 'etShowResult')
			{
				nameTarget = $(this).attr('name');
				idTarget = $(this).attr('src');
			}
        $etPopup.height( $etPopup.height() );
        $etPage
            .fadeOut(function() {
				str = massiv.join('_');
                $ajaxLoader.show();
                $etPage.load(linkTarget, {name: nameTarget, test: idTarget, point: str}, function() {
                    $ajaxLoader.hide();
                    $etPage.fadeIn();
                    $etPopup.animate({ height : $etPage.height() });
                });
            });
        return false;
    });

    $('#expressTestPopup').delegate('#etShowResult', 'click', function() {
        if (!$(this).hasClass('nextPage')) {
	        if (window.console) { // TODO: Удалить перед выкатом на продакшн
		        var consoleDate = new Date();
                console.info('Ну не заработает она, пока не отметишь все штучки. ' + consoleDate.toLocaleTimeString());
            }
        }
        return false;
    });

    $('#expressTestPopup').delegate('input[type="radio"]', 'click', function() {
		var num = $(this).attr('class');
		massiv[num-1] = $(this).val();

        var $fsets = $(this).parents('.etColHolder').find('fieldset'),
            checkStatus = true;

        $fsets.each(function() {
            checkStatus = checkStatus && !!$(this).find('input[type="radio"]:checked').length;
        });

        if (checkStatus === true) $('#etShowResult').addClass('nextPage');
    });

    // Псевдо-ховер на карточке экперта
	$('.expertBox dt a').hover(function() {
		$(this).parents('.expertBox').find('.expertPhoto').addClass('epHover');
	}, function() {
		$(this).parents('.expertBox').find('.expertPhoto').removeClass('epHover');
	});

	$('.expertBox a.expertPhoto').hover(function() {
		$(this).parents('.expertBox').find('dt a').addClass('elHover');
	}, function() {
		$(this).parents('.expertBox').find('dt a').removeClass('elHover');
	});

    // Переопределение ссылок при включенном JS
	$('.painCategory a:eq(0)').attr('href', '#deseasesTab');
	$('.painCategory a:eq(1)').attr('href', '#methodsTab');
	$('.painCategory a:eq(2)').attr('href', '#branchesTab');

    // Переключение болезней
	$('.painCategory a').click(function() {
		var $hash = $(this).attr('href');
		var $parentLi = $(this).parent('li');

		if( !$parentLi.hasClass('painActive') ) {
			$('.painCategory').find('li.painActive').removeClass('painActive');
			$parentLi.addClass('painActive');

			$('#painShop .painTab').hide();
			$('#painShop').find('div'+$hash).show();

		}

		return false;
	});

	$('.painCategory a:eq(0)').trigger('click');

    // Табы на странице болезней
	$('.pageTabs li a:not(.exLink a)').click(function() {
		var $hash = $(this).attr('href'),
			$parentLi = $(this).parent('li'),
			$parentWrap = $(this).parents('.pageTabs');

		if( !$parentLi.hasClass('ptList-a') ) {
			$parentWrap.find('li.ptList-a').removeClass('ptList-a');
			$parentLi.addClass('ptList-a');

			$('.ptItem', $parentWrap).hide();
			$($parentWrap).find('div'+$hash).show();
		}

		return false;
	});

    // Установка одинаковой ширины
	$('.ptList li').each(function() {
		$(this).css({ width : $(this).width() + 46 })
	});

	$('.pageTabs a:eq(0)').trigger('click');

    // Попап записи на прием
	$('#plAppointment').click(function() {
		showPopup('plAppointmentPopup');
		$('.sqCols input', '#plAppointmentPopup').eq(appointmentTab).trigger('click');
		return false;
	});

    // Попап прайс-листа
	$('#plPrice').click(function() {
		showPopup('plPricePopup');
		return false;
	});

    // Функционал попапа записи на прием
	$('.sqCols input', '#plAppointmentPopup').click(function() {
		var $targetTab = $('#' + $(this).attr('id') + 'Tab', '#plAppointmentPopup');

		if( !$(this).hasClass('sqActive') ) {
			$('.sqActive' , '#plAppointmentPopup').removeClass('sqActive');
			$('.sqTab', '#plAppointmentPopup').hide();
			$(this).addClass('sqActive');
			$targetTab.show();
		}

		setCenter( $('#plAppointmentPopup') );
	});

    // Инициализация карусели
	if( document.getElementById('painShop') ) {
		painTabInit('deseases');
		painTabInit('methods');
		painTabInit('branches');
	}

    // Раскрывающиеся прайс-листы
	$('.priceList dd').hide();
	$('.priceList dt a').click(function() {
		$(this).parent().next().slideToggle();
		return false;
	});

	// Попапы на станице списка видосов
	$('.videoBox a[rel]').click(function() {
		showPopup($(this).attr('rel'));
		return false;
	});

	// Placeholder поиска
	$('#searchbox_text').bind({
		focusin : function() {
			if ( $(this).val() == $(this).attr('title') ) $(this).val('').css({color: '#202325'});
		},
		focusout : function() {
			if ( $(this).val() == '' ) $(this).val( $(this).attr('title') ).css({color: '#969fa6'});
		}
	});

    // Fancybox-попапы на фотографии условий лечения
    $('.PhGalBox, .certBox').fancybox({
        overlayColor : '#0a559a',
        overlayOpacity : '.6',
        titlePosition : 'inside',
        padding: 30
    });

    $('.sendQuestion form').validate({
        rules: {
            'sq-text': 'required',
            'sq-name': 'required',
            'sq-contact': 'required'
        }
    });

    $('#sqForm').validate({
        rules : {
            'sqName' : {
                required : true
            },
            'sqContact' : {
                required : true
            }
        }
    });

    // Раскрывающийся блок «Другие заболевания»
    $('.moreDes a').click(function() {
        $(this).parent().next('.moreDes_slide').slideToggle();
        return false;
    });

    $('.priceListSubFlip h3 a').click(function() {
        $(this).parent().next('.priceListSubFlipItem').slideToggle();
        return false;
    });
});
