var hash_link = document.location.hash;
var loading_page = false;

check_hash();
function check_hash(){
    var tmpHsh = document.location.hash;
    if(!empty(tmpHsh) && tmpHsh.substr(0, 2) == "#!"){
        load_page(tmpHsh.substr(2));
    }
}

function load_page(link){
        if(!loading_page){
            $("#primary").prepend("<div id=\"content_shade\"></div>");
            $("#content_shade").css({
                                    "width": $("#primary").width()+"px",
                                    "height": ($("#primary").height()+1)+"px",
                                    "margin-top" : "-1px",
                                    "position": "absolute",
                                    "z-index" : "998",
                                    "background" : 'url("/images/overlay_dot.png") repeat scroll 0 0 transparent'
                });
            loading_page = true;
            //$("#primary").animate({"opacity" : "0.7" }, "normal");
            $.get(link, function(data){
                //$("#primary").animate({ "opacity" : "1" }, "normal");
                $("#primary").html(data);
                document.location.hash="!"+link;
                hash_link = document.location.hash;
                loading_page = false;
                makePhotoNavigation();
            });
        }
        
}

setInterval(function(){
    if (document.location.hash != hash_link) check_hash();
        
}, 100);



function makePhotoNavigation(){
        if(!empty($("div.big_photo:first img").get(0)) && !loading_page){
            var imgSrc = $("div.big_photo:first img").attr("src");
            var imgAlt = $("div.big_photo:first img").attr("alt");
            $("div.photo_navigation:first").css({'display' : 'none'});
            var mouseOnPhoto = false;
            var lockFade  = false;
            $('<img alt="'+imgAlt+'"/>')
                .attr('src', imgSrc)
                .load(function(){
                    //$("div.photo_navigation").css({'display' : 'block'});
                    $('div.big_photo:first img').replaceWith( $(this) );
                    $("div.big_photo:first, div.photo_navigation").hover(function(){
                                                mouseOnPhoto = true;
                                                if(!lockFade){
                                                    showPhotoNavigation();
                                                }
                                             },
                                             function(){
                                                mouseOnPhoto = false;
                                                if(!lockFade){
                                                    hidePhotoNavigation();
                                                }
                                             }
                                           );
                    $("div.photo_navigation").css({
                                          "margin-top"  : "-"+($(this).height()+15)+"px",
                                          "margin-left" : ($("div.page-content").width() - $(this).width())/2+"px",
                                          "width"       : $(this).width()+"px"
                                          //"width"       : $("div.page-content").width()
                                          });
                    
                    $("div.photo_navigation a").css("height", $(this).height()+"px");
            });
            function showPhotoNavigation(){
                lockFade = true;
                $("div.photo_navigation").fadeIn('normal', function(){
                    if(!mouseOnPhoto) hidePhotoNavigation();
                        else lockFade = false;
                });
            }
            
            function hidePhotoNavigation(){
                lockFade = true;
                $("div.photo_navigation").fadeOut('normal', function(){
                    if(mouseOnPhoto) showPhotoNavigation();
                        else lockFade = false;
                });
            }
            
        }
}


