$(document).ready(function()  {

    $('#main_block').fadeIn(1000, function() {setTimeout("slide_hide()", 5000)});
    $('#second_menu').children('a').hide();
    
    $('a.text_pad').click(function() {
        //$('#content').html(limg());

        id = '[cat_id=' + $(this).attr('parent_id') + ']';
        
        cat = $(this).attr('cat_id') || $(this).attr('parent_id');
        par = $(this).attr('parent_id');
        
        if(cat != 1 && cat != 2 && cat != 3 && cat != 25) {
            if( $(this).attr('use') == 1) {
                bg.set( c.random() );
                
            	$('#text_block').hide()
            	$('#big_block').fadeIn(300);
            	title = typeof( $(this).attr('parent_id') ) != 'undefined' ? $(id).html() + ' > ' + $(this).html() : $(this).html();
        		$('#cat_title').html( title );
            	$.getJSON($(this).attr('href'), function(json) { gal.update(json);$('#content').empty(); } )
            }
        }
        else {
            if (cat != 1 || typeof(par) != 'undefined')
                bg.set( c.random() );
            
            $('#big_block').hide();
            $('#text_block').hide().load($(this).attr('href'), function() {
                if ( (cat == 1 || cat == 25) && typeof(par) == 'undefined')
                    $('#text_inner').css('width', '650px');
                else
                    $('#text_inner').css('width', '400px');
                
                $(this).fadeIn(200)
            });
        }
        return false;
    }).filter("a[cat_id]").mouseover(function() {
        $('#second_menu').children('a br').hide();
        $('#second_menu').css('top', ( $(this).attr('pos')*13 ) ).children('a[parent_id='+ $(this).attr('cat_id') +']').show().after('<br>');
    })
    
    $.ajaxSetup({
        beforeSend: function() { $('#content').html( limg() )  },
        success: function() { $('#content').empty();  }
    });
    
    $('#big_pic').click( function() {
        show_image( this )
    }).mouseover( function() {
        ide = 300;
        
        h = ( ide - $('#img_descr').height() - 10 );
        $('#img_descr').show().css({ 'top': h} );
        //alert( $('#img_descr').html() )
    }).mouseout( function() {
        $('#img_descr').hide();
    })
    
    $('#img_descr').mouseover(function() {
        return false;
    });
});

function cload(href) {
    $('#text_block').fadeOut(200).load(href, function() {
        $('#text_inner').css('width', '400px');
        $(this).fadeIn(200)
    });
}
var gal = {
    update: function(s) {
        $('#pictures').empty()//.hide();
        n=0;i=0;dv='';
        for(i in s) {
            src = s[i].image;
            descr = s[i].description;
            title = s[i].title;
            
            el = $('<img>').attr( {'title': title, 'descr': descr, 'height': 100, 'width': 100} );
            el.attr({'src': 'media/upload/'+src});
            el.addClass('pic');
            
            $(el).click(
                function() {
                    gal.insert_image(this);
                }
            );
            
            if(n == 0) {
                dv = $('<div style="height:200px;width:120px;float:left;"></div>');
                dv.html(el);
            }
            else
                dv.append(el);
            
            if(i == 0)
                gal.insert_image(el);
            
            if(n == 1)
                $('#pictures').append(dv);
            
            n = (n == 0) ? 1 : 0;
            i++;
        }
        if(n == 1){
            dv = $('<div style="height:200px;width:120px;float:left;"></div>');
            dv.html(el);
            $('#pictures').append(dv);
        }
        if(i == 0) {
            $('#big_pic').css('background', '').attr('src', '').html('<h1 style="padding-top:275px;font-size:13px;text-align:center;">Раздел в стадии разработки.</h1>')//.unbind();
        }
        
        this.handlers()
        
        $('#pictures').fadeIn(400);
    },
    handlers: function() {
        num_photos = $(slides.inner_id + ' img').size()
        w = ( slides.imw *num_photos) /2 + 200;
        $(slides.inner_id).width(w).css('left', 0);
        
        $('#l_arrow').unbind().mousedown( function() { slides.move_left()})
        $('#r_arrow').unbind().mousedown( function() { slides.move_right()})
    },
    insert_image: function(el) {
        titl = $(el).attr('title');
        dsc = $(el).attr('descr');
        sr = $(el).attr('src');
        
        $('#img_descr').remove();
        $('#big_pic').empty().hide().attr('src', sr).css('background', 'url('+ sr +') top center no-repeat').fadeIn();
        if(typeof(titl) != 'undefined') {
            if(typeof(dsc) === 'undefined')
                dsc = '';
            
            dscr = '<div id="img_descr"><h2>'+ titl +'</h2>'+ dsc +'</div>';
            $('#big_pic').append(dscr);
        }
    }
}
var slides = {
	imw: 120,
	default_scroll: 2,
    inner_id: '#pictures',
	/* Прокрутка вправо */
	move_right: function() {
		this.do_move('left');
	},
	/* Прокрутка влево */
	move_left: function() {
		this.do_move('right');
	},
	do_move: function(dir, sc) {
		curr_left = parseInt( $(this.inner_id).css('left'), 10);
		num_slides = $(this.inner_id).children('div').size();
        
		if(dir == 'left')
			scrol = -(slides.imw*slides.default_scroll);
		else
			scrol = slides.imw*slides.default_scroll;
            
		left = curr_left + scrol;
        end = -(num_slides*this.imw)
        /* Если в начале или конце слайдов */
            if(left > 0 || left < end)
                return false;
        //alert(left)
		$(this.inner_id).animate( {'left': left}, {'easing': 'easeout', 'duration': 400} );
	}
}
var bg = {
    id: '#bg_block',
    
    set: function(bg) {
        bg = 'bg/' + bg;
        $(this.id).css('background', 'url('+ bg +')'+ ' no-repeat')
    },
    del: function() {
        $(this.id).css('background', '')
    }
}
function show_image(el) {
    if($(el).attr('src') == '' || typeof($(el).attr('src')) == 'undefined')
        return false;
    grey();
    left = $(window).width() / 2 - 200;
    gr = $('#greyDiv');
    d = $('#shown_image');
    
    im = $('<img src="'+ $(el).attr('src') +'">');
    d.css( {'left': left, 'top': 20} )
    
    clos = $('<div id="close_div">x&nbsp</div>').css('opacity', '0.9').click( function() { $('#shown_image').add('#greyDiv').hide().empty() } );
    d.append(clos).append(im).fadeIn();
}
function limg() {
    return '<img src="media/img/loading.gif" class="loading">';
}

function grey() {
	gr = $('#greyDiv');
	w = $(document).width()+'px';
	h = $(document).height()+'px';
	
	gr.css('opacity', 0);
	gr.css({width: w, height: h}).show();

	gr.fadeTo(100, 0.8);
}

// Array.random( range ) - Return a random element, optionally up to or from range
Array.prototype.random = function( r ) {
    var i = 0, l = this.length;
    if( !r ) { r = this.length; }
    else if( r > 0 ) { r = r % l; }
    else { i = r; r = l + r % l; }
    return this[ Math.floor( r * Math.random() - i ) ];
};

function slideshow() {
    t = 2000;
    $('.slide:first').next().fadeIn(t, function() {
        setTimeout("slide_hide()", 8000)
    });
}
function slide_hide() {
    t = 2000;
    $('.slide:first').fadeOut(t, function() {
        $(this).appendTo('#slideshow');
    }).next();
    setTimeout("slideshow()", 100)
}