/*******************************************************************************

*******************************************************************************/


$(document).ready(function() {
	
    // set sidebar height
    var contentHeight = $('#content').height();
    $('#sidebar').css({
        'min-height': contentHeight - 37 + 'px'
    }); 
    if($.browser.msie && parseInt($.browser.version) == 6) $('#sidebar').css({
        'height': contentHeight - 37 + 'px'
    });
	
	
    Cufon.replace('#navigation a, #home-bottom-nav a, .branze li am, #shop-details #location li a, #shop-details .back, .news .more a, .action a, .vote a, .archive .download a, .subnav li a, .lista-branz li a, #shop-list dl, .branze li a, .alfabet2 li a, #gallery-plan a', {
        hover: true
    });
	
    Cufon.replace('#content h1, .alphabetic-list li a, #newsletter-content h4, #shop-details #location li, #shop-description p.visit, .news .date, .krasnale .action h6, #krasnal .description h3, .archive li h6, .archive li h5, #hours .name h6, .addr dt, #contact-container h3, #contact-container .right-col h2, #contact-container .right-col label, #contact-container .submit-holder button, #alphabetic-list2 li a, #shop-list dt, #branza-intro p, #content #branza-sklepy p, #contact-container .form-row span.req, .data-wydarzenia, .press .download, #branza-sklepy, .promo-image-details h2, .promo-image-details p, .legend-zero, .legend-max');

    // center homepage vertically
    if($('.homepage').length) {
        var topMargin = Math.floor(($(window).height() - $('body').height()) / 2);
        if (topMargin > 0)
            $('body.homepage div.container')[0].style.marginTop = topMargin + "px";
        else 
            $('body.homepage div.container')[0].style.marginTop = "0px";
    }
	
    // contact form validation
    if($("#contact-form").length) {
        $("#contact-form").validate({	
            messages: {
                zapytanie: "Proszę podać treść zapytania",
                name: "Proszę podać Imię i Nazwisko",
                phone: "Proszę podać nr telefonu",
                email: "Nieprawidłowy adres e-mail"
            }
        });
    }
	
    $('.press li').hover(
        function() {
            $(this).addClass('hover');
        },
        function() {
            $(this).removeClass('hover');
        }
        );


    $('#facebook').hover(
        function() {
            $(this).stop(true, false).animate({
                right: '0'
            },'medium');
        },
        function() {
            $(this).stop(true, false).animate({
                right: '-235px'
            }, 'medium');			
        }
        );
	
    $('.search-input-holder, #search-btn').hover(
        function() {
            $(this).addClass('hover');
        },
        function() {
            $(this).removeClass('hover');			
        }
        );
	
    $('a#close-trip').click(function(event){
        event.preventDefault();
        $('#trip-wrapper').hide();
    })
        
    $('a#open-trip').click(function(event){
        event.preventDefault();
        $('#trip-wrapper').show();
    })

    $.datepicker.regional['pl'] = {
        closeText: 'Zamknij',
        prevText: '&#x3c;Poprzedni',
        nextText: 'Następny&#x3e;',
        currentText: 'Dziś',
        monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
        'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
        monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
        'Lip','Sie','Wrz','Pa','Lis','Gru'],
        dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
        dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
        dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
        weekHeader: 'Tydz',
        dateFormat: 'yy-mm-dd',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['pl']);
    
    $.getJSON('ajax-events', function(data, textStatus, jqXHR){
        initCalendar(data);
    });
    function getToolTipT(dayData){
        var output = new Array();
        for (var i in dayData){
            output[i] = dayData[i].name;
        }

        return output.join("<br />");
    }

    function initCalendar(eventsData){
        $('#calendar').datepicker({
            onChangeMonthYear: function(year, month, inst) {
            	setTimeout("$('#calendar .ui-datepicker-calendar td').tooltip()", '250');
		    },
            beforeShowDay: function(date) {
                var d = date.getDate(),
                m = date.getMonth()+1,
                y = date.getFullYear();
                var sunday = '';
                if(date.toString().indexOf('Sun ')!=-1){
                    sunday = ' sunday';
                }
                
                var currentDate = y+'-'+m+'-'+d;
                if (eventsData[currentDate.toString()]){
                    return [true, 'clickable'+sunday, getToolTipT(eventsData[currentDate.toString()])];
                }else{
                    return [false, sunday];
                }
                
            },
            onSelect: function(date) {
                window.location = '/wydarzenia/'+date;
            }
        });

        $('#calendar .ui-datepicker-calendar td').tooltip();
        
    }

});


// DD_belatedPNG fix for IE6
if (typeof DD_belatedPNG !== 'undefined') {
    var PNG_fix_selectors = [
    '#shadow-top',
    '.shadow-container',
    '#content',
    '#cols-holder',
    '#contact-container',
    '#contact-container h3',
    '.contact-shadow-top',
    '.contact-shadow-bottom',
    '#facebook span',
    '.text-holder',
    '.textarea-holder',
    '.alphabetic-list li a',
    '#alphabetic-list2 li a',
    '#shop-list dd',
    '.branze li a',
    '#contact-container .submit-holder button',
    '#krasnal-holder img',
    '#krasnal .quote',
    '.access',
    '.gallery li a',
    '.newsletter-container',
    '#shop-description .image-holder',
    '.mask',
    '.news .more a',
    '.midget img',
    '.konkurs-items .item-pic a',
    '.vote a',
    '.archive li img',
    '.archive .download a',
    '.press li',
    '.press .download a',
    '.press .pdf span'
		
    ];
    DD_belatedPNG.fix(PNG_fix_selectors.join(','));
        
}

