function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

(function($) {
    $.fn.showPopup = function() {
        return $(this).each(function() {
            var root = $(this);			
            root.find('.popupLink').each(function() {
                var popup = $(this).parent().find('.Popup').appendTo('Body');
                $(this).data('popup', popup.attr('id'));
                $(this).click(function(e) {				
                    e.preventDefault();
                    popup.fadeIn('fast', function() {
                        popup.css('top', $(window).height() / 2 - popup.height() / 2);
                    });
                    createCookie(popup.attr('id'), 1, 365);
                });
            });

            $(function() {
                root.find('.popupLink').each(function() {
                    var pop = $('#' + $(this).data('popup'));
                    var a = $('<a></a>').attr('href', '#').addClass('closePopup').text('Sulje').click(function(e) {
                        e.preventDefault();						
                        pop.fadeOut('fast');
                        createCookie(pop.attr('id'), 1, 365);
                    });
                    pop.append(a);                    
                    if (!readCookie($(this).data('popup'))) {                        
						pop.fadeIn('fast', function() {
							pop.css('top', $(window).height() / 2 - pop.height() / 2);
						});
                    }
                });
            });
        });
    };

})(jQuery);
