var currentCityId = null;

var scrollPaneOptions = {
    showArrows: false,
    horizontalDragMinWidth: 87,
    horizontalDragMaxWidth: 87,
    speed: 350,
    animateScroll: true
};

var scrollPaneOptionsArrow = {
    showArrows: true,
    horizontalDragMinWidth: 87,
    horizontalDragMaxWidth: 87,
    speed: 350,	
    animateScroll: true
};

$(document).ready(function() {
	initMainMenu();
    initSalonsMap();
    initService();
    initSpecials();
    initPopUpImpression();
    initModals();
    initSalonsIn();
    initCareerIn();

    if ($('#content.academy').size() > 0)
    {
        initAcademy();
    }

	$('div.services > h2.service:first-child').click();
	$('.invisible').fadeIn(1000);

    $(".tabs li").click(function() {
        var $tab = $(this);
        var $allTab = $('li', $tab.parent());
        var $tabWrap = $tab.parent().parent().next();
        if (!($tab.hasClass("active"))) {
            var tabIndex = $allTab.index($tab);
            $allTab.removeClass("active");
            $tab.addClass("active");
            $(".tab", $tabWrap).removeClass("active");
            $(".tab", $tabWrap).eq(tabIndex).addClass("active");
        }
    });

	$(".signup span").live('click', function(){
		$(".application_form").fadeIn(600);
	});
	 
	$(".application_form .close").live('click', function(){
		$(".application_form").fadeOut(600);
	});

	$(".general_request span").live('click', function(){
		$(".general_request_form").fadeIn(600);
	});
	 
	$(".general_request_form .close").live('click', function(){
		$(".general_request_form").fadeOut(600);
	});
	 	
	if ( navigator.userAgent.indexOf('iPad') != -1 ) {
		$("#wrap_main_menu #main_menu ul li ul li").css("margin-right","-1px");
	}
	
	/*royal slider*/
	if($('.jsSlider').length > 0){
        jsSlider();		
		$('.jsSlider .royalSlide').show();
    }	
	
	if($('#mainSlider').length > 0){
        sliderMainIphone();		
    }
	
	if($(".academy_tab .courses-list li").length > 2){
       // sliderMainAcademy();		
    }	
	
	if($('#listSalonsSlider li.royalSlide li').length > 9 ){
        sliderListSalonsIphone();
    }	
	
	if( $('.gallery_scroll').length > 0 ){
		sliderGalleryScroll();
	}
	/*end royal slider*/

});

$(window).load(function() {	
	initLazyLoad();
	initHorSliderEvents();
	initHorSlider();
	initGalleryCollection();
});

initMainMenu = function() {
	$("#wrap_main_menu #main_menu ul li ul li:last-child").css("padding-right","12px");	
};

initPopUpImpression = function() {
	$('a.about_the_contest').click(
		function(){	
			$(this).removeClass('active').find('span.close').hide();		
			$(this).next().hide();
			return false;			
		}		
	)	
	$('a.about_the_contest').mouseenter(
		function(){			
			$(this).addClass('active');
			$(this).find('span.close').show();
			$(this).next().show();			
		}
	)	
	$('.all_members .pop_up').mouseleave(
		function(){	
			$(this).prev().removeClass('active').find('span.close').hide();		
			$(this).hide();			
		}
	)	
};

initSalonsIn = function() {
	$('.wrap_salons_in h1:nth-child(1) a').click(
		function(){			
			$(this).parent().next().fadeIn(200);			
		}		
	)
	$('.wrap_salons_in .salons_in').mouseleave(
		function(){			
			$(this).fadeOut(200);
		}
	)
};

