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);
    var webstring = '';
    if (ws.searchtype[1].checked) {
        webstring = '?web';
    }
    location.href = 'http://' + location.hostname + '/live/' + encodeURIComponent(k) + webstring;
}
function search_blogo_get() {
    k = document.getElementById('search_keywords').value;
    location.href = 'http://' + location.hostname + '/cerca/' + escape(k); //.replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

//external link tracking

function cs_isExternalLink(url){
  if(!url){ return false; }
  if(typeof(url) != 'string'){ return true; }
  url = url.toLowerCase();

  /* what else is missing from the protocol list below? */
  if(url.indexOf('https://') == 0){ url = url.substring(8); }
  else if(url.indexOf('http://') == 0){ url = url.substring(7); }
  else if(url.indexOf('ftp://') == 0){ url = url.substring(6); }
  else if(url.indexOf('ssl://') == 0){ url = url.substring(6); }
  else if(url.indexOf('mailto:') == 0){ return true; }
  else{ return false; }

  if(url.indexOf('www.') == 0){ url = url.substring(4); }
  var hn = document.location.hostname.toLowerCase();
  if(hn.indexOf('www.') == 0){ hn = hn.substring(4); }

  if(url.indexOf(hn) != 0){ return true; }
  return false;
}
function cs_getParentClickable(obj, flag){
  for(var j=0; j<=5; j++){
    if(flag == 1){ if(obj && obj.nodeName.toUpperCase() == 'A'){ return obj; } } //look for <A> tag
    if(flag == 2){ if(obj && obj.nodeName.toUpperCase() != 'BODY' && obj.onclick){ return obj; } } //look onclick tag
    obj = obj.parentNode;
  }
  return null;
}
function cs_context_click(e){//right click on link
  var tg = null;
  if(e){ tg = e.target; }
  else{ tg = window.event.srcElement; }
  cs_do_track(tg, false);
}
function cs_on_click(e){//left click
  var tg = null;
  if(e){ tg = e.target; }
  else{ tg = window.event.srcElement; }
  cs_do_track(tg, true);
}
function cs_do_track(tg, delay){
  var url = null;
  var text = null;
  try{
    if(tg){
      tgP = cs_getParentClickable(tg, 1);
      if(tgP && tgP.nodeName.toUpperCase() == 'A'){ tg = tgP; }

      if(tg.nodeName.toUpperCase() == 'A'){//A tag - most popular case
        url = tg.href;
        if(tg.innerHTML){ text = tg.innerHTML; } //most browsers
        else if(tg.innerText){ text = tg.innerText; } //ie only
        else if(tg.text){ text = tg.text; } //mozilla only
        else{}
      }else if(tg.nodeName.toUpperCase() == 'INPUT' && tg.type.toUpperCase() == 'SUBMIT'){//form submit button
        url = tg.form.action;
        text = tg.value;
      }else{
       /* this eliminates all other onclick events */

      }
      if(url == null || text == null){ return true; } //both url and text must not be NULL

      if(cs_isExternalLink(url)){
        url = escape(url);
        text = escape(text);
        cs_track_oc(text, url, delay);
      }
    }
  }catch(err){ }
}
// THIS FUNCTION TRACKS EXTERNAL URL CLICKS //
function cs_track_oc(text, url, delay){
  try{
    var now = new Date();
    var trackURL = t_url + '?u=' + url + '&t=' + text + '&i=' + b_ID + '&n=' + now.valueOf();
    var x = new Image();
    x.src = trackURL;
    if(delay){ cs_pause(900); }
  }catch(err){ }
}
function cs_pause(numberMillis) {
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while(true){
    now = new Date();
    if(now.getTime() > exitTime){ return; }
  }
}

function ReadCookie(name) {
    var cookie = "" + document.cookie;
    var i = cookie.indexOf(name);
    if (i==-1 || name=="")
        return; 
    var j = cookie.indexOf(';', i);
    if (j==-1)
        j = cookie.length; 
    return unescape(cookie.substring(i + name.length + 1, j));
}

var lp_login;

function setUserData() {
    lp_login = ReadCookie('lp_login');
    if (lp_login) {
        var username = lp_login.split(",")[0];
        $("ol#commentuserfields").empty();
        $("p#registerp").remove();
        $("ol#commentuserfields").append("<li>Nickname: " + username.replace(/\+/g," ") + " (<a href=\"/user/profile\">Profilo</a>)</li>");
        $("a#logoutlink").css({display: "block"});
        $("a#loginlink").css({display: "none"});
        $("a#profilelink").css({display: "block"});
        $("a#registerlink").css({display: "none"});
    } else {
        var lp_cookie = ReadCookie('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 commento anonimo nascosto";
            } else {
                comment_phrase = numcomments + " commenti anonimi nascosti";
            }
            $("li.anoncomment").fadeOut("slow");
            $.cookie('lp_comments','hide', {expires: 30, path: '/'});
            $("a#hideanon").empty();
            $("a#hideanon").append('Mostra i commenti anonimi');
            $("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 commento anonimo nascosto";
        } else {
            comment_phrase = numcomments + " commenti anonimi nascosti";
        }
        $("li.anoncomment").hide();
        $("a#hideanon").empty();
        $("a#hideanon").append('Mostra i commenti anonimi');
        $("a#hideanon").after("<span id=\"numanon\"> - " + numcomments + " commenti anonimi nascosti</span>");
    }
    setUserData();
    rate_comment_init();
});

