if(document.all && !document.getElementById) {
    document.getElementById = function(id) { return document.all[id]; }
}

function search_get(keywords,searchform) {
    var k = document.getElementById(keywords).value;
    var ws = document.getElementById(searchform);
    location.href = 'http://' + location.hostname + '/cerca/' + encodeURIComponent(k);
}
function search_blogo_get() {
    k = document.getElementById('searchkeywords').value;
    location.href = 'http://' + location.hostname + '/cerca/' + escape(k); //.replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

var lp_login;
var lp_comments;
var lp_bloglist;

function setUserData() {
    lp_login = $.cookie('lp_login');
    lp_bloglist = $.cookie('lp_bloglist');
    if (lp_login) {
        var username = lp_login.split(",")[0];
        $("div#commentuserfields").empty();
        $("p#registerp").remove();
        $("div#commentuserfields").append("Nickname: " + username.replace(/\+/g," ") + " (<a href=\"/user/profile\">Profilo</a>)");
        $("a#logoutlink").css({display: "block"});
        $("a#loginlink").css({display: "none"});
        $("a#profilelink").css({display: "block"});
        $("a#registerlink").css({display: "none"});
    } else {
        var lp_cookie = $.cookie('lp_identity');
        if (!lp_cookie)
            return;
        var lp_identity = PHP_Unserialize(lp_cookie);
        if (!lp_identity) 
            return; 
        for (var k in lp_identity) {
            var el = document.getElementById(k);
            if (el)
                el.value = decodeURIComponent(lp_identity[k]).replace(/\+/g," ");
        }
    }
}

$(document).ready(function() {
    $("a#loginlink").click(function() {
        if ($("div#headerlogin").css("display") == "none") {
            if ($.browser.safari) {
                $("div#headerlogin").slideDown("slow");
            } else {
                $("div#headerlogin").fadeIn('slow');
            }
        } else {
            $("div#headerlogin").fadeOut("slow");
        }
        return false;
    });
    $("a#newpassword").click(function() {
        $("form#newpasswordform").toggle()
        return false;
    });
    $("a#hideanon").click(function() {
        if ($("li.anoncomment").css("display") == "none") {
            if ($.browser.safari) {
                $("li.anoncomment").slideDown("slow");
            } else {
                $("li.anoncomment").fadeIn("slow");
            }
            $.cookie('lp_comments','', {expires: -1, path: '/'});
            $("a#hideanon").empty();
            $("#numanon").remove();
            $("a#hideanon").append('Nascondi i commenti anonimi');
        } else {
            numcomments = $('.anoncomment').size();
            if (numcomments == 1) {
                comment_phrase = "1 " + messages["single_comment_hidden"];
            } else {
                comment_phrase = numcomments + messages["plural_comment_hidden"];
            }
            $("li.anoncomment").fadeOut("slow");
            $.cookie('lp_comments','hide', {expires: 30, path: '/'});
            $("a#hideanon").empty();
            $("a#hideanon").append(messages["show_anon_comments"]);
            $("a#hideanon").after("<span id=\"numanon\" style=\"text-transform:lowercase\"> - " + comment_phrase + "</span>");
        }
        return false;
    });
    if ($.cookie('lp_comments') == 'hide') {
        numcomments = $('.anoncomment').size();
        if (numcomments == 1) {
            comment_phrase = "1 " + messages["single_comment_hidden"];
        } else {
            comment_phrase = numcomments + messages["plural_comment_hidden"];
        }
        $("li.anoncomment").css('display', 'none');
        $("a#hideanon").empty();
        $("a#hideanon").append(messages["show_anon_comments"]);
        $("a#hideanon").after("<span id=\"numanon\"> - " + comment_phrase + "</span>");
    }
    $("a.chiudi-etichetta").bind('click',toggle_bloglist);
    $("a.apri-tab").bind('click',toggle_bloglist);
    setUserData();
    rate_init();
});

function toggle_bloglist() {
    //$("div.network-panel").animate({width:'toggle'}, 'fast');
    if ($("div.network-panel div").css("display") == "none") {
        $("div.network-panel div").css('display', 'block');
        $.cookie('lp_bloglist','', {expires: -1, path: '/'});
        return false;
    } else {
        $("div.network-panel div").css('display', 'none');
        $.cookie('lp_bloglist','hide', {expires: 365, path: '/'});
        return false;
    }
}

// Post rating variables
var post_id = 0;
var post_rating = 0;
var ratings_max = 5;
// Comment rating variables
var comment_id = 0;
var rating = 0;
var is_being_rated = false;
var ajax_url = '/ajax/ajax.php';
var site_url = 'http://static.blogo.it/images/stars/';

// Process Ratings
var hover_stars = Array();
function rate_init() {
    $("img.rate-comment").bind('click',submit_rating);
    $("a.s_link").bind('click',submit_rating);
    $("div.post-ratings img").bind('click',submit_rating);
    $("div.post-ratings img").hover(
        function() {
            var rate_img_id = $(this).attr("id").split('-');
            var star_num = rate_img_id[2];
            for (i = 1; i <= star_num; i++) {
                hover_stars[i] = $("img#" + rate_img_id[0] + "-" + rate_img_id[1]+ "-" + i).attr("src");
                $("img#" + rate_img_id[0] + "-" + rate_img_id[1]+ "-" + i).attr("src", site_url + "rating_over.gif");
            }
        },
        function() {
            var rate_img_id = $(this).attr("id").split('-');
            var star_num = rate_img_id[2];
            for (i = 1; i <= star_num; i++)
                $("#" + rate_img_id[0] + "-" + rate_img_id[1]+ "-" + i).attr("src", hover_stars[i]);
        }
    );
}
// Preload img
if (document.images) {
    loading_pic = new Image(16,16);
    loading_pic.src = site_url + "loading.gif";
}

var img_loading = "<img src=\"" + loading_pic.src + "\" width=\"16\" height=\"16\" alt=\"" + messages["now_voting"] + "...\" title=\"" + messages["now_voting"] + "...\" />&nbsp;" + messages["now_voting"] + "...";
var post_rating_content;

function fun_ajax_post(){
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: ajax_url,
            data: "id="+rate_id+"&rate="+rating+"&action=rp",
            beforeSend: function() {
                post_rating_content = $('#post-ratings-' + rate_id).html();
                $('#post-ratings-' + rate_id).html(img_loading);
            },
            success: function(msg) { 
                $('#post-ratings-' + rate_id).html(msg);
            },
            error: function(msg) {
                $('#post-ratings-' + rate_id).html(post_rating_content + msg);
            }
        });
    });
}

