function grayscale(src){
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                var imgObj = new Image();
                imgObj.src = src;
                canvas.width = imgObj.width;
                canvas.height = imgObj.height;
                ctx.drawImage(imgObj, 0, 0);
                var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
                for(var y = 0; y < imgPixels.height; y++){
                        for(var x = 0; x < imgPixels.width; x++){
                                var i = (y * 4) * imgPixels.width + x * 4;
                                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                                imgPixels.data[i] = avg;
                                imgPixels.data[i + 1] = avg;
                                imgPixels.data[i + 2] = avg;
                        }
                }
                ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
                return canvas.toDataURL();
    }

var prev_top_user_slide = 0;
function limiter(s){
    return s;
}




function unloading(elem){
	$(elem).children('.load').remove();
}

function loading(elem){
	unloading(elem);
	$(elem).prepend('<div class="load"><div class="loader"></div></div>');
	$(elem).children('.load').css({'width':$(elem).width(),'height':$(elem).height()}).children('.loader').css({'width':$(elem).width(),'height':$(elem).height()});
}

function setGray(elem){
		//if($(elem).width() || $(elem).parent().css('display')=='none'){
			var el = $(elem);
	        el.//css({"position":"absolute"}).
				wrap("<div class='img_wrapper'>").
				clone().
				addClass('img_grayscale').
				css({"position":"absolute","z-index":"1","opacity":"0"}).
				insertBefore(el).queue(function(){
	        		var el = $(el);
	        		el.parent().css({"width":$(elem).width(),"height":$(elem).height(),"opacity":"1"});
	        		el.dequeue();
	        	});
	  		if($.browser.msie)
	  			$(elem).css("filter","Gray()");
	  		else
				$(elem).attr('src',grayscale($(elem ).attr('src')));							
		//}
		//else
		//{
		//	setTimeout(function(){setGray(elem);},100);
		//}
}
	
function loadImg(img_gray, set_only){
	$(img_gray+set_only).each(function(){
		setGray($(this));
	});
	
	$('.img_grayscale').mouseout(function(){
		if(!$(this).closest('#gallery .small_gallery img').length)
     	$(this).stop().animate({opacity:0}, 1000);
    });
    
 	$(img_gray).mouseover(function(){
 		if(!$(this).closest('#gallery .small_gallery img').length)
    	$(this).parent().find('img:first').stop().animate({opacity:1}, 1000);
  	});
	
	
//	if(!loaded)
//		setTimeout(function(){loadImg(img_gray, set_only)},100);
//	else
//		makeGray(img_gray, set_only);
}


function makeGray(img_gray, set_only){

	$(img_gray+set_only).each(function(){
 		var el = $(this);
        el.css({"position":"absolute"}).
			wrap("<div class='img_wrapper'>").
			clone().
			addClass('img_grayscale').
			css({"position":"absolute","z-index":"1","opacity":"0"}).
			insertBefore(el).queue(function(){
        		var el = $(this);
        		el.parent().css({"width":this.width,"height":this.height,"opacity":"1"});
        		el.dequeue();
        	});
  		if($.browser.msie)
  			$(this).css("filter","Gray()");
  		else
			this.src = grayscale(this.src);
	});

 	$(img_gray).mouseover(function(){
 		if(!$(this).closest('#gallery .small_gallery img').length)
    	$(this).parent().find('img:first').stop().animate({opacity:1}, 1000);
  	});

	$('.img_grayscale').mouseout(function(){
		if(!$(this).closest('#gallery .small_gallery img').length)
     	$(this).stop().animate({opacity:0}, 1000);
    });
}

