// Style Switcher + Cookie
if ($.cookie("css")) {
    $("#contrast").attr("href", $.cookie("css"));
}
else {
    $.cookie('css', '/media/css/no-contrast.css', {expires: 365, path: '/'});
}

var prefix;

$(document).ready(function() {

    // Globals
    if ($.cookie("css")=== "/media/css/hi-contrast.css") {
        var source = $('.map-container img').attr("src").replace("/media/img/mapka-polski.png", "/media/img/contrast/mapka-polski.png");
        $('.map-container img').attr('src', source);
    }

    // Style Switcher
    $(".visual-impairment a").click(
        function() {
            if ($.cookie("css") === "/media/css/hi-contrast.css") {
                $("#contrast").attr("href", "/media/css/no-contrast.css");
                $.cookie('css', '/media/css/no-contrast.css', {expires: 365, path: '/'});
                var prefix = "/media/img/map/";
                $("#regiomap-sidebar").attr("src", "/media/img/map/find-your-region-map.png");
                var source = $('.map-container img').attr("src").replace("/media/img/contrast/mapka-polski.png", "/media/img/mapka-polski.png");
                $('.map-container img').attr('src', source);

                return false;
            } else {

                $("#contrast").attr("href", "/media/css/hi-contrast.css");
                $.cookie('css', '/media/css/hi-contrast.css', {expires: 365, path: '/'});
                var prefix = "/media/img/map/contrast/"
                $("#regiomap-sidebar").attr("src", "/media/img/map/contrast/find-your-region-map.png");
                var source = $('.map-container img').attr("src").replace("/media/img/mapka-polski.png", "/media/img/contrast/mapka-polski.png");
                $('.map-container img').attr('src', source);

                return false;
            }

        });


    $(document).bind('keydown', function(e) {
        if (e.which == 27) {
            $('.prompt-popup').fadeOut(500, function () {
                // $('.prompt-popup').remove();
                //$(document).unbind('keydown');
            });
            $('#topbar-search').fadeOut(500, function () {
                //$('#topbar-search').remove();
                //$(document).unbind('keydown');
            });
            e.stopPropagation();
            e.preventDefault();
        }
    });


    /*  $(document).ready(function() {
     $("#splash-screen-link").fancybox({'showCloseButton' : 'true', 'centerOnScroll':'true'}).trigger('click');
     });

     $('#splash-screen a:eq(1)').click(function(){
     $(this).fancybox.close();
     });

     */

    $("#people-in-platform .people li").hover(function () {
            $("#people-in-platform .people li").stop().animate({opacity:0.8}, 500);
            $(this).stop().animate({opacity:1}, 200);
        },
        function() {
            $("#people-in-platform .people li").stop().animate({opacity:1}, 200);
        })
//    var zoomelement = '<div class="program-zoom"><a class="program-zoomin" href="#">A</a></div>';
//    $(zoomelement).insertAfter('.article-content h1.bigfont');
});


