document.write('<script type="text/javascript" src="/js/jquery/js/plugins/jquery.cookie.js"></script>');
document.write('<script type="text/javascript" src="/js/cleditor/jquery.cleditor.js"></script>');
document.write('<script type="text/javascript" src="/js/sexybookmarks.js"></script>');
document.write('<script type="text/javascript" src="/js/fullsize/jquery.fullsize.js"></script>');
document.write('<script type="text/javascript" src="/js/jquery/js/plugins/jquery.livequery.js"></script>');
document.write('<script type="text/javascript" src="/js/jquery/js/plugins/jquery-ui-1.8.2.custom.min.js"></script>');

var loader = '<span class="loader"><img src="/gfx/loading.gif" /></span>';
var cleditor;
var bubbleDelay = 4000;
var ref = -1;

function loading(name)
{
    $('input[name=' + name + ']').hide().parent().append(loader);
}

function complete(name)
{
    $('input[name=' + name + ']').show().parent().find('.loader').remove();
}

function vote(item_id, rate)
{
    var id = $("#item-" + item_id);
    var bubble =  $(id).find('.objectVote .bubbleWrapper');
    $(id).find('.bubbleWrapper').hide();

    jQuery.ajax
    ({
        type: 'post',
        url: '/item/vote/item_id/' + item_id + '/rate/' + rate,
        beforeSend: function()
        {
            $(id).find(".objectVote div.rateLoader").show().html(loader + " ocenianie...");
        },
        success: function(data, textStatus)
        {
            $(id).find(".objectVote div.rateLoader").hide();
            $(bubble).fadeIn(200);
            if (data == 0)
            {
                $(bubble).addClass("redBubble").delay(bubbleDelay).fadeOut(200).find(".bubble").html('Zaloguj się, aby ocenić zapytę.');
                return 0;
            }

            if (data == -1)
            {
                $(bubble).addClass("redBubble").delay(bubbleDelay).fadeOut(200).find(".bubble").html('Oddałeś już głos na tą zapytę.');
                return -1;
            }

            if (data == -2)
            {
                $(bubble).addClass("redBubble").delay(bubbleDelay).fadeOut(200).find(".bubble").html("Nie możesz oddać głosu na swoją zapytę!");
                return -2;
            }

            eval("var result = " + data)
            $(id).find(".votes_ayes").text(result.votes_ayes);
            $(id).find(".votes").text(result.votes);
            $(bubble).addClass('greenBubble').delay(bubbleDelay).fadeOut(200).find(".bubble").html("Dziękujemy! Głos został oddany.");
        }
    });
}

function add2favorites(item_id)
{
    var id = $("#item-" + item_id);
    var bubble =  $(id).find('.objectFav .bubbleWrapper');
    $(id).find('.bubbleWrapper').hide();

    jQuery.ajax
    ({
        type: 'post',
        url: '/favorite/add/item_id/' + item_id,
        beforeSend: function()
        {
            $(id).find(".fav").removeClass('fav_add').addClass('objectLoader').html(loader);
        },
        success: function(data, textStatus)
        {
            $(bubble).fadeIn(300);
            $(id).find(".fav").removeClass("objectLoader").addClass("fav_add").empty();
            if (data == 0)
            {
                $(bubble).delay(bubbleDelay).fadeOut(200).find(".bubble").html('Zaloguj się, aby dodać do ulubionych.');

                return 0;
            }

            if (data == -1)
            {
                $(bubble).addClass("redBubble").delay(bubbleDelay).fadeOut(200).find(".bubble").html('Ta zapyta znajduje się już na Twojej liście ulubionych.');
                
                return -1;
            }

            $(bubble).addClass('greenBubble').delay(bubbleDelay).fadeOut(200).find(".bubble").html("Zapyta została dodana do Twojej listy ulubionych.");
        }
    });
}

function deleteFromFavorites(item_id)
{
    var id = $("#item-" + item_id);
    var bubble =  $(id).find('.objectFav .bubbleWrapper');
    $(id).find('.bubbleWrapper').hide();

    jQuery.ajax
    ({
        type: 'post',
        url: '/favorite/delete/item_id/' + item_id,
        beforeSend: function()
        {
            $(id).find(".fav").removeClass('fav_delete').addClass('objectLoader').html(loader);
        },
        success: function(data, textStatus)
        {
            $(bubble).fadeIn(300);
            $(id).find(".fav").removeClass("objectLoader").addClass("fav_delete").empty();
            $(bubble).addClass('greenBubble').delay(bubbleDelay).fadeOut(200).find(".bubble").html("Zapyta została usunięta z Twojej listy ulubionych.");
        }
    });
}

