/*
function mazza(el){

		if(el.value == "Физические лица"){
				el.parent().next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
				el.parent().next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
				el.parent().next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
				el.parent().next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
		}
		else{
				el.parent().next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
				el.parent().next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
				el.parent().next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
				el.parent().next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
		}

}
*/
$(document).ready(function() {

			
	
	/* Info Texts
	var info_ru = new Array(
		{'info_1','В данную стоимость включены: регистрация компании, оплата государственных пошлин, номинальный руководитель за один месяц, юридический адрес за один месяц. умма с учетом  НДС.'}
	);
	 */
	 
	/* Styling Content Wrapper if no content in Sidebar */
	sidebar = $('.sb');
	if(sidebar[0]){
		$('.sd').css({'paddingLeft':36.6+'%'});
	}
	else{$('.sd').css({'paddingLeft':11+'%'});}
	
	/* Styling OL */
	$('ol').each(function(){
		for(var li=1; li<=$(this).find('li').length; li++){
			$(this).find('li').eq(li-1).prepend('<span class="oln">'+li+'. '+'</span>');
		}
	});
	
    $(".form form, #askForm").each(function(){
        $(this).validate({
            rules: {
                fio: "required",
short_info: "required",
                mail: {
                    required: true,
                    email: true
                }
           },
            errorPlacement: function(error, element) {
                error.insertAfter( element.parent() ).parent().addClass('error');
            },
            success: function(label) {
                label.parent().removeClass('error');
            }
        });
    });

    $("#orderOnline").each(function(){
        $(this).validate({
            rules: {
                yname: "required",
                ymail: {
                    required: true,
                    email: true
                }
           },
            errorPlacement: function(error, element) {
                error.insertAfter( element.parent() ).parent().addClass('error');
            },
            success: function(label) {
                label.parent().removeClass('error');
            }
        });
    });

    /* Locations Action */
    $('.ll li').hover(
        function(){
            $('.loc-color .'+$(this).find('a').attr('class').replace('col-','l')+'').fadeIn('fast').siblings().fadeOut('fast');
            $('.loc-markers .'+$(this).attr('class').replace('active ','').replace('loc','m')+'').addClass('active');
        },
        function(){
            $('.loc-color .'+$(this).attr('class').replace('active ','').replace('oc-','')+'').fadeOut('slow');
            $('.loc-markers .'+$(this).attr('class').replace('active ','').replace('loc','m')+'').removeClass('active');
        }
    );





    //Opera overflow hack
    if ($.browser.opera) {
        $("body, html").css({'position':'absolute', 'overflowX':'auto', 'overflowY':'auto'});
    }

    /* Styling Top Menu */
    $('.mw li:last').addClass('last');

    /* Drop Down Menu in Phones Block */
    $('.dd li:first').addClass('first');
    $('.dd li:not(".first")').hide();

    $('.dd li').click(function(){
        if($(this).parent().hasClass('closed')){
            $(this).parent().removeClass('closed').addClass('opened');
            $('.dd li').show();
        }
        else{
            $(this).parent().removeClass('opened').addClass('closed');
            $('.dd li').hide().removeClass('first');
            $(this).show().addClass('first');
        }
    });

    /* Show Order Online Popup */
    $('a').click(function(){
        if($(this).find('span').html() == 'Вопрос онлайн' || $(this).html() == 'Вопрос онлайн' || $(this).find('span').html() == 'Question online' || $(this).html() == 'Question online'){
            $('.popups').show();
            $('#ask').show();
        }
    });
	
	$('.sd table').each(function(){
		$(this).wrap('<div class="tb tbl"></div>');
	});
	
    /* Phones Tabs Actions */
    $('.ph .es:first').show();
    for(var c=0; c<$('.dd li').length; c++){
        $('.dd li a').eq(c).addClass('tloc-'+c+'');
        $('.ph .es').eq(c).addClass('tloc-'+c+'');
    }
    $('.dd li a').click(function(){
        $('.ph .'+$(this).attr('class')+'').show().siblings('.es').hide();
    });

    /* Order Online Actions */
    $('select[name="country"]').change(function(){
        if($(this).find('option:selected').val() == 'США (LLC)' || $(this).find('option:selected').val() == 'США (Corporation)'){
            $(this).parent().next().removeClass('hidden');    
        }
        else{$(this).parent().next().addClass('hidden'); }
    });

    /* Add Another Person */
    $('.o3 .add-person').click(function(){

$('.o3 .hidden:first').removeClass('hidden');

		$('.d-inner').toggleClass('ie-fix');
    });
	$('.o4 .add-person').click(function(){
        lastGr = $('.o4 .gr:last');
		var FileName = lastGr.find('input[type="file"]').attr('name')
        lastGr.clone().insertAfter(lastGr).find('input[type="file"]').attr('name',FileName+'1');
		lastGr.nextAll('.gr').find('input[type="text"]').val('');
		$('.d-inner').toggleClass('ie-fix');
    });

    var inputFile = $("input[type=file]");
    if(inputFile[0]){
        $("input[type=file]").filestyle({
            image: "assets/templates/urist/img/btn-file.png",
            imageheight : 33,
            imagewidth : 92,
            width : 356
        });
    }


	/* Online Order Logic */

    $('.oo ul li.o1').show(); // При загрузке показываем первый вопрос "Выбирите страну"

	// Вопрос №1 "Выбирите страну", валидация + показ всплывающего окна + переход к следующему вопросу №2 "Название компании"
    $('.o1 .btn-next').click(function(){
        if($('#buy-comp').attr('checked')){ // Показываем попап
            $('.popups .pop').hide();
            $('.popups').show();
			$('#note').show();
        }
        else if($('#reg-new').attr('checked')){ // Переход к следующему вопросу №2 "Название компании"
            $('.o1').hide(); // Закрываем текущий вопрос
			$('.o2').show(); // Показываем следующий вопрос
        }
    });
	
	// Вопрос №2 "Название компании", валидация + переход к следующему вопросу №3 "Учредители"
    $('.o2 .btn-next').click(function(){
        $('.o2 input').each(function(){
            if($(this).val() == ''){
                $(this).parent().parent().addClass('error');
            }
            else if($(this).parent().parent().siblings().find('input').val() != ''){
				$('.o2').hide(); // Закрываем текущий вопрос
				$('.o3').show(); // Показываем следующий вопрос
			}
        });
    });
	
	// Вопрос №3 "Учредители", валидация + логика перехода на следующий вопрос
	
	// Скрываем учредителей компании и соотв. поля 
	$('.o3 h3, .o3 .gr, .o3 .add-person').hide();
	$('#uch-phiz, #uch-ur').parent().hide();
	
	// Скрываем учредителей компании и соотв. поля при клике на "Использовать номинальный сервис"
    $('#nomin').parent().click(function(){
        $('.o3 h3, .o3 .gr, .o3 .add-person').hide();
        $('#uch-ur, #uch-phiz').parent().hide();
    });
	// Показываем учредителей компании и соотв. поля при клике на "Указать определенных лиц в качестве учредителей"
    $('#spec-people').parent().click(function(){
        $('.o3 h3, .o3 .gr, .o3 .add-person').show();
        $('#uch-ur, #uch-phiz').parent().show();
    });
    // Скрываем директоров компании и соотв. поля при клике на "Использовать номинальный сервис"
    $('.o4 h3, .o4 .gr, .o4 .add-person').hide();
    $('#nomin-d').parent().click(function(){
        $('.o4 h3, .o4 .gr, .o4 .add-person').hide();
    });
	// Показываем директоров компании и соотв. поля при клике на "Указать определенных лиц в качестве учредителей"
    $('#spec-people-d').parent().click(function(){
        $('.o4 h3, .o4 .gr, .o4 .add-person').show();
    });
    
	/* Переключаем подписи в соотв. с выбранным видом */
    $('#uch-phiz').parent().click(function(){
		$(this).next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
        $(this).next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
        $(this).next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
        $(this).next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
    });
    $('#uch-ur').parent().click(function(){
        $(this).next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
        $(this).next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
        $(this).next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
        $(this).next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
    });    
	
    $('#uch-phiz1').parent().click(function(){
        $(this).next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
        $(this).next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
        $(this).next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
        $(this).next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
    });
    $('#uch-ur1').parent().click(function(){
        $(this).next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
        $(this).next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
        $(this).next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
        $(this).next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
    });   

	
    $('#uch-phiz11').parent().click(function(){
        $(this).next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
        $(this).next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
        $(this).next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
        $(this).next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
    });
    $('#uch-ur11').parent().click(function(){
        $(this).next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
        $(this).next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
        $(this).next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
        $(this).next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
    });  

	
    $('#uch-phiz111').parent().click(function(){
        $(this).next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
        $(this).next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
        $(this).next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
        $(this).next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
    });
    $('#uch-ur111').parent().click(function(){
        $(this).next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
        $(this).next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
        $(this).next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
        $(this).next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
    });  

	
    $('#uch-phiz1111').parent().click(function(){
        $(this).next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
        $(this).next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
        $(this).next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
        $(this).next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
    });
    $('#uch-ur1111').parent().click(function(){
        $(this).next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
        $(this).next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
        $(this).next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
        $(this).next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
    });  

	
    $('#uch-phiz11111').parent().click(function(){
        $(this).next().next().find('input[name="fio[]"]').parent().prev().html('Фамилия, имя:');
        $(this).next().next().find('input[name="passport[]"]').parent().prev().html('Номер паспорта:');
        $(this).next().next().find('input[name="birthday[]"]').parent().prev().html('Дата рождения:');
        $(this).next().next().find('input[name="address[]"]').parent().prev().html('Адрес проживания:');
    });
    $('#uch-ur11111').parent().click(function(){
        $(this).next().find('input[name="fio[]"]').parent().prev().html('Название компании:');
        $(this).next().find('input[name="passport[]"]').parent().prev().html('Регистрационный номер:');
        $(this).next().find('input[name="birthday[]"]').parent().prev().html('Дата регистрации:');
        $(this).next().find('input[name="address[]"]').parent().prev().html('Юридический адрес:');
    });  
	
	// Логика + валидация
    $('.o3 .btn-next').click(function(){
        $('.o3 .gr').each(function(){
            if($(this).find('input[type="text"]').val() == '' && $('#spec-people').attr('checked')){
                $(this).find('input[type="text"]').parent().parent().addClass('error');
            }
            
			if($(this).find('input[name="fio[]"]').val() != '' && $(this).find('input[name="passport[]"]').val() != '' && $(this).find('input[name="birthday[]"]').val() != '' && $(this).find('input[name="address[]"]').val() != '' && $(this).find('input[name="dolya[]"]').val() != '' ){
				$('.o3').hide(); // Закрываем текущий вопрос
				$('.o4').show(); // Показываем следующий вопрос
			}
			if($('#nomin').attr('checked')){
				$('.o3').hide(); // Закрываем текущий вопрос
				$('.o4').show(); // Показываем следующий вопрос
			}
        });
    });

	// Вопрос №4 "Директора", валидация + логика
    $('.o4 .btn-next').click(function(){
        $('.o4 .gr').each(function(){
            if($(this).find('input[type="text"]').val() == '' && $('#spec-people-d').attr('checked')){
                $(this).find('input[type="text"]').parent().parent().addClass('error');
            }
            if($(this).find('input[name="fio-d[]"]').val() != '' && $(this).find('input[name="passport-d[]"]').val() != '' && $(this).find('input[name="birthday-d[]"]').val() != '' && $(this).find('input[name="address-d[]"]').val() != ''){
				
				
				/* Если Учред. НЕ Ном. и Дир. НЕ Ном. */
				if($('#spec-people').attr('checked') && $('#spec-people-d').attr('checked')){
					$('.o4').hide();
					$('.o7').show(); // Показываем вопрос №7 "Акции"
				};
				
				/* Если Учред. Ном. и Дир. НЕ Ном. */
				if($('#nomin').attr('checked') && $('#spec-people-d').attr('checked')){
					$('.o4').hide();
					$('.o6').show(); // Показываем вопрос №6 "Бенефициары"
				};
			}
			/* Если Учред. Ном. и Дир. Ном. */
			if($('#nomin').attr('checked') && $('#nomin-d').attr('checked')){
				$('.o4').hide();
				$('.o5').show(); // Показываем вопрос №5 "Доверенное лицо"
			};
			
			/* Если Учред. НЕ Ном. и Дир. Ном. */
			if($('#spec-people').attr('checked') && $('#nomin-d').attr('checked')){
				$('.o4').hide();
				$('.o5').show(); // Показываем вопрос №5 "Доверенное лицо"
			};
		});
    });
	
	// Вопрос №5 "Доверенное лицо"
    $('.o5 .btn-next').click(function(){
        $('.o5 .gr').each(function(){
            if($(this).find('input').val() == ''){
                $(this).find('input').parent().parent().addClass('error');
            }
            else if($(this).find('input[name="fio-dov"]').val() != '' && $(this).find('input[name="passport"]').val() != ''){
				
				/* Если Учред. НЕ Ном. и Дир. Ном. */
				if($('#spec-people').attr('checked') && $('#nomin-d').attr('checked')){
					$('.o5').hide();
					$('.o7').show(); // Показываем вопрос №7 "Акции"
				};
				
				/* Если Учред. Ном. и Дир. Ном. */
				if($('#nomin').attr('checked') && $('#nomin-d').attr('checked')){
					$('.o5').hide();
					$('.o6').show(); // Показываем вопрос №6 "Бенефициары"
				};
            }
        });
    });
	
	/* Отправка аяксом запроса на получение суммы */
	function goAjax(){
		var comp_i_is = $('.o3 input[type="radio"]:checked').val(); // Отправляем в аякс выбранный тип учредителей
		var comp_d_is = $('.o4 input[type="radio"]:checked').val();	// Отправляем в аякс выбранный тип директоров
		
		$.ajax({
			type: 'POST',
			url: '/ajax/',
			data: {'country':$('select[name="country"] option:selected').val(), 'comp_i':comp_i_is, 'comp_d':comp_d_is},
			success: function(msg)
			{
				$('<div class="cost" style="display:none;">'+msg+'</div>').insertAfter($('.o8 h2')); // Генерим div.cost и вставляем в него ответ от аякса
				$('.price_1').html($('.price_2').html()); // Вставляем в .price1 часть суммы
			}
		});
	}
	
	// Вопрос №6 "Бенефициары"
    $('.o6 .btn-next').click(function(){
        $('.o6 .gr').each(function(){
            if($(this).find('input').val() == ''){
                $(this).find('input').parent().parent().addClass('error');
            }
            else if($(this).find('input[name="fio-dov-b"]').val() != '' && $(this).find('input[name="passport-b"]').val() != ''){
				goAjax();
				$('.o6').hide();
				$('.o8').show();
            }
        });
    });

	
	// Вопрос №7 "Акции"
    $('.o7 .btn-next').click(function(){

        if($('#akc-im').attr('checked') || $('#akc-pred').attr('checked')){
			goAjax();
			$('.o7').hide();
			$('.o8').show();
        }
        else {
            $('#akc-im, #akc-pred').parent().addClass('error');
        }
    });

    /* Show/Hide input hints */
    $('input[type="text"]').focus(function(){
        if($(this).val() == 'Поиск' || $(this).val() == 'Search' || $(this).val() == 'Например: юриспруденция, морское право' || $(this).val() == 'For example: law, maritime law'){
            $(this).attr('rel', $(this).val()).val('');
            $(this).next().css({'backgroundPosition':'0 -26px'});
        }
    });
    $('input[type="text"]').blur(function(){
        if($(this).val() == ''){
            $(this).val($(this).attr('rel'));
            $(this).next().css({'backgroundPosition':'0 0'});
        }
    });

    $('.i_block input').focus(function(){
        $(this).parent().css({'backgroundPosition':'0 -26px'});
        $(this).prev().prev().css({'backgroundPosition':'0 -26px'});
        $(this).prev().css({'backgroundPosition':'-12px -26px'});
    });
    $('.i_block input').blur(function(){
        $(this).parent().css({'backgroundPosition':'0 0'});
        $(this).prev().prev().css({'backgroundPosition':'0 0'});
        $(this).prev().css({'backgroundPosition':'-12px 0'});
    });

    /* Clear Form */
    $('.clear-f').click(function(){
        $(this).parent().parent().find('input[type="text"], textarea').val('');
    });

    /* Close Form */
    $('.pop .close').click(function(){
        $('.popups').hide().find('.pop').hide();
    });

    /* Big Menu Actions */
    $('.bmw .bb').hover(
        function(){
            if($(this).hasClass('closed')){
                $(this).removeClass('closed').addClass('opened');
                $(this).siblings('.bb').removeClass('opened').addClass('closed');
            }
        },
        function(){
		/*
            if($(this).hasClass('opened')){
                $(this).removeClass('opened').addClass('closed');
                $(this).siblings('.bb').removeClass('opened').addClass('closed');
            }
		*/
        }
    );
	
	$('.bmw .sum').hover(
		function(){},
		function(){
			if($(this).parent().parent().hasClass('opened')){
				$(this).parent().parent().removeClass('opened').addClass('closed');
                $(this).parent().parent().siblings('.bb').removeClass('opened').addClass('closed');
			}
		}
		
	);
	
    /* Left Big Menu Actions */
    $('.sb .bb .bt').click(function(){
        if($(this).parent().parent().hasClass('closed')){
            $(this).parent().parent().removeClass('closed').addClass('opened');
            $(this).parent().parent().siblings().removeClass('opened').addClass('closed');
        }
        else if($(this).parent().parent().hasClass('opened')){
            $(this).parent().parent().removeClass('opened').addClass('closed');
        }
    });

    /* Tabs Actions */
    if($('.tabs').children().hasClass('tw')){
        for(var i=0; i<$('.tw li').length; i++){
            $('.tw li').eq(i).addClass('tab_'+i+'');
        }
        for(var j=0; j<$('.tc > ul > li').length; j++){
            $('.tc > ul > li').eq(j).addClass('tab_'+j+'');
        }
        $('.tc li.'+$('.tw li.active').attr('class').replace('active ','')+'').show();

        $('.tt li').click(function(){
            $(this).addClass('active').siblings().removeClass('active');
            $('.tc > ul > li.'+$(this).attr('class').replace(' active','')+'').show().siblings().hide();
        });
    }
    
    /* FAQ Actions */
    $('.tc-w h2').click(function(){
        if($(this).parent().hasClass('closed')){
            $(this).parent().removeClass('closed').addClass('opened').siblings().removeClass('opened').addClass('closed');
			if($.browser.msie && $.browser.version == '8.0'){$("#content").css({'paddingBottom':550+'px'});}
			
			
        }
        else if($(this).parent().hasClass('opened')){
            $(this).parent().removeClass('opened').addClass('closed');
        }
    });
	
	$('.collapse').click(function(){
		$(this).parent().parent().removeClass('opened').addClass('closed');
	});
	
    /* Styling X Block */
    if(((($('.data').height()-$('.sidebar').height())-$('.xb').height())/2) > 0 ){
//        $('.xb').css({'marginTop':((($('.data').height()-$('.sidebar').height())-$('.xb').height())/2)+'px'});
    }
    else{return false;}

    /* Prices Table Info Actions */
    $('.info').hover(
        function(){
            $(this).css({'zIndex':50}).parent().css({'zIndex':50}).parent().css({'zIndex':50});
            $(this).find('.ip').show();
        },
        function(){
			$(this).css({'zIndex':0}).parent().css({'zIndex':0}).parent().css({'zIndex':0});
            $(this).find('.ip').hide();
        }
    );
    /* Подсвечиваем маркер активного пункта меню при загрузке страницы 
    var llEl = $('.ll');
    if(llEl[0]){
        var actEl = llEl.find('li.active').attr('class').replace('active ','').replace('loc','m');
        $('.loc-markers .'+actEl+'').addClass('active');
    }
	*/
	
	/*$('.tabs').css({'height':$(".tabs .tc ul li:first").height()+500+'px'});*/

/* Hover effect on page of special offers */
    $('.spec').children().hover(
        function(){
            $(this).find('a').css({'text-decoration':'none'});
            $(this).siblings().find('a').css({'text-decoration':'none'});
        },
        function(){
            $(this).find('a').css({'text-decoration':'underline'});
            $(this).siblings().find('a').css({'text-decoration':'underline'});
        }
    );
});


function load_phone_number()
{
	$.ajax({
	   type: "POST",
	   url: "/load_phone_number_ajax.php",
	   success: function(msg)
	   {
		if (msg!='')
		{
			var p_block = $('#ulp-14');
			if (p_block.length)
			{
				p_block.html(msg);
			}
			var p_block = $('#ulc-55');
			if (p_block.length)
			{
				p_block.html(msg);
			}
			var p_block = $('#ulc-84');
			if (p_block.length)
			{
				p_block.html(msg);
			}
		}
	   }
	});
} // load_phone_number
