/*страница "он-лайн регистрация" добавление анкеты участника*/
var noHide = false;
var elementForDelete = null;

function trim(text) {
	return text.replace(/^\s+|\s+$/g, '');
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}


$(window).load(function(){

    //проверка формы "Авторизация"
    $("#authForm").submit(function (){

        window.reEmail = /^([a-z0-9\.\-\_])+\@(([a-zA-Z0-9\-\_])+\.)+([a-zA-Z0-9]{2,6})+$/i;

        if ( trim($("#auth_login").val()) == '') {
             alert(lang['AUTH_MSG_1']);
             $('#auth_login').focus();

        } else  if (!reEmail.test($("#auth_login").val())) {
             alert(lang['AUTH_MSG_2']);
             $('#auth_login').focus();

        } else if ( $("#auth_password").val() == '' ) {
             $('#auth_password').focus()
             alert(lang['AUTH_MSG_3']);

        } else {

            $.post($('#authForm').attr('action'), $('#authForm').serialize(), function(data){
                if (data == 'error') {

                    if ($("#error_auth_").length > 0)
                        $("#error_auth_").html('<b class="rederror">' + lang['AUTH_MSG_4'] + '</b>');
                    else
                        alert(lang['AUTH_MSG_4']);
                    
                    $("#auth_password").val('');
                    $("#auth_password").focus();
                } else {
                    document.location.replace(data);
                }
            });
        }

        return false;
    });


    $("#subscribeForm").submit(function (){

        window.reEmail = /^([a-z0-9\.\-\_])+\@(([a-zA-Z0-9\-\_])+\.)+([a-zA-Z0-9]{2,6})+$/i;

        if ($('#emailSubscr').val() == '') {
            alert(lang['SUBSCRIBE_MSG_1']);
            $('#emailSubscr').focus();
        } else if (!reEmail.test($("#emailSubscr").val())) {
            alert(lang['SUBSCRIBE_MSG_2']);
            $('#emailSubscr').focus();
        } else return true;

        return false;
    });

	$('.sound').click(function(){
		if ($(this).attr("alt") == 'on') {

			$(".imglink").css("backgroundPosition",'left top');
			$(".sound").attr('alt','off');

			$('.mp3').html('');
		} else {

			$(".imglink").css("backgroundPosition",'left bottom');
			$(".sound").attr('alt','on');
			$('.mp3').jmp3().css("opacity","0").css('width','1px').css('height','1px');
			$('.mp3').html(player);
		}
		return false;
	})

	/*прокрутка победителей*/
	$('#winners>div ul').ready(function(){
		var width = 0;
		$('#winners>div ul li').each(function(){
			width = width + parseInt($(this).outerWidth(true));
		});
		$('#winners>div ul').css('width', width);

		var winnersTimerLeft = null;
		var winnersTimerRight = null;

		function winnersScrollLeft(){
			$('#winners>div').scrollLeft(parseInt($('#winners>div').scrollLeft()) - 2);
			winnersTimerLeft = setTimeout(function(){winnersScrollLeft();}, 20);
		}

		function winnersScrollRight(){
			$('#winners>div').scrollLeft(parseInt($('#winners>div').scrollLeft()) + 2);
			winnersTimerRight = setTimeout(function(){winnersScrollRight();}, 20);
		}

		$('#winners a.left').mouseover(function(){
			winnersTimerLeft = setTimeout(function(){winnersScrollLeft();}, 20);
		});

		$('#winners a.left').mouseout(function(){
			clearTimeout(winnersTimerLeft);
			winnersTimerLeft = null;
		});

		$('#winners a.right').mouseover(function(){
			winnersTimerRight = setTimeout(function(){winnersScrollRight();}, 20);
		});

		$('#winners a.right').mouseout(function(){
			clearTimeout(winnersTimerRight);
			winnersTimerRight = null;
		});
	});

	//история
	$('.gallerywrapper').ready(function(){

		var width = 0;
		$('.gallerywrapper ul li').each(function(){
			width = width + parseInt($(this).outerWidth(true));
		});

		$('.gallerywrapper ul').css('width', width);

		var interaction = false;
		var mouseX = 0;
		var scrollerLeft = 0;

		$('.gallerywrapper .scroller').mousedown(function(ev){
			interaction = true;
			var offset = $(this).offset();
			mouseX = parseInt(ev.pageX) - parseInt(offset.left);
			ev.preventDefault();
		});

		$('.gallerywrapper').mouseup(function(){
			interaction = false;
		});

		$('.gallerywrapper').mouseout(function(){
			//interaction = false;
		});

		$('.gallerywrapper').mouseleave(function(){
			interaction = false;
		});

		$('.gallerywrapper').mousemove(function(ev){

			if (!interaction){
				return false;
			}

			var scroller = $(this).children('div.scroller');
			var offset = $(this).offset();
			var x = parseInt(ev.pageX) - parseInt(offset.left) - mouseX;
			var maxX = $(this).width() - $(scroller).width();

			if (x > 0 && x < maxX){
				$(scroller).css('left', x);
			} else if (x <= 0){
				$(scroller).css('left', 0);
				x = 0;
			} else {
				$(scroller).css('left', maxX);
				x = maxX;
			}

			var maxScrollLeft = $(this).children('div.gallerywrapper2').children('ul').outerWidth() - maxX - $(scroller).width();
			$(this).children('div.gallerywrapper2').scrollLeft(Math.round((x / maxX) * maxScrollLeft));
			ev.preventDefault();

		});
		
		
		var currentImageIndex = 0, hashvideo = 0;
		if ( document.location.hash == '#video') hashvideo = 1;
		$('.gallerywrapper ul li a').click(function(){
		
			if (hashvideo != 1 ){
				
				$('#enlargedvideo').hide();
				$('#enlargedimg').show();
				
				$('#enlargedimg img').attr('src', $(this).attr('href') ).load(function() {
						$('#enlargedimg').css('height', $(this).height() );
					});

				currentImageIndex = $(this).parent().index() + 1;
				$('#enlarged .left:hidden').show();
				$('#enlarged .right:hidden').show();
			}
			
			hashvideo = 0;
			return false;
		});
		

		$('#enlarged .left').click(function(){
			if (currentImageIndex > 1){
				currentImageIndex--;
				
				
				$('#enlargedimg img').attr('src', $('.gallerywrapper ul li:nth-child(' + currentImageIndex + ') a').attr('href') ).load(function() {
					$('#enlargedimg').css('height', $(this).height() );
				});
			}
			
			$('#enlarged .right').attr('class', 'right');
			if (currentImageIndex == 1)   $('#enlarged .left').attr('class', 'left left_');   else   $('#enlarged .left').attr('class', 'left');
			return false;
		});

		$('#enlarged .right').click(function(){
			if (currentImageIndex < $('.gallerywrapper ul li').length){
				currentImageIndex++;
				
				$('#enlargedimg img').attr('src', $('.gallerywrapper ul li:nth-child(' + currentImageIndex + ') a').attr('href')).load(function() {
					$('#enlargedimg').css('height', $(this).height() );
				});

			}
			
			$('#enlarged .left').attr('class', 'left');
			if (currentImageIndex == $('.gallerywrapper ul li').length)  $('#enlarged .right').attr('class', 'right right_'); else   $('#enlarged .right').attr('class', 'right');
			return false;
		});

		$('.video a').click(function(){
			$('#enlargedimg').hide();
			$('#enlarged .left:visible').hide();
			$('#enlarged .right:visible').hide();
			
			$('#enlargedvideo').show();
			$('#enlargedvideo').html('<object type="application/x-shockwave-flash" data="/images/tpl/uppod.swf" width="867" height="375"><param name="bgcolor" value="#ffffff"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/><param name="movie" value="../../' + $(this).attr('href') + '"/><param name="flashvars" value="st=' + escape('/images/tpl/video68-672.txt') + '&amp;file=' + escape( $(this).attr('href') ) + '"/><embed src="images/tpl/uppod.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" flashvars="st=' + escape('/images/tpl/video68-672.txt') + '&amp;file=' + $(this).attr('href') + '" width="867" height="375"></embed></object>');
			return false;
			
		});
		
	

	});


	/*добавление полупрозрачного белого фона к появляющимся формам*/
	var whiteshaderFunc = function(){

		var shader = document.createElement('div');
		$('.shaded, .shaded_2').show();
		$('#deletemember').css('left', Math.round( (parseInt($('body').outerWidth()) - parseInt($('#deletemember').outerWidth()) ) / 2));
		
		$(shader).attr('id', 'shader').css('background-color', '#FFF').css('opacity', '0.75').css('position', '').css('left', '0').css('right', '0').css('top', '0').css('bottom', '0').css('z-index', '3999');

		if ($(this).attr('rel')){

            // Карта дистинций
            var displayed = $(this).parent().find('.programm_map');
			$(displayed).css('left', Math.round( (parseInt($('body').outerWidth()) - parseInt($(displayed).outerWidth()) ) / 2));
			$(displayed).show();
      
		} else if ($(this).attr('href') && $(this).attr('href') != '#'){

			var shader2 = document.createElement('div');
			$(shader2).attr('id', 'shadercontainer').css('position', 'absolute').css('left', '0').css('right', '0').css('top', '0').css('bottom', '0');
			$('body').append(shader2);

			var box = document.createElement('div');
			$(box).attr('id', 'shaderbox').css('width', '1000px').css('height', $(window).height()+'px').css('margin', '0 auto').css('position', 'relative');
			$(shader2).append(box);

			var img = document.createElement('img');
			$(img).attr('src', $(this).attr('href')).css('display', 'none');
			$(img).load(function(){
				$(img).css('position', 'absolute').css('left', Math.round( (parseInt($(box).outerWidth()) - parseInt($(img).outerWidth()) ) / 2)).css('top', 
				Math.round( (parseInt( $(window).height() ) - parseInt( $(img).outerHeight() ) ) )+'px').css('z-index', '4000');
				$(img).show();
			//	alert($(window).height());
			});

			
			$(img).click(function(){
				noHide = true;
				return true;
			});

			$(box).append(img);
		}
		$('body').append(shader);
		
		return false;
	}

	$('.whiteshader').click(whiteshaderFunc);


  	//поле Время
	$("#time").keyup( function(){

		 var time_ = $(this).val().replace(/[^\d\:]/g, "");
		 if ( time_.substr(0,2) < -1  ||  time_.substr(0,2) > 23 ) time_ = '00';
		 if ( time_.length == 2 ) time_ = time_+':';
		 if ( time_.substr(3,1) == ':' ) time_ = time_.substr(0,2)+time_.substr(3,2);
		 if ( time_.substr(3,2) < -1  ||  time_.substr(3,2) > 59 ) time_ = time_.substr(0,3)+'00';
		 $(this).val(time_);

	});

	/*добавление класса последнему пункту меню*/
	//$('#nav li:last-child').addClass('last');


	var addit = ($.browser.version == "7.0" || $.browser.version == "6.0")  ? 1 : 0;
	
	$("#nav li").mouseover(function(){

	  var me = ($(this).parent().hasClass('hidden')) ? $(this).parent() : $(this).children('.hidden');

	  if (!$(me).hasClass('mouseovered')){
	   $('.hidden').removeClass('mouseovered');
	   $(me).addClass('mouseovered');
	  }

	  $(me).parent().children('.hidden:hidden').fadeIn('fast');
	  $('.hidden:visible:not(.mouseovered)').fadeOut('fast');

	  return false;
	});
	
	/*выпадающее меню при наведении на пункт меню в header*/
	/*$("#nav li").mouseover(function(e){
		$(this).children('.hidden').fadeIn('fast');
		return false;
	});*/

	
	$('body').mouseover(function(){
		$('.hidden').fadeOut('fast');
	});
	
	/*выпадающее меню при наведении на пункт меню в header*/
	$(".p1, .p2, .p3, .p4").mouseover(function(e){
		$(this).children('.wrap3').fadeIn('fast');
		return false;
	});
	
	$('body').mouseover(function(){
		$('.wrap3').fadeOut('fast');
	});
	
	


	/*блок партнеры, изменение логотипа с ч/б на цветной*/
	$("#partners a").mouseover(function () {
			 $(this).children("img").eq(0).css({'display' : 'none'});
 			 $(this).children("img").eq(1).css({'display' : 'inline'});
 	});

	$("#partners a").mouseout(function () {
 			$(this).children("img").eq(0).css({'display' : 'inline'});
			$(this).children("img").eq(1).css({'display' : 'none'});
 	});


	$("#sponsors a").mouseover(function () {
			 $(this).children("img").eq(0).css({'display' : 'none'});
 			 $(this).children("img").eq(1).css({'display' : 'inline'});
 	});

	$("#sponsors a").mouseout(function () {
 			$(this).children("img").eq(0).css({'display' : 'inline'});
			$(this).children("img").eq(1).css({'display' : 'none'});
 	});


	/*Поиск*/
	$('#search').focus(function(){
		if ($(this).val() == lang['TEXT_SEARCH'])
			$(this).val('');
	}).blur(function(){
		if ($(this).val() == '')
			$(this).val(lang['TEXT_SEARCH']);
	});

	$('#mainsearch').focus(function(){
		if ($(this).val() == lang['TEXT_SEARCH'])
			$(this).val('');

	}).blur(function(){
		if ($(this).val() == '')
			$(this).val(lang['TEXT_SEARCH']);
	});

	/*внутренняя текстовая страница*/
	$('.base_auth_form #auth_login').focus(function(){
		if ($(this).val() == lang['TEXT_EMAIL'])
			$(this).val('');
	}).blur(function(){
			if ($(this).val() == '')
				$(this).val(lang['TEXT_EMAIL']);
	});

	$('.base_auth_form #auth_password').focus(function(){
		if ($(this).val() == '*******')
			$(this).val('');
	}).blur(function(){
			if ($(this).val() == '')
				$(this).val('*******');
	});

	$('.cross').click(function(){
		$('#registration').hide();
		return false;
 	});

	/*форма авторизации*/
	$('.autorisation').click(function(){
		$('#registration:visible').hide();
		$('#question:visible').hide();
		$('#autorisation').css('left', Math.round( (parseInt($('body').outerWidth()) - parseInt($('#autorisation').outerWidth()) ) / 2));
		/*$('#autorisation').css('top', Math.round( (parseInt($(window).height() + $(window).scrollTop()) - parseInt($('#autorisation').outerHeight()) ) / 2));*/
		$('#autorisation').show();
        $("#auth_login").focus();
		return false;
	});

	$('.autorisation').click(function(){
		$('.shaded_, .shaded_2_').show();
        $("#auth_login").focus();
	});

	$('.cross').click(function(){
		$('#autorisation').hide();
		$('.shaded_, .shaded_2_').hide();
		return false;
 	});

	$('#autorisation').click(function(event){
		noHide = true;
		return !(event.target.nodeName == 'DIV');
	});

	$('.programm_map').click(function(event){
		noHide = true;
		return !(event.target.nodeName == 'DIV');
	});

	//форма "Задать вопрос"
	$('.askquestion a').click(function(){
		$('#registration:visible').hide();
		$('#autorisation:visible').hide();
		$('#question').css('left', Math.round( (parseInt($('body').outerWidth()) - parseInt($('#question').outerWidth()) ) / 2));
		/*$('#question').css('top', Math.round( (parseInt($(window).height() + $(window).scrollTop()) - parseInt($('#question').outerHeight()) ) / 2));*/
		$('#question').show();
		return false;
	});

	$('.askquestion a').click(function(){
			$('.shaded, .shaded_2').show();
	});

	$('.cross').click(function(){
		$('#question').hide();
		$('.shaded, .shaded_2').hide();
		return false;
 	});

	$('#question').click(function(event){
		noHide = true;
		return !(event.target.nodeName == 'DIV');
	});


	//блок вопрос-ответ
	$('.questionanswer a.title').click(function(){
			$(this).parent().parent().toggleClass('viewed');
		return false;
	});
	
	
	



	//блок "Начни движение"
	$('.advice a.title').click(function(){
		var flag = $(this).parent().parent().hasClass('viewed');
		$('.advice li').removeClass('viewed');
		if (!flag){
			$(this).parent().parent().addClass('viewed');
		}
		return false;
	});


	//страница "Схема трасс", меню
	$('.contestmenu li a').click(function(){
		$('.contestmenu li.selected').removeClass('selected');
		$(this).parent().addClass('selected');
		$('.right h2').html($(this).html());
		$('.rightwrap').html($(this).parent().children('.hidedcontent').html());
		$('.rightwrap .whiteshader').click(whiteshaderFunc);
		return false;
	});

    $('.contestmenu li a:first').click();

	//страница "История"
	$('#righthistory .header li a').click(function(){
		$('#righthistory .header li.selected').removeClass('selected');
		$(this).parent().addClass('selected');
		$('#contentwrapper').html($(this).parent().children('.hidedcontent').html());
		return false;
	});

	//главная страница "календарь мероприятий"
	var lastEventCalendar = null;
	$("#eventscalendar li").mouseover(function(e){
		if (lastEventCalendar == this){
			return false;
		}
		$('#eventscalendar li .shade:visible').fadeOut('fast');
		$(this).children('.shade:hidden').fadeIn('fast');
		lastEventCalendar = this;
		return false;
	});

	$('body').mouseover(function(){
		$('.shade').hide();
		lastEventCalendar = null;
	});


	$('body').click(function(){
		if (!noHide){
			$('#registration:visible').hide();
			$('#autorisation:visible').hide();
			$('#confirmpayment:visible').hide();
			$('#question:visible').hide();
			$('#deletemember:visible').hide();
			$('.shaded:visible, .shaded_2:visible').hide();
			$('.shaded_:visible, .shaded_2_:visible').hide();
			$('.programm_map:visible').hide();
			$('#shadercontainer').remove();
			$('#shader').remove();
		} else{
			noHide = false;
		}
 	});

});