var PO = {

    init: function() {

        if ($('div#promo-slider').length > 0) {
            this.slidePromoSection();
        }

        if ($('a.quick-news-expand').length > 0) {
            this.quickNewsExpanderInit();
        }

        $('form.jqtransform').jqTransform();

        if ($('input[type="text"]').length > 0) {
            $('input[type="text"]').each(function(el) {
                PO.inputDefaulter($(this))
            });
        }

        if ($('input[type="email"]').length > 0) {
            $('input[type="email"]').each(function(el) {
                PO.inputDefaulter($(this))
            });
        }

        if ($('textarea').length > 0) {
            $('textarea').each(function(el) {
                PO.inputDefaulter($(this))
            });
        }

        if ($('#what-we-did').length > 0) {
            this.equalHeights();
        }

        this.fontResize();
        this.searchDropdown();
        this.equalTabs();
        this.articleZoom();
        this.initMap();
        this.initArticle();
    },

    initArticle: function () {


        $('html').click(function() {
            $('.prompt-popup').fadeOut(500, function () {
                $('.prompt-popup').remove();
                $(document).unbind('keydown');
            });
        });

        $('.article-email-send').click(function (e) {
            e.preventDefault();
            e.stopPropagation();

            var html = '<form><input type="text" name="email" value="Wpisz adres e-mail..." /><button type="submit">OK</button></form>';

            $(document).bind('keydown', function(e) {
                if (e.which == 27) {
                    $('#topbar-search').fadeOut(500, function () {

                        $(document).unbind('keydown');
                    });
                    e.stopPropagation();
                    e.preventDefault();
                }
            });


            $('.prompt-popup').remove();
            $('<div>', {'class': 'prompt-popup', 'html': html}).appendTo('body');
            $('.prompt-popup').css({'top': parseInt(($(this).offset().top + $(this).height() / 2) - ($('.prompt-popup').height() / 2)), 'left': parseInt(($(this).offset().left + $(this).width() / 2) - ($('.prompt-popup').width() / 2))})


            $('.prompt-popup').click(function(e) {
                e.stopPropagation();
            });

            $('.prompt-popup input').data('default', $('.prompt-popup input').val()).focus(
                function () {
                    if ($(this).val() == $(this).data('default')) {
                        $(this).val('')
                    }
                }).blur(function () {
                    if ($(this).val() == '') {
                        $(this).val($(this).data('default'))
                    }
                })

            $('.prompt-popup form').submit(function (e) {
                e.preventDefault();

                window.location = 'mailto:' + $('.prompt-popup input').val() + '?subject=' + $('article.main-article > h2:first-child').text() + "&body=Witaj, %0AChcę się z Tobą podzielić artykułem, który przeczytałem na Platforma.org%0A%0A" + ARTICLE_LEAD + '%0A%0A' + window.location.href;

                $('.prompt-popup').fadeOut(500, function () {
                    $('.prompt-popup').remove();
                    $(document).unbind('keydown');
                });

                /*$.getJSON('-- TUTAJ WPISZ SCIEZKE --', {'email': $('.prompt-popup input').val()}, function (result) {
                 if (result.status == 'OK') {
                 $('.prompt-popup').fadeOut(500, function () {
                 $('.prompt-popup').remove();
                 $(document).unbind('keydown');
                 });
                 } else {
                 // error
                 $('button', this).removeAttr('disabled')
                 }
                 })*/
            })

        })
    },


    initMap: function() {

        var target = $('#regiomap-sidebar');
        var map = $('#regiomap');
        var prefix = "/media/img/map/";

		if (map.size() == 0) { return false; }

        var change = [
            'find-your-region-map-1.png',
            'find-your-region-map-2.png',
            'find-your-region-map-6.png',
            'find-your-region-map-4.png',
            'find-your-region-map-3.png',
            'find-your-region-map-5.png',
            'find-your-region-map-8.png',
            'find-your-region-map-9.png',
            'find-your-region-map-10.png',
            'find-your-region-map-11.png',
            'find-your-region-map-13.png',
            'find-your-region-map-14.png',
            'find-your-region-map-12.png',
            'find-your-region-map-15.png',
            'find-your-region-map-7.png',
            'find-your-region-map-16.png'
        ];

        if ($.cookie("css") === "/media/css/hi-contrast.css") {
            prefix = "/media/img/map/contrast/";
        } else {
            prefix = "/media/img/map/";
        }

        for (i in change) {
            var im = new Image();
            im.src = prefix+change[i];
        }

        $('area', map).hover(function () {

            if ($.cookie("css") === "/media/css/hi-contrast.css") {
                prefix = "/media/img/map/contrast/";
            } else {
                prefix = "/media/img/map/";
            }

            $(target).attr('src', prefix + change[$(this).index()]);
        }, function () {

            if ($.cookie("css") === "/media/css/hi-contrast.css") {
                prefix = "/media/img/map/contrast/";
            } else {
                prefix = "/media/img/map/";
            }
            $(target).attr('src', prefix + 'find-your-region-map.png');
        })
    },

    articleZoom: function () {

        var article = $('article.main-article p, article.main-article, .main-article span').data('size', 16)
        var title = $('article.main-article > h2:first-child');
        var container = $('<div>', {'class': 'article-zoom'}).insertAfter(title)

        $('<div class="article-zoom"><a class="zoom-in" href="#">A</a></div>').insertAfter('.main-article >h2:first-child');

        $(".article-zoom a").toggle(
            function() {
                $(".main-article > h2, .main-article p, .main-article span, .main-article").children().each(function() {
                    var txtSize = parseFloat($(this).css('fontSize'));
                    var newSize = txtSize * 1.2;

                    $(this).css('fontSize', newSize);
                });
            },
            function() {
                $(".main-article > h2, .main-article p, .main-article span, .main-article").children().each(function() {
                    var txtSize = parseFloat($(this).css('fontSize'));
                    var newSize = txtSize / 1.2;

                    $(this).css('fontSize', newSize);
                });
            });
    },




    equalTabs: function () {
        /*  if($('h2.hd:contains("KW PO")').length > 0) {

         $(".filters ul li a").css(
         {
         "paddingTop": "7px",
         "paddingRight": "18px",
         "paddingBottom": "7px",
         "paddingLeft": "18px",

         }
         )

         } else {}*/
        var tabs = $('.filters .tabs li')
        var container = $('.filters .tabs')
        var itemWidth = (container.width() / tabs.size()) - (tabs.size() - 1);
        $('.filters .tabs a').css({width: itemWidth})
    },

    equalHeights: function() {

        $articles = $('#what-we-did').find('article');
        var maxHeight = 0;

        $articles.each(function() {
            var currentHeight = $(this).find('.content').height();
            if (!$(this).hasClass('find-a-member') && !$(this).hasClass('photostory')) {
                if (currentHeight > maxHeight) {
                    maxHeight = currentHeight;
                }
            }
        });

        $articles.each(function() {
            if (!$(this).hasClass('find-a-member') && !$(this).hasClass('photostory')) {
                $(this).find('.content').height(maxHeight);
            }
        });
    },

    inputDefaulter: function($elem) {
        if ($elem.attr('data-placeholder')) {
            var defaultText = $elem.attr('data-placeholder');
            $elem.val(defaultText);

            $elem.blur(function(e) {
                if ($elem.val() == '') {
                    $elem.val(defaultText);
                }
            });

            $elem.focus(function(e) {
                if ($elem.val() == defaultText) {
                    $elem.val('');
                }
            });

        }
    },

    searchDropdown: function() {
        $('#topbar .search a').click(function(e) {
            e.preventDefault();

            $('#topbar-search').toggle();
            $("#search-phrase").focus();

        });
    },




    fontResize: function() {
        $('li.text-size a').click(function(e) {
            e.preventDefault();

            var currentFontSize = $(document.body).attr('data-fontsize');
            var currentClasses = $(document.body).attr('class');

            if (currentFontSize != undefined) {
                currentFontSize = jQuery.trim(currentFontSize);
            }

            if (currentClasses != undefined) {
                currentClasses = currentClasses.replace(currentFontSize, '');
            } else {
                currentClasses = '';
            }

            // Decrease font size
            if ($(this).hasClass('smaller')) {
                switch (currentFontSize) {
                    case 'smaller':
                        currentFontSize = ' smaller';
                        break;
                    case 'bigger':
                        currentFontSize = '';
                        break;
                    case 'biggest':
                        currentFontSize = ' bigger';
                        break;
                    case '':
                    case undefined:
                        currentFontSize = ' smaller';
                        break;
                }
            }

            // Increase font size
            if ($(this).hasClass('bigger')) {
                switch (currentFontSize) {
                    case 'smaller':
                        currentFontSize = '';
                        break;
                    case 'bigger':
                        currentFontSize = ' biggest';
                        break;
                    case 'biggest':
                        currentFontSize = ' biggest';
                        break;
                    case '':
                    case undefined:
                        currentFontSize = ' bigger';
                        break;
                }
            }

            // Set the new font size
            $(document.body)
                .attr('data-fontsize', currentFontSize)
                .attr('class', currentClasses + ' ' + currentFontSize);

        });
    },

    slidePromoSection: function() {

        var _self = this;

        // Fetch all articles
        var current = 0;
        var slider = $('div#promo-slider');
        var articles = $(slider).find('div.single-article');

        var currentTitle = '';
        var sliderNavBullets = '';

        var slideContainer = $(slider).find('div.container');

        // Create title placeholder element
        var sliderTitle = document.createElement('span');
        sliderTitle.className = 'title';

        // Set up the titles
        // Create bullets
        for (var i = 0; i < articles.length; i++) {

            currentTitle = $(articles[i]).find('h3 a').text();

            if (i === 0) {
                sliderNavBullets += '<li class="current"><a title="' + currentTitle + '" href="#' + i + '">' + (i + 1) + '</a></li>';
                sliderTitle.innerHTML = currentTitle;
            } else {
                sliderNavBullets += '<li><a title="' + currentTitle + '" href="#' + i + '">' + (i + 1) + '</a></li>';
            }

        }

        // Append bullets
        $(slider).find('ul.slider-nav').append(sliderNavBullets);

        // Apend title element
        $(slider).find('div.nav-wrapper').append(sliderTitle);

        // Add click event to the bullets
        $(slider).find('ul.slider-nav a').click(function(e) {
            e.preventDefault();
            _self.animateSlider(this, slider, slideContainer);
        });

        // Set auto animation interval
        PO.animationInterval = setInterval(function() {
            _self.animateSlider(null, slider, slideContainer, articles);
        }, 20000);
        // Stop animation if user hovers
        $(articles)
            .mouseover(function(e) {
                clearInterval(PO.animationInterval);
            })
            .mouseout(function(e) {
                PO.animationInterval = setInterval(function() {
                    _self.animateSlider(null, slider, slideContainer, articles);
                }, 20000);
            });
    },

    animateSlider: function(link, slider, slideContainer, articles) {

        // Current element
        var current;
        var toMark = null;

        // If called by interval
        if (link === null) {

            // Grab current link
            link = $(slider).find('ul.slider-nav li.current a');
            current = parseInt($(link).attr('href').split('#')[1]) + 1;

            // If it's the last one - go back to start
            if (current >= articles.length) {
                current = 0;
                toMark = $(slider).find('ul.slider-nav li')[0];
            } else {
                toMark = $(slider).find('ul.slider-nav li.current').next();
            }

        } else {
            current = $(link).attr('href').split('#')[1];
        }

        // Reset current values
        $(slider).find('ul.slider-nav li.current').removeClass('current');

        // Animate slide
        var margin = current * 980;
        $(slideContainer).animate({'margin-left' : '-' + margin + 'px'})

        // Mark current bullet
        if (toMark === null) {
            $(link).parent('li').addClass('current');
        } else {
            $(toMark).addClass('current');
        }

        // Switch the title
        var articles = $(slider).find('div.single-article');
        $(slider).find('span.title').html($(articles[current]).find('h3 a').text());
    },

    quickNewsExpanderInit: function() {

        var _self = this;
        var $quickNews = $('#quick-news');
        var header = $quickNews.find('header')
        var fullArticle = $quickNews.hasClass('full-article');
        var excerpt = $('#quick-news').find('.excerpt');
        var $switcher = $quickNews.find('a.quick-news-expand');

        $(header).click(function(e) {
            e.preventDefault();
            e.stopPropagation();

            _self.quickNewsExpander(this, fullArticle, $switcher, excerpt, header);
        });

        $('a.quick-news-expand').click(function(e) {
            e.preventDefault();
            e.stopPropagation();

            _self.quickNewsExpander(this, fullArticle, $switcher, excerpt, header);

        });
    },

    quickNewsExpander: function(elem, fullArticle, $switcher, excerpt, expanded, header) {
        if ($(elem).hasClass('expanded')) {
            $(elem).removeClass('expanded');
            $switcher.removeClass('expanded').html('Rozwiń');

            if (fullArticle) {
                if ($(elem).parent()[0].tagName.toLowerCase() === 'h2') {
                    window.location = $(elem).attr('href');
                }
            }

        } else {
            $(elem).addClass('expanded');
            $switcher.addClass('expanded').html('Zwiń');
        }


        if ($(excerpt).css('display') == 'none') {
            $(excerpt).fadeIn('fast');
        } else {
            $(excerpt).fadeOut('fast');
        }

    }

}