$(document).one("ready", function(){
        
    $("div.photo_navigation a").live("click", function(){
        load_page($(this).attr("href"));
        return false;
    });
    
    
    // Прелоад картинок
    makePhotoNavigation();
        
    if(typeof(not_binded)=='undefined'){
        
	   $("a.themes_switcher:first").click(function(){
            $(this).parents("li:first").find("ul.themes").toggleClass("show");
            return false;
        });
        
        $("#calendar div.row div.day, div.user-of-theme div.photo div.thumb, div.equalizer div.data").hover(
                    function(){
                        var tooltip = $(this).find("div.more_tooltip");
                        tooltip.stop();
                        tooltip.css({"opacity" : ''});
                        tooltip.fadeIn();
                    },
                    function(){
                        var tooltip = $(this).find("div.more_tooltip");
                        tooltip.stop();
                        tooltip.fadeOut();
                    }

        );
        
        $("#secondary ul.switcher.tabs a").live("click", function(){
            $("#secondary ul.switcher.tabs li").removeClass("active");
            $(this).parent().addClass("active");
            $("#secondary div.tab").removeClass("show");
            $("#"+$(this).attr("rel")).addClass("show");
            return false;
        });
        
        //Ajax for comments
        $("#comment_reply_form").live("submit", function(){
            var form = $(this);
            var params="";
            $(this).find("input, textarea").each(function(){
                params += $(this).attr("name")+"="+$(this).val()+"&";
            });
            params +="ajax_add_comment=1";
            $("#comment_reply_form").replaceWith("<div id='loading_comments'><img src='/images/preload_small_white.gif' alt=\"Загрузка\" /></div>");
            $.post(form.attr("action"), params, function(data){
                if($("ul.comments").get(0)){
                    //Если  у поста уже есть коменты
                    if($("ul.comments #loading_comments").get(0))
                    {
                        // Если отвечаем в тред. у которого уже есть ответы
                        if($("#loading_comments").parent().find("ul.comments").length > 0){
                            $("#loading_comments").parent().parent().find("ul.comments").append($(data).find("ul.comments li:first"));
                            $("#loading_comments").remove();
                        }
                        else{
                            $("#loading_comments").parent().parent().append($(data).find("ul.comments"));
                            $("#loading_comments").remove();
                        }
                    }
                    else{
                        //Если в треде еще нет ответов
                        $("#loading_comments").remove();
                        if(!$("ul.comments:first").parents("div.content").hasClass("technic") && !$("ul.comments:first").parents("div.sidebar").hasClass("team")) $("ul.comments:first").append($(data).find("ul.comments li:first"));
                            else $("ul.comments:first").prepend($(data).find("ul.comments li:first"));
                    }
                }
                else{
                    // Если коментов нет
                    $("#loading_comments").replaceWith($(data).find("ul.comments"));
                }
                
                if(!$("ul.comments:first").parents("div.content").hasClass("technic") && !$("ul.comments:first").parents("div.sidebar").hasClass("team")) $("#comments").after($(data).find("#comment_reply_form"));
                    else $("#comments").before($(data).find("#comment_reply_form"));
                
            });    
            
            return false;
        });
        
        $("#comments a.delete_comment").live("click", function(){
            var li = $(this).parents("li:first");
            if(li.find("ul.comments").length > 0){
                li.find("div.head:first").remove();
                li.find("div.comment-entry:first").html("<p class='deleted'>Wtf? тут был комментарий!?</p>");
                $.get($(this).attr("href"));
            }
            else{
                li.remove();
                $.get($(this).attr("href"));
            }
            
            return false;
        });
        
        //End Ajax for comments
                
        
        $("div.stunts-theme-block:not(.active)").find("ul.stunts").css({ 'display': 'none' });
        $("div.stunts-theme-block h4.stunts-theme").css({
                                                        'cursor': 'pointer'
                                                        
                                                        });
        $("div.stunts-theme-block h4.stunts-theme").live("click", function(){
            if($(this).parent().hasClass("active")) return false;
            $("div.stunts-theme-block").removeClass("active");
            $(this).parent().addClass("active");
            
            $("div.stunts-theme-block ul.stunts").slideUp();
            
            $(this).parent().find("ul.stunts").slideDown();
        });
        
        var more_info_conn;
        $("div.profile div.head a.more_information").live("click", function(){
            $("div.profile div.head a.more_information").toggleClass("hide");
            if(is_object(more_info_conn)) more_info_conn.abort();
            $(this).parents("div.head:first").find("div.content").slideToggle();
            more_info_conn = $.post($(this).attr("href"), { "change_more_info" : 1, "isAjax" : 1});
            return false;
        });
        
	   
	   $("#change_status").live("click", function(){
		  var parent = $(this).parents("div.status:first");
		  parent.find("p.status_text").css({ "display" : "none" });
		  $("#change_status_form").css({ "display" : "block" });
		  $("#change_status").css({ "display" : "none" });
		  $("#cancel_change_status").css({ "display" : "block" });
		  return false;
	   });
	   
	   $("#cancel_change_status").live("click", function(){
		  var parent = $(this).parents("div.status:first");
		  parent.find("p.status_text").css({ "display" : "block" });
		  $("#change_status_form").css({ "display" : "none" });
		  $("#change_status").css({ "display" : "block" });
		  $("#cancel_change_status").css({ "display" : "none" });
		  return false;
	   });
	   $("#user_profile_status, #team_status").keypress(function (e) {
		  if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			 var textarea = $(this);
			 var params="";
			 $("#change_status_form").find("input, textarea").each(function(){
				params += $(this).attr("name")+"="+$(this).val()+"&";
			 });
			 $.post($("#change_status_form").attr("action"), params, function(){
				$("p.status_text").html(textarea.val());
				$("#cancel_change_status").trigger("click");
			 });
			 return false;
		  }
		  
	   });
    
	   BindTypeFilters();
    
	   $(window).scroll(function (){
			 if($(window).scrollTop() > $("#header").outerHeight()-20) {
				    $("#header div.toolbar-shade").fadeIn(300);
			 } else {
				    $("#header div.toolbar-shade").fadeOut(200);
			 }
	   });
    
    
	    // page-head select
	    
	    $(".page-head select").each( function () {
		    var subst = $("<div class='head-select'><a rel='"+$(this).attr("id")+"' class='select_id' style='display:none;'></a><div class='current-value'>"+$(this).find(":selected").html()+"</div><ul class='options'></ul></div>");
		    get_select_options($(this), subst.children('ul.options'));
		    $(this).after(subst);
		    $(this).hide();
		    
		    subst.click( function(){
			    $(this).children(".options").slideToggle('fast');
		    });
	    });
	    
	    
	   
	   $("div.head-select ul.options li.option a").live("click", function(){
		  var parentSelect = $(this).parents("div.head-select:first")
		  var selectId = parentSelect.find("a.select_id").attr("rel");
		  $("#"+selectId).val($(this).attr("rel"));
		  parentSelect.find("div.current-value").html($(this).html());
		  return false;
	   });
	    
	   // Голосовалка для трюков
        if($("div.performance_vote").get(0) != ""){
            
            $("a.performance_vote_do").click(function(){
			  $(this).css({"display" : "none"});
			  $(this).parents("div.performance:first").find(".performance_vote").addClass("show");
                 $(this).parents("div.performance:first").find("div.ammount").addClass("show")
			  return false;
		  });
            
            $("div.performance_vote.active").live("mousemove", function(e){
                maxX = 121;
                if (e.layerX !== undefined) curX = e.layerX;
                    else if (e.x !== undefined)  curX = e.x;
                        else if(e.offsetX !== undefined) curX = e.offsetX;
                
                $(this).find("div.value").css("width", Math.ceil(curX/10)*10);
                var percent = Math.ceil(curX*10 / maxX );
                var ammount_id = $(this).find("a").attr("rel");
                $("#"+ammount_id).find("span.value").html(percent);
                if(percent > 5){
                    $("#"+ammount_id).removeClass("negative");
                    $("#"+ammount_id).addClass("positive");
                }
                else{
                    $("#"+ammount_id).addClass("negative");
                    $("#"+ammount_id).removeClass("positive");
                }
            });
            
            $("div.performance_vote.active").click(function(){
                 var ammount_id = $(this).find("a").attr("rel");
                 var url = $(this).find("a").attr("href");
                 var voter = $(this);
                 voter.removeClass("active");
			  $.post(url, {"value" : $("#"+ammount_id).find(".value").text() }, function(data){
			    var points = parseFloat(data);
			    $("#"+ammount_id).find("span.value").html(number_format(points, 2, "."));
			    if(points > 5){
                        $("#"+ammount_id).removeClass("negative");
                        $("#"+ammount_id).addClass("positive");
                    }
                    else{
                        $("#"+ammount_id).addClass("negative");
                        $("#"+ammount_id).removeClass("positive");
                    }
                   voter.find("div.value").width(points*12.1);
                   voter.unbind("click");
			  } );
			  return false;
		  });
            
            
        }
        
    
	   $("a.comments_page").click(function(){
		  if(!$(this).hasClass("selected")){
			 // Выдираем форму коментов, чтоб потом воткнуть на страницу
			 var form = $("#comment_reply_form");
			 form.find('input#comment_parent_id').val(0);
			 // <--
    
			 $("ul#comments").replaceWith("<img id='preloader_comments' src='/images/preload_big.gif' alt='Загрузка'/>");
			 $.post("/ajax/getComments/"+$(this).attr("rel")+"/"+$(this).text()+"/", function(data){
				$("#preloader_comments").parent().replaceWith(data);
				if($("div.pager").get()) $("div.pager").after(form)
				    else $("ul#comments").after(form);
				
				$("a.comment_reply").click(function(){
				    BindCommentReply($(this));
				    return false;
				});
    
			 } );
			 $("a.comments_page").removeClass("selected");
			 $(this).addClass("selected")
		  }
		  return false;
	   });
	   
	   var send_message_blocked = false;
	   $("a.send_message_link").live("click", function(){
		  if(!send_message_blocked){
			 var id = $(this).attr("rel");
			 $("body").append("<div id='big_shade'></div>");
			 if(empty($("#new_message_window_"+id).get())){
				send_message_blocked = true;
				$.ajax({
					   url: $(this).attr("href"),
					   type: "GET",
					   success: function(data){
						  send_message_blocked = false;
						  $("body").append("<div class='new_message' id='new_message_window_"+id+"'><div class='inner'><a class=\"close_new_message\" href=\"#\">Закрыть</a>"+data+"</div></div>");
						  $("#new_message_window_"+id).css({ 'top': ($(document).scrollTop() + 200 )+"px" });
					   }
				    });
			 }
			 else{
				$("#new_message_window_"+id).css("display", "block");
			 }
		  }
		  return false;
	   });
	   
	   $("div.new_message form.send_message_form_new").live("submit", function(){
											 $(this).parent().find("a.close_new_message").remove();
											 var params = "";
											 $(this).find("input, textarea").each(function(){
												params += $(this).attr("name")+"="+$(this).val()+"&";
											 });
											 var parentDiv = $(this).parent();
											 params += "isAjax=1";
											 parentDiv.find("h1").html("Отправка сообщения");
											 $(this).replaceWith("<img src='/images/preload_small_white.gif' alt='Загрузка' />");
											 $.ajax({
												url: $(this).attr("action"),
												type: "POST",
												data: params,
												dataType: "jsonp"
												
											 });
											 return false;
								    });
	   
	   $("a.close_new_message").live("click", function(){
		  $(this).parents("div.new_message").css("display", "none");
		  $("#big_shade").remove();
		  return false;
	   });
    
	   $("div.rating a.rate, ul.stats a.rate").live("click", function(){
		  var link = $(this);
            var ratingDiv = link.parents("div.rating");
            $.get(link.attr("href"), function(data){
                var points = parseFloat(data);
                $(ratingDiv).find("span").html(points);
                $(ratingDiv).find("span").removeClass("negative");
                $(ratingDiv).find("span").removeClass("positive");
                if(points > 0) $(ratingDiv).find("span").addClass('positive')
                    else $(ratingDiv).find("span").addClass('negative');
                $(ratingDiv).find("a.rate").remove();
            });
		  return false;
	   });
    
	   $("a.ajax_action").live("click", function(){
		  var link = this;
		  $.getJSON($(this).attr("href"), {'isAjax' : 1}, function(data){
			 if(!empty(data.message)) $(link).replaceWith("<span class='success'>"+data.message+"</span>");
			 if(!empty(data.link)) $(link).replaceWith(data.link);
		  } );
		  return false;
	   } );
	   
	   var dialog_blocked = false;
	   
	   $("a.dialog").die( "click" );
	   $("a.dialog").live("click", function(){
		  if(!dialog_blocked){
			 $("body").append("<div id='big_shade'></div>");
			 dialog_blocked = true;
			 $.ajax({
				    url: $(this).attr("href"),
				    type: "GET",
				    data: {"isAjax" : 1},
				    success: function(data){
					   dialog_blocked = false;
					   $("body").append("<div class='dialog_window' id='dialog_window'><div class='inner'><a class=\"close_dialog_window\" href=\"#\">Закрыть</a>"+data+"</div></div>");
					   $("#dialog_window").css({ 'top': ($(document).scrollTop() + 200 )+"px" });
				    }
				});
			 
		  }
		  return false;
    
	   });
	   
	   $("a.close_dialog_window").live("click", function(){
		  $("#big_shade").remove();
		  $(this).parents("div.dialog_window:first").remove();
		  return false;
	   });
    
	   $("a.comment_reply").live("click", function(){
		  if($("form#comment_reply_form").get()){
                var form = $("form#comment_reply_form");
                $("form#comment_reply_form").remove();
                var parent_id = parseInt($(this).attr("rel"));
                if(empty(parent_id)) parent_id = 0;
                form.find('input[id$="comment_parent_id"]').val(parent_id);
                if(!empty($(this).attr("rel"))){
                    $("li#comment_"+$(this).attr("rel")).find("div.actions:first").after(form);
                    $("div.comments_list a.comment_reply:first").removeClass("hidden");
                }
                else{
                    $("div.comments_list").before(form)
                    $("div.comments_list a.comment_reply:first").addClass("hidden");
                }
            }
		  return false;
	   });
	    
	   // Показываем листалку по постам
	   CreatePublicationsListing();
	   
	   not_binded = false;
    }

});




