/**
 *		o2.pl Spolka z o.o.
 *		Copyright (c) o2.pl Spolka z o.o.
 *		http://www.o2.pl/
 *
 *		Created by:
 *			@author		Gabor Wnuk <gabor.wnuk@firma.o2.pl>
 *			@date		2007-07-23, 10:16:58
 *			@package	RADAR.pl
 */

var boolConstructed = false;

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, "");
}

jQuery.fn.extend (
{
    fadeToggle: function(speed, callback)
    {
        return this.each(function()
        {
            var state = jQuery(this).is(":hidden") ? "show" : "hide";
            jQuery(this).animate({
                opacity: state
            }, speed, callback);
        });
    }
});

jQuery.fn.exists = function(){return jQuery(this).length>0;}

function showVideoPlayer(title, url) {

        $('#video_player').html('');
        $('<b>' +  title + '</b><br />\n\
    <object width="425" height="350">\n\
    <param name="movie" value="'+url+'&autoplay=0"></param>\n\
    <param name="wmode" value="transparent"></param>\n\
    <embed src="'+url+'&autoplay=1" type="application/x-shockwave-flash" wmode="transparent" width=425" height="350">\n\
    </embed>\n\
    </object>').appendTo('#video_player');
}

function showAjaxLoader($) {

    $('#videos').html('');
    $('<div class="loader"><p>Proszę czekać...</p><img src="/design/design_gif/ajax-loader.gif" alt="Wczywywanie..." /></div>')
    .appendTo('#videos');

}