initCareerIn = function() {
    if ($('.wrap_career_in').length == 0)
    {
        return;
    }

	$('.wrap_career_in h1:nth-child(1) a').live('click', function(){
        $(this).parent().next().fadeIn(200);
        return false;
    });
	$('.wrap_career_in .career_in').live('mouseleave', function() {
        $(this).fadeOut(200);
        return false;
    });
    $('.career_in a').live('click', function() {
        var $link = $(this);
        currentCityId = $link.data('id');		
        $('.wrap_career_in .career_in').fadeOut(200);
        updateCitiesList();
        return false;
    });
    updateCitiesList();

    $('#sliderAbout').mousedown(function() {
        $('.publish-resume-form').fadeOut(600);
        return true;
    });

};

updateVacanciesList = function() {
    $('.vacancies_cities').children().addClass('hidden');
    $('.vacancies_cities li[data-id="' + currentCityId + '"]').removeClass('hidden');
    $(".application_form, .general_request_form").css("display","none");
    $('.vacancies_cities li[data-id="' + currentCityId + '"] .tabs ul li:first-child').click();
};

updateCitiesList = function() {
    var $currentCity = $('.title_career a');
    var $citiesList = $('.career_in ul');
    if ($citiesList.length == 0)
    {
        return;
    }

    $citiesList.children().remove();
    
    $currentCity.html(allCities[currentCityId]);
    
    for (cityId in allCities) {
        if (cityId == currentCityId) {
            $citiesList.append('<li><h1 class="active title_career">' + allCities[cityId] + '</h1></li>')
        }
    }
    for (cityId in allCities) {
        if (cityId != currentCityId) {
            $citiesList.append('<li><h1 class="title_career"><a href="#" data-id="' + cityId + '">' + allCities[cityId] + '</a></h1></li>')
        }
    }

    updateVacanciesList();
};

initModals = function() {
	$('.nyroModal').nyroModal();
	
    $('.gallery_preview a').click(function(e) {
        $('a:first', $(this).parent().prev()).click();
        return false;
    });

    $('.archive_collection li').click(function(e) {
        $('a:first', $(this))
            .click(function() {
                return false;
            })
            .click();
		return false;
    });

    $('.nyroModalClose').live('click', function() {
        setTimeout(function() {
            $('.nyroModalBg').next().hide();
            $('.nyroModalBg').hide();
        }, 200);
    });
   	
    $('.publish-resume').live('click', function() {
        var $form = $('.publish-resume-form');
        $('input[name="form_text_49"]', $form).val($(this).data('vacancyId'));
        $form.removeClass("hidden").fadeIn(600);
        return false;
    });

};

resizeNyroModal = function() {
    setTimeout(function() {
        if ($.nmTop())
        {
            //$.nmTop().resize(true);
        }
    }, 200);
};

sliderMainIphone = function() {		
	var mainSlider = $('#mainSlider').royalSlider(
	{
		slideTransitionSpeed: 200,			
		directionNavEnabled: false,
		controlNavEnabled: true,
		slideshowEnabled: true,
		slideshowDelay: 5000,
		slideshowPauseOnHover: true,
		keyboardNavEnabled: true
	}).data("royalSlider");	
};

sliderMainAcademy = function() {		
	var mainSlider = $('.courses-list').royalSlider(
	{
		slideTransitionSpeed: 200,			
		directionNavEnabled: false,
		controlNavEnabled: true,
		slideshowEnabled: true,
		slideshowDelay: 5000,
		slideshowPauseOnHover: true,
		keyboardNavEnabled: true
	}).data("royalSlider");	
};	

jsSlider = function() {	
	var jsSlider = $('.jsSlider').royalSlider(
	{	
		directionNavEnabled: false,
		controlNavEnabled: true,
		keyboardNavEnabled: true
	}).data("royalSlider");

    $("#main_menu ul li a[href*='#']").click(function() {
        var href = $(this).attr("href");
        var slideId = href.substr(href.indexOf('#'));
        var slideIndex = $(slideId).index();
        jsSlider.goTo(slideIndex);
        return false;
    });

	
    setInterval(function() {        	
		var $slide = $(".jsSlider ul > li:eq(" + jsSlider.currentSlideId + ")");
        var slideId = $slide.attr('id');
        if ($slide.attr('id') != 'slide-vacancies')
        {
            $('.publish-resume-form').fadeOut(600);
        }
        var $menuLink = $("#main_menu ul li a[href*='" + slideId + "']");
        $menuLink.parent().siblings().removeClass("item-selected");
        $menuLink.parent().addClass("item-selected");
    }, 200);

};