function encodeBase64(input)
{
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    do
    {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2))
            enc3 = enc4 = 64;
        else if (isNaN(chr3))
            enc4 = 64;

        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

    }
    while (i < input.length);

    return output;
}

function addRefLink(adplace, id)
{
    var reflink = false;

    if (ref == -1)
        ref = $.cookie('ref');

    if (adplace == "null" && ref != null)
    {
        reflink = '?utm_source=zapyty.pl&utm_medium=' + ref;
    }
    else if (adplace != "null")
    {
        if (ref != null)
            reflink = "wr/" + encodeBase64(adplace + "." + ref);
        else
            reflink = "wr/" + encodeBase64(adplace);
    }

    if (reflink)
        $(id).attr('href', $(id).attr('href') + reflink);
}

$(document).ready(function()
{
    $(".input_advice").focus(function()
    {
        $(this).parents('.row').find('.focusBubble').show();
    });

    $(".input_advice").focusout(function()
    {
        $(this).parents('.row').find('.focusBubble').hide();
    });

    $(".visual").cleditor
    ({
          width:        350,
          height:       150,
          controls:     "bold italic underline",
          useCSS:       false, // use CSS to style HTML when possible (not supported in ie)
          docCSSFile:   "", // CSS file used to style the document contained within the editor.
          bodyStyle:    "margin:4px; font:10pt Arial,Verdana; cursor:text"
    })

    cleditor = $(".cleditor-comment").cleditor
    ({
          width:        450,
          height:       100,
          controls:     "bold italic underline",
          useCSS:       false, // use CSS to style HTML when possible (not supported in ie)
          docCSSFile:   "", // CSS file used to style the document contained within the editor.
          bodyStyle:    "margin:4px; font:10pt Arial,Verdana; cursor:text"
    })[0];

    $('#smiley img').click(function()
    {
        var img = $(this);
        cleditor.execCommand('insertimage', img.attr('src'));
        return false;
    });

    $("#facebook_widget").hover(function()
    {
        $("#facebook_widget").stop(true, false).animate({right:"0"}, "medium");
    },function()
    {
        $("#facebook_widget").stop(true, false).animate({right:"-238"}, "medium");
    },500);

    $('#itemTypeSelect').hover
    (
        function() {$('ul', this).css('display', 'block');},
        function() {$('ul', this).css('display', 'none');}
    );

    $('#pageMenu a').hover
    (
        function() {$(this).parent().addClass('menuElementHover');},
        function() {$(this).parent().removeClass('menuElementHover');}
    );

    $('.element .image').each(function()
    {
        if($(this).attr('width') == 750)
        {
            var src = $(this).attr("src");
            $(this).attr('longdesc', src.substring(0, src.length - 9) + "full.jpg");
            $(this).fullsize({shadow: true});
        }         
    });

    $('#contestHideInfo').click(function()
    {
        $.cookie("hide_contest_info", "1", {expires: 3});
        $(this).parent().fadeOut();
    });

    $('.adlink').livequery(function()
    {
        $(this).each(function()
        {
            var adplace = $(this).attr('class').match(/adplace:([a-z_]+)/);

            addRefLink(adplace[1], $(this));
        });
    });

    var height = 0;
    $('.related h3 a').each(function()
    {
        if (height < $(this).height())
            height = $(this).height();
    });

    $('.related h3 a').height(height);

    $('.commentDelete').click(function()
    {
        if (!confirm('Czy napewno chcesz usunąć ten komentarz?'))
            return false;
        
        var comment = $(this).parents('.comment');

        $.post('/comment/delete', 'id=' + comment.attr('id').match(/[0-9]+/), function(data)
        {
            comment.find('.commentMainBodyWrapper').html('<div align="center">Komentarz został usunięty.</div>');
            setTimeout(function() {comment.fadeOut()}, 2000);
        });
    });
});
