$(document).ready(function(){
    
    var sWidth;
    var sHeight;

    // устанавливаем вид списка карточек по умолчанию compact
    if ( !$.cookies.get("cardViewType") ) {
        $.cookies.set("cardViewType", 1); 
        $.cookies.set("descView", 1); 
        $.cookies.set("phoneView", 1);
        $.cookies.set("addrView", 1);
        $.cookies.set("profView", 1);
        $.cookies.set("secView", 1);
    }
    
    //alert($.cookies.get("cardViewType"));

    switch($.cookies.get("cardViewType"))
    {
        case "0": 
            $("#compactCardView").attr("checked", "checked"); 
        break;
        case "1": 
            $("#fullCardView").attr("checked", "checked"); 
        break;
        case "2": 
            $("#customCardView").attr("checked", "checked"); 
        break;
    }                                                  

    function popupMask(action) {
        switch(action) {
            case "show":
                $('.popupMask').height(document.documentElement.scrollHeight + 1).removeClass("hidden");                
            break;
            case "hide":
                $('.popupMask').addClass("hidden");
            break;
        }
    }

    // центруем модальное окно
    function setSubmodalPos(w, h) {
        if ($.browser.msie) {
            sTop = Math.round((document.documentElement.clientHeight - (h + 43)) / 2) + document.documentElement.scrollTop;
            sLeft = Math.round((document.documentElement.clientWidth - w) / 2) + document.documentElement.scrollLeft;
        }
        else {
            sTop = Math.round((innerHeight - (h + 43)) / 2) + pageYOffset;
            sLeft = Math.round((innerWidth - w) / 2) + pageXOffset;
        }
        $("#submodal").css({left: sLeft, top: sTop}).width(w);
        $("#submodal #popupFrame").height(h).width(w);
    }

    // скрываем верхний float-баннер
    $('.toggler a').click(function(e){
        e.preventDefault();
        $(this).parents('#banner').hide();
    });

    // анимация формы поиска на фокусе
    $(':text').bind("focus blur", function(){
        $(this).toggleClass('focused');
    });

    $('#searchForm :submit').bind("mouseover mouseout click", function(){
        $(this).toggleClass('search_submitInputHover');
    });

    // показываем popup с картой
    $('.toggle-map').click(function(e){
        e.preventDefault();
        var position = $(this).offset();
        var container = $('.mapContainer');
        popupMask("show");
        container.css({left: position.left + 5, top: position.top - container.height() - 15});
    });

    // скрываем popup'ы
    // клик на popupMask или closeDialogImg
    $('.popupMask, img.closeDialogImg').click(function(){
        popupMask("hide");
        if ( $("#submodal").is(":visible") ) {
            $("#submodal").addClass("hidden");
        }
        else if ( $(".mapContainer").is(":visible") ) {
        $('.mapContainer').removeClass("YMaps");
        $('.mapContainer').removeClass("YMaps-cursor-grab");
            $('.mapContainer').addClass("hidden");
        }
        else if ( $("#statPopup").is(":visible") ) {
            $("#statPopup").hide();
        }
    });


    // показываем/сворачиваем слайдбокс
    $('a.toggleSlideBox').click(toggleSlideBox);

    function toggleSlideBox(e){
        e.preventDefault();
        $this = $(this);
        cBox = $this.siblings('.slideBoxContent');
        width = $this.parent().width();

        if ($this.hasClass('collapsed')) {

            $this.find('.togglerIcon').animate({top: 0}, 300);

            cBox.find('.left').css({opacity: 0});
            cBox.slideDown('normal', function(){
                $(this).find('.left').css({display: 'none', opacity: 1}).each(function(i){
                    $(this).fadeIn('slow');
                });
            });
            $this.removeClass('collapsed').addClass('expanded');
            $this.children().attr({title: 'свернуть'});
        }
        else {
            if (cBox.parent().hasClass('.gallery')) {
                cBox.find('.left').animate({opacity: 0}, 'slow', 'linear', function(){
                    cBox.slideUp('normal');
                    $this.removeClass('expanded').addClass('collapsed').find('.togglerIcon').animate({top: -31}, 300);
                    $this.children().attr({title: 'развернуть'});
                });
            } 
            else {
                cBox.slideUp('normal');                
                $this.removeClass('expanded').addClass('collapsed').find('.togglerIcon').animate({top: -31}, 300);
                $this.children().attr({title: 'развернуть'});
            }
        }
    }


    $("#catalogueViewFilter :radio").click(function(){
        if($(this).val() == 0)top.location.href='index.php';
        if($(this).val() == 1)top.location.href='contemporary.php';
        else if($(this).val() == 2)top.location.href='aplhabet.php';
    });
    
    $(".customCardView :checkbox").click(function(){
        $('.' + $(this).attr("id")).toggleClass("hidden");
        if ( $(this).is(":checked") ) {
            $.cookies.set($(this).attr("id") + "View", 1);
        }
        else {
            $.cookies.set($(this).attr("id") + "View", 0);
        }
    });

    // подсказка к блокноту
    $("a.empty").click(function (e) {
        e.preventDefault();
    }).mouseover(function (e) {
        var offset = $(this).offset();
        $("#notepadPopupHelp").css({left: offset.left, top: 30}).show();
    }).mouseout(function () {
        $("#notepadPopupHelp").hide();
    });
    
    
    
    function profFilterForm(){
    // показываем модальное окно
    $("a[class^='submodal']").click(function (e) {
        e.preventDefault();
        params = this.className.split('-');
        if (params.length == 3){
            sWidth = parseInt(params[1]);
            sHeight = parseInt(params[2]);
        }

        setSubmodalPos(sWidth, sHeight);
        
        $("#submodal #popupFrame").attr("src", this.href);
        $("#submodal .t span").text(this.title);
        popupMask("show");
        $("#submodal").removeClass("hidden");//css({opacity: 0, display: "block", visibility: "visible"}).animate({opacity: 1}, 300, "linear");
    });

    // добавляев карточку в избранное
    $('img.add').click(function(){
        // само добавление в блокнот
        // ...
        note = $.cookies.get(this.id);
        if(note == this.id){
            $.cookies.set(this.id, null);
            cnt = $.cookies.get("cr_note_cnt") - 0;
            if(cnt>0){
                cnt = cnt - 1;
                $.cookies.set("cr_note_cnt", cnt);
            }
        }else{
            $.cookies.set(this.id, this.id);
            cnt = $.cookies.get("cr_note_cnt") - 0;
            cnt = cnt + 1;
            $.cookies.set("cr_note_cnt", cnt);
        }
        
        $(this).toggleClass('fav');
        if ( $(this).hasClass('fav') ) $(this).attr("title", "Удалить из избранного").attr('src', '/images/kill-from-fav.gif');
        else $(this).attr("title", "Добавить в избранное").attr('src', '/images/add-to-fav.gif');
        
        if(cnt){
            $("a.empty").unbind();
            $("a.notepad").removeClass("empty");
        }else{
            $("a.notepad").addClass("empty");
            // подсказка к блокноту
            $("a.empty").click(function (e) {
                e.preventDefault();
            }).mouseover(function (e) {
                var offset = $(this).offset();
                $("#notepadPopupHelp").css({left: offset.left, top: 30}).show();
            }).mouseout(function () {
                $("#notepadPopupHelp").hide();
            });
        }
    });

    // свроачиваем/разворачиваем карточку
    $(".expandCard").click(function(e){
        e.preventDefault();
        if ($.cookies.get("cardViewType") == 0) {
            $(this).parent().nextAll("p.addr, p.prof, p.sec").toggleClass("hidden");
        }
        else if ($.cookies.get("cardViewType") == 1) {
            $(this).parent().nextAll("p.addr, p.prof, p.sec").toggleClass("hidden");
        }
        $(this).toggleClass("collapse");
        $(this).hasClass('collapse') ? $(this).attr('title', 'Cвернуть карточку').attr('src', '/images/collapse-card.gif') : $(this).attr('title', 'Развернуть карточку').attr('src', '/images/expand-card.gif');
    });
    // фильтр выборки
    $("#profFilterForm :checkbox").click(function(){
        var str = "/catalog/search/search_content.php?";

        $('.popupMask').css({opacity: 0.5}).toggleClass('hidden');
        $('.popupMask').height(document.documentElement.scrollHeight);
        
        $("#profFilterForm :checked").each(function(n, element){
            str += $(element).attr("name") + "=1&";
        });

        $("#searchForm input[type!='submit']").each(function(n, element){
            if($(element).attr("name") != 'hs')
            str += $(element).attr("name") + "=" + $(element).val() + "&";
        });
        $.get(str, function(data){
            $("#s_results").html(data);
            $('.popupMask').toggleClass("hidden");
            profFilterForm();
        });

    });

    // выборочный вид карточек
    $("#cardViewFilter :radio").click(function(e){
        $(this).is(":not(#customCardView)") ? $(".customCardView").addClass("hidden") : $(".customCardView").toggleClass("hidden") ;

        if ( $(".customCardView").hasClass("hidden") ) {
        if ( $(this).is("#compactCardView") ) {

            $("h4 > img.expandCard").removeClass("hidden").removeClass("collapse").attr('title', 'Развернуть карточку').attr('src', '/images/expand-card.gif');

            $.cookies.set("cardViewType", $(this).attr("value"));
            $("ol li > p").removeClass("hidden").filter(".addr, .sec., .prof").addClass("hidden");
            $(".customCardView :checkbox").attr("checked", "").filter("#phone, #desc, #name, #site, #sec_expanded").attr("checked", "checked");

            $.cookies.set("descView", 1);
            $.cookies.set("phoneView", 1);
            $.cookies.set("addrView", 0);
            $.cookies.set("profView", 0);
            $.cookies.set("secView", 0);
        }
        else if ( $(this).is("#fullCardView") ) {

            $("h4 > img.expandCard").removeClass("hidden").addClass("collapse").attr('title', 'Cвернуть карточку').attr('src', '/images/collapse-card.gif');

            $.cookies.set("cardViewType", $(this).attr("value"));
            $("ol li > p").removeClass("hidden");
            $(".customCardView :checkbox").attr("checked", "checked");

            $.cookies.set("descView", 1);
            $.cookies.set("phoneView", 1);
            $.cookies.set("addrView", 1);
            $.cookies.set("profView", 1);
            $.cookies.set("secView", 1);
        }
        }
        else {
            var show = '';
            $(".customCardView input:checked").each(function(n, element){
                show += ' .' + $(element).attr("name") + ',';
            });
            $("ol li > p").addClass("hidden").filter(show).removeClass("hidden");

            $.cookies.set("cardViewType", $(this).attr("value"));
            $("h4 > img.expandCard").addClass("hidden");
        }
    });

    // sendmessage img hover
    $("img.sendm").hover(
        function () {
            $(this).attr("src", "/images/sendm-h.gif");
        },
        function () {
            $(this).attr("src", "/images/sendm.gif");
        }
    );
    };

    profFilterForm();

    // поведение выпадающего дива subselect и ссылки
    $(".subselectLink").click(function(e){
        e.preventDefault();
        if ($(this).prevAll().is(":hidden")) {
            $(this).prevAll().show();
            $(this).nextAll().hide();
            //$(this).nextAll().animate({opacity: 0}, 300).slideDown("normal").addClass("hidden");
        }
        else {
            //$(this).prevAll().fadeOut("slow");                
            $(this).prevAll().hide();
            $(this).nextAll().css({opacity: 0}).show().removeClass("hidden").animate({opacity: 1}, 300);
            //$(this).nextAll().slideDown("normal").css({opacity: 0}).removeClass("hidden").animate({opacity: 1}, 300);
        }
    });

    $(window).resize(function(){
        setSubmodalPos(sWidth, sHeight);
    });


    $(":radio[id^='opf']").click(function() {
    	if (this.id == 'opf-5') {
    		$("#opf-other").removeClass("disabled").addClass("enabled").attr("disabled", "");
    	}
    	else {
    		$("#opf-other").removeClass("enabled").addClass("disabled").attr("disabled", "disabled");
    	}
    });

    
    $("#statPopupLink").click(function(e) {
        e.preventDefault();
        var offset = $(this).offset();
        $("#statPopup").css({left: offset.left, top: offset.top - $("#statPopup").height() - $(this).height()}).show();
        popupMask("show");
    });

    $("#weekdays-break-from, #saturday-break-from, #sunday-break-from").click(function() {
        var stack = $(this).attr("id").split("-");
        var linkedObj = $(":input[name='" + stack[0] + "-" + stack[1] + "-till']");
//		alert("input[name='" + stack[0] + "-" + stack[1] + "-till']");

    	if ($(this).val() != "none") linkedObj.removeAttr("disabled");
    	else linkedObj.attr("disabled", "disabled");
    });

	$("#sat_chk, #sun_chk").click(function() {
		var cont = $(this).parent().parent();

		if ($(this).is(":checked")) {
//			alert('a');
			cont.children().addClass("enabled");
			cont.find(":input:not(.sbt)").removeAttr("disabled");
		}
		else {
//			alert('b');
			cont.children().removeClass("enabled");
			cont.find(":input:not(:checkbox)").attr("disabled", "disabled");
		}
	});

/*	$('#ul1').MultiFile({ 
		STRING: { 
			file: '<span title="Удалить" onclick="$(this).parent().prev().click()" style="cursor: pointer; //cursor: hand;">$file</span>', 
			remove: '<img src="/images/killFile.gif" alt="Удалить" style="float: left; padding-top: 1px; margin-right: 0.5em;"/>',
			selected: 'Выбран файл: $file',
			duplicate: 'Вы уже выбрали файл "$file"',
			denied:'Вы не можете загружать файлы $ext!\nК загрузке доступны файлы *.gif, *.jpg, *.png'
		}
	});

	$('#up1').MultiFile({ 
		STRING: { 
			file: '<span title="Удалить" onclick="$(this).parent().prev().click()" style="cursor: pointer; //cursor: hand;">$file</span>', 
			remove: '<img src="/images/killFile.gif" alt="Удалить" style="float: left; padding-top: 1px; margin-right: 0.5em;"/>',
			selected: 'Выбран файл: $file',
			duplicate: 'Вы уже выбрали файл "$file"',
			denied:'Вы не можете загружать файлы $ext!\nК загрузке доступны файлы *.gif, *.jpg, *.png'
		}
	});

	$('#uf1').MultiFile({ 
		STRING: { 
			file: '<span title="Удалить" onclick="$(this).parent().prev().click()" style="cursor: pointer; //cursor: hand;">$file</span>', 
			remove: '<img src="/images/killFile.gif" alt="Удалить" style="float: left; padding-top: 1px; margin-right: 0.5em;"/>',
			selected: 'Выбран файл: $file',
			duplicate: 'Вы уже выбрали файл "$file"',
			denied:'Вы не можете загружать файлы $ext!\nК загрузке доступны файлы *.doc, *.docx, *.xls, *.pdf, *.rar, *.zip'
		}
	});*/
});

$(document).keydown(function(event){
    if (window.event) event = window.event;
    if (event.ctrlKey)
    {
        var link = null;
        var href = null;
        switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
        {
            case 0x25:
                link = $("#PrevLink");
                break;
            case 0x27:
                link = $("#NextLink");
                break;
        }
        if (link && link.attr("href")) document.location = link.attr("href");
    }           
});
