$( function() {
    //menuLeft
    (function(){
        var	$menu = $('.menuLeft');
        var	$li = $('li', $menu);
        var h;
        $li.each(function(i){
            h = $(this).outerHeight();			
            $(this).stop().animate({ height: h });
        });
    })();

    if($( "#tabsblock").length > 0){
        $( "#tabsblock").tabs();    
    }

    setIndicator(1);
    loginLink(); // форма авторизации
    navigatorbutton(); // кнопка навигатора
    navmess(); // сообщения в шапку

    $(".onlybykva").keypress(function (e){ 
        var c = String.fromCharCode(e.which) // or e.keyCode
        rgxp = /[^~`=+_a-zA-Z@0-9!"№;%:?*()#$%\^&*]/;
        if (!rgxp.test(c)){
            return false;
        }
    });
    $(".onlybykvanum").keypress(function (e){ 
        var c = String.fromCharCode(e.which) // or e.keyCode
        rgxp = /[^~`=+_a-zA-Z@!";%:?*()#$%\^&*]/;
        if (!rgxp.test(c)){
            return false;
        }
    });
    
    //yandex search filter
    var
    	frameElement = $('#search_one_site');
    
    $('body').on('click', '.b-specification-item_type_date', function() {
    	$('.b-form-button__text').html('Применить');
    	$('.b-calendar__title').html('Выберите даты');
    });
    
    $('body').on('click', '.b-form-input__input', function() {
    	BX.calendar({node:this, field:this, form: '', bTime: false, bHideTime: false});
    });
    
    /* незаконченная функция запоминания дат при переключении вкладок на поиске
    $('body').on('change', '.b-form-input__input', function() {
    	if ( $(this).parents('.b-calendar__input').index() == 0 ) {
    		input1val = $(this).val();
    		alert('input1val = ' + input1val);
    	}
    	else if ( $(this).parents('.b-calendar__input').index() == 2 ) {
    		input2val = $(this).val();
    		alert('input2val =' + input2val);
    	}
    });
    
    $('body').on('click', '.b-pseudo-link_js_inited', function() {
    	$('.b-form-input__input').trigger('change');
    });
    */
    
    frameElement.load(function(){
    	$(this).contents().find('body').on('click', '.b-specification-item_type_date', function(event) {
  			$(this).contents().find('.b-form-button__text').html('Применить');
    		$(this).contents().find('.b-calendar__title').html('Выберите даты');
  		});
    	
    	var thisFrame = $(this);
  		$(this).contents().find('body').on('click', '.b-form-input__input', function(event) {
  			BX.calendar({node:this, field:this, form: '', bTime: false, bHideTime: false});
  			
  			var framePos = thisFrame.offset();
  			var currPos = $('.popup-window').parents('div').offset();
  			$('.popup-window').parents('div').css({ 'left': currPos.left+framePos.left, 'top': currPos.top+framePos.top });
  		});
	});
	
	$('.bhead_result_tabs__item a').click(function() {
		$('body').trigger('click');
		frameElement.contents().find('body').trigger('click');
	});
	
	//iframe auto resize
	var iframeNewWidth = $('.wrapper').width();
	var iframeNewHeight = $('.wrapper').height();
	frameElement.width(iframeNewWidth);
	frameElement.height(iframeNewHeight);
	$(window).resize(function() {
		iframeNewWidth = $('.wrapper').width();
		iframeNewHeight = $('.wrapper').height();
		frameElement.width(iframeNewWidth);
		frameElement.height(iframeNewHeight);
	});
	
});


var fields = [{'p':10,'f':['LOGIN','EMAIL','PERSONAL_PHONE','PERSONAL_GENDER']},
    {'p':10,'f':['LAST_NAME','NAME','SECOND_NAME','PERSONAL_BIRTHDAY']},
    {'p':10,'f':['UF_REGISTERED_ADDRES','PERSONAL_STREET']},
    {'p':20,'f':['UF_SERIES_PASSPORT','UF_PASSPORT_NUMBER','UF_DATE_ISSUE','UF_PLACE_ISSUE', 'UF_SUBDIVISION_CODE']},
    {'p':20,'f':['UF_SNILS']},
    {'p':10,'f':['UF_SERIES_ZPASSPORT','UF_ZPASSPORT_NUMBER','UF_ZPLACE_ISSUE','UF_ZDATE_ISSUE']},
    {'p':10,'f':['WORK_COMPANY','WORK_STREET','WORK_PHONE','WORK_POSITION']},
    {'p':10,'f':['UF_DRIVER_LICENSE']}];

function setIndicator(f){
    if (f) resetArray(); // first run - cache inputs
    var indicator = $('.profileInf');
    var iperc = $('dt span', indicator);
    var iline = $('.fillbar').find('div,span');
    var perc = 0;
    for (var i=0; i<fields.length; i++) {
        perc += countPerc(fields[i]);
    }
    iperc.text(perc+'%');
    iline.attr('class','p'+perc);
}
function resetArray(){
    for (var i=0; i<fields.length; i++) {
        for (var k=0; k<fields[i].f.length; k++) {
            var inp = $(':input[name="'+fields[i].f[k]+'"]');
            inp.bind('change', function(){setIndicator()});
            fields[i].f[k] = inp;
        }
    }
}
function countPerc(flds) {
    var p = flds.p;
    for (var k=0; k<flds.f.length; k++) {
        if (flds.f[k].val() == '') {
            p = 0;
            break;
        }
    }
    return p*1;
}




function loginLink() {
    var loginlink = $('#loginlink');
    var authform = $('#authform');
    authform.find('.rel').each(function(){
        var l = $(this).find('label');
        var i = $(this).find('input');
        i.focus(function(){
            l.hide();
        });
        i.blur(function(){
            var v = $.trim($(this).val());
            if (v == '') {
                $(this).val(v);
                l.show();
            }
        });
    });
    if (loginlink.length > 0 && authform.length > 0) {
        authform.slideUp(1);
        loginlink.toggle(function(){

            $('.paramList').hide();

            var authHeight=$(authform).height();
            $('BODY').trigger('resaiz_frame', [{param:'height',value:authHeight}]);

            authform.slideDown();
            return false;
            }, function(){

                $('.paramList').hide();

                authform.slideUp(function() {

                    var topPanelHeight=$('.topPanel').height();
                    $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight}]);

                });

                return false;
        });
    }
}

