//////////////////////////////////////////
//                                      //
//       hello source-reader :)         //
//        (c) omedia. with <3           //
//                                      //
//////////////////////////////////////////



function bindActions() {


    //
    // disabling submit elements on form submit
    //

    $("form").submit(function(){
        $("input[type='submit']", this).attr("disabled", "disabled");
        return true;
    });
    
    


    //
    // selecting input element on CLICK
    //

    $(".select_on_click").click(function(){
        $(this).select();
    });


    //
    //  minor styling tweaks
    //
    
    function activeTriggerFocus(){
        // include textareas
        if( this.tagName.toLowerCase() != "textarea" ) {
            var type = $(this).attr("type");
        } else {
            var type = "text";
        }
        
        if( type == "text" || type == "password" ) {
            $(this).addClass("active");
        }
    }
    
    function activeTriggerBlur(){
        $(this).removeClass("active");
    }
    
    $(".broll_form input").focus(activeTriggerFocus);
    $(".broll_form textarea").focus(activeTriggerFocus);
    $(".broll_form input").blur(activeTriggerBlur);
    $(".broll_form textarea").blur(activeTriggerBlur);


    //
    // voting story
    //

    $(".post_voting a").click(function(){
    
        var action = $(this).attr("rel");
        var postBlock = $(this).closest(".post_block");
        var postId = $("h2 a", postBlock).attr("rel");
        
        var voteButtons = $(this).parent();
        var votesNum = $(".post_voting strong", postBlock);
        
        $(voteButtons).slideUp("normal", function(){
        
            $(this).remove();
        
            if(action == 'like') {
                $(votesNum).text( parseInt( $(votesNum).text() ) + 1 );
            } else {
                $(votesNum).text( parseInt( $(votesNum).text() ) - 1 );
            }
            
            $(votesNum).effect("highlight");
            
            $.post(site_url + '/p/' + action + '/?method=ajax', {postid:postId});
        
        });
        
        return false;
    
    });




    //
    // post_text hover events
    //
    /*
    $(".post_block").hover(
        function(){
            
            $(".post_voting span", this).show();
            
        },
        function(){
            
            $(".post_voting span", this).hide();
            
        }
    );
    */



    //
    // validate new topic form
    //
    
    $("#new_topic_form").submit(function(){
    
        var thisForm = this;
        var allGood = true;
    
        $('.ka', this).each( function() {
            if( $.trim( $(this).val() ) == '' ) {
                allGood = false;
            }
        });
        
        if(allGood) {
            return true;
        } else {
            alert("გთხოვთ შეავსოთ ყველა ველი!");
            $('input[type="submit"]', thisForm).removeAttr("disabled");
            return false;
        }
    
    });




}


var testOut = '';
var topgeInserted = false;