var t_url = 'http://www.blogo.it/track.php';
if(document.body){//if the script is inside the body tag - which it should be
  document.body.onclick = cs_on_click;
  document.body.oncontextmenu = cs_context_click;
}else if(document){//script is outside the body tag - works in some browsers
  document.onclick = cs_on_click;
  document.oncontextmenu = cs_context_click;
}else{}


// Post rating variables
var post_id = 0;
var post_rating = 0;
var ratings_max = 5;
// Comment rating variables
var comment_id = 0;
var comment_rating = 0;
var rate_fadein_opacity = 0;
var rate_fadeout_opacity = 100;
var is_ie = (document.all && document.getElementById);
var is_moz = (!document.all && document.getElementById);
var is_opera = (navigator.userAgent.indexOf("Opera") > -1);
var is_being_rated = false;
var ajax_url = '/ajax/ajax.php';
var site_url = 'http://static-a.blogo.it/images/stars/';
var ratings_mouseover_image = new Image();
ratings_mouseover_image.src = site_url + 'rating_over.gif'

// Rating Post Fade In Text
function rade_fadein_text() {
    if(rate_fadein_opacity < 100) {
        rate_fadein_opacity += 10;
        if(is_opera)  {
            rate_fadein_opacity = 100;
        } else   if(is_ie) {
            document.getElementById('post-ratings-' + post_id).filters.alpha.opacity = rate_fadein_opacity;
        } else   if(is_moz) {
            document.getElementById('post-ratings-' + post_id).style.MozOpacity = (rate_fadein_opacity/100);
        }
        setTimeout("rade_fadein_text()", 100); 
    } else {
        rate_fadein_opacity = 0;
        rate_unloading_text();
        is_being_rated = false;
    }
}

// Mouse over ratings
function current_rating(id, rating) {
    if(!is_being_rated) {
        post_id = id;
        post_rating = rating;
        for(i = 1; i <= rating; i++) {
            document.images['rating_' + post_id + '_' + i].     src = eval("ratings_mouseover_image.src");
        }
    }
}

// Mouse out from ratings
function ratings_off(rating_score, insert_half) {
    if(!is_being_rated) {
        for(i = 1; i <= ratings_max; i++) {
            if(i <= rating_score) {
                document.images['rating_' + post_id + '_' + i].src = site_url + 'rating_on.gif';
            } else if(i == insert_half) {
                document.images['rating_' + post_id + '_' + i].src = site_url + 'rating_half.gif';
            } else {
                document.images['rating_' + post_id + '_' + i].src = site_url + 'rating_off.gif';
            }
        }
    }
}

// Post Ratings Loading Text
function rate_loading_text() {
    document.getElementById('post-ratings-' + post_id + '-loading').style.display = 'inline';
}