function BindTypeFilters(){
    $("ul.posts li div.post-type a").unbind("click");
    $("ul.posts li div.post-type a").click(function(){
        var this_type = $(this).parent().parent().parent().attr('class');
        $("ul.posts li."+ this_type +" div.post-type a").toggleClass('selected');
        var scroll_to = $("#header").outerHeight();
        // var scroll_to = $('html').scrollTop();
        var cur_posts = $(this).parent().parent().parent();
        if($(this).hasClass('selected')){ // Фильтруем по типу
                LoadPublications($(this), $(this).parents("li").attr("class"));
                $("ul.posts li."+ this_type).slice(0, $("ul.posts li."+ this_type).index(cur_posts)).each( function() {
                        scroll_to += $(this).outerHeight();
                });
        } else { // Показываем все публикации
                // догружаем посты
                LoadPublications($(this));
                $("ul.posts li").slice(0, $("ul.posts li").index(cur_posts)).each( function() {
                        scroll_to += $(this).outerHeight();
                });
        }
        classes = this_type.split( );
        var expression = "";
        for(i in classes ) expression + "[."+classes[i]+"]";
        $("ul.posts li:not("+expression+")").slideToggle(200);

        $('html, body').animate({scrollTop: scroll_to-70}, 200);

        return false;
    });

}