$(document).ready(function(){


    jQuery("#advert .slider").wowSlider({effect:"fade",prev:"",next:"",duration:10*100,delay:30*100,outWidth:295,outHeight:143,width:295,height:143,caption:false,controls:true,autoPlay:true,bullets:0,stopOnHover:true});
    jQuery("#top_user .slider").wowSlider({effect:"fade",prev:"",next:"",duration:10*100,delay:30*100,outWidth:295,outHeight:143,width:295,height:143,caption:false,controls:true,autoPlay:true,bullets:0,stopOnHover:true,
         onStep: function(par){
             var array = $("#top_user .ws_images img");
             $("#top_user_opacity").html(   limiter($(array[par]).attr('alt'))  );

             $("#top_user_href").html($(array[par]).closest('a').attr('href'));
         }
     });
	//.pos1 img, .pos2 img, .pos3 img,
    var img_gray='#gallery .big_gallery img, .grayscale'; //tupoi firefoh
    var set_only=', #gallery .small_gallery img';
    setTimeout(function(){loadImg(img_gray, set_only)},1000);
    //makeGray(img_gray, set_only);


    /*gallery*/
    var li=$('#gallery .big_gallery li');
    var lis=$('#gallery .small_gallery li');
    var gallen=4;
    $(lis[0]).addClass('c');
    $(lis[0]).find('img:first').stop().animate({opacity:1}, 1000);
    for(var i=0;i<gallen;i++){
  		$(li[i]).css('z-index',gallen-i);
  		if(i>0) $(li[i]).css('display','none');
	}

    galint=setInterval(gallery,10000);
    lis.mouseover(function(){
    	set_gallery(parseInt($(this).attr('id')));
    });

    $('#gallery .big_gallery li').mouseover(function(){
    	clearInterval(galint);
    });

    $('#gallery .big_gallery li').mouseout(function(){
    	galint=setInterval(gallery,10000);
    });

});

var gallen=4;
var galnow=0;
function gallery(){

	var lis=$('#gallery .small_gallery li');
	var li=$('#gallery .big_gallery li');
	$(lis[galnow]).removeClass('c');
	$(lis[galnow]).find('.img_grayscale').stop().animate({opacity:0}, 1000);

	if(galnow==gallen) galnow=0;
 	$(li[galnow]).fadeOut();
 	galnow++;
 	if(galnow==gallen) galnow=0;
 	$(li[galnow]).fadeIn();
 	$(lis[galnow]).addClass('c');
 	$(lis[galnow]).find('img:first').stop().animate({opacity:1}, 1000);
}

function set_gallery(new_pos){
	var lis=$('#gallery .small_gallery li');
	var li=$('#gallery .big_gallery li');

	$(lis[galnow]).removeClass('c');
	$(lis[galnow]).find('.img_grayscale').stop().animate({opacity:0}, 1000);
	//$(li[galnow]).fadeOut();
	$(li[galnow]).css('display','none');

	galnow=new_pos;
	//$(li[galnow]).fadeIn();
	$(li[galnow]).css('display','block');
	$(lis[galnow]).addClass('c');
	$(lis[galnow]).find('img:first').stop().animate({opacity:1}, 1000);
	clearInterval(galint);
	galint=setInterval(gallery,10000);
}