$(document).ready(function() {
    PO.init();
    $(".single-article .expansion").css('cursor', 'pointer');
    $(".single-article .expansion").each(function() {
        $(this).click(function() {
            var anchor = $(this).parent().parent().find("a").attr("href");
            if (anchor)
                window.location.href = anchor;
            else return false;
        });
    });
    $("#what-we-did article").css('cursor', 'pointer');
    $("#what-we-did article").click(function() {
        var anchor = $(this).find("a").attr("href");
        window.location.href = anchor;
    });
    if ($("#support-us").length > 0) {
        jQuery.validator.addMethod("password", function(value, element) {
            var password_first = $("#password").val();
            var result = true;
            if (value != password_first) result = false;
            if (!result) {
                var validator = this;
                setTimeout(function() {
                    validator.blockFocusCleanup = true;
                    element.focus();
                    validator.blockFocusCleanup = false;
                }, 1);
            }
            return result;
        }, "hasła nie zgadzają się");


        var validator = $("#support-us").validate({
            rules: {
                email: {
                    required: true,
                    email: true
                },
                name: "required",
                surname: "required",
                password: {
                    required: true,
                    password: true
                },
                password_rpt: {
                    required: true,
                    password: true
                },
                personal_data :"required"
            },
            messages: {
                email: {
                    email: "Podaj poprawny adres e-mail"
                },
                product: "wybierz produkt z powyższej listy",
                password_rpt: "powtórz hasło",
                housenumber: "wpisz nr domu",
                personal_data: "wyraź zgodę"
            }
        });
        $.validator.messages.required = "wypełnij poprawnie to pole";
        $(".confirmation-msg-close").click(function() {
            $("#confirmation-msg-container").hide();
            return false;
        });
        $(".jqTransformCheckbox").removeClass('jqTransformChecked');
        $(".additional").hide();
        $("#want-gadget").change(function() {
            if ($(".want-gadget .jqTransformCheckbox").hasClass('jqTransformChecked')) {
                $(".additional").show();
                $(".additional input").addClass("required")
                $("#flatnumber").removeClass("required");
                $(".form-fields li.checkbox.want-gadget").css({'padding-top':'5px', 'margin-bottom':'5px'})
            }
            else {
                $(".additional").hide();
                $(".additional input").removeClass("required");
                $(".form-fields li.checkbox.want-gadget").css({'padding-top':'0px', 'margin-bottom':'10px'})
                if ($(".volunteer .jqTransformCheckbox").hasClass('jqTransformChecked')) {
                    $(".additional input#city").addClass("required");
                    $(".additional input#district").addClass("required");
                    $(".additional.city").show();
                    $(".additional.district").show();
                }
            }
        });
    }
    $(".volunteer #wolontariusz").change(function() {
        if ($(".want-gadget .jqTransformCheckbox").hasClass('jqTransformChecked')) {
            return;
        }
        else {
            if ($(".volunteer .jqTransformCheckbox").hasClass('jqTransformChecked')) {
                $(".additional input#city").addClass("required");
                $(".additional input#district").addClass("required");
                $(".additional.city").show();
                $(".additional.district").show();
            }
            else {
                $(".additional").hide();
                $(".additional input").removeClass('required');
            }
        }
    });

}); 


