$(document).ready(function() {

        $(".act .choose-act:first-child").live("click",function() {
            $(".popup").hide();
            $(this).parent().find(".popup").show();
            return false;
        });

        $(".act .popup .close").live("click",function()  {
            $(this).parent().prev().show();
            $(this).parent().hide();
            return false;
        });

	$('#designers_perspective_toggle').click(function() {
	    
	    $(this).parent().parent().find('li.select').find('div').remove();
	    $(this).parent().parent().find('li').removeClass('select');
	    $(this).parent().addClass('select');
	    $(this).parent().append('<div class="corner tl"><div></div></div><div class="corner tr"><div></div></div><div class="corner bl"><div></div></div><div class="corner br"><div></div></div>');
	    
		$('#designers_best').fadeOut(300,function() {
			$('#designers_perspective').fadeIn(300);
		});
		
            return false;
	});	
	
	$('#designers_best_toggle').click(function() {
		
	    $(this).parent().parent().find('li.select').find('div').remove();
	    $(this).parent().parent().find('li').removeClass('select');
	    $(this).parent().addClass('select');
	    $(this).parent().append('<div class="corner tl"><div></div></div><div class="corner tr"><div></div></div><div class="corner bl"><div></div></div><div class="corner br"><div></div></div>');
	    
		$('#designers_perspective').fadeOut(300,function() {
			$('#designers_best').fadeIn(300);
		});
        
            return false;
	});	
       

        //$.facebooklist('#tags', '#preadded', '#facebook-auto',{url:'/forum/tags/ajaxsuggest/',cache:1,  newel: true}, 10, {userfilter:1,casesensetive:0});


        $('#tags').fcbkcomplete({
                json_url: "/forum/tags/ajaxsuggest/",
                json_cache: true,
                filter_case: true,
                filter_hide: true,
                newel: true,
                complete_text: "Введите теги, к которым Вы хотите привязать пост"
        });


	// Форум
	$('a.theme_select').live('click', function() {	

		var theme = $(this).attr('id').split('_')[1];

		if (theme == 'main') {
			Settings.setFilter('theme','');			
		} else {	
			Settings.setFilter('theme',theme);							
		} 
		
                $('li.ico a').attr('href','/forum/add_post/?theme='+theme);
        
		ShowLoaderForum(false);
		Switch(this);

		return false;
	});
	
	
	
	// Видео рубрикатор

	$('a.video_rubrica_select').live('click', function() {	

		var rubrica = $(this).attr('id').split('_')[1];

		if (rubrica == 'main') {
			Settings.setFilter('theme','');			
		} else {	
			Settings.setFilter('theme', rubrica);							
		} 
		
                //$('li.ico a').attr('href','/forum/add_post/?theme='+rubrica)
        
		ShowLoaderForum(false);
		Switch(this);

		return false;
	});
    
    
 	// Рубрикатор статей

	$('a.article_rubrica_select').live('click', function() {	

		var rubrica = $(this).attr('id').split('_')[1];

		if (rubrica == 'main') {
			Settings.setFilter('theme','');			
		} else {	
			Settings.setFilter('theme',rubrica);							
		} 
		
                //$('li.ico a').attr('href','/forum/add_post/?theme='+theme)
        
		ShowLoaderForum(false);
		Switch(this);
                
		return false;
	});   
    
    
        /////////////////////////////////////////////////////////////////////////////////////////


        // Изменение полей тема и текст сообщения
        // Если они не пустые, то форму можно отправить и активировать кнопку отправки

        var post_theme = '';
        var post_text = '';


        function check_post() {
            post_theme = $('#theme').val();
            post_text = $('textarea.text_editor_post').val();

            //console.log(post_theme, post_text);


            if (post_theme.trim() != '' && post_text.trim() != '') {
                $('#post_submit').removeAttr('disabled');
            } else {
                $('#post_submit').attr('disabled', true);
            }

        }


        $('#theme').keyup(function() {
            //post_theme = $('#theme').val();
            check_post();
        });
    
    
  

       $('textarea.text_editor_post').wysiwyg({
           change: function(event) {
                if (event.type == 'keyup') {
                    //post_text = $('textarea.text_editor_post').val();
                    check_post();
                }
           }
        });
    
    
        $('#post_cancel').live('click', function() {
            if (theme == 0 ) {
                window.location = '/forum/';
            } else {
                window.location = '/forum/blog/'+theme+'/';
            }

            return false;
        });
    
    
        // Форма добавления сообщения
        // TODO Нет вывода возможных ошибок
        var add_form_options = {
            beforeSubmit:   add_form_beforeSubmit,
            success:        add_form_success,
            error:          add_form_error,
            dataType:       'json'
        };


        // bind form using 'ajaxForm'
        $('#add_post').ajaxForm(add_form_options);


	// pre-submit callback 
	function add_form_beforeSubmit(formData, jqForm, options) { 	
		$('div.submit input').attr("disabled", true);	
		$('#login_error').slideUp(100);
                $('#post_submit').attr('disabled', true);
        
	    return true; 
	} 
	 
	// post-submit callback 
	function add_form_success(response, statusText)  { 
            $('#post_submit').removeAttr('disabled');
    
	    if (response.error == 0) {
                window.location = response.redirect;
            }
	
	}

        function add_form_error(XMLHttpRequest, textStatus, errorThrown) {
            $('div.submit input').removeAttr('disabled');
            $('#post_submit').removeAttr('disabled');
        }


        /////////////////////////////////////////////////////////////////////////////////////////

        // Личное сообщение
        // Изменение полей тема и текст сообщения
        // Если они не пустые, то форму можно отправить и активировать кнопку отправки
        function pm_check_post() {
            post_theme = $('#pm_theme').val();
            post_text = $('textarea.text_editor_pm').val();

            if (post_theme.trim() != '' && post_text.trim() != '') {
                $('#post_submit').removeAttr('disabled');
            } else {
                $('#post_submit').attr('disabled', true);

            }

            if (post_theme.trim() != '') {
                $('#pm_theme').css("color", "black");
            } else {
                $('#pm_theme').css("color", "#B8C0C4");
            }
        }

        $('#pm_theme').keyup(function() {
            post_theme = $('#pm_theme').val();
            pm_check_post();
        })


        $('#pm_wysiwyg').wysiwyg({
            change: function(event) {
                if (event.type == 'keyup') {
                    post_text = $('textarea.text_editor_pm').val();
                    pm_check_post();
                }
            }
        });


        // Форма добавления личного сообщения

        var add_formpm_options = {
            beforeSubmit:   add_formpm_beforeSubmit,
            success:        add_formpm_success,
            dataType:       'json'
        };


        // bind form using 'ajaxForm'
        $('#add_pm').ajaxForm(add_formpm_options);


	// pre-submit callback 
	function add_formpm_beforeSubmit(formData, jqForm, options) { 	
		$('div.submit input').attr("disabled", true);	
		$('#login_error').slideUp(100);
                $('#post_submit').attr('disabled', true);
                $('#pm_theme').css("color", "#B8C0C4");
        
                return true;
	} 
	 
	// post-submit callback 
	function add_formpm_success(response, statusText)  { 
                $('#post_submit').removeAttr('disabled');
    
                if (response.error == 0) {
                    window.location = response.redirect;
                }
	
	}   
    
    
    
        /////////////////////////////////////////////////////////////////////////////////////////
    
	// Интерьеры, количетсво комнат
	$('ul.room_select a').live('click', function() {			
		var room = $(this).attr('id').split('_')[1];
		
		if (room == 0) {
			Settings.setFilter('room') = '';
		} else {
			Settings.setFilter('room') = room;
		}
		
		ShowLoaderForum(false);
		Switch(this);

		return false;
	});
    

	// Интерьеры, уровень пользователя
	$('ul.userlevel_select a').live('click', function() {
		var level = $(this).attr('id').split('_')[1];

		if (level == 'any') {
			Settings.setFilter('userlevel','');
		} else {
			Settings.setFilter('userlevel', level);
		}
                
		ShowLoaderForum(false);
		Switch(this);

		return false;
	});

    
	// Интерьеры, уровень пользователя
	$('ul.intmain_select a').live('click', function() {
		var level = $(this).attr('id').split('_')[1];

                if (level == 'photo' || level == '3dprojects') {
                    $("#top_filter").show();
                    $("#pright").show();
                    $("div.pager").show();

                    if (level == 'photo') {
                        $('#left_tags_2d').show();
                        $('#left_tags_3d').hide();
                    }

                    if (level == '3dprojects') {
                        $('#left_tags_2d').hide();
                        $('#left_tags_3d').show();
                    }

                } else if (level == 'plans') {
                    $("div.pager").show();
                }   else {
                    $("#top_filter").hide();
                    $("#pright").hide();
                    $("div.pager").hide();
                }

		if (level == '3dinteriers') {
			Settings.setFilter('intmain','');
		} else {
			Settings.setFilter('intmain', level);
		}

		ShowLoaderForum(false);
		Switch(this);

		return false;
	});

	
	$('li.sort ul li:not(.name):not(.select)').live('click',function() {	
		Settings.sort = $(this).attr('id');
	
		var text = $(this).text(); 
		$(this).parent().find('li:not(.name)').not($(this)).wrapInner('<span></span>').removeClass('select');			
		$(this).addClass('select').find('span').remove();
		$(this).html(text+'<span></span>');
		
		ShowLoaderForum(false);

		return false;
	});
	
        //var lastids = '';
    
	// Интерьер, серии домов 
	$("div.filter:not(div.no_ajax) a.more").live('click',function() {
                /*
                var ids = new Array();

                $('#list_houses_popup input[type=checkbox]:checked').each(function() {
                    ids.push($(this).val())
                })

                lastids = ids.join(',');
                */
       
		$("div.overlay").show(); 
		$("#window_more").show();
		 
		Switch(this);

		return false;
	});
	
	$("div.filter:not(div.no_ajax) ul.series a:not(.more)").live('click',function() {
                Settings.setFilter('houses','');
                ShowLoaderForum(false)
                Switch(this);

                return false;
	});
	
	//$('item-tags').live('click', function() {
	//})
	

	fillHouses(false);
	
	// Реакция на выбор этажа
	$('#house_floor_selector a').live('click',function() { 
		$('#list_houses_popup').html('<ul></ul><ul></ul><ul></ul>');
		
		$(this).parent().parent().find('li').removeClass('select');
		
		$(this).parent().addClass('select');
		
		var floors = $(this).attr('id').split('_')[1];
		
		if (floors == 'any') {
			fillHouses(false);
		}
		else {
			fillHouses(floors);
		}
			 
	});
	
	
	// Рейтинги интерьеров
	
	$('li.rating a').live('click', function() {
	
		var id = $(this).attr('id').split('_')[1];
		var type = $(this).attr('id').split('_')[0];
            /*
                scores = Vote.objects.get_score(p)

                if scores['num_votes'] != 0 :
                    normalized = scores['num_votes'] + scores['score']

                    import math
                    total = int(math.ceil(normalized / (scores['num_votes'] * 2) * 5))
                else:
                    total = 3


                    {"score": {"score": 1, "num_votes": 1}, "success": true}


                    $.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
                        alert("JSON Data: " + json.users[3].name);
                    });





            */
                $.post('/interier/'+id+'/'+type, {}, function(json) {
                    if ( json.success ) {
                        if ( json.score.num_votes != 0 ) {
                            stars = (json.score.num_votes + json.score.score) / (json.score.num_votes * 2) * 5;
                            stars = Math.ceil( stars );
                        } else {
                            stars = 3;
                        }

                        $('ul.interier_menu li.rating').html('<div class="rate level-'+stars+'" title="'+stars+'">'+stars+'</div><span class="number">'+json.score.num_votes+'</span>');
                    }
                }, "json");
		
		
		return false;
	});



        // Фильтр по имени
        $(".panel .search .text").keyup(function() {
                if ($(this).val() != '') {
                    $(".exit").show();
                } else {
                    $(".exit").hide();
                }
                clearTimeout(Settings.timer);

                //Settings.string_filter = $(this).val()
                Settings.setStringFilter($(this).val());

                Settings.timer = setTimeout("Settings.stringFilter();", 500);

        });

        // Отключение фильтра по имени
        $(".panel .search .exit").click(function() {
                $(this).hide();
                $('#text_filter').val('');
                $('input.text').val('');

                //Settings.string_filter = '';
                Settings.setStringFilter('');
                ShowLoaderForum(false);
        });


        // Выбор класса пользователей
        $('ul.user_level_select a').live('click', function() {

                var level = $(this).attr('id').split('_')[1];

                if (level == 'any') {
                            Settings.setFilter('level', '');
                } else {
                    Settings.setFilter('level',level);
                }

                ShowLoaderForum(false);
                Switch(this);

                return false;
        });
    
    
    
        // Выбор типа домов - фильт интерьеров
        $('#house_select').live('click', function() {
                $(".overlay").hide();
                $('#window_more').hide();

                var ids = new Array();

                $('#list_houses_popup input[type=checkbox]:checked').each(function() {
                    ids.push($(this).val())
                })

                Settings.setFilter('houses', ids.join(','));
                ShowLoaderForum(false);

                return false;
        });


        $(".close").not('#add_file_panel_close').click(function() {
                $(this).parent().hide();
                $(".overlay").hide();
                if (typeof(Settings.filter['houses']) == 'undefined' || Settings.filter['houses'] == '') {
                   Switch($('#series_all'));
                } else {

                }
        });
    
    
        $('#list_houses_popup input[type=checkbox]').live('change', function() {
            var one_checked = false;

            $('#list_houses_popup input[type=checkbox]:checked').each(function() {
                one_checked = true;
            });

            if (one_checked) {
                $('#house_select').removeAttr('disabled');
            } else {
                $('#house_select').attr('disabled', true);
            }

        });
    
    
        // буквы на странице дизайнеров
        $('#letter_pager a').live('click', function() {

            var txt = $(this).parent().parent().parent().find('li.select span').html();
            $(this).parent().parent().parent().find('li.select').html('<a href="#">'+txt+'</a>');

            $(this).parent().parent().parent().find('li.select').removeClass('select').find('div').remove();
                $(this).parent().addClass('select');

            var txt = $(this).html();
            $(this).parent().html('<span>'+txt+'</span><div class="corner tl"><div></div></div><div class="corner tr"><div></div></div><div class="corner bl"><div></div></div><div class="corner br"><div></div></div>');

            Settings.pager = false;
            Settings.setFilter('starts', txt);
            ShowLoaderForum(false);

            return false;
        });
    
   
        if (typeof(goLeft) != 'undefined') {
        //    $(document).bind('keydown', 'Ctrl+left', goLeft);
        }

        if (typeof(goRight) != 'undefined') {
        //   $(document).bind('keydown', 'Ctrl+right', goRight);
        }

        $('div.pager a').live('click', function() {
            Settings.page = $(this).attr('id').split('_')[1];
            ShowLoaderForum(false);
            
            return false;
        });
    
    
        //----------------------------------------------------------------------------------------------

        // Личные сообщения
    
        $('#pm_area').wysiwyg({
           change: function(event){
            /*
            if (event.type == 'keyup') {
                post_text = $('textarea.text_editor_post').val();
                check_post();
            }
            */

            }
        });
    
    
        $('#delete_pm').live('click', function() {
            var answer=confirm("Вы уверены?");
            if (answer) {
                var ids = new Array();

                $('div.content li input[type=checkbox]:checked').each(function() {
                    ids.push( $(this).attr('id').split('_')[1] );
                })

                $.post('/designers/profile/delete_pm/', { 'ids' : ids.join(',') }, function() {
                    window.location.reload();
                })
            }

            return false;
        });


        $('#read_pm').live('click', function() {

            var ids = new Array();

            $('div.content li input[type=checkbox]:checked').each(function() {
                ids.push( $(this).attr('id').split('_')[1] );
                $(this).parent().removeClass('select');
            })

            $.post('/designers/profile/read_pm/', { 'ids' : ids.join(',') });

            return false;
        });
    

    
        $('#adv-top').flash({
            swf: '/media/banners/apartama_3d_redaktor_no_date.swf',
            height: 90,
            width: '100%',
            params : { wmode : 'transparent' }
        });

        $('#adv-right').flash({
              swf: '/media/banners/apartama_plan_200x300_v5.swf',
              width: 200,
              height: 300,
              params : { wmode : 'transparent' }
        });

        $('#middle').flash({
              swf: '/media/banners/banner.swf',
              width: 750,
              height: 261,
              params : { wmode : 'transparent' }
        });


        $('#adv-right2').flash({
              swf: '/media/swf/banner_with_link.swf',
              width: 200,
              height: 120,
              params : { wmode : 'transparent' }
        });

	
        $('#left_tags_2d a, #left_tags_3d a').click(function() {
                if ($(this).parent().hasClass('select')) {
                        $(this).parent().removeClass('select').find('span').remove();
                        Settings.setFilter('tag',"");
                } else {
                        $(this).parent().parent().find('li').removeClass('select').find('span').remove();
                        $(this).append('<span class="corner tl"><span></span></span><span class="corner tr"><span></span></span><span class="corner bl"><span></span></span><span class="corner br"><span></span></span>');
                        $(this).parent().addClass('select');
                        Settings.setFilter('tag', $(this).text());
                }

                ShowLoaderForum(false);

                return false;
        });
	
   //$('#main_menu li').corner();

}) // end document ready    




    
function popup(url) {
     params  = 'width='+screen.width;
     params += ', height='+screen.height;
     params += ', top=0, left=0';
     params += ', fullscreen=no';

     newwin=window.open(url,'mywin', params);
     if (window.focus) {
         newwin.focus();
     }
     
     return false;
}

function tpopup(url) {
     params = '';

     newwin=window.open(url,'mywin', params);
     if (window.focus) {
         newwin.focus();
     }

     return false;
}