function LoadPublications(element, type){
    if(!type) type='';
        else{
            var tmpType = type.split(" ");
            type="."+tmpType[0];
        }
    $("ul.posts:last").after("<img id='preloader_publications' src='/images/preload_big.gif' alt='Загрузка'/>")
    $("div.more-posts").remove();
    var start = $("div.page_num:last").next().find("li:first div.post-type a").attr("rel");
    
    if(empty(start)) start = $(element).parents("ul.posts li"+type+":first div.post-type a").attr("rel");
    
    $.get($(element).attr("href"),"start="+start,function(data){
        
        /*data = "<div>"+data+"</div>";
        $(data).find("li").each(function(){
            if(empty($("#"+$(this).attr("id")).html()))  $("ul.posts").append(this);
        });
       $("div.more-posts").replaceWith($(data).find("div.more-posts").get());*/

       $("#preloader_publications").remove();
       $("ul.posts:last").replaceWith(data);
       CreatePublicationsListing();
       BindTypeFilters();
    });
}

function CreatePublicationsListing(){
    $("div.more-posts").css({'display' : 'block'});
    $("div.more-posts a").click(function(){
        GetMorePosts($(this));
        return false;
    });
}

function GetMorePosts(element){
    $(element).parent().replaceWith("<img id='preloader_publications' src='/images/preload_big.gif' alt='Загрузка'/>");
    $.get($(element).attr("href"), function(data){
        $("#preloader_publications").replaceWith("<div class='page_num'><span>"+$(element).attr("rel")+" стр.</span></div>"+data);
        $("div.more-posts").css({'display' : 'block'});
        $("div.more-posts a").unbind();
        BindTypeFilters();
        $("div.more-posts a").click(function(){
            GetMorePosts($(this));
            return false;
        });
    })
}