// Post Ratings Finish Loading Text
function rate_unloading_text() {
    document.getElementById('post-ratings-' + post_id + '-loading').style.display = 'none';
}

// Process Post Ratings
function rate_post() {    
    if(!is_being_rated) {
        is_being_rated = true;
        rate_loading_text();
        rate_process(); 
    } else {
        alert('Per favore, vota un solo post per volta');
    }
}

// Process Post Ratings
function rate_process() {
    if(rate_fadeout_opacity > 0) {
        rate_fadeout_opacity -= 10;
        if(is_opera) {
            rate_fadein_opacity = 0;
        } else if(is_ie) {
            document.getElementById('post-ratings-' + post_id).filters.alpha.opacity = rate_fadeout_opacity;
        } else if(is_moz) {
            document.getElementById('post-ratings-' + post_id).style.MozOpacity = (rate_fadeout_opacity/100);
        }
        setTimeout("rate_process()", 100); 
    } else {
        rate_fadeout_opacity = 0;       
        fun_ajax();
        rade_fadein_text();
        rate_fadein_opacity = 0;
        rate_fadeout_opacity = 100;
        is_being_rated = false;
    }
}

function fun_ajax(){
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: ajax_url,
            data: "id="+post_id+"&rate="+post_rating+"&action=rp",
            success: function(msg){
            $('#post-ratings-' + post_id).html(msg);
            }

        });
    });
}

// Process Comment Ratings

function rate_comment_init() {
    $("div.comment-ratings/img.rate-comment").bind('click',submit_rating);
}

function submit_rating(evt) {
    if(!is_being_rated) {
        is_being_rated = true;
        var tmp = evt.target.getAttribute('id');
        var updown = tmp.substr(0,tmp.indexOf('-'));
        comment_id = tmp.substr(tmp.indexOf('-') + 1);
        if (!lp_login) {
            pop_login_comment(comment_id);
            is_being_rated = false;
            return false;
        }
        if (updown == 'rcu')
            comment_rating = 1;
        else if (updown == 'rcd')
            comment_rating = -1;
        else
            comment_rating = 0;
        fun_ajax_comment();
        is_being_rated = false;
    } else {
        alert('Per favore, vota un solo commento per volta.');
    }
}

function fun_ajax_comment(){
    var karma = 0;
    var karma_msg = '';
    var rating = '';
    $.ajax({
        type: "GET",
        url: ajax_url,
        data: "id="+comment_id+"&rate="+comment_rating+"&action=rc",
        beforeSend: function() {
            if ($.browser.safari) {
                $("#ckb_" + comment_id).slideUp("fast");
            } else {
                $("#ckb_" + comment_id).fadeOut("fast");
            }
        },
        success: function(msg) {
            karma = parseInt(msg);
            rating = msg;
            if (Math.abs(karma) == 1)
                karma_msg = "punto";
            else
                karma_msg = "punti";
        },
        complete: function() {
            $('#comment_karma_' + comment_id).html(rating);
            $('#comment_karma_text_' + comment_id).html(karma_msg);
            $('#comment-ratings-' + comment_id).fadeOut("fast", setTimeout(function(){$('#comment-ratings-' + comment_id).remove()}, 20));
            if ($.browser.safari) {
                $("#ckb_" + comment_id).slideDown("fast");
            } else {
                $("#ckb_" + comment_id).fadeIn("fast");
            }
        },
        error: function() {
            $("#ckb_" + comment_id).css({color:"red"})
        }
    });
}

function pop_login(post_id) {
    $("#post-id" + post_id).append("<div id=\"pop-login\"><div><p>Vota anche tu! <a href=\"/user/registration\">Registrati</a> o fai la <a href=\"/user/login\">login</a> <a href=\"javascript:unpop_login()\" id=\"close\"><img src=\"http://static.blogo.it/images/cancel.png\" alt=\"chiudi\" /></a></p></div>");
}

function unpop_login() {
    $("#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>Vota anche tu! <a href=\"/user/registration\">Registrati</a> o fai la <a href=\"/user/login\">login</a> <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();
}