sliderGalleryScroll = function() {

	var gallerySlider = $('.gallery_scroll').royalSlider({
		directionNavEnabled: true,
		controlNavEnabled: true,
		keyboardNavEnabled: true,
		imageAlignCenter: $('.bg_journal_detail').length > 0 ? false : true,			
		controlNavThumbs: true,
		controlNavEnabled: true,
		controlNavThumbsNavigation: true,
		preloadNearbyImages : true,
		imageScaleMode: $('.bg_journal_detail').length > 0 ? "none" : "fit",
		afterSlideChange: function(){
			grayscale.reset( $('.royalThumb img') );
			grayscale( $('.royalThumb.current img') );
		}
	}).data("royalSlider");
	
    $('.gallery_scroll').royalSliderInjectJScrollPane(scrollPaneOptions, {
        scrollPaneHeight: '27px',
        scrollPaneTimeout: 300
    });

};

sliderListSalonsIphone = function() {	
	var listSalonsSlider = $('#listSalonsSlider').royalSlider(
	{			
		directionNavEnabled: true,
		controlNavEnabled: false,
		keyboardNavEnabled: true
	}).data("royalSlider");	
		
	$('.arrow-left').click(function() {
		if( listSalonsSlider.currentSlideId != 0 )	
			listSalonsSlider.goTo(listSalonsSlider.currentSlideId-1);		
		return false;	
	});

	$('.arrow-right').click(function() {				
		if( listSalonsSlider.currentSlideId != listSalonsSlider.numSlides-1 )	
			listSalonsSlider.goTo(listSalonsSlider.currentSlideId+1);			
		return false;	
	});
	
	listSalonsSlider.settings.beforeSlideChange = function() {
		if( listSalonsSlider.currentSlideId == 0 ){
			$('.arrow-right').show();
			$('.arrow-left').hide();
		}
		
		if( listSalonsSlider.currentSlideId == listSalonsSlider.numSlides-1 ){
			$('.arrow-left').show();
			$('.arrow-right').hide();
		}
    }	
};

initService = function() {  
  $("<div class='services_visual'></div>").insertAfter("nav.list_salons_city");

  $('div.services > div.wrap_service').hide();
  $('tr.hiddenContent').hide();
    var toggles = $('div.services > h2.service');
    toggles.addClass('toggle');
    toggles.click(function() {		
        var toggled = $(this);
        
		if (!toggled.hasClass('expanded')){										
			if( $('.services_visual img').length == 0 ) $("<img src='' alt='' title='' />").appendTo(".services_visual");
			$('div.services_visual img')
				.hide()
				.attr('alt',toggled.find('span').text())
				.attr('title',toggled.find('span').text())
				.attr('src',toggled.attr('data-image'))
				.fadeIn(2000);
		}

        var $nextDiv = toggled.next();
        var $visibleSiblings = $nextDiv.siblings('div.wrap_service:visible');
        if(toggled.hasClass('expanded')){
            $('.expanded').removeClass('expanded');
            $nextDiv.slideToggle(500);
        }
        else {
            $('.expanded').removeClass('expanded');
            if ($visibleSiblings.length) {
                $visibleSiblings.slideUp(500, function() {
                    $nextDiv.slideToggle(500);
                });
                toggled.addClass('expanded');
            }
            else {
                $nextDiv.slideToggle(500);
                toggled.addClass('expanded');
            }
        }
     
		if( $('h2.service.expanded').length == 0 ){
			$('.services_visual img').remove();
		}
	 	 
	 });
	$('td.hasHiddenContent').click(function(){
		var toggled = $(this).parent('tr');
		var hidden = toggled.next('tr.hiddenContent');
		if (hidden.is(":hidden")) {
			toggled.children('td').addClass('withoutBorder');
		} else {
			toggled.children('td').removeClass('withoutBorder');
		}
		hidden.toggle();
	});
};