/*events on document loaded*/
$(document).ready(function(){
	$('#to_video').click(function(){
		$('#comm_blog').css('display','none');
		$('#comm_video').fadeIn();
		$('#to_video').addClass('c');
		$('#to_blog').removeClass('c');
	});

	$('#to_blog').click(function(){
		$('#comm_video').css('display','none');
		$('#comm_blog').fadeIn();
		$('#to_blog').addClass('c');
		$('#to_video').removeClass('c');
	});

	$('#login a#login_auth').click(function(){
		$('#ajaxauth').fadeTo("slow",0.8);
		$('#ajaxauth-form').fadeIn("slow");
	});

	$('#ajaxauth-close').click(function(){
		$('#ajaxauth').fadeOut("slow");
		$('#ajaxauth-form').fadeOut("slow");
	});

/*
	$('#login a#login_reg').click(function(){
		$('#ajaxreg').fadeTo("slow",0.8);
		$('#ajaxreg-form').fadeIn("slow");
	});
*/

	$('#ajaxreg-close').click(function(){
		$('#ajaxreg').fadeOut("slow");
		$('#ajaxreg-form').fadeOut("slow");
	});


        $("body").keydown(function(event){
            if (event.keyCode == 27 ) $('#ajaxauth-close').click();
            if (event.keyCode == 27 ) $('#ajaxreg-close').click();
        });


    $(".confirm").click(function(){
            return confirm('Подтвердите!');
    });

    $("#nxt_newcomm").click(function(){
        var data = Object();
        data.step = 'next';
        data.count_post = $('#count_post').val();
        var part = '';
        
        loading('#new_comm');

        if($('#comm_blog').is(':visible'))
        {
            data.part = 'blog';
            part =  'blog';
        }
        else
        {
            data.part = 'video';
            part =  'video';
        }
        $.ajax({
            type: 'POST',
            data: data,
            url: '/comment/ajaxnewcomments',
            success: function(resp){
            	unloading('#new_comm');
                if(part=='blog')
                {
                    data_ok = $(resp).find('#comm_blog').html();
                    $('#comm_blog').html(data_ok);
                }
                else
                {
                    data_ok = $(resp).find('#comm_video').html();
                    $('#comm_video').html(data_ok);
                }
            }
        });
    });
    $("#prw_newcomm").click(function(){
        var data = Object();
        data.step = 'prew';
        data.count_post = $('#count_post').val();
        var part = '';
        
        loading('#new_comm');

        if($('#comm_blog').is(':visible'))
        {
            data.part = 'blog';
            part =  'blog';
        }
        else
        {
            data.part = 'video';
            part =  'video';
        }

        $.ajax({
            type: 'POST',
            data: data,
            url: '/comment/ajaxnewcomments',
            success: function(resp){
				unloading('#new_comm');
                if(part=='blog')
                {
                    data_ok = $(resp).find('#comm_blog').html();
                    $('#comm_blog').html(data_ok);
                }
                else
                {
                    data_ok = $(resp).find('#comm_video').html();
                    $('#comm_video').html(data_ok);
                }
            }
        });
    });


    //$("#author_widget")
    $("#author_widget_next").live('click', function(){
        //author_widget
        $.post('/site/ajaxauthorposts',
        {page: parseInt($("#author_widget_hidden").val())+1, 'id': $("#author_widget_id").val()},
        function(data){
            if (data.length == 0 ){
                alert('Достигнут конец');
                return;
            }
            $("#author_widget").html(data);
        });
    });


    $("#author_widget_prev").live('click', function(){
        if (parseInt($("#author_widget_hidden").val()) == 1) {
            alert('Достигнуто начало');
            return;
        }

        $.post('/site/ajaxauthorposts',
        {page: parseInt($("#author_widget_hidden").val())-1, 'id': $("#author_widget_id").val()},
        function(data){
            $("#author_widget").html(data);
        });
    });




    $("#freshposts_next").live('click', function(){
        $.post('/site/ajaxfreshposts',
        {page: parseInt($("#freshposts_page").val())+1},
        function(data){
            if (data.length == 0 ){
                alert('Достигнут конец');
                return;
            }
            $("#fresh_posts").html(data);
        });
    });



    $("#freshposts_prev").live('click', function(){
        if (parseInt($("#freshposts_page").val()) == 1) {
            alert('Достигнуто начало');
            return;
        }

        $.post('/site/ajaxfreshposts',
        {page: parseInt($("#freshposts_page").val())-1},
        function(data){
            $("#fresh_posts").html(data);
        });
    });


    $("#top_user_opacity").click(function(){
        location.href = $("#top_user_href").html();
    });











	/*
    $("#post .text img:even").css("float", "left");
    $("#post .text img:even").css("clear", "left");
    $("#post .text img:even").css("margin-right", "15px");

    $("#post .text img:odd").css("float", "right");
    $("#post .text img:odd").css("clear", "right");
    $("#post .text img:odd").css("margin-left", "15px");

    $("#posts .text img").css("float", "left");
    $("#posts .text img").css("margin-right", "15px");
    $("#author_posts .text img").css("float", "left");
    $("#author_posts .text img").css("margin-right", "15px");*/

});