$(document).ready(function()
{

    if ($('#videos').exists()) {
        
        showAjaxLoader($);

        var searchQuery1 = $('.product_details h1').text();
        $.ajax({
            type: 'GET',
            url: '/video-search',
            data: {
                search_query: searchQuery1
            },
            dataType: 'html',
            success: function(response) {
                $('#videos').html(response);
                if ($('#videos #video-list li').size() == 0) {
                    $('#videos').parent().hide();
                }
            }
        });

        $('#videos').click(function(event) {
            event.preventDefault();
            var $target = $(event.target);

            if ($target.is('a.thumbnail img')) {
                var title = $('input.video-title', $target.parent().parent()).val();
                var url   = $('input.video-url', $target.parent().parent()).val();

                showVideoPlayer(title, url);
            }
        });

        $('#photo-list').click(function(event) {
            event.preventDefault();
            var $target = $(event.target);

            if ($target.is('img')) {
                var url    = $('input.photo-url', $target.parent().parent()).val();
                var width  = $('input.photo-width', $target.parent().parent()).val();
                var height = $('input.photo-height', $target.parent().parent()).val();

                var scale = '';
                if (width > 425) {
                    scale += ' width=425" ';
                }
                if (height > 350) {
                    scale += ' height="350" ';
                }
                
                $('#photo-preview')
                    .html($('<img src="' + url + '" ' + scale + ' alt="Zdjęcie" />'));
            }
        });
    }

    $('#stringQuery').autocomplete(
        '/podpowiedzi/',
        //                            'http://www.radar.pl/podpowiedzi/',
        //                            'http://lkrzysiak.radar.pl/podpowiedzi/',
        {
            minChars: 2,
            max: 15,
            selectFirst: false,
            formatItem: function(row) {
                var result = '<div style="float:left">' + row[0] + '</div>';

                return result;
            }
        }
        ).focus();

        $('#tabs-control li a').click(function(e) {
            e.preventDefault();
            var tabId = $(this).attr('href');
            $('div.tab').hide();
            var tab = document.getElementById(tabId);
            $(tab).show();
            $(this).parent().addClass('tab-active').siblings('li').removeClass('tab-active');
        })

//        $('#popular_products_tabs').tabs();



//    $('.product_image a[rel=lightbox]').lightBox({
//        fixedNavigation:true,
//        txtImage: '',
//        txtOf: '',
//        imageBtnClose: '/design/design_gif/zamknij.gif',
//        containerResizeSpeed: 200,
////        containerBorderSize: 40,
//        overlayOpacity: 0.4
//
//    });

 /* powiadom znajomego */
        var content = $("#email_content"),
        email = $("#email_address"),
        allFields = $([]).add(content).add(email),
        tips = $("#validateTips");

        $("#send_email_dialog").dialog({
            bgiframe: true,
            title: "Poleć ten produkt",
            autoOpen: false,
            width: 570,
            height: 390,
            modal: true,
            buttons: {
                'Wyślij': function() {
                    var bValid = true;
                    allFields.removeClass('ui-state-error');

                    bValid = bValid && checkLength(content,"content",4,1600);
                    bValid = bValid && checkLength(email,"email",6,80);

                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");

                    if (bValid) {
                        
                        $.ajax({
                           type: "POST",
                           url: "/wyslij-email/",
                           dataType: 'json',
                           data: {
                               url: $('#product_url').val(),
                               name: $('#product_name').val(),
                               email: $('#email_address').val(),
                               content: $('#email_content').val(),
                               word: $('#word_2').val()
                           },
                           success: function(response) {
                               if (response.status == true) {
                                   var sMessage = 'Wiadomość wysłana pomyślnie.<br />';
                                   $('#email_status').removeClass('message-box-error').addClass('message-box-ok');
                               }
                               else {
                                   $('#email_status').removeClass('message-box-ok').addClass('message-box-error');
                                   var sMessage = 'Wystąpił błąd.<br />';
                                   
                                   if (response.captcha_ok != true) {
                                       sMessage += 'Niepoprawny kod z obrazka.<br />';
                                   }
                               }
                               $('#email_status').html(sMessage).show();
                                $("#send_email_dialog").css('height' , '320px' );
                           }
                        });
//                        $(this).dialog('close');
                    }
                },
                'Anuluj': function() {
                    $(this).dialog('close');
                }
            },
            close: function() {
                allFields.val('').removeClass('ui-state-error');
            }
        });

        $('#mail_a_friend').click(function(e) {
            e.preventDefault();
            
            $('#send_email_dialog').dialog('open');
        });
         /* koniec powiadom znajomego */

         /* zgłoś błędną ofertę */

         $('#problem_type').change(function(e) {
             if ($(this).children('[selected]').val() == 'other') {
                 $('#report_description').show();
             }
             else {
                 $('#report_description').hide();
             }
         });
         
        $("#report_invalid_offer_dialog").dialog({
            bgiframe: true,
            title: "Zgłoś problem z ofertą",
            autoOpen: false,
            width: 450,
            height: 230,
            modal: true,
            buttons: {
                'Wyślij': function() {

                    var iProductId  = $('#product-id').val();
                    var iBadOfferId  = $('#bad-offer-id').val();
                    var sProblemType = $('#problem_type').children('[selected]').val();
                    var sDescription = $('#report_description').val();
                    $.ajax({
                       type: "POST",
                       url: "/zglos-blad-z-oferta/",
                       dataType: 'json',
                       data: {
                           product_id:  iProductId,
                           offer_id:    iBadOfferId,
                           problem:     sProblemType,
                           description: sDescription
                       },
                       success: function(response) {
                           if (response.status == 'ok') {
                               var sMessage = 'Dziękujemy za zgłoszenie problemu.<br />';
                               $('#report_invalid_offer_status').removeClass('message-box-error').addClass('message-box-ok');
                           }
                           else {
                               var sMessage = 'Wystąpił błąd.<br />';
                               $('#report_invalid_offer_status').removeClass('message-box-ok').addClass('message-box-error');
                           }
                           $('#report_invalid_offer_status').html(sMessage).show();
//                               $("#report_invalid_offer_dialog").css('height' , '120px' );
                       }
                    });
                },
                'Zamknij': function() {
                    $('#bad-offer-id').val('');
                    $('#report_invalid_offer_status').html("").hide();
                    $(this).dialog('close');
                }
            },
            close: function() {
               $('#report_invalid_offer_status').html("").hide();
            }
        });

        $('.report-bad-offer').click(function(e) {
            e.preventDefault();

            $('#bad-offer-id').val($(this).attr('offer_id'));
            $('#report_invalid_offer_dialog').dialog('open');
        });

     /* koniec zgłoś błędną ofertę */

    $('#header span.info').hover(function(){
        $('#header span.info-text').show();
				
    },function(){
        $('#header span.info-text').hide();
				
    });
    $(".catbox > h2").click(function()
    {
        $(this).parent(".catbox").toggleClass("roll");
        $(this).toggleClass("roll").next("ul").slideToggle('400');

        if ($(this).parent(".catbox").attr("class") == "catbox") {
            deleteCategory(parseInt($(this).parent(".catbox").attr("id")));
        }
        else {
            saveCategory(parseInt($(this).parent(".catbox").attr("id")));
        }
    });

    $('#setcat li a.search-filter').click(function(event) {
        checkCheckbox(this, event)
    });
    $('#setprod li a').click(function(event) {
        checkCheckbox(this, event)
    });
    $('#setshop li a').click(function(event) {
        checkCheckbox(this, event)
    });

    $("#setprod > h2").click(function()
    {
        var boolChanged = false;
        if ($(this).attr("class") == "setprod")
        {
            boolChanged = true;
            $("#setprod > h2").toggleClass("setprod_minimized");
        }

        $(this).next("fieldset").slideToggle('400', function() {
            if (boolChanged == false)
                $("#setprod > h2").toggleClass("setprod_minimized");
        });
    });


    $('.product_name_qwe').hover(
        function(e) {
            //                    $(this).children('a.show_in_new_window').show();
            var orangeBox = document.getElementById('orange_box');
            if (orangeBox != null) {
                //                        var x  = Number(this.offsetLeft + 100).toString();
                //                        orangeBox.style.left  = x + 'px';
                //                        var y  = Number(this.offsetTop - 40).toString();
                //                        orangeBox.style.top = y + 'px';
                $('#orange_box').appendTo(this);
                $('#orange_box').show();
            }
        },
        function(e) {
            $(this).children('a.show_in_new_window').hide();
            $('#orange_box').hide();
        });

    $("#setshop > h2").click(function()
    {
        var boolChanged = false;
        if ($(this).attr("class") == "setshop")
        {
            boolChanged = true;
            $("#setshop > h2").toggleClass("setshop_minimized");
        }

        $(this).next("fieldset").slideToggle('400', function() {
            if (boolChanged == false)
                $("#setshop > h2").toggleClass("setshop_minimized");
        });
    });

    $("#setcat > h2").click(function()
    {
        var boolChanged = false;
        if ($(this).attr("class") == "setcat")
        {
            boolChanged = true;
            $("#setcat > h2").toggleClass("setcat_minimized");
        }

        $(this).next("fieldset").slideToggle('400', function() {
            if (boolChanged == false)
                $("#setcat > h2").toggleClass("setcat_minimized");
        });
    });

    $("#setprod .bot .showMore").click(function()
    {
        $("#setprod .layerProducers").slideToggle();

        if ($(this).html() == "Pokaż więcej &gt;")
            $(this).html("&lt; Ukryj");
        else
            $(this).html("Pokaż więcej &gt;");
    });

    $("#setshop .bot .showMore").click(function()
    {
        $("#setshop .layerShops").slideToggle();

        if ($(this).html() == "Pokaż więcej &gt;")
            $(this).html("&lt; Ukryj");
        else
            $(this).html("Pokaż więcej &gt;");
    });

    $("#setcat .bot .showMore").click(function()
    {
        $("#setcat .layerCategories").slideToggle();

        if ($(this).html() == "Pokaż więcej &gt;")
            $(this).html("&lt; Ukryj");
        else
            $(this).html("Pokaż więcej &gt;");
    });

    $('#sameaddress > input').click(
        function() {
            $("#secondaddress").slideToggle("slow");
        });

    $('#confirmation > input').click(
        function() {
            if ($(this).attr("checked") == true)
                $(".sub").fadeIn("slow");
            else
                $(".sub").fadeOut("slow");
        });

    $('.markthisshop a').click(
        function()
        {
            $("#addcomment").fadeIn("slow");
        });

    $('#addcomment #hide').click(
        function()
        {
            $("#addcomment").slideUp("slow");
        });
});

function checkCheckbox(element, event) {
    event.preventDefault();
    $(element).siblings('input').attr('checked', true);
    $("#catform").submit();
}