$(document).ready(function(){

    //
    //  on load
    //
    
    bindActions();
    
    
    
    //
    // top.ge
    //
    /*
    $(".column_secondary:last").each(function(){
    
        if(!topgeInserted) {
        
            $(this).append('<div class="topge"><a href="http://counter.top.ge/cgi-bin/showtop?42294" target="_blank"><img src="http://counter.top.ge/cgi-bin/count?ID:42294+JS:false" alt="TOP.GE" /></a></div>');
            topgeInserted = true;
        
        }
    
    });
    */
    

    //
    //  search box lovin'
    //
    
    // on init
    // select posts if none is selected
    if( $("#top_search li a.active").length < 1 ) {
        $("#top_search li:eq(1) a").addClass("active");
    }
    // assign selected what to hidden field
    $("#top_search input[name='what']").val( $("#top_search li a.active").attr("href").substr(1) );
    
    // if selected one is users, remove georgian keyboard
    if( $("#top_search li a.active").attr("href") == "#users" ) {
        $("#top_search input[name='search']").removeClass("ka");
    }
    
    
    
    // on search input focus
    $("#top_search input[name='search']").focus(function(){
    
        var thisInput = this;
        
        // make shine!
        $(thisInput).closest("form").addClass("focused");
        
        // alter text
        if( $(thisInput).attr("title") == $(thisInput).val() ) {
            $(thisInput).val("");
        }
        
    });
    
    // on search input blur
    $("#top_search input[name='search']").blur(function(){
    
        var thisInput = this;
        
        // only if we don't have a custom text
        if( $(thisInput).val() == "" ) {
            
            // turn off the lights
            $(thisInput).closest("form").removeClass("focused");
            
            // return default value
            $(thisInput).val( $(thisInput).attr("title") );
            
        }
    
    });
    
    
    // on what option click
    $("#top_search li a").click(function(){
    
        // remove the active class for all of them
        var thisUl = $(this).closest("ul");
        $("a", thisUl).removeClass("active");
        // add to clicked one
        $(this).addClass("active");
        
        // assign selected what to hidden field (and get what we've assigned)
        var what = $("#top_search input[name='what']").val( $(this).attr("href").substr(1) ).val();
        
        // if selected one is users, remove georgian keyboard
        if(what == 'users') {
            $("#top_search input[name='search']").removeClass("ka");
        } else {
            $("#top_search input[name='search']").addClass("ka");
        }
        
        return false;
    
    });








    //
    // switcher thingy
    //

    $(".switcher a").bind('click', function(){
    
        var $div = $(this).parent();
        
        $("a", $div).removeClass("on").addClass("off");
        $(this).removeClass("off").addClass("on");
        
        if( $(this).closest(".tag_cloud").length > 0 ) {
            return false;
        } else {
            return true;
        }
    
    });




    //
    // calendar story
    //

    // clicking on years or months
    $(".calendar ul a").click(function(){
    
        var par = $(this).parent().parent();
    
        $("li.active", par).removeClass("active");
        $(this).parent().addClass("active");
        
        // update
        updateCalendar();
        
        return false;
    
    });
    
    // updating calendar
    function updateCalendar() {
    
        var newMonth = $(".calendar ul.months li.active a").attr("rel");
        var newYear  = $(".calendar ul.years li.active a").text();
        
        $.post( site_url+"/posts/calendar/?method=ajax", {year:newYear, month:newMonth}, function(data){
        
            $(".calendar .calendar_container").html(data);
        
        });
    
    }
    
    
    
    
    //
    // open new topic box
    //
    
    $("#new_topic_box_opener").toggle(
    
        function() {
    
            var thisLink = this;
                
            $.get( $(thisLink).attr("href") + "?method=ajax", function(data){
            
                $(thisLink).addClass("sidebar_link_button_opened");
                $("#new_topic_box").html(data).slideDown();
                // re-binding
                bindActions();
            
            });
            
            return false;
        },
        
        function() {
            
            $(this).removeClass("sidebar_link_button_opened");
            $("#new_topic_box").slideUp();
            
            return false;
        }
    
    );
    
    
    
    
    //
    // autocompleting PM
    //
    
    $("#messages .autocomplete").autocomplete(site_url+"/search/usersautocomplete/?method=ajax", {
        width: 157,
        selectFirst: false,
        minChars: 0
    });
    
    
    
    //
    // hiding PM sent success message
    //
    
    if( $("#messages p.success").length > 0 ) {
    
        setTimeout(function(){
        
            $("#messages p.success").effect("pulsate", {mode:"hide", times:2}, 700);
        
        }, 5000);
    
    }
    
    
    
    //
    // share on facebook links
    //
    
    $(".facebook").click(function(){
    	u=location.href;
    	t=document.title;
    	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
    	return false;
    });



    //
    // add to favorites links
    //

    $(".add_to_faves").click(function(){
    
        var thisLink = this;
        var blogId = $(thisLink).attr("rel");
        var transferTo = $("#main_faves_link");
        
        $(thisLink).effect("transfer", {to:transferTo, className:"transfer_box"}, 1000);
        
        $.get(site_url+"/favorites/add/"+blogId+"/?method=ajax", function(){
        
            $(thisLink).fadeOut();
        
        });
        
        return false;
    
    });
    
    
    //
    // remove from favorites and menu
    //
    
    $(".blog_list_menu .remove_favorite").hide();
    
    $(".blog_list_menu li").hover(
        function(){
            $(".remove_favorite", this).show();
        },
        function(){
            $(".remove_favorite", this).hide();
        }
    );
    
    $(".blog_list_menu .remove_favorite").click(function(){
    
        if(confirm("ნამდვილად გსურთ ამ ბლოგის ფავორიტებიდან ამოშლა?")) {
            var thisLink = this;
            var blogId = $(thisLink).attr("rel");
            
            $.get(site_url+"/favorites/remove/"+blogId+"/?method=ajax", function(){
                $(thisLink).closest("li").slideUp("normal", function(){
                    $(".blog_" + blogId).slideUp();
                });
            });
        }
        
        return false;
    
    });
    
    
    
    //
    // commenting
    //
    
    $("#new_comment").submit(function(){
    
        var thisForm = this;
        var action = $(this).attr("action") + "?method=ajax";
        var commentsContainer = $("#comments_container");
        var h1 = $("h1", commentsContainer);
        
        if( $.trim( $("textarea", thisForm).val() ) == '' ) {
        
            $('input[type="submit"]', thisForm).removeAttr("disabled");
            alert("გთხოვთ ჩაწეროთ კომენტარი");
        
        } else {
        
            $.post(action, $(thisForm).serialize(), function(data){
            
                if(h1.length < 1) {
                    $(commentsContainer).append("<h1>კომენტარები:</h1>");
                }
                
                $(commentsContainer).append(data);
                
                $(thisForm).closest(".comment_form").slideUp();
            
            });
        
        }
        
        return false;
        
    
    });
    
    
    
    //
    // add blog tabs
    //
    
    var doAddBlogTabs = function(obj){
    
        var thisLink = obj;
        var parentUl = $(thisLink).closest("ul");
        var contentContainer = $("+ .content_block_tabs_container", parentUl);
        
        $("a", parentUl).removeClass("active");
        $(thisLink).addClass("active");
        
        var hash = $(thisLink).attr("href").substr(1);
        
        $("form", contentContainer).hide();
        $("#"+hash, contentContainer).show();
        
        return false;
    
    }

    $("#myblogs .content_block_tabs a").click(function(){
        return doAddBlogTabs(this);
    });
    
    // select active tab on load
    if( $("#myblogs .content_block_tabs a.active").length > 0 ) {
        doAddBlogTabs( $("#myblogs .content_block_tabs a.active") );
    }
    
    
    
    //
    // selecting categories on add blog 
    //
    
    $("#myblogs #cats-element input").click(function(){
    
        if( $(this).is(":checked") ) {
    
            checkedOnes = $(this).closest("dd").find("input:checked");
            
            if(checkedOnes.length > 5) {
            
                alert("აირჩიეთ მაქსიმუმ 5 კატეგორია!");
                $(this).attr("checked", false);
                
            } else {
            
                $(this).closest("label").addClass("checked");
            
            }
            
        } else {
        
            $(this).closest("label").removeClass("checked");
        
        }
        
    });
    
    // highlighting pre-selected categories (for edit blog page)
    
    $("#blog #myblogs #cats-element input:checked").closest("label").addClass("checked");
    
    
    
    //
    // overriding "gagrdzeleba >" on edit blog page
    //
    
    $('#blog #add_blog_form input[type="submit"]').val("ცვლილებების შენახვა");
    
    
    
    //
    // checking for validation link (myblogs)
    //
    
    $("#myblogs .check_link form").submit(function(){
    
        var thisForm = this;
        var vars = $(this).serialize();
        var action = $(this).attr("action") + "?method=ajax";
        
        $(thisForm).parent().addClass("loading");
        $(".fail", thisForm).hide();
        
        $.post(action, vars, function(data){
        
        
            if($.trim(data) == 'win') {
            
                $(".win", thisForm).slideDown();
                $('input[type="submit"]', thisForm).parent().hide();
            
            } else {
            
                $(".fail", thisForm).slideDown();
                setTimeout(function(){
                    $(".fail", thisForm).slideUp();
                }, 10000);
                $('input[type="submit"]', thisForm).removeAttr("disabled");
            
            }
        
            $(thisForm).parent().removeClass("loading");
        
        });
        
    
        return false;
    
    });



    //
    // deactivating blog
    //
    
    $("#deactivate_form input[type='button']:eq(0)").click(function(){
        $(this).closest("form").find(".question").slideDown();
        return false;
    });

    $("#deactivate_form input[type='button']:eq(1)").click(function(){
        $(this).closest("form").find(".question").slideUp();
        return false;
    });
    
    
    
    
    
    //
    // post show and hide
    //
    
    $(".post_hide").click(function(){
        var postId = $(this).attr("rel");
        var postBlock = $(this).closest(".post_block");
        
        if(confirm("ნამდვილად გსურთ ამ პოსტის დამალვა?")) {
            $.get( site_url + '/p/' + postId + '/hide/?method=ajax', function() {
                $(postBlock).slideUp();
            });
        }
        return false;
    });
    
    $(".post_show").click(function(){
        var postId = $(this).attr("rel");
        var postBlock = $(this).closest(".post_block");
        var thisLink = this;
        
        $.get( site_url + '/p/' + postId + '/show/?method=ajax', function() {
            $(postBlock).removeClass("post_block_deleted");
            $(thisLink).fadeOut();
        });
        return false;
    });
    
    



    //
    // georgian keyboards
    //
    
    klav=new kaklav({elements:'ka',checkbox:'geochk',layout:'kalat',ctrlchar:'`',cap:'no',old5:'false'});
    
    
    
    //
    // say to in discussions
    //
    
    $(".sayto").click(function(){
    
        var uName = $(this).attr("alt");
        var textareaVal = $("form[name='addpost'] textarea").val();
        
        $("form[name='addpost'] textarea").val( textareaVal + '@' + uName + ",\n" ).focus();
        window.scroll(0,999999);
    
    });
    
    
    
    //
    // placeholder for tag cloud switcher
    //
    
    /*
    $("#index .tag_cloud .switcher a").bind("click", function(){
    
        SEE TEMPORARY TWEAK IN MAIN CLICK FUNCTION
    
    });
    */




    //
    // inserting charts in numbers
    //
    
    if($("#numbers").length > 0) {
    
        
        $("#chart_posts_daily").flash({
            swf: site_url + "/charts/linechart.swf",
            width: "100%",
            height: 350,
            params: { bgcolor: "#fff" },
            flashvars: {
                        path: site_url + "/charts/",
                        settings_file: site_url + "/charts/posts_daily/settings.xml",
                        data_file: site_url + "/charts/posts_daily/data.csv"
                       }
        });
        
        $("#chart_blogs_daily").flash({
            swf: site_url + "/charts/linechart.swf",
            width: "100%",
            height: 350,
            params: { bgcolor: "#fff" },
            flashvars: {
                        path: site_url + "/charts/",
                        settings_file: site_url + "/charts/blogs_daily/settings.xml",
                        data_file: site_url + "/charts/blogs_daily/data.csv"
                       }
        });
        
        $("#chart_platforms").flash({
            swf: site_url + "/charts/piechart.swf",
            width: "100%",
            height: 360,
            params: { wmode: "transparent" },
            flashvars: {
                        path: site_url + "/charts/",
                        settings_file: site_url + "/charts/platforms/settings.xml",
                        data_file: site_url + "/numbers/platforms/?method=ajax"
                       }
        });
        
        $("#chart_genders").flash({
            swf: site_url + "/charts/piechart.swf",
            width: "100%",
            height: 360,
            params: { wmode: "transparent" },
            flashvars: {
                        path: site_url + "/charts/",
                        settings_file: site_url + "/charts/genders/settings.xml",
                        data_file: site_url + "/numbers/genders/?method=ajax"
                       }
        });
    
    
    
    }
    
    
    
    //
    // showing favorited users list in ratings
    //
    
    if($(".topfavorite").length > 0) {
        $(".topfavorite .karma a").toggle(
            function(){
                
                var thisDl = $(this).closest("dl");
                if( $("dd.info", thisDl).length > 0 ) {
                    $("dd.info", thisDl).slideDown();
                } else {
                    $.get( $(this).attr("href") + "favorites/?method=ajax", function(data){
                        $(thisDl).append('<dd class="info">'+data+'</dd>');
                        $("dd.info", thisDl).slideDown();
                    } );
                }
                return false;
                
            },
            
            function(){
                
                var thisDl = $(this).closest("dl");
                if( $("dd.info", thisDl).length > 0 ) {
                    $("dd.info", thisDl).slideUp();
                }
                return false;
            
            }
        );
    }




    //
    // redirecting blog hash url
    //
    
    if($("#index").length > 0) {
    
        var hashLink = window.location.hash;
        if(hashLink.length > 5) {
            hashLink = hashLink.substr(1);
            window.location.href = site_url + "/blog/_" + hashLink;
        }
        
    }
    
    



    //
    // testing
    //
/*
    $("#blog_title").bind("dblclick", function(){
    
        var thisItem = this;
        
        var replaceWith = '<input type="text" class="wider" id="blog_title_field" value="';
        replaceWith += $(thisItem).text();
        replaceWith += '" />';
        
        $(thisItem).parent().addClass("broll_form");
        
        $(thisItem).replaceWith( replaceWith );
        $("#blog_title_field").after(' <img src="'+site_url+'/images/icon_tick_circle.png" style="vertical-align:middle" id="blog_title_field_submit" alt="" />');
        
        $("#blog_title_field_submit").bind("click", function(){
            
            var fieldValue = $("#blog_title_field").val();
            $("#blog_title_field").replaceWith('<span>' + fieldValue + "</span>");
            $(this).remove();
        
        });
    
    });

    $("#blog_desc").bind("dblclick", function(){
    
        var thisItem = this;
        
        var replaceWith = '<textarea class="wider high" id="blog_desc_field" style="vertical-align:text-top">';
        replaceWith += $(thisItem).text();
        replaceWith += '</textarea>';
        
        $(thisItem).parent().addClass("broll_form");
        
        $(thisItem).replaceWith( replaceWith );
        $("#blog_desc_field").after('<img src="'+site_url+'/images/icon_tick_circle.png" style="vertical-align:super" id="blog_desc_field_submit" alt="" />');
        
        $("#blog_desc_field_submit").bind("click", function(){
            
            var fieldValue = $("#blog_desc_field").val();
            fieldValue = fieldValue.replace(/([^>]?)\n/g, '$1<br>\n');
            alert(fieldValue);
            $("#blog_desc_field").replaceWith('<p>' + fieldValue + "</p>");
            $(this).remove();
        
        });
    
    });
*/

















});