initSpecials = function() {
    if ($('.specials-list').length > 0)
    {
			
        $(".specials-list li:first-child").addClass("isActive");

        $(".specials-list-img").cycle({
            fx:'fadeZoom',
            timeout: 0,
            speed:   600,
            startingSlide: 0
        });
        $(".specials-list li").click(function() {
            currentIndex = $(this).prevAll().length;
            $(".specials-list li[class='isActive']").removeClass("isActive");
            $(this).addClass("isActive");
            $('.specials-list-img').cycle(currentIndex);
            return false;
        });
		
		if(window.location.hash) $(".specials-list li"+window.location.hash).click();
    }
};
		
initGalleryCollection = function() {
	
	if($('div.wrap_min_img').length > 0){	
		grayscale( $('div.wrap_min_img img:first') );
		$('div.wrap_min_img img:first').css('opacity','0.5').parent().addClass('active');
	}
	
	
	$('div.wrap_min_img img').next().click(function() {																		
		if(!$(this).parent().hasClass('active')){		
			/*reset*/
			grayscale.reset( $('div.wrap_min_img div.active img') );
			$('div.wrap_min_img div.active img').css('opacity','1').parent().removeClass('active');						
			/*end reset*/
			
			grayscale($(this).prev());
			$(this).prev().css('opacity','0.5').parent().addClass('active');
					
			$('img#big_img')
				.attr('src',$(this).prev().attr('data-big-img'))
				.attr('original',$(this).prev().attr('data-big-img'))
				.lazyload({   
					placeholder : $(this).prev().attr('data-big-img'),
					effect : "fadeIn",
					effectspeed: 500
				});
		}	
		
	});	
};

initHorSlider = function() {	
	if( $('#gallery .scroll-pane').length > 0 || 			//мир моне - журнал
		$('.masters_scroll .scroll-pane').length > 0 || 	//салоны - мастера		
		$(".archive_collection .scroll-pane").length > 0 ||	//архив коллекций	
		$(".wrap_gallery_preview .scroll-pane").length > 0	//событие детально нижний скролл	
		)
	{		
		var margin_item = parseInt($('.scroll-pane li')
			.css("margin-right")
			.substring(0,$('.scroll-pane li')
			.css("margin-right")
			.indexOf("px"))
		);			
		var width_item = $('.scroll-pane li').width() + margin_item;					
		var count_item = $('.scroll-pane li').length;					
		$('.scroll-pane ul').css('width',(width_item*count_item) - margin_item);				
		
		
		if ($('#inspiration .scroll-pane').length > 0 && $('#gallery .scroll-pane').length > 0){
			$('#inspiration .scroll-pane').jScrollPane(scrollPaneOptionsArrow);
			$('#gallery .scroll-pane').jScrollPane(scrollPaneOptions);	
		}
		else $('.scroll-pane').jScrollPane(scrollPaneOptions);
	}
};

initHorSliderEvents = function() {
	if( $('.events .scroll-pane ul.list_event').length > 0 ){		
		var width_item = $('.events .scroll-pane ul.list_event li').width();
		var count_item = $('.events .scroll-pane ul.list_event li').length;

		$('.events .scroll-pane ul.list_event').css('width',(width_item*count_item) - 20);
		
		var event_top = $('.events .scroll-pane ul.list_event li div.event.top'), max_top = 0;
		event_top.each(function () {
			if ($(this).height() > max_top) max_top = $(this).height();
		});	
		$('.events .scroll-pane ul.list_event li div.event.top').height(max_top);
		
		var event_bottom = $('.events .scroll-pane ul.list_event li div.event.bottom'), max_bottom = 0;
		event_bottom.each(function () {
			if ($(this).height() > max_bottom) max_bottom = $(this).height();
		});	
		$('.events .scroll-pane ul.list_event li div.event.bottom').height(max_bottom);
		
		$('.events .scroll-pane').css('height',(max_top+max_bottom)+130+'px').jScrollPane(scrollPaneOptions);
	}
};