function toggleFilters(stringFilter)
{
    var boolChanged = false;
    if ($("#" + stringFilter + " > h2").attr("class") == "minimized")
    {
        boolChanged = true;
        $("#" + stringFilter + " > h2").removeClass("minimized");
    }

    $("#" + stringFilter + " > h2").next("fieldset").slideToggle('400', function() {
        if (boolChanged == false)
            $("#" + stringFilter + " > h2").toggleClass("minimized");
    });
}

function checkCategories()
{
    $("div.catbox").each(function()
    {
        if (checkCategory(parseInt($(this).attr("id"))))
        {
            $(this).toggleClass("roll");
            $(this).find("h2").toggleClass("roll");
            $(this).find("ul").slideToggle('400');
        }
    });

}

function checkCategory(intCategoryId)
{
    if (isNaN(intCategoryId))
        return;

    var stringCategoriesData = $.cookie('categoriesState');

    if (stringCategoriesData == null || stringCategoriesData.length == 0)
        return;

    var arrayCategories = stringCategoriesData.split("|");
    var intElementsCount = arrayCategories.length;

    for(i = 0; i < intElementsCount; i++)
    {
        if (parseInt(arrayCategories[i]) == parseInt(intCategoryId))
            return true;
    }

    return false;
}

function saveCategory(intCategoryId)
{
    if (isNaN(intCategoryId) || checkCategory(intCategoryId) == true || parseInt(intCategoryId) == 284)
        return;

    stringCategoriesData = $.cookie('categoriesState');

    if (stringCategoriesData != null && stringCategoriesData.length > 0)
        stringCategoriesData += "|" + intCategoryId
    else
        stringCategoriesData = intCategoryId;

    $.cookie('categoriesState', stringCategoriesData, {
        expires: 7
    });
}

function deleteCategory(intCategoryId)
{
    if (isNaN(intCategoryId) || checkCategory(intCategoryId) == false)
        return;

    var stringCategoriesData = $.cookie('categoriesState');
    if (stringCategoriesData == null || stringCategoriesData.length == 0)
        return;

    var arrayCategories = stringCategoriesData.split("|");
    var intElementsCount = arrayCategories.length;
    var stringReturn = '';

    for(i = 0; i < intElementsCount; i++)
    {
        if (parseInt(arrayCategories[i]) != parseInt(intCategoryId))
        {
            if (stringReturn.length > 0)
                stringReturn += "|" + arrayCategories[i]
            else
                stringReturn = arrayCategories[i];
        }
    }

    $.cookie('categoriesState', stringReturn, {
        expires: 7
    });
}

function removeProduct(intProductId)
{
    $("." + intProductId).fadeOut('400');

    intProductsCount = parseInt($("#intProductsCount").html()) - 1;
    $("#intProductsCount").html(intProductsCount)

    if (intProductsCount <= 2)
        $(".del").hide('400');
}

function voidPreFetch()
{
    var arrayArguments = voidPreFetch.arguments;
    for(i = 0; i < arrayArguments.length; i++)
    {
        arrayCacheImages = new Image();
        arrayCacheImages.src = arrayArguments[i];
    }
}

function searchAddKeyword(stringKeyword)
{
    $("#search .txt").attr("value", (stringKeyword).trim()).focus();

    return false;
}

function resizeColumns(intLastRowId)
{
    var intMaxSize = 0;

    for (i = 0; i <= intLastRowId; i++)
    {
        intMaxSize = 0;

        $(".box[@name=row_"+ i +"]").each(function()
        {
            if ($(this).height() > intMaxSize)
                intMaxSize = $(this).height();
        });

        $(".box[@name=row_"+ i +"]").each(function()
        {
            $(this).height(intMaxSize);
        });
    }
}

function validateNIP(stringNIP)
{
    arrayCoefficients = new Array;

    arrayCoefficients[0] = 6;
    arrayCoefficients[1] = 5;
    arrayCoefficients[2] = 7;
    arrayCoefficients[3] = 2;
    arrayCoefficients[4] = 3;
    arrayCoefficients[5] = 4;
    arrayCoefficients[6] = 5;
    arrayCoefficients[7] = 6;
    arrayCoefficients[8] = 7;

    if (!isNaN(stringNIP))
    {
        intSum = 0;
        for (i = 0; i < 9; i ++)
            intSum =  intSum + stringNIP.substring(i, i + 1) * arrayCoefficients[i];

        if ((intSum % 11) != stringNIP.substring(9, 10))
            return false;
        else
            return true;
    }

    return false;
}

function validateREGON(stringREGON)
{
    arrayCoefficients = new Array;
	
    arrayCoefficients[0] = 8;
    arrayCoefficients[1] = 9;
    arrayCoefficients[2] = 2;
    arrayCoefficients[3] = 3;
    arrayCoefficients[4] = 4;
    arrayCoefficients[5] = 5;
    arrayCoefficients[6] = 6;
    arrayCoefficients[7] = 7;

    if (!isNaN(stringREGON))
    {
        intSum = 0;

        for (i = 0; i < 8; i ++)
            intSum = intSum + stringREGON.substring(i, i + 1) * arrayCoefficients[i];

        if ((intSum % 11) != stringREGON.substring(8, 9))
            return false;
        else
            return true;
    }

    return false;
}

function validateURL(stringURL)
{
    var regularExpression = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regularExpression.test(stringURL);
}

function validateLogin(stringLogin)
{
    var regularExpression = /^([a-zA-Z0-9_-]+)$/
    return regularExpression.test(stringLogin);
}

function validateName(stringName)
{
    if (stringName == null)
        return false;

    return true;
}

function validateEmail(stringEmail)
{
    var intAtIndex = stringEmail.indexOf("@");
    var stringAfterAt = stringEmail.substring((intAtIndex + 1), stringEmail.length);
    var intDotIndex = stringAfterAt.indexOf(".");

    intDotIndex = intDotIndex + intAtIndex + 1;
    stringAfterAt = stringEmail.substring((intAtIndex + 1), intDotIndex);

    var stringAfterDot = stringEmail.substring((intDotIndex + 1), stringEmail.length);
    var stringBeforeAt = stringEmail.substring(0,(intAtIndex));

    var regexpEmail = /^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,3}/

    if ((stringEmail.indexOf("@") != "-1") &&
        (stringEmail.length > 5) &&
        (stringAfterAt.length > 0) &&
        (stringBeforeAt.length > 1) &&
        (stringAfterDot.length > 1) &&
        (regexpEmail.test(stringEmail)))
        {
        return true;
    }
    else
        return false;

}

