function cluetip_minus()
{
    //cluetip minusa
    $(document).ready(function() {
        $('a.minus').cluetip({positionBy: 'mouse', local: true, activation: 'click', mouseOutClose: true, showTitle: false, closeText: '', closePosition: 'title', sticky: true, width: '180px', cluetipClass: 'jtip'});
    });
}

jQuery.fn.preview = function() {
    var name = $(this).attr('name');

    var content = $(this).attr('value');
    $('#preview_'+name).html(content);

    $(this).blur(function() {
        var content = $(this).attr('value');
        $('#preview_'+name).html(content);
    });
}

jQuery.fn.zliczajZnaki = function()
{ 
    $(this).each(function()
    {
        var max = $(this).attr('maxlength');
        var val = $(this).attr('value');
        var name = $(this).attr('name');
        var cur = 0;
        if(val) // value="" lub brak wartości spowoduje błąd
            cur = val.length;

        var left = max-cur;
        //$(this).after("<div class='error' id='errorTitleCounter'>" + left.toString()+"&nbsp;znaków pozostało</error>");
        $(this).next("#error"+name+"Counter").empty().append(left.toString()+"&nbsp;znaków pozostało");

        $(this).keyup(function(i) {
            var max = $(this).attr('maxlength');
            var val = $(this).attr('value');
            var cur = 0;
            if(val)
                cur = val.length;

            var left = max-cur;
            $(this).next("#error"+name+"Counter").empty().append(left.toString()+"&nbsp;znaków pozostało");
            return this;
        });
    });
    return this;
}

jQuery.fn.zliczajZnakiTextarea = function(max, settings) {
    max = max || 100;
    settings = $.extend({
        container: "<div>",
        name: "description",
        format: "%1&nbsp;znaków pozostało"
    }, settings);
    var p;

    function count(el, container) {
        el = $(el);
        if (el.val().length > max) {
            el.val(el.val().substring(0, max));
        };
        container.html(settings.format.replace(/%1/, (max - el.val().length)));
    };

    return this.each(function() {
        var container = $('#error'+settings.name+'Counter');
        $(this)
            .bind("keydown", function() { count(this, container); })
            .bind("keypress", function() { count(this, container); })
            .bind("keyup", function() { count(this, container); })
            .bind("focus", function() { count(this, container); })
            .bind("mouseover", function() { count(this, container); })
            .bind("mouseout", function() { count(this, container); })
            .bind("paste", function() {
                var me = this;
                setTimeout(function() { count(me, container); }, 10);
            });
        if (this.addEventListener) {
            this.addEventListener('input', function() { count(this, container); }, false);
        };
        count(this, container);
    });
 };


 function add_valid()
{
	$("#add_item").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent());
		},
		rules: {
                        name : {
                            required: true
                        },
                        tags : {
                            required: true
                        },
                        description: {
                            required: true
                        },
                        url: {
                            required: function(element) {
                                if(($('select[name="type"]').val() != 3 && $('input[name="url"]').val() != '') || $('select[name="type"]').val() == 3)
                                {
                                    return false;
                                }
                                return true;
                            }
                        },
                        image: {
                            required: function(element) {
                                if($('select[name="type"]').val() == 3 && $('input[name="url"]').val() != '')
                                {
                                    return true;
                                }
                                return false;
                            },
                            url: true
                        },
			category: {
                            required: function(element) {
                                if($('select[name="category"]').val() > 0)
                                {
                                    return false;
                                }
                                return true;
                            }
			},
			subcategory: {
                            required: function(element) {
                                if($('select[name="subcategory"]').val() > 0 || $('select[name="subcategory"]').css('display') == 'none')
                                {
                                    return false;
                                }
                                return true;
                            }
			}
		},
		messages: {
                    name: "Podaj tytuł lookaczu",
                    category: "Wybierz kategorie",
                    subcategory: "Wybierz podkategorie",
                    tags: "Podaj tagi lookaczu",
                    description: "Podaj opis lookaczu",
                    url: "Wpisz poprawny adres url",
                    image: "Wpisz poprawny adres obrazka"
                    
		}
	});
}

