jQuery.fn.exists = function(){
    return this.length > 0;
}

$(document).ready(function(){

    if ($('#logofirmy').exists()) 
        $('#logofirmy').customFileInput();
    if ($('#photo').exists()) 
        $('#photo').customFileInput();
    if ($('#plik').exists()) 
        $('#plik').customFileInput();
    
    //Dodawanie kategorii
    $('#plus').click(function(){
        var kategoria = $(this).parent().children('select').last().clone().insertBefore(this);
        var kategorianame = isNaN(parseInt(kategoria.attr('name').substring(9))) ? 'kategoria1' : 'kategoria' + (parseInt(kategoria.attr('name').substring(9)) + 1);
        $(kategoria).attr({
            name: kategorianame,
            id: kategorianame
        });
    });
    $('.kategoria').children(":contains(' * ')").addClass('subcat');
    $('.kategoria').children().not('.subcat').addClass('topcat');
    
    
    $('.kategoria:last').live('change', function(){
        if ($(".kategoria option[value='" + $(this).val() + "']").hasClass('topcat')) {
        
            $(".kategoria:last option[value='" + $(this).val() + "']").nextUntil('.topcat').addClass('dodaj');
            while ($('.dodaj').exists()) {
                sel = $('.dodaj').first().val();
                $('.dodaj').first().removeClass('dodaj');
                var kategoria = $('.kategoria').last().clone().insertBefore('#plus');
                var kategorianame = isNaN(parseInt(kategoria.attr('name').substring(9))) ? 'kategoria1' : 'kategoria' + (parseInt(kategoria.attr('name').substring(9)) + 1);
                $(kategoria).attr({
                    name: kategorianame,
                    id: kategorianame
                }).children('.dodaj').removeClass('dodaj');
                $('#' + kategorianame).children("option[value='" + sel + "']").attr('selected', 'selected');
            }
        }
    });
    //Mapa google
    if ($("#mapa").exists() && $("#mapa").val() != '') {
        pozycja = $("#mapa").attr('value');
    }
    if ($("#mapagoogle").exists()) {
        $('#mapagoogle').gmap({
            'center': new google.maps.LatLng(54.434009, 18.550587),
            'zoom': 11
        });
    }
    if (typeof pozycja != "undefined") {
        pozycja = pozycja.split(", ");
        $('#mapagoogle').gmap({
            'center': new google.maps.LatLng(pozycja[0], pozycja[1]),
            'zoom': 13
        });
        $('#mapagoogle').gmap('addMarker', {
            'position': new google.maps.LatLng(pozycja[0], pozycja[1]),
            'draggable': true,
            'icon': new google.maps.MarkerImage('http://www.autofobik.pl/presentation/mapmarker.png')
        }).dragend(function(event){
            event.latLng;
            $("#mapa").val(event.latLng);
            $("#mapa").val($("#mapa").val().substring(1, $("#mapa").val().length - 1));
        });
        $('.addmarker').hide();
    }
    else {
        $('.removemarker').hide();
    }
    
    $('.addmarker').click(function(){
        if ($("#miasto").val() != '') {
            if ($("#ulica").val() != '') 
                adres = $("#ulica").val() + ', ' + $("#miasto").val();
            else 
                adres = $("#miasto").val();
            $('#mapagoogle').gmap('search', {
                'address': adres
            }, function(results){
                $("#mapa").val(results[0].geometry.location);
                $("#mapa").val($("#mapa").val().substring(1, $("#mapa").val().length - 1));
                $('#mapagoogle').gmap('getMap').panTo(results[0].geometry.location);
                $('#mapagoogle').gmap('addMarker', {
                    'position': results[0].geometry.location,
                    'draggable': true,
                    'icon': new google.maps.MarkerImage('http://www.autofobik.pl/presentation/mapmarker.png')
                }).dragend(function(event){
                    $("#mapa").val(event.latLng);
                    $("#mapa").val($("#mapa").val().substring(1, $("#mapa").val().length - 1));
                });
            });
        }
        if ($("#mapagoogle").gmap('getMarkers').length < 1) {
            $('#mapagoogle').gmap('addMarker', {
                'position': new google.maps.LatLng(54.434009, 18.550587),
                'draggable': true,
                'icon': new google.maps.MarkerImage('http://www.autofobik.pl/presentation/mapmarker.png')
            }).dragend(function(event){
                $("#mapa").val(event.latLng);
                $("#mapa").val($("#mapa").val().substring(1, $("#mapa").val().length - 1));
            });
        }
        
        $('.addmarker').hide();
        $('.removemarker').show();
    });
    $('.removemarker').click(function(){
        $('.addmarker').show();
        $('#mapagoogle').gmap('clearMarkers');
        $('.removemarker').hide();
        $("#mapa").val('');
    });
    
    // Podpowiedzi
    if ($('.tip').exists()) {
        $('.tip').cluetip({
            splitTitle: '|',
            showTitle: false
        });
    }
    //ckeditor
    if ($('.editor').exists()) {
        $(".editor").ckeditor();
        
    }
    
	//datepicker
    $.datepicker.setDefaults($.datepicker.regional["pl"]);
    if ($('.date').exists()) 
        $('.date').datepicker({
            maxDate: '+2m',
            minDate: '+1d',
            dateFormat: 'yy-mm-dd',
            dayNames: ['Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota', 'Niedziela'],
            dayNamesMin: ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'Nd'],
            monthNames: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień']
        });
    
    //fancybox
    if ($('.firma_galeria a').exists()) 
        $('.firma_galeria a').not('.usun').fancybox({
            'hideOnContentClick': true,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
        });
    
	//form example
	if ($("#miasto").exists()) {
        $("#miasto").example(" Wpisz miasto...");
    }
	if ($("#tag").exists()) {
        $("#tag").example(" Wpisz słowa kluczowe...");
    }
	if ($("#firma").exists()) {
        $("#firma").example(" Wpisz nazwę firmy...");
    }
    
	//tablesort
	if ($("#tabusers").exists()) {
		$("#tabusers").tablesorter();
	}
	
	if ($(".polecanelist").exists()) {
		$(".polecanelist").cycle({
			fx: 'scrollDown',
			speed:    1000, 
    		timeout:  5000,
			pause: 1,
			next:   '#nextpolecane', 
    		prev:   '#prevpolecane'
		});
	}
});