function validateRegistrationData()
{
    if ($("input[@name=shopname]").attr("value") == null || $("input[@name=shopname]").attr("value").length == 0)
    {
        alert("Pole \"Nazwa sklepu\" nie może być puste.\n\nProsimy o uzupełnienie informacji o nazwie sklepu i sprobowanie ponownie.");
        return false;
    }

    if (!validateURL($("input[@name=url]").attr("value")))
    {
        alert("Podany adres www jest niepoprawny.\n\nUpewnij się, czy format adresu jest poprawny, czy nie popełniono w nim przypadkowych literówek, oraz czy na początku adresu znajduje się człon \"http://\".");
        return false;
    }

    if ($("input[@name=email]").attr("value") == null || !validateEmail($("input[@name=email]").attr("value")))
    {
        alert("Podany adres e-mail jest niepoprawny.\n\nUpewnij się, czy format adresu jest poprawny oraz czy nie popełniono w nim przypadkowych literówek.");
        return false;
    }

    if ($("input[@name=login]").attr("value") == null || $("input[@name=login]").attr("value").length < 3 || $("input[@name=login]").attr("value").length > 32)
    {
        alert("Podany login jest niepoprawny.\n\nUpewnij się, czy podany login jest dłuższy niż 3 a krótszy niż 32 znaki i spróbuj ponownie. ");
        return false;
    }

    if (!validateLogin($("input[@name=login]").attr("value")))
    {
        alert("Podany login jest niepoprawny.\n\nUpewnij się, czy w loginie nie znajdują się niedozwolone znaki specjalne oraz polskie znaki diakrytyczne i spróbuj ponownie.");
        return false;
    }

    if ($("input[@name=pass]").attr("value") == null || $("input[@name=pass]").attr("value").length < 5 || $("input[@name=login]").attr("value").length > 16)
    {
        alert("Podane hasło jest niepoprawne.\n\nUpewnij się, czy podane hasło jest dłuższe niż 5 a krótsze niż 16 znaków i spróbuj ponownie. ");
        return false;
    }

    if ($("input[@name=pass]").attr("value") == null || ($("input[@name=pass]").attr("value") != $("input[@name=reppass]").attr("value")))
    {
        alert("Hasła w polach \"Hasło\" i \"Powtórz hasło\" nie są takie same.\n\nUpewnij się, czy podane hasła zostały wpisane poprawnie i spróbuj ponownie. ");
        return false;
    }
	
    return true;
}

function validateCommentsData()
{
    if (!validateName($("input[@name=userinfo]").attr("value")))
    {
        alert("Pole \"Twoje imię\" jest puste.\n\nProsimy o poprawne wypełnienie tego pola i spróbowanie ponownie.");
        return false;
    }

    if ($("textarea[@name=commentcontent]").val().length < 20)
    {
        alert("Podany komentarz jest zbyt krótki.\n\nUpewnij się, czy treść komentarza składa się z conajmniej 20 znaków i spróbuj ponownie.");
        return false;
    }

    if (isNaN($("select[@name=markservice]").attr("value")) || isNaN($("select[@name=markdelivery]").attr("value")) || isNaN($("select[@name=mainmark]").attr("value")))
    {
        alert("Aby kontynuować, należy wybrać poprawne wartości w polach wyboru ocen.\n\nUpewnij się, czy wszystkie oceny zostały wybrane poprawnie i spróbuj ponownie.");
        return false;
    }

    return true;
}

function validateProductCommentsData()
{
    if (!validateName($("input[@name=userinfo]").attr("value")))
    {
        alert("Pole \"Twoje imię\" jest puste.\n\nProsimy o poprawne wypełnienie tego pola i spróbowanie ponownie.");
        return false;
    }

    if ($("textarea[@name=commentcontent]").val().length < 20)
    {
        alert("Podany komentarz jest zbyt krótki.\n\nUpewnij się, czy treść komentarza składa się z conajmniej 20 znaków i spróbuj ponownie.");
        return false;
    }

    if (isNaN($("select[@name=mainmark]").attr("value")))
    {
        alert("Aby kontynuować, należy wybrać poprawną wartość w polu oceny.\n\nUpewnij się, czy ocena została wybrana poprawnie i spróbuj ponownie.");
        return false;
    }

    return true;
}

function findPosition(object)
{
    var intCursorLeft = intCursorTop = 0;
    if (object.offsetParent)
    {
        intCursorLeft = object.offsetLeft
        intCursorTop = object.offsetTop
        while (object = object.offsetParent)
        {
            intCursorLeft += object.offsetLeft;
            intCursorTop += object.offsetTop;
        }
    }
    return [intCursorLeft, intCursorTop];
}

function getStyle(object, stringProperty)
{
    if (object.currentStyle)
        var mixedReturn = object.currentStyle[stringProperty];
    else if (window.getComputedStyle)
        var mixedReturn = document.defaultView.getComputedStyle(object, null).getPropertyValue(stringProperty);

    return mixedReturn;
}