initLazyLoad = function() {    
	$("#mone_photo,#philosophy_girl").show().lazyload();
};

initSalonsMap = function() {
	
	$('a.marker').mouseenter(
		function () {	
			$(this).parent().css('z-index','2');
			$(this).css('z-index','2');
			$(this).next()
				.css({'z-index':'1','display':'block'})
				.stop()				
				.animate({opacity:1},300);			
		}
	)
	
	$('div.wrap_marker').mouseleave(
		function () {	
			$(this).css('z-index','0');
			$(this).find('a.marker').css('z-index','0');
			$(this).find('div.marker_address')
				.css({'z-index':'0','display':'none'})
				.stop()				
				.animate({opacity:0},300);			
		}
	)
	
	$('.list_salon li.item_salon').hover(
		function () {				
			var idi = $(this).find('a').attr('data-marker');
			
			$('#marker_'+idi).css('z-index','2');
			$('#marker_'+idi+' a.marker').css('z-index','2');
			
			$('#marker_'+idi+' div.marker_address')
				.css({'z-index':'1','display':'block'})
				.stop()				
				.animate({opacity:1},300);				
		},
		function () {						
			var idi = $(this).find('a').attr('data-marker');
			
			$('#marker_'+idi).css('z-index','0');
			$('#marker_'+idi+' div.marker_address')
				.css({'z-index':'0','display':'none'})
				.stop()
				.animate({opacity:0},300,function(){				
					$(this).prev().css('z-index','0');
				});							
		}
	);
};

initAcademy = function() {
    $("#content.academy .academy_tab:eq(0)").show();
	
	var params = {
        changedEl: "select",
        visRows: 50,
        scrollArrows: true
    }
	cuSel(params);

    var i=0;
    var delta = 0;
    var dop = 0;
    var num = 0;
    $("#content.academy .tab ol").each(function() {
        i = 0;
        delta = 0;
        if ($(this).hasClass("start_10")) {
            delta = 9;
        }
        num = $(this).find("li").size();
        for (i = 0; i < num; i++) {
            dop = (i + delta < 9) ? "0" : "";
            $(this).children("li").eq(i).prepend("<div>"+dop+(i+delta+1)+".</div>");
        }
    });

    $("#sideRight .list_academy li").click(function() {
        var index = $("#sideRight .list_academy li").index($(this));

        $("#content.academy .academy_tab").slideUp();
        $("#content.academy .academy_tab").eq(index).slideDown();

        if (index > 0) {
            $(".aside_image").hide();
        } else {
            $(".aside_image").show();
        } if ((index == 1) || (index == 2) || (index == 3) || (index == 4)) {
            $(".masterclass_sign_up").show();
        } else {
            $(".masterclass_sign_up").hide();
        }

        var height = $(".academy_tab").eq(index).height();
        $(".specials-list-img").css({height: height+"px"});
    });

    $(".masterclass_sign_up span").click(function(){
        $(".list_academy").slideUp();
        $(".contact_line").slideUp();
		$(".masterclass_sign_up").hide();
        $(this).slideUp();
        $(".masterclass_form").slideDown();
    });

    $(".masterclass_form .close").live('click', function() {
        $(".list_academy").slideDown();
        $(".contact_line").slideDown();
		$(".masterclass_sign_up").show();
        $(".masterclass_sign_up span").slideDown();
        $(".masterclass_form").slideUp();
    });
};