var navopener = false;
function navigatorbutton() {
    $('#navigatorbutton').click(function(){

        if($('BODY').hasClass('frame_block')){
            $('BODY').trigger('resaiz_frame_full', [0]);    
        }else{
            CreateNavBlock();  
        }
        return false;
    });
}

function CreateNavBlock(){
    if (navopener) return false;
    navopener = true;

    var ob = $('#navigatorbutton');
    var navHref=$(ob).attr('href');
    var button = $(ob);
    var navlayer = $('#navlayer');
    if (navlayer.length < 1) {
        navlayer = $('<div id="navlayer" class="navlayer"></div>');
        navlayer.appendTo('body');
        navlayer.dialog({
            minWidth: 1003,
            minHeight: 620,
            width: 1003,
            height: 'auto', 
            modal: true,
            resizable: true,
            draggable: false,
            dialogClass: 'navblock',
            position: ['center','top'],
            closeText: '',
            beforeClose: function(event, ui) {
                var topPanelHeight=$('.topPanel').height();
                topPanelHeight = topPanelHeight * 1;
                if(topPanelHeight <= 0 )
                    topPanelHeight = 45;
                console.log('NavBlock '+topPanelHeight);
                $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight}]);
            },
            open:function(event, ui){ 
                if (typeof window['post'] == 'function'){
                    post('parent_body_overflow_hidden',{}); 
                }
            },
            close:function(event, ui){ 
                if (typeof window['post'] == 'function'){
                    post('parent_body_overflow_auto',{}); 
                }
            }
        });

    } else {
        navlayer.dialog({position: ['center','top']}).dialog('open');

    }

    var navwindow = $('#navwindow');
    if (navwindow.length < 1) {
        navwindow = $('<iframe src="'+navHref+'" name="navwindow" id="navwindow" width="1003" height="620" scrolling="no" frameborder="0" marginwidth="0" marginheight="0"></iframe>');
        navlayer.html(navwindow);
        navwindow.load(function(){
            navopener = false;
        });
    } else {
        navopener = false;
    }
    var wh = $(window).height();
    if ( wh < 660 ) {
        var whn = wh - 50;
        navwindow.height(whn);
    } else {
        //console.log(wh, whn);
        navwindow.height(660);
    }
    var navbut  = navlayer.find('#navigatorbutton');
    // if (navbut.length < 1) {
    //     navlayer.append('<a href="#" class="navigator" id="navigatorbutton"><span>НАВИГАТОР</span></a>');
    //     navbut = navlayer.find('#navigatorbutton');
    // }
    navbut.click(function(){
        navlayer.dialog('close');
        return false;
    });
}