function getPageSize(){
    var windowWidth, windowHeight, pageWidth, pageHeight;

    if ( window.innerHeight && window.scrollMaxY ) {
        pageWidth = document.body.scrollWidth;
        pageHeight = window.innerHeight + window.scrollMaxY;
    } else if ( document.body.scrollHeight > document.body.offsetHeight ){
        pageWidth = document.body.scrollWidth;
        pageHeight = document.body.scrollHeight;
    } else {
        pageWidth = document.body.offsetWidth;
        pageHeight = document.body.offsetHeight;
    }

    if ( self.innerHeight ) {
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if ( document.documentElement && document.documentElement.clientHeight ) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if ( document.body ) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    return [ ( ( pageWidth < windowWidth ) ? windowWidth : pageWidth ),  ( ( pageHeight < windowHeight ) ? windowHeight : pageHeight ), windowWidth, windowHeight ];
}


function showMaximized(stringImageSource)
{
    var pageSize = getPageSize();
    var objectImageThumbnail = $("#image_thumbnail");
    var arrayOffset = objectImageThumbnail.offset();
    var layerImage = document.createElement('div');
    var objectImage = document.createElement('img');
    var layerPreloadImage = document.createElement('div');
    var objectPreloadImage = document.createElement('img');

    if (boolConstructed == false)
    {
        layerImage.className = 'imagePreview';
        layerImage.style.display = 'none';
		
        objectImage.src = stringImageSource;
        objectImage.style.cursor = 'pointer';

        objectPreloadImage.src = "http://www.radar.pl/design/design_gif/progress_bar.gif";
        layerPreloadImage.appendChild(objectPreloadImage);
        layerPreloadImage.appendChild(document.createElement('br'));
        layerPreloadImage.appendChild(document.createTextNode('Ładowanie zdjęcia'));
        layerPreloadImage.style.cssText = 'margin-left: auto; margin-right: auto; margin-top: 182px; text-align: center';
	
        layerImage.style.width = "400px";
        layerImage.style.height = "400px";

        var layerClose = document.createElement('div');
        layerClose.innerHTML = '<a href="" onclick="$(\'.imagePreview\').fadeOut(\'200\'); return false"><img src="http://www.radar.pl/design/design_gif/zamknij.gif" /></a>';
        layerClose.style.cssText = 'float: right';
        layerImage.appendChild(layerClose);
        layerImage.appendChild(layerPreloadImage);

        objectImage.style.display = 'none';
    }

    objectImage.onload = function()
    {
        layerPreloadImage.style.display = 'none';

        layerImage.style.width = objectImage.width + "px";
        layerImage.style.height = objectImage.height + 30 + "px";

        layerImage.style.left = ( ( pageSize[2] / 2 ) - ( layerImage.offsetWidth / 2 ) ) + 'px';
        layerImage.style.top = ( ( pageSize[3] / 2 ) - ( layerImage.offsetHeight / 2 ) ) + 'px';

        objectImage.style.display = 'inline';
    }

    objectImage.onclick = function() {
        $(".imagePreview").fadeOut("200");
    }

    if (boolConstructed == false)
    {
        layerImage.appendChild(objectImage);
        document.body.appendChild(layerImage);

        layerImage.style.left = ( ( pageSize[2] / 2 ) - 200 ) + 'px';
        layerImage.style.top = ( ( pageSize[3] / 2 ) - 200 ) + 'px';
    }

    $(".imagePreview").fadeToggle("200");

    boolConstructed = true;
}

function getPosition(event)
{
    event = event || window.event;
    var cursor = {
        x : 0,
        y : 0
    };

    if (event.pageX || event.pageY)
    {
        cursor.x = event.pageX;
        cursor.y = event.pageY;
    }
    else
    {
        var deElement = document.documentElement;
        var dBody = document.body;
        cursor.x = event.clientX + (deElement.scrollLeft || dBody.scrollLeft) - (deElement.clientLeft || 0);
        cursor.y = event.clientY + (deElement.scrollTop || dBody.scrollTop) - (deElement.clientTop || 0);
    }

    return cursor;
}

function showToolTip(event, object, stringText)
{
    var layerToolTip = document.createElement('div');
    layerToolTip.className = 'layerToolTip';
    layerToolTip.appendChild(document.createElement('p'));
    layerToolTip.childNodes[0].innerHTML = stringText;

    $(".layerToolTip").fadeIn("200");

    object.move = function(event)
    {
        arrayCursorPosition = getPosition(event);

        layerToolTip.style.left = arrayCursorPosition.x + 20 + 'px';
        layerToolTip.style.top = arrayCursorPosition.y + 20 + 'px';
    }

    object.move(event);
    document.body.appendChild(layerToolTip);

    object.onmousemove = function(event)
    {
        object.move(event)
    }

    object.onmouseout = function(event)
    {
        layerToolTip.parentNode.removeChild(layerToolTip);
    }
}

function toggleCheckbox(stringId, intCategoryId)
{
    stringValue = stringId.substring(11, stringId.length);
//    $("#catform").find("input[@type$='checkbox']").each(function() {
    $("#catform input[type=checkbox]").each(function() {
        if (intCategoryId > 0 && this.name == 'arraySuperCategories[]')
        {
            if (this.value != intCategoryId)
            {
                this.checked = false;
            }
            else
            {
                this.checked = true;
            }
        }
        else if (intCategoryId == 0 && this.name == 'arraySuperCategories[]')
        {
            if (this.value != stringValue)
                this.checked = false;
            else
                this.checked = true;
        }
        else
        {
            if (this.value != stringValue)
                this.checked = false;
            else
                this.checked = true;
        }
    });
    $('#' + stringId).attr({
        checked: 'checked'
    });
	
    //	$("#catform").submit();

    return false;
}

function checkAllSubcategories(forceCheck)
{
    if (forceCheck == true)
        var isChecked = true;
    else
        var isChecked = $('#checkboxCheckAll').attr('checked');

//    $("#catform").find("input[@type$='checkbox']").each(function() {
    $("#catform input[type=checkbox]").each(function() {
        if (this.name == 'arraySuperCategories[]')
        {
            if (isChecked == true)
                this.checked = true;
            else
                this.checked = false;
        }
    });
	
    // hm ?
    if (forceCheck == true)
        $("#catform").submit();
}

function checkSubcategoriesOf(intParent, forceCheck)
{
    if (forceCheck == true)
        var isChecked = true;
    else
        var isChecked = $('#checkboxCheckAll_' + intParent).attr('checked');

//    $("#catform").find("input[@type$='checkbox']").each(function() {
    $("#catform input[type=checkbox]").each(function() {
        if (parseInt(this.id.substring(11, this.id.length)) == intParent)
        {
            if (isChecked == true)
                this.checked = true;
            else
                this.checked = false;
        }
        else
        {
    //		if (this.name == 'arraySuperCategories[]')
    //		    this.checked = false;
    }
    });
	
    // hm ?
    if (forceCheck == true)
        $("#catform").submit();

    return false;
}


/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */

(function($) {

    $.fn.extend({
        autocomplete: function(urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function(value) {
                return value;
            };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        },
        result: function(handler) {
            return this.bind("result", handler);
        },
        search: function(handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function() {
            return this.trigger("flushCache");
        },
        setOptions: function(options){
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function() {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function(input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch(event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if ( select.visible() ) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if ( select.visible() ) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if ( select.visible() ) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if ( select.visible() ) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if( selectCurrent() ) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    break;

                case KEY.ESC:
                    select.hide();
                    break;

                default:
                    clearTimeout(timeout);
                    timeout = setTimeout(onChange, options.delay);
                    break;
            }
        }).focus(function(){
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function() {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function() {
            // show select when clicking in a focused field
            if ( hasFocus++ > 1 && !select.visible() ) {
                onChange(0, true);
            }
        }).bind("search", function() {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if( data && data.length ) {
                    for (var i=0; i < data.length; i++) {
                        if( data[i].result.toLowerCase() == q.toLowerCase() ) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if( typeof fn == "function" ) fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function(i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function() {
            cache.flush();
        }).bind("setOptions", function() {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ( "data" in arguments[1] )
                cache.populate();
        }).bind("unautocomplete", function() {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if( !selected )
                return false;

            var v = selected.result;
            previousValue = v;

            if ( options.multiple ) {
                var words = trimWords($input.val());
                if ( words.length > 1 ) {
                    v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function onChange(crap, skipPrevCheck) {
            if( lastKeyPressCode == KEY.DEL ) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if ( !skipPrevCheck && currentValue == previousValue )
                return;

            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if ( currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if ( !value ) {
                return [""];
            }
            var words = value.split( options.multipleSeparator );
            var result = [];
            $.each(words, function(i, value) {
                if ( $.trim(value) )
                    result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if ( !options.multiple )
                return value;
            var words = trimWords(value);
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue){
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
                    function (result){
                        // if no value found, clear the input box
                        if( !result ) {
                            if (options.multiple) {
                                var words = trimWords($input.val()).slice(0, -1);
                                $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
                            }
                            else
                                $input.val( "" );
                        }
                    }
                    );
            }
            if (wasVisible)
                // position cursor at end of input field
                $.Autocompleter.Selection(input, input.value.length, input.value.length);
        };

        function receiveData(q, data) {
            if ( data && data.length && hasFocus ) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
            // if an AJAX url has been supplied, try loading the data now
            } else if( (typeof options.url == "string") && (options.url.length > 0) ){

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function(key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    //				// try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    //				// limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        prefix: lastWord(term),
                        lang: 'pl'
                    }, extraParams),
                    success: function(data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {

            var cleanData = '[' + data.replace('sugg.getResponse(', '').replace(');', '') + ']';
            data = JSON.parse(cleanData);

            var parsed = [];
            $.each(data[1].suggestions, function(i, v) {
                var row = v.t;
                if (row) {
                    row = row.split("<sep>");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            });

            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 10,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function(row) {
            return row[0];
        },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 180
    };

    $.Autocompleter.Cache = function(options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength){
                flush();
            }
            if (!data[q]){
                length++;
            }
            data[q] = value;
        }

        function populate(){
            if( !options.data ) return false;
            // track the matches
            var stMatchSets = {},
            nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if( !options.url ) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i+1, options.data.length);
                if ( value === false )
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if( !stMatchSets[firstChar] )
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if ( nullData++ < options.max ) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function(i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush(){
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function(q) {
                if (!options.cacheLength || !length)
                    return null;
                /*
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
                if( !options.url && options.matchContains ){
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for( var k in data ){
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if( k.length > 0 ){
                            var c = data[k];
                            $.each(c, function(i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                if (data[q]){
                    return data[q];
                } else
                if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c, function(i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub[csub.length] = x;
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function (options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
        active = -1,
        data,
        term = "",
        needsInit = true,
        element,
        list;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
            .hide()
            .addClass(options.resultsClass)
            .css("position", "absolute")
            .appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover( function(event) {
                if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function(event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                return false;
            }).mousedown(function() {
                config.mouseDownOnSelect = true;
            }).mouseup(function() {
                config.mouseDownOnSelect = false;
            });

            if( options.width > 0 )
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while(element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if(!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if(options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function() {
                    offset += this.offsetHeight;
                });
                if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if(offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
            ? options.max
            : available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i=0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
                if ( formatted === false )
                    continue;
                var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if ( options.selectFirst ) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }
            // apply bgiframe if available
            if ( $.fn.bgiframe )
                list.bgiframe();
        }

        return {
            display: function(d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function() {
                moveSelect(1);
            },
            prev: function() {
                moveSelect(-1);
            },
            pageUp: function() {
                if (active != 0 && active - 8 < 0) {
                    moveSelect( -active );
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function() {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect( listItems.size() - 1 - active );
                } else {
                    moveSelect(8);
                }
            },
            hide: function() {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible : function() {
                return element && element.is(":visible");
            },
            current: function() {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function() {
                var offset = $(input).offset();
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                    top: offset.top + input.offsetHeight,
                    left: offset.left
                }).show();
                if(options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function() {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
                        }
                    }

                }
            },
            selected: function() {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function (){
                list && list.empty();
            },
            unbind: function() {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function(field, start, end) {
        if( field.createTextRange ){
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if( field.setSelectionRange ){
            field.setSelectionRange(start, end);
        } else {
            if( field.selectionStart ){
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

})(jQuery);

/* http://www.JSON.org/json2.js Public Domain. */

var JSON=JSON||{};(function(){
    function f(n){
        return n<10?'0'+n:n;
    }
    if(typeof Date.prototype.toJSON!=='function'){
        Date.prototype.toJSON=function(key){
            return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
            f(this.getUTCMonth()+1)+'-'+
            f(this.getUTCDate())+'T'+
            f(this.getUTCHours())+':'+
            f(this.getUTCMinutes())+':'+
            f(this.getUTCSeconds())+'Z':null;
        };String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){
            return this.valueOf();
        };
    }
    var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={
        '\b':'\\b',
        '\t':'\\t',
        '\n':'\\n',
        '\f':'\\f',
        '\r':'\\r',
        '"':'\\"',
        '\\':'\\\\'
    },rep;function quote(string){
        escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){
            var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);
        })+'"':'"'+string+'"';
    }
    function str(key,holder){
        var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){
            value=value.toJSON(key);
        }
        if(typeof rep==='function'){
            value=rep.call(holder,key,value);
        }
        switch(typeof value){
            case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){
                return'null';
            }
            gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){
                length=value.length;for(i=0;i<length;i+=1){
                    partial[i]=str(i,value)||'null';
                }
                v=partial.length===0?'[]':gap?'[\n'+gap+
                partial.join(',\n'+gap)+'\n'+
                mind+']':'['+partial.join(',')+']';gap=mind;return v;
            }
            if(rep&&typeof rep==='object'){
                length=rep.length;for(i=0;i<length;i+=1){
                    k=rep[i];if(typeof k==='string'){
                        v=str(k,value);if(v){
                            partial.push(quote(k)+(gap?': ':':')+v);
                        }
                        }
                    }
                }else{
                for(k in value){
                    if(Object.hasOwnProperty.call(value,k)){
                        v=str(k,value);if(v){
                            partial.push(quote(k)+(gap?': ':':')+v);
                        }
                        }
                    }
                }
            v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
                mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;
        }
        }
    if(typeof JSON.stringify!=='function'){
        JSON.stringify=function(value,replacer,space){
            var i;gap='';indent='';if(typeof space==='number'){
                for(i=0;i<space;i+=1){
                    indent+=' ';
                }
                }else if(typeof space==='string'){
                indent=space;
            }
            rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){
                throw new Error('JSON.stringify');
            }
            return str('',{
                '':value
            });
        };
    }
    if(typeof JSON.parse!=='function'){
        JSON.parse=function(text,reviver){
            var j;function walk(holder,key){
                var k,v,value=holder[key];if(value&&typeof value==='object'){
                    for(k in value){
                        if(Object.hasOwnProperty.call(value,k)){
                            v=walk(value,k);if(v!==undefined){
                                value[k]=v;
                            }else{
                                delete value[k];
                            }
                            }
                        }
                    }
                return reviver.call(holder,key,value);
            }
            cx.lastIndex=0;if(cx.test(text)){
                text=text.replace(cx,function(a){
                    return'\\u'+
                    ('0000'+a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){
                j=eval('('+text+')');return typeof reviver==='function'?walk({
                    '':j
                },''):j;
            }
            throw new SyntaxError('JSON.parse');
        };
    }
    }());

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-08-17 13:14:11 -0500 (Fri, 17 Aug 2007) $
 * $Rev: 2759 $
 *
 * Version: 1.1.2
 *
 * Requires: jQuery 1.1.3+
 */
eval(function(p,a,c,k,e,r){
    e=function(c){
        return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))
        };if(!''.replace(/^/,String)){
        while(c--)r[e(c)]=k[c]||e(c);k=[function(e){
            return r[e]
            }];e=function(){
            return'\\w+'
            };c=1
        };while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p
    }('(9($){l e=$.1q.C,r=$.1q.r;$.1q.M({C:9(){3(!1[0])f();3(1[0]==p)3($.7.O||($.7.E&&U($.7.13)>11))6 n.19-(($(5).C()>n.19)?i():0);k 3($.7.E)6 n.19;k 6 $.I&&5.P.1E||5.o.1E;3(1[0]==5)6 1C.1y(($.I&&5.P.1w||5.o.1w),5.o.1u);6 e.1T(1,1P)},r:9(){3(!1[0])f();3(1[0]==p)3($.7.O||($.7.E&&U($.7.13)>11))6 n.1b-(($(5).r()>n.1b)?i():0);k 3($.7.E)6 n.1b;k 6 $.I&&5.P.1N||5.o.1N;3(1[0]==5)3($.7.1M){l a=n.1p;n.1a(27,n.1o);l b=n.1p;n.1a(a,n.1o);6 5.o.1c+b}k 6 1C.1y((($.I&&!$.7.E)&&5.P.1L||5.o.1L),5.o.1c);6 r.1T(1,1P)},19:9(){3(!1[0])f();6 1[0]==p||1[0]==5?1.C():1.14(\':N\')?1[0].1u-h(1,\'q\')-h(1,\'1I\'):1.C()+h(1,\'1h\')+h(1,\'1H\')},1b:9(){3(!1[0])f();6 1[0]==p||1[0]==5?1.r():1.14(\':N\')?1[0].1c-h(1,\'s\')-h(1,\'1F\'):1.r()+h(1,\'1v\')+h(1,\'1D\')},21:9(a){3(!1[0])f();a=$.M({A:w},a||{});6 1[0]==p||1[0]==5?1.C():1.14(\':N\')?1[0].1u+(a.A?(h(1,\'L\')+h(1,\'1x\')):0):1.C()+h(1,\'q\')+h(1,\'1I\')+h(1,\'1h\')+h(1,\'1H\')+(a.A?(h(1,\'L\')+h(1,\'1x\')):0)},1Y:9(a){3(!1[0])f();a=$.M({A:w},a||{});6 1[0]==p||1[0]==5?1.r():1.14(\':N\')?1[0].1c+(a.A?(h(1,\'K\')+h(1,\'1U\')):0):1.r()+h(1,\'s\')+h(1,\'1F\')+h(1,\'1v\')+h(1,\'1D\')+(a.A?(h(1,\'K\')+h(1,\'1U\')):0)},m:9(a){3(!1[0])f();3(a!=1S)6 1.1Q(9(){3(1==p||1==5)p.1a(a,$(p).u());k 1.m=a});3(1[0]==p||1[0]==5)6 n.1p||$.I&&5.P.m||5.o.m;6 1[0].m},u:9(a){3(!1[0])f();3(a!=1S)6 1.1Q(9(){3(1==p||1==5)p.1a($(p).m(),a);k 1.u=a});3(1[0]==p||1[0]==5)6 n.1o||$.I&&5.P.u||5.o.u;6 1[0].u},12:9(a){6 1.1O({A:w,J:w,v:1.z()},a)},1O:9(b,c){3(!1[0])f();l x=0,y=0,H=0,G=0,8=1[0],4=1[0],T,10,Z=$.D(8,\'12\'),F=$.7.1M,S=$.7.26,18=$.7.O,1n=$.7.E,R=$.7.E&&U($.7.13)>11,1m=w,1l=w,b=$.M({A:Q,15:w,1k:w,J:Q,1K:w,v:5.o},b||{});3(b.1K)6 1.1J(b,c);3(b.v.1j)b.v=b.v[0];3(8.B==\'Y\'){x=8.V;y=8.X;3(F){x+=h(8,\'K\')+(h(8,\'s\')*2);y+=h(8,\'L\')+(h(8,\'q\')*2)}k 3(18){x+=h(8,\'K\');y+=h(8,\'L\')}k 3((S&&1g.I)){x+=h(8,\'s\');y+=h(8,\'q\')}k 3(R){x+=h(8,\'K\')+h(8,\'s\');y+=h(8,\'L\')+h(8,\'q\')}}k{17{10=$.D(4,\'12\');x+=4.V;y+=4.X;3((F&&!4.B.1G(/^t[d|h]$/i))||S||R){x+=h(4,\'s\');y+=h(4,\'q\');3(F&&10==\'1i\')1m=Q;3(S&&10==\'25\')1l=Q}T=4.z||5.o;3(b.J||F){17{3(b.J){H+=4.m;G+=4.u}3(18&&($.D(4,\'24\')||\'\').1G(/23-22|20/)){H=H-((4.m==4.V)?4.m:0);G=G-((4.u==4.X)?4.u:0)}3(F&&4!=8&&$.D(4,\'1e\')!=\'N\'){x+=h(4,\'s\');y+=h(4,\'q\')}4=4.1B}W(4!=T)}4=T;3(4==b.v&&!(4.B==\'Y\'||4.B==\'1d\')){3(F&&4!=8&&$.D(4,\'1e\')!=\'N\'){x+=h(4,\'s\');y+=h(4,\'q\')}3(((1n&&!R)||18)&&10!=\'1r\'){x-=h(T,\'s\');y-=h(T,\'q\')}1A}3(4.B==\'Y\'||4.B==\'1d\'){3(((1n&&!R)||(S&&$.I))&&Z!=\'1i\'&&Z!=\'1z\'){x+=h(4,\'K\');y+=h(4,\'L\')}3(R||(F&&!1m&&Z!=\'1z\')||(S&&Z==\'1r\'&&!1l)){x+=h(4,\'s\');y+=h(4,\'q\')}1A}}W(4)}l a=j(8,b,x,y,H,G);3(c){$.M(c,a);6 1}k{6 a}},1J:9(b,c){3(!1[0])f();l x=0,y=0,H=0,G=0,4=1[0],z,b=$.M({A:Q,15:w,1k:w,J:Q,v:5.o},b||{});3(b.v.1j)b.v=b.v[0];17{x+=4.V;y+=4.X;z=4.z||5.o;3(b.J){17{H+=4.m;G+=4.u;4=4.1B}W(4!=z)}4=z}W(4&&4.B!=\'Y\'&&4.B!=\'1d\'&&4!=b.v);l a=j(1[0],b,x,y,H,G);3(c){$.M(c,a);6 1}k{6 a}},z:9(){3(!1[0])f();l a=1[0].z;W(a&&(a.B!=\'Y\'&&$.D(a,\'12\')==\'1r\'))a=a.z;6 $(a)}});l f=9(){1Z"1X: 1g 1W 14 1V";};l h=9(a,b){6 U($.D(a.1j?a[0]:a,b))||0};l j=9(a,b,x,y,d,c){3(!b.A){x-=h(a,\'K\');y-=h(a,\'L\')}3(b.15&&(($.7.E&&U($.7.13)<11)||$.7.O)){x+=h(a,\'s\');y+=h(a,\'q\')}k 3(!b.15&&!(($.7.E&&U($.7.13)<11)||$.7.O)){x-=h(a,\'s\');y-=h(a,\'q\')}3(b.1k){x+=h(a,\'1v\');y+=h(a,\'1h\')}3(b.J&&(!$.7.O||a.V!=a.m&&a.X!=a.m)){d-=a.m;c-=a.u}6 b.J?{1f:y-c,1t:x-d,u:c,m:d}:{1f:y,1t:x}};l g=0;l i=9(){3(!g){l a=$(\'<1s>\').D({r:16,C:16,1e:\'2d\',12:\'1i\',1f:-1R,1t:-1R}).2c(\'o\');g=16-a.2b(\'<1s>\').2a(\'1s\').D({r:\'16%\',C:29}).r();a.28()}6 g}})(1g);',62,138,'|this||if|parent|document|return|browser|elem|function|||||||||||else|var|scrollLeft|self|body|window|borderTopWidth|width|borderLeftWidth||scrollTop|relativeTo|false|||offsetParent|margin|tagName|height|css|safari|mo|st|sl|boxModel|scroll|marginLeft|marginTop|extend|visible|opera|documentElement|true|sf3|ie|op|parseInt|offsetLeft|while|offsetTop|BODY|elemPos|parPos|520|position|version|is|border|100|do|oa|innerHeight|scrollTo|innerWidth|offsetWidth|HTML|overflow|top|jQuery|paddingTop|absolute|jquery|padding|relparent|absparent|sf|pageYOffset|pageXOffset|fn|static|div|left|offsetHeight|paddingLeft|scrollHeight|marginBottom|max|fixed|break|parentNode|Math|paddingRight|clientHeight|borderRightWidth|match|paddingBottom|borderBottomWidth|offsetLite|lite|scrollWidth|mozilla|clientWidth|offset|arguments|each|1000|undefined|apply|marginRight|empty|collection|Dimensions|outerWidth|throw|inline|outerHeight|row|table|display|relative|msie|99999999|remove|200|find|append|appendTo|auto'.split('|'),0,{}))

/* jquery.hoverIntent.minified.js */


        function updateTips(t) {
            tips.text(t).effect("highlight",{},1500);
        }

        function checkLength(o,n,min,max) {

            if ( o.val().length > max || o.val().length < min ) {
                o.addClass('ui-state-error');
                updateTips("Długość nie może być mniejsza niż  "+max+".");
                return false;
            } else {
                return true;
            }

        }

        function checkRegexp(o,regexp,n) {

            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass('ui-state-error');
                updateTips(n);
                return false;
            } else {
                return true;
            }
        }