function get_select_options(element, where) {
		    $(element).children().each( function () {
			    if($(this).is('optgroup')) {
				    where.append('<li class="group-title">' + $(this).attr('label') + '</li>');
				    get_select_options($(this), where);
			    } else {
				    where.append('<li class="option"><a href="#" rel="'+$(this).attr("value")+'">' + $(this).html() + '</a></li>');
			    }
		    });
}


/*function AjaxActionClick(link){
        $.getJSON($(link).attr("href"), function(data){
            if(!empty(data.message)) $(link).replaceWith("<span class='success'>"+data.message+"</span>");
        } );
        return false;
    }
							*/

function empty (mixed_var) {
    
    var key;
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }return true;
    }

    return false;
}

function strpos (haystack, needle, offset) {
    
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function is_object (mixed_var) {
    // Returns true if variable is an object  
    // 
    // version: 1102.614
    // discuss at: http://phpjs.org/functions/is_object    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // *     example 1: is_object('23');
    // *     returns 1: false    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
    if (mixed_var instanceof Array) {        return false;
    } else {
        return (mixed_var !== null) && (typeof(mixed_var) == 'object');
    }
}
	

function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}


function messageSent(data){
    $("#new_message_window_"+data.recepient_id+" div.inner").html(data.html);
    setTimeout(function(){
				$("#new_message_window_"+data.recepient_id).fadeOut("slow", function(){
				    $("#new_message_window_"+data.recepient_id).remove();
				});
				$("#big_shade").fadeOut("slow", function(){
				    $("#big_shade").remove();
				});
			 }, 2000);
}