function submit_rating(evt) {
    if(!is_being_rated) {
        is_being_rated = true;
        var tmp = evt.target.getAttribute('id');
        var id_split = tmp.split('-');
        var updown = id_split[0];
        rate_id = id_split[1];
        if (updown == 'rcu') {
            what = 'comment';
            rating = 1;
        } else if (updown == 'rcd') {
            what = 'comment';
            rating = -1;
        } else if (updown == 'rtu') {
            what = 'tip';
            rating = 1;
        } else if (updown == 'rp') {
            what = 'post';
            rating = id_split[2];
        } else {
            rating = 0;
        }
        if (!lp_login) {
            pop_login(rate_id, what);
            is_being_rated = false;
            return false;
        }
        if (what == 'comment')
            fun_ajax_comment();
        else if (what == 'post')
            fun_ajax_post();
        else if (what == 'tip')
            fun_ajax_tip();
        is_being_rated = false;
    } else {
        alert(messages["now_voting_error"]);
    }
}

function fun_ajax_comment(){
    var karma = 0;
    var karma_msg = '';
    var result = '';
    var vote_error;
    $.ajax({
        type: "GET",
        url: ajax_url,
        data: "id="+rate_id+"&rate="+rating+"&action=rc",
        beforeSend: function() {
            if ($.browser.safari) {
                $("#ckb_" + rate_id).slideUp("fast");
            } else {
                $("#ckb_" + rate_id).fadeOut("fast");
            }
        },
        success: function(msg) {
            if (isNaN(msg))
                vote_error = true;
            else
                vote_error = false;
            if (vote_error) {
                $("#comment-" + rate_id).prepend("<div class=\"error_vote\">" + messagess['error'] + " - " + msg + "</div>");
            } else {
                karma = parseInt(msg);
                result = msg;
                if (Math.abs(karma) == 1)
                    karma_msg = messages['point'];
                else
                    karma_msg = messages['points'];
            }
        },
        complete: function() {
            if (!vote_error) {
                $('#comment_karma_' + rate_id).html(result);
                $('#comment_karma_text_' + rate_id).html(karma_msg);
                $('#comment-ratings-' + rate_id).fadeOut("fast", setTimeout(function(){$('#comment-ratings-' + rate_id).remove()}, 20));
            }
            if ($.browser.safari) {
                $("#ckb_" + rate_id).slideDown("fast");
            } else {
                $("#ckb_" + rate_id).fadeIn("fast");
            }
        },
        error: function() {
            $("#ckb_" + rate_id).css({color:"red"})
        }
    });
}

function fun_ajax_tip(){
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: ajax_url,
            data: "id="+rate_id+"&rate="+rating+"&action=vt",
            success: function(msg) {
                if (isNaN(msg)) {
                    $("#tip-" + rate_id + " div.s_corpo").prepend("<div class=\"error_vote\">" + messages['error'] + " - " + msg + "</div>");
                } else {
                    
                    $('#tip-ratings-' + rate_id).html(msg);
                }
            },
            complete: function() {
                $('#rtu-' + rate_id).fadeOut("fast", setTimeout(function(){$('#rtu-' + rate_id).remove()}, 20));
            }
        });
    });
}

