var ajaximg;
var redaktejo = false;

$(document).ready(function() {
    installTooltips();
    installTabs();
    if($.browser.msie && $.browser.version=="6.0") installMenu();

    ajaximg = '/img/ajax-loader.gif';
    $.AjaxifyDefaults.loading_txt = 'Atendu...';
    $.AjaxifyDefaults.loading_img = ajaximg;
    $.jGrowl.defaults.closerTemplate = '<div>[fermi ĉion]</div>';
    $.jGrowl.defaults.position = 'bottom-right';
    $.jGrowl.defaults.life = 10000;

    $("a[href^='http']").each(function (i) {
        $(this).attr('target','_blank');
        if ($("img", $(this)).length > 0) {
        } else {
        	$(this).addClass('external');
        }
    });

    $('a.ajax_bildo').live('mouseover', function() {
        $(this).fancybox({'autoDimensions' : false, 'titleShow' : true, 'titleFormat' : formatTitle, 'titlePosition': 'inside' });
        return false;
    });
    
    $('.aktualepedio').live('click', function() {
    	if ($(this).hasClass("fenestrido") || $(this).parent().hasClass("fenestrido")) {
	        aSendiDatumojn($(this).attr("rel"), true);
	    } else
		    aSendiDatumojn($(this).attr("rel")); 
        return false;
    });

    $('a.ajax_sendo').live('mouseover', function() {
        $(this).fancybox({'autoDimensions' : true, 'titleShow' : false,  'autoScale' : true, 'width' : 750, 'height' : 550, 'centerOnScroll': false });
        return false;
    });
});

function formatTitle(title, currentArray, currentIndex, currentOpts) {
	return $(currentArray[currentIndex]).parent().find(".imgCaption").html();
}

function installTooltips() {
    $('a').tooltip({
        showURL: false,
        track: true,
        delay: 0
    });
    $('.tooltip').tooltip({
        showURL: false,
        track: true,
        delay: 0
    });
}

function flag(id) {
    var code = $('#'+id).val().toLowerCase();
    var celo = id + '_flag';
    enmetiFlagon(id, code, celo);
}

function enmetiFlagon(id, code, celo) {
    if (code == "") {
        $('#'+ id + '_flag').css('background-position', '0 0');
        $('#'+ id + '_flag').hide();
    } else {
        $('#'+ id + '_flag').show();
        var x = (code.toUpperCase().charCodeAt(0) - 65) * 16;
        var y = (code.toUpperCase().charCodeAt(1) - 65) * 11;
        $('#'+ celo).css('background-position', '-'+ x + 'px '+ '-' + y + 'px');
    }
}

function installTabs() {
    $(".tabs li").each(function (i) {
        this.onclick = function() {
            makeActive(this);
        }
    });
}

function makeActive(d) {
    $(".tabs li").each(function () {
        $(this).removeClass('active');
        $(this.id).hide();
    });
    $(d).addClass('active');
    $(d.id).show();
}

function installMenu() {
    $(".dropmenu li").each(function (i) {
        this.onmouseover = function() {
            $(this).addClass('hover');
        }
        this.onmouseout = function() {
            $(this).removeClass('hover');
        }
    });
}

function addAdv(url) {
    var iframe = $('<iframe id="reklamo" scrolling="no" height="90" style="left: 0; position: absolute; top: 0;" frameborder="0" width="728" vspace="0" src="' + url + '" name="" marginwidth="0" marginheight="0" hspace="0" allowtransparency="true"></iframe>');
    $('#adv').html(iframe);
}

function strim(s, t) {
	var l=0; var r=s.length -1;
	while(l < s.length && s[l] == t) {	l++; }
	while(r > l && s[r] == t) {	r-=1;	}
	return s.substring(l, r+1);
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function unloadAction(d) {
    window.onbeforeunload = function(e) {
        if (d != null) return d;
    }
}

function setUnloadMessage(q, a) {
    $(q).bind("change", function(e){
        $(q).unbind("change");
        unloadAction(a);
    });
}

function prilaboriEtikedujon(celo, etikedujo) {
    $('span', etikedujo).click(
        function(e) {
            var val = $(this).text();
            $("option", celo).each(function() {
                if ($(this).text() == val) {
                    var d = $(this).val();
                    $(celo).trigger("addItem",[{"title": val, "value": d}]);
                    return;
                }
            });
        }
    );
}

function multipleSelect(id) {
    $('#' + id + '_listo').html("");
    var teksto = "";
    $('#'+id+' :selected').each(function(i, selected){ 
        teksto += $(selected).text() + "<br />"; 
    });
    $('#' + id + '_listo').html('<small>'+teksto+'</small>');
}

function dosierujo_montriSpecojn(id, celo) {
    var marko = $('#'+id).val();

    $('#' + celo).find('option').remove();
    $('#' + celo + '_ekzemplo option').each(function(){
        if ($(this).attr("name") == celo + '_' + marko) {
            $('#' + celo).append($(this).clone());
        }
        $(this).attr('selected', false);
    });
}

function deleteEmptyItemsFromForm(id) {
    $('#'+id).find('input, select, textarea').each(function() {
        if ($(this).val() == '' || $(this).attr("type") == 'submit') {
            $(this).attr("disabled", true);
        }
    });
}

function montriDosierujon() {
    $.fancybox({ 'href': '/eo/ext/dosierujo', 'type':'iframe', 'autoDimensions': false, 'width' : 850, 'height' : 500, 'centerOnScroll': false });
}

function montriAktualepedion() {
    $.fancybox({ 'href': '/eo/ext/aktualepedio?serchilo=1', 'autoDimensions': false, 'width' : 350, 'centerOnScroll': false });
}

function lanchiAktualepedion(r) {
	if (r) redaktejo = true;
	$("#aktualepedioInput").autocomplete("/ext/aktualepedio", {}).result(function(event, data, formatted){if (data) aSendiDatumojn(data[1]);});
}

function aSendiDatumojn(v, r) {
	var plena = 0;
	var url = "/ext/aktualepedio?v=" + v + "&plena=" + plena;
	if (redaktejo) {
		plena = 1;
		url = "/eo/ext/aktualepedio?v=" + v + "&plena=" + plena;
	}
    $.ajax({
      url: url,
      dataType: "json",
      success: function(data) {
      	var akt = $('#aktualepedioResult');
      	if (akt.length) {
	        akt.slideUp('fast', function() {
	            $("#aktualepedioText").hide();
	            akt.html(data.teksto);
	            $("#aktualepedioInput").val(data.plena);
	            $("#aktualepedioButton").show();
	            akt.slideDown('fast', function() {
	            	if (r) {
                        $.fancybox({'content': '<div class="fenestrido">' + data.teksto + '</div>', 'autoDimensions' : false, 'titleShow' : false,  'width' : 350, 'height': 'auto' });
				   	}
	            });
	        });
        } else {
			if (r) {
				$.fancybox({'content': '<div class="fenestrido">' + data.teksto + '</div>', 'autoDimensions' : false, 'titleShow' : false,  'width' : 350, 'height': 'auto' });
            }
        }
      }
    });
}

function aNuligiRezultojn() {
    $('#aktualepedioResult').slideUp('fast', function() {
        $('#aktualepedioResult').html('');
        $('#aktualepedioInput').val('');
        $('#aktualepedioText').slideDown('fast', function() {});
        $("#aktualepedioButton").hide();
    });
}