function add_vote(id_lookacz, point, type_point)
{
    $.ajax({
      type: "POST",
      url: HOST_TOWN+"/lookacz/add_vote",
      data: "id_lookacz="+id_lookacz+"&point="+point+"&type_point="+(point == -1 ? type_point : 0),
      success: function(msg){
        if(msg == 'yes')
        {
            //aktualizujemy ilosc punktow
            var points = parseInt($('#item_'+id_lookacz+' .points p.point').text());
            $('#item_'+id_lookacz+' .points p.point').html(point+points);

            //usuwamy plus/minus w zaleznosci na co klikalismy
            $('#item_'+id_lookacz+' .points a.'+(point == 1 ? 'plus' : 'minus')).hide();
            $('#item_'+id_lookacz+' .points a.'+(point == 1 ? 'minus' : 'plus')).show();

            //jesli minus to usuwamy okienko

        }
        return false;
      }
    });
    return false;
}



function item_links_go()
{
   $('ul.links a').click(function() {
       var id = $(this).attr('class').split('_');
       if(id == '')
       {
           window.location = $(this).attr('href');
       }

       var id_lookacz = id[2];
       var type = id[1];

       if(type == 'observe')
       {
            add_observe(id_lookacz, id[3], 'lookacz');
       }
       else
       {
           var type_function = new Array();
           type_function['abuse'] = 'send_report_abuse_email';
           type_function['recommend'] = 'send_recommend_email';

           if($('#div_'+type+'_'+id_lookacz+'_lookacz').css('display') == 'none')
           {
               $('#div_'+type+'_'+id_lookacz+'_lookacz').html($('#'+type+'_pattern').html()).show();
               $('#div_'+type+'_'+id_lookacz+'_lookacz button').click(eval(type_function[type]));
           }
           else
           {
               $('#div_'+type+'_'+id_lookacz).remove();
           }
       }

       return false;
   }) ;
}

function add_valid_comment()
{
	$("#add_comment").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent());
		},
		rules: {
			comment_text: {
                            required: true
			}
		},
		messages: {
                    comment_text: "Wpisz treść komentarza"
		}
	});
}

function comments_pagination()
{
    $("#comments_pagination").pagination(comments_count, {
		num_edge_entries: 2, //czy ma zawsze wyswietlac nastepny poprzedni
		num_display_entries: 5, //ile linkow numerycznych ma byc widocznych
		items_per_page:comments_per_page, //ilosc rekordow na stronie
		id_item: 0,
        type: 0,
        callback: show_comments
    });
}

function show_comments(page_id, jq, id_item, type)
{
    var start = page_id*comments_per_page;
    var end = start+comments_per_page;

    //przechodzimy przez wszystkie rekordy i wyswietlamy od start do end
    $('table.list_comment tr.item_comment').each(function() {
       var id = $(this).attr('id').split('_')[1];
       if(id > start && id<=end) $(this).show();
       else $(this).hide();
    });
}

function delete_comment()
{
    $('a.del_comment').click(function(obj) {
        var id_post = $(this).parent().parent().attr('id_post');
        $.ajax({
          type: "POST",
          url: HOST_TOWN+"/lookacz/delete_comment",
          data: "id_post="+id_post,
          success: function(msg){
            if(msg == 'yes') $('tr[id_post="'+id_post+'"]').remove();
          }
        });

        return false;
    });
}

function edit_comment()
{
    $('a.edit_comment').click(function(obj) {
        //alert($(this).parent().parent().attr('id_item'));
        var id_post = $(this).parent().parent().attr('id_post');
        var container_text = $(this).parent().parent().find('td.text');
        var text = container_text.text();

        container_text.html('<textarea cols="50" rows="5" class="edit_form">'+text+'</textarea>');

	//jak wychodzimy z inputa to zapisujemy
	$('tr.item_comment[id_post="'+id_post+'"] textarea.edit_form').blur(function() {
            var new_text = $(this).val();

            //rozne wiec zapisujemy
            if(text != new_text)
            {
		 $.ajax({
		   type: "POST",
		   url: HOST_TOWN+"/lookacz/edit_comment",
		   data: "id_post="+id_post+"&text="+new_text,
		   success: function(msg){}
		 });
            }
            $(this).parent().html(new_text);
	});

        return false;
    });
}