function pop_login(id, what) {
    if (what == 'post') {
        $("#id" + id + " div.meta").before("<div id=\"pop-login\">" + messages["login_or_register"] + " <a href=\"javascript:unpop_login()\" id=\"close\"><img src=\"http://static.blogo.it/images/cancel.png\" alt=\"chiudi\" /></a></div>");
    } else if (what == 'comment') {
        $("#comment-" + id + " div.comment_head").prepend("<div id=\"pop-login-comment\">" + messages['login_or_register'] + " <a href=\"javascript:unpop_login()\" id=\"close\"><img src=\"http://static.blogo.it/images/cancel.png\" alt=\"chiudi\" /></a></p></div>");
    }
}

var open_vids = new Array();
function pop_video(tip_id, embed_code) {
    if (!open_vids[tip_id]) {
        $("#tip-" + tip_id + " span.s_url").prepend("<div class=\"s_video\">" + decodeURIComponent(embed_code) + "</div>");
        open_vids[tip_id] = true;
    } else {
        $("#tip-" + tip_id + " div.s_video").remove();
        open_vids[tip_id] = false;
    }
}

function unpop_login(what) { $("#pop-login").remove(); }

// Process Comment Queue
function queue_comment(id) {
    comment_id = id;
    fun_ajax_comment_queue();
}

function fun_ajax_comment_queue(){
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: ajax_url,
            data: "id="+comment_id+"&action=qc",
            success: function(msg){
                $('#comment-' + comment_id).fadeOut("slow", function() {
                        $('#comment-' + comment_id).remove();
                    });
            }

        });
    });
}

function pop_login_comment(comment_id) {
    $("#comment-" + comment_id).append("<div id=\"pop-login-comment\"><div><p>" + messages["login_or_register"] + " <a href=\"javascript:unpop_login_comment()\" id=\"close\"><img src=\"http://static.blogo.it/images/cancel.png\" alt=\"chiudi\" /></a></p></div>");
}

function unpop_login_comment() { $("#pop-login-comment").remove(); }

function show_comment(comment_id) {
    $('#comment-' + comment_id + "-alt").fadeOut("slow", function() {
        $("#comment-" + comment_id).fadeIn("slow")
    });
}
function hide_comment(comment_id) {
    $('#comment-' + comment_id).fadeOut("slow", function() {
        $("#comment-" + comment_id + "-alt").fadeIn("slow")
    });
}

// Share this - adapted from Alex King's Share this plugin
function akst_share(id, url, title) {
    var form = $("div#akst_form");
    if ($("div#akst_form").css("display") == "block" && post_id.value == id) {
        $("div#akst_form").css("display", "none");
        return;
    }
    
    var link = $('akst_link_' + id);
    var obj = document.getElementById('akst_link_' + id);
    var offset = findPos(obj);

    $("#akst_delicious").attr("href", akst_share_url("http://del.icio.us/post?url={url}&title={title}", url, title));
	$("#akst_mailaction").attr("action", url + "#add_comment");
	$("#akst_oknotizie").attr("href", akst_share_url("http://oknotizie.alice.it/post?url={url}&title={title}", url, title));
    $("#akst_segnalo").attr("href", akst_share_url("http://segnalo.alice.it/post.html.php?url={url}&title={title}", url, title));
    $("#akst_digg").attr("href", akst_share_url("http://digg.com/submit?phase=2&url={url}&title={title}", url, title));
    $("#akst_stumble").attr("href", akst_share_url("http://www.stumbleupon.com/submit?url={url}&title={title}", url, title));
    $("#akst_furl").attr("href", akst_share_url("http://furl.net/storeIt.jsp?u={url}&t={title}", url, title));
    $("#akst_netscape").attr("href", akst_share_url("http://www.netscape.com/submit/?U={url}&T={title}", url, title));
    $("#akst_yahoo_myweb").attr("href", akst_share_url("http://myweb2.search.yahoo.com/myresults/bookmarklet?u={url}&t={title}", url, title));
    $("#akst_google_bmarks").attr("href", akst_share_url("http://www.google.com/bookmarks/mark?op=edit&bkmk={url}&title={title}", url, title));
    $("#akst_reddit").attr("href", akst_share_url("http://reddit.com/submit?url={url}&title={title}", url, title));

    post_id.value = id;

    $("div#akst_form").css({left : (offset[0] + 16) + "px", top : (offset[1] - 150) + "px"});
    $("div#akst_form").css("display", "block");
}

function akst_share_url(base, url, title) {
    base = base.replace('{url}', url);
    return base.replace('{title}', title);
}

function akst_share_tab(tab) {
    var tab1 = document.getElementById('akst_tab1');
    var tab2 = document.getElementById('akst_tab2');
    var body1 = document.getElementById('akst_social');
    var body2 = document.getElementById('akst_email');
    
    switch (tab) {
        case '1':
            tab2.className = '';
            tab1.className = 'selected';
            body2.style.display = 'none';
            body1.style.display = 'block';
            break;
        case '2':
            tab1.className = '';
            tab2.className = 'selected';
            body1.style.display = 'none';
            body2.style.display = 'block';
            break;
    }
}

function akst_xy(id) {
    var element = $(id);
    var x = 0;
    var y = 0;
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}