function getXML(responseText) {
	if (jQuery.browser.msie) {
 		// если это IE то создаем ActiveX объект и приобразуем строковую переменную в XML
   		xml_data = new ActiveXObject( 'Microsoft.XMLDOM');
        xml_data.async = false;
        xml_data.loadXML(responseText);
	} else {
 		xml_data = responseText;
 	}

 	return $(xml_data);
}




function videoFunct(){
		
		$("#video__ li").each(function(){
		
			$('#enlargedimg').hide();
			$('#enlarged .left:visible').hide();
			$('#enlarged .right:visible').hide();
			
			$('#enlargedvideo').show();
			$('#enlargedvideo').html('<object type="application/x-shockwave-flash" data="/images/tpl/uppod.swf" width="867" height="375"><param name="bgcolor" value="#ffffff"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/><param name="movie" value="../../' + $(this).attr('href') + '"/><param name="flashvars" value="st=' + escape('/images/tpl/video68-672.txt') + '&amp;file=' + escape( $(this).children('a').attr('href') ) + '"/><embed src="images/tpl/uppod.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" flashvars="st=' + escape('/images/tpl/video68-672.txt') + '&amp;file=' + $(this).children('a').attr('href') + '" width="867" height="375"></embed></object>');
			
			exit();
		});
		
}