var lookacz_cache = Array();
function lookacz_list_items()
{ 
    $('#lookacz_box li.click a').click(function() {
        $('#lookacz_content').addClass('loader');

        //wartosc kliknietego linka
        var value = $(this).parent().attr('id');

        //zaznaczamy klikniety link
        var section = $(this).parent().attr('class').split(' ')[0];
        $('li.'+section).each(function() {
            if($(this).attr('id') == value)
                $(this).addClass('active');
            else
                $(this).removeClass('active');
        })

        //pobieramy wartosci do filtracji
        //jesli klikamy w okres czasu to pobieramy tylko najpopularniejsze
        if($(this).parent().hasClass('period'))
        {
            $('#lookacz_type .type[id="2"]').addClass('active');
            $('#lookacz_type .type[id="1"]').removeClass('active');
        }

        var category = $('#lookacz_categories .category.active').attr('id');
        var order = $('#lookacz_type .type.active').attr('id');
        var time = $('#lookacz_type .period.active').attr('id');

        if(!lookacz_cache[category+'_'+order+'_'+time])
        {
             $.ajax({
               type: "POST",
               url: HOST_TOWN+"/lookacz/ajax_list_items",
               data: "category="+category+"&order="+order+'&time='+time,
               success: function(msg){
                   lookacz_cache[category+'_'+order+'_'+time] = msg;
                   $('#lookacz_content').html(msg);
                   $('#lookacz_content').removeClass('loader');
                   $(document).ready(help_lookacz);
               }
             });
        }
        else
        {
            $('#lookacz_content').html(lookacz_cache[category+'_'+order+'_'+time]);
            $('#lookacz_content').removeClass('loader');
        }

        return false;
    });

    //wywolujemy triggera aby po loadzie strony wykonala sie akcja pobierania lookaczow
    $("#lookacz_box li.category.click#0 a").trigger('click');
}


function lookacz_items_pagination()
{
    $("#lookacz_items_pagination").pagination(lookacz_items_count, {
		num_edge_entries: 2, //czy ma zawsze wyswietlac nastepny poprzedni
		num_display_entries: 5, //ile linkow numerycznych ma byc widocznych
		items_per_page:lookacz_items_per_page, //ilosc rekordow na stronie
		id_item: 0,
        type: 0,
        callback: show_lookacz_items
    });
}

function show_lookacz_items(page_id, jq, id_item, type)
{
    var start = page_id*lookacz_items_per_page;
    var end = start+lookacz_items_per_page;

    //przechodzimy przez wszystkie rekordy i wyswietlamy od start do end
    $('#lookacz div.item').each(function() {
       var id = $(this).attr('id').split('_')[1];
       if(id > start && id<=end) $(this).show();
       else $(this).hide();
    });
}

function valid_add_logo()
{
	var error = 'false';
	var url_error = $('#url_error');
	var file_error = $('#file_error');
	var url = $('#url').val();
	var file = $('#is_file').val();

	if(url == '')
	{
		url_error.html('wpisz adres www').show();
		error = 'true';
	}
	else
	{
		url_error.hide();
	}

	if(file == 0)
	{
		file_error.html('wgraj logo').show();
		error = 'true';
	}
	else
	{
		file_error.hide();
	}

	if(error == 'true') return false;
	return true;
}

function delete_lookacz_logo(id)
{
    $('#wrap_table').append('<div class="loader"></div>');

    $.ajax({
        type: "POST",
        url: HOST_TOWN+"/lookacz_admin/delete_logo",
        data: "id_logo="+id,
        success: function(msg){
            if(msg == 'yes')
	    {
	        $('#row'+id).remove();
		var text = 'Logo zostało usunięte';
	    }
	    else
	        var text = 'Logo nie może zostać teraz usunięte';

	    show_message(text);
            $('.loader').remove();
        }
    });
}

function help_lookacz()
{
	$('a.help_lookacz').cluetip({splitTitle: '|', positionBy: 'bottomTop', dropShadow: false, showTitle: false, sticky: false, mouseOutClose: true, closeText: '', cluetipClass: 'blue'});
}