$( function() {
    var $bottomPanel = $('.bottomPanel');

    //
    (function(){			
        var $door = $('.door', $bottomPanel);

        $door.click( function(){	
            var $wrap = $(this).closest('dl');

            $(this).toggleClass('show');
            $wrap.find('> dd').slideToggle(500);
        });		
    })();

    //gallery	
    (function(){
        function gallery( $block, srtLine){

            var $next = $block.find('.next');
            var $prev = $block.find('.prev');
            var $view = $block.find('.lenta');

            var $blocks = $view.find('.block');


            var w = $blocks.outerWidth()+34;
            var size = 1;
            var line = srtLine;
            var step = w*size;

            var border;
            var cur = 0;

            $prev.hide();
            $view.css({ marginLeft:0 });

            if( $blocks.length <= srtLine ){
                $next.hide();
                $prev.hide();

            } else
                border = line*w-($blocks.length*w);


            // next
            $next.click(function(){
                cur -= step;

                if( cur == border ){
                    $next.hide();
                }

                $view.animate({ marginLeft: cur });

                $prev.show();
            });


            // prev
            $prev.click(function(){

                cur += step;

                if( cur == 0 ){
                    $prev.hide();
                }

                $view.animate({ marginLeft: cur });

                $next.show();
            });
        };

        var $lentaMoscow = $('._moscow', $bottomPanel);
        var $lentaRussia = $('._russia', $bottomPanel);

        gallery($lentaMoscow, 6);
        gallery($lentaRussia, 5);

        }());

    //autohide 
    (function(){

        var $hiders = $('._autohide');

        $hiders.each(function(i){

            var $hider = $hiders.eq(i);
            var $input = $('#'+$hider.attr('for'));

            $hider.click(function(){
                $hider.hide();
                $input.focus();
            });

            $input.focusin(function(){
                $hider.hide();
            });

            $input.focusout(function(){
                if(!$input.val()){
                    $hider.show();
                }
            });	
        });

    })();

    //searchBlock
    (function(){

        var $top = $('.topPanel');
        var $search = $('.searchBlock', $top);
        var $nav = $('.nav', $top);
        var $user = $('.userWrap, .authlink', $top);
        var $input = $('input[type=text]', $search);
        var $list = $('.moreParams .paramList', $search);


        /* $input.focus(function(){
        $search.toggleClass('show');
        $nav.toggle();
        $user.toggle();

        if(document.body.clientWidth <= '1210') {
        $list.addClass('right');
        }
        });*/

    })();

    //paramList
    (function(){

        var $top = $('.topPanel');
        var $search = $('.searchBlock', $top);
        var $door = $('.moreParams .door', $search);
        var $list = $('.moreParams .paramList', $search);
        var $li = $('li', $list);
        var $user = $('.userWrap', $top);



        $door.click(function(){
            $(this).parent().find('.paramList').toggle();

            if($('.paramList').css('display')=='block'){
                var topPanelHeight=$('.topPanel').height();
                var paramListHeight=$('.paramList').height()+40;
                $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight+paramListHeight}]);
            }else{
                var topPanelHeight=$('.topPanel').height();
                $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight}]);
            }

            $('#authform').slideUp();
        });

        $li.click(function(){

            if($("#form_search input[name=iss]")){
                $("#form_search input[name=iss]").val($(this).attr('rel'));
            }

            var txt = $(this).text();
            $list.hide();
            var ind = $(this).index();
            if( ind == 0 ){
                $(this).parent().parent().parent().find('.door span').html('по сайту');
            }
            else {
                $(this).parent().parent().parent().find('.door span').html(txt);
            }

            var topPanelHeight=$('.topPanel').height();
            $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight}]);
        });
    })();

    //backclose
    (function(){

        var $back = $('.backBlock');
        var $close = $('.close', $back);

        $close.click(function(){
            $.cookie('BITRIX_SM_hide_ref_block', 'Y', { path: '/', domain:'.'+document.domain});
            $back.fadeOut(500);
        });
    })();


});


function navmess() {
    var popmessages = $('.popmessages');
    $('#navmess').find('a').toggle(function(){
        popmessages.hide();
        $($(this).attr('href')).show();
        /*            
        * увеличиваем высоту фрейма
        */
        var topMessageHeight=$($(this).attr('href')).height();
        $('BODY').trigger('resaiz_frame', [{param:'height',value:topMessageHeight+70}]);


        return false;
        }, function(){
            popmessages.hide();

            /*            
            * отправляем запрос о том что сообщение прочитано
            */
            $.post("/api/informers_set_read.php", {type:$(this).attr('rel')});            

            /*            
            * Уменьшаем выосту фрейма до исходной
            */
            var topPanelHeight=$('.topPanel').height();
            $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight}]);
            return false;
    });
    popmessages.find('a').click(function(){
        popmessages.hide();

        /*            
        * отправляем запрос о том что сообщение прочитано
        */
        $.post("/api/informers_set_read.php", {type:$(this).closest('.popmessages').attr('rel')});            


        /*            
        * Уменьшаем выосту фрейма до исходной
        */
        var topPanelHeight=$('.topPanel').height();
        $('BODY').trigger('resaiz_frame', [{param:'height',value:topPanelHeight}]);
    });
}


function TrackHash(page_url, tabsonpage, current_url_w_hash) {
    if (document.location != current_url_w_hash) {
        var page_url = window.location.href.replace(window.location.hash,''); // full path leading up to hash;
        var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123
        tabsonpage.each(function(){
            var ind = $(this).find('div'+window.location.hash).index();
            if (ind) {
                $(this).tabs('select', window.location.hash);
            }
        });
    }
    var RunTabs = setTimeout(function(){
        TrackHash(page_url, tabsonpage, current_url_w_hash);
        }, 500);

    return false;
}
$(function(){
    var tabsonpage = $('.ui-tabs');
    if (tabsonpage.length > 0) {
        var page_url = window.location.href.replace(window.location.hash,''); // full path leading up to hash;
        var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123
        TrackHash(page_url, tabsonpage, current_url_w_hash);
    }
});

function declOfNum(number, titles)  
{  
    cases = [2, 0, 1, 1, 1, 2];  
    return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];  
}  