function showMail(e,d,f){
    document.write('<a href="mailto:'+e+"@"+d+"."+f+'">'+e+"@"+d+"."+f+"</a>")
}

function openPanorama(id){
    document.getElementById('panorama'+id).onclick();
}
(function($) {
    jQuery.fn.slider = function(options) {
        var defaults = {
            width : 600,//szerokosc slidera
            height : 200,//wysokosc slidera
            slideTime : 2,//interwał
            slideSpeed : 1000,//szybkosc przewijania
            autoHideButtons : true,//ukrywanie przyciskow
            overlayAlt : true,// czu ma byc dodawany tytul brany z  atrybutu alt obrazka
            overlayHeight: 50,// wysokosc nakladki
            autoStart : true // autostart slidera
        };

        //definiowanie ustawien oraz zmiennych podstawowych
        var intervalInstance = null;
        var $container = $(this);
        var $current = $container.find('a:first:has(img)');
        var $slideControls = $('<ul class="slide-controls"></ul>')
        options = $.extend(defaults, options);

        $container.find('a:not(:first)').css('left', parseInt(options.width)).css('display','none');
        $container.find('a').css('width',options.width).css('height',options.height).attr('class','slide');
        $container.attr('class', 'slide-bar');
        $container.css('width', options.width);
        $container.css('height', options.height);
        

        //wstawianie przyciskow numerycznych
        $container.find('a:has(img)').each(function(key){
            $(this).attr('rel', "slider-" + key)
            //nakladka tytulowa
            if (options.overlayAlt == true) {
                $img = $(this).find('img');
                if ($img.attr('alt') != undefined) {
                    $(this).append('<div class="overlay" style="height:' + options.overlayHeight + 'px;' + ((key == 0)?'display:block;':'') + '">' + $img.attr('alt') + '</div>');
                }
            }
            
            $slideControls.append('<li><a href="#' + key + '" ' + ((key == 0)?'class="selected"':'') + ' title="">' + (key + 1) + '</a></li>');
        });

        $container.append($slideControls);

        //pokazywanie/ukrywanie przyciskow
        if (options.autoHideButtons == true) {
            $slideControls.css('display','none');
            $container.mouseenter(function(){
                $slideControls.fadeIn();
            })

            $container.mouseleave(function(){
                $slideControls.fadeOut();
            })
        }

        //start autoprzewijania
        function start() {
            intervalInstance = window.setInterval(slideLeft, (options.slideTime * 1000 + options.slideSpeed), false);
        }

        //przewijanie w lewo
        function slideLeft(id) {
            $current.find('.overlay').fadeOut();
           
            $current.animate({
                left: '-=' + options.width
            }, options.slideSpeed, function() {
                $(this).css('display','none').css('left', parseInt(options.width));
            });
            
            if (id) {
                $current = $container.find('a:has(img)[rel=slider-' + id + ']')
            } else {
                $current = $current.next('a');
                if ($current.length == 0) {
                    $current = $container.find('a:first:has(img)');
                }
            }

            $current.css('display','block').animate({
                left: '-=' + options.width
            }, options.slideSpeed,function(){
                $current.find('.overlay').fadeIn();
            });

            setActiveLink(getId($current.attr('rel')));
        }

        //przewijanie w prawo
        function slideRight(id) {
            $current.find('.overlay').fadeOut();
            $current.animate({
                left: '+=' + options.width
            }, options.slideSpeed, function() {
                $(this).css('display','none').css('left', parseInt(options.width));
            });

            if (id) {
                $current = $container.find('a:has(img)[rel=slider-' + id + ']')
            } else {
                $current = $current.prev('a');

                if ($current.length == 0) {
                    $current = $container.find('a:has(img):last');
                }
            }
            $current.css('display','block').css('left', -parseInt(options.width)).animate({
                left: '+=' + options.width
            }, options.slideSpeed, function(){
                $current.find('.overlay').fadeIn();
            });
            setActiveLink(getId($current.attr('rel')));
        }

        //ustawienie aktywnego przycisku nuerycznego
        function setActiveLink(id) {
            $slideControls.find('a').removeClass('selected');
            $slideControls.find('a[href=#' + id + ']').attr('class','selected');
        }

        //funkcja przewijania do slidu o id
        function slideTo(id) {
            var currentId = getId($current.attr('rel'));

            if ((currentId - id) < (id - currentId)) {
                slideLeft(id);
            } else if( (currentId - id) > (id - currentId) ) {
                slideRight(id);
            }

            start();
        }

        function getId (id) {
            return id.substr(7, id.length);
        }


        //dodawanie eventu do przycisku
        $slideControls.find('a').click(function() {
            if ($container.find('a:has(img)').is(":animated")) {
                return false;
            }
            clearInterval(intervalInstance);
            slideTo($(this).attr('href').substr($(this).attr('href').search('#') + 1, $(this).attr('href').length));
            return false;
        });

        if (options.autoStart == true) {
            start();
        }
    };
    
})(jQuery);
