var Modal = {
    disable: false,
    _handle: null,
    _clear : false,
    _bg : null,
    id: 'unique-modal-id',
    init: function() {
        if (Modal.disable) return;
        Modal._handle = $('<div id="' + Modal.id + '"> </div>');
        Modal._handle.appendTo('body');
    },
    show: function(clear){
        if (Modal.disable) return;
        if (Modal._handle == null) {
            Modal.init();
        }
        if (clear==true) {
            this._handle.addClass('clear');
        }
        Modal._handle.height($(document.body).height());
        Modal._handle.width($(document.body).width());
        //$('object').css('visibility','hidden');
        Modal._handle.show();
    },
    hide: function(){
        if (Modal.disable) return;
        if (Modal._handle == null) {
            return;
        }
        Modal._handle.removeClass('clear')
        Modal.unbind();
        Modal._handle.height(0);
        Modal._handle.width(0);
        Modal._handle.hide();
    //$('object').css('visibility','visible');
    },
    bind: function(event, callback) {
        Modal._handle.bind(event, callback)
    },
    unbind: function () {
        Modal._handle.unbind()
    },
    click: function() {
        Modal._handle.click()
    }
}

$(document).ready(function(){
    Modal.init();
    Toolbar.init();
    YouTubeFilter.init();



    //akcje otwierania i zamykania boxa about
    $('#about_button_open').click(function(){
        $(this).stop();
        $('#help').show(500);
        $(this).hide(500);
        return false;
    });

    $('#help_button_close').click(function(){
        $(this).stop();
        $.cookies.set('cookie_hide_main_about','true',3)
        $('#help').hide(500);
        $('#about_button_open').show(500);
        return false;
    });

    $('#myselectbox').selectbox();

    if ($('#main .selectbox').length) {
        $(function() {
            var zIndexNumber = 500;

            $('#main div').each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 1;
            });

            zIndexNumber = 500 + 2;
            $('#footer').css('zIndex', zIndexNumber-1);
            $('#footer div').each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber += 1;
            });
        });
    }


    $('#tabsex a').click(function(){
        $(this).stop();
        var c = $('#tabsex').find('a[class=active]');
        c.removeClass('active');
        $(this).addClass('active');
        $(c.attr('href')).hide();
        $($(this).attr('href')).show();
        return false;
    });

    $('div[title^=axis]').each(function(){
        $(this).attr('axis',$(this).attr('title').replace(/^axis:(.*?)$/, '$1'));
        $(this).attr('title','');
    });

    $('.dodaj-wpis a.btn-orange').click(function(){
        $(this).stop()
        $('.fb_post_error').remove();
        var p = {
            'fb_wall_message':$('#fb_wall_message').val()
        }
        if (!$('#fb_wall_message').val().length) {
            $('<p class="fb_post_error" style="color:red;">Wyst\u0105pi\u0142 b\u0142\u0105d!!! Proszę wprowadzi\u0107 tre\u015b\u0107 posta.</p>').insertAfter('#fb_wall_message');
            return false;
        }
        jQuery.post('/default/facebook/post-fanpage-wall', p, function(data){
            if (data['state']=='error') {
                var code = data['code'];
                var message = '';
                if (code == 100)
                {
                    message =  'Jeden z parametrów jest nieprawid\u0142owy.';
                }
                else if (code == 102)
                {
                    message =  'Sesja u\u017cytkownika straci\u0142a wa\u017cno\u015b\u0107.';
                }
                else if (code == 200)
                {
                    message =  'U\u017cytkownik nie wyrazi\u0142 zgody na publikacj\u0119.';
                }
                else if (code == 210)
                {
                    message =  'U\u017cytkownik nie jest fanem/lubi\u0105cym stron\u0119 a przez to nie mo\u017ce pisa\u0107 na Tablicy.';
                }
                else
                {
                    message =  'Nieznany b\u0142\u0105d. Najprawdopodobniej co\u015b z po\u0142\u0105czeniem z FB.'
                }
                if (message.length) {
                    $('<p class="fb_post_error" style="color:red;">Wyst\u0105pi\u0142 b\u0142\u0105d!!! '+message+'</p>').insertAfter('#fb_wall_message');
                }
            } else {
                $('#fb_wall_message').val('')
                PopupInfo.init('<div id="popup-info"><div class="popup-top"><p><img src="/images/popup-title-dziekuje.png" alt="Dzi\u0119kujemy" /></p></div><div class="popup-middle"><div><p class="message">Dzi\u0119kujemy za dodanie wiadomo\u015bci. Zostanie ona opublikowana w ci\u0105gu kilku minut</p></div></div><div class="popup-bottom"><div><a title="Zamknij" href="#" id="btn-close-popup"><img src="/images/popup-btn-zamknij.png" alt="Zamknij" /></a></div></div></div>')
                $('#fb_wall>ul').prepend($(data['post']));
            }
        }, 'json');
        return false;
    });

});

/**
* Funkcja do obsługi błędów.
* form - id formularza
*/
var Errors = {
    popupErrors : function(form) {
        $("#" + form + " .popup_error").each(function() {
            if ($(this).attr('axis').match(/^article_(sub)?category_id/)) {
                var owner = $('#article_subcategory_id_input');
                $('#article_subcategory_id').parent().parent().show().css('visibility', 'hidden');
            } else if ($(this).attr('axis').match(/^question_(sub)?category_id/)) {
                var owner = $('#question_category_id_input').parents("ul");
                $('#question_subcategory_id').parent().parent().show().css('visibility', 'hidden');
            } else {
                var owner = $('#' + $(this).attr('axis'))
            }
            var element = {
                top  : owner.position().top - 36 + (owner.height()/2),
                left : owner.position().left + owner.width() + 20
            };
            $(this).attr("style", "top:" + element.top + "px;left:" + element.left +  "px").show(10);
        });
    }
}

// Kolekcja dymków
var Smog = {
    _collection : [],
    add : function(id) {
        this._collection[id] = new Smoke(id);
    },
    get : function(id) {
        if (this._collection[id]==undefined) {
            this.add(id);
        }
        return this._collection[id];
    },
    hide : function() {
        for (i in this._collection) {
            this._collection[i].remove();
        }
        this._collection = [];
    }
}

// Pojedyńczy dymek
var Smoke = function(id) {
    this._topModifier = 0;
    this._leftModifier = 0;
    this._related = $(id);
    this._handle = null;
    this._cuurentTxt = null;
    this._currentCls = null;
    this._getHtml = function() {
        return '<div class="popup_' + this._currentCls + '"><div class="popup_' + this._currentCls + '_main">' +
        '<div class="popup_' + this._currentCls + '_arrow"></div>' +
        '<div class="popup_' + this._currentCls + '_top"></div>' +
        '<div class="popup_' + this._currentCls + '_middle">' +
        ' <p></p>' +
        '</div>' +
        '<div class="popup_' + this._currentCls + '_bottom"></div>' +
        '</div>' +
        '</div>';
    };
    this.setTopModifier = function( val ) {
        this._topModifier = val;
        return this;
    };
    this.setLeftModifier = function( val ) {
        this._leftModifier = val;
        return this;
    };
    this.resetPosition = function(topOnly) {
        var offset = this._related.offset();
        var parent = this._related.parents('form:first');
        var i = offset['top'];
        offset['top'] -= ((this._handle.height()-this._related.height())/2);
        offset['top'] += this._topModifier;
        this._handle.css('top',offset['top']+'px');
        // Reset arrow position
        var arrow = this._handle.find('div[class$="_arrow"]:first');
        var arrowTop = (this._handle.height() - parseInt(arrow.css('height')))/2;
        arrow.css('top', arrowTop);
        if (!topOnly) {
            offset['left'] = parent.offset()['left']+ parent.width() + this._leftModifier;
            this._handle.css('left',offset['left']+'px');
        }
    };
    this.show = function(type, txt) {
        if (type=='ok' || type=='success' || type=='message') {
            type='password';
        }
        if ( this._currentTxt == txt && this._currentCls == type ) {
            this.resetPosition(true);
            this._handle.show();
            return this;
        }

        if (this._handle != null) {
            this._handle.remove();
        }

        this._currentTxt = txt;
        this._currentCls = type;

        this._handle = $(this._getHtml());
        this._handle.hide()
        this._handle.appendTo('body');
        this._handle.find('p').html(txt);
        this._setClickable();
        this._handle.show();
        this.resetPosition();
        return this;
    };
    this.hide = function() {
        if (this._handle != null) {
            this._handle.hide();
        }
        return this;
    };
    this._setClickable = function() {
        if (this._handle != null && this._currentCls=='password') {
            this._handle.css('cursor','pointer');
            this._handle.click(function(){
                $(this).hide(200)
            });
        }
    };
    this.remove = function() {
        this._handle.remove();
    };
}

var Toolbar = {
    currentExpert : false,

    init: function() {
        $('#toolbar .arrow a').bind('click', Toolbar.currentExpert ? Toolbar.showExperts : Toolbar.showArticles);
        $('#toolbar .b1 a').click(Toolbar.showArticles);
        $('#toolbar .b2 a').click(Toolbar.showExperts);

        $('#toolbar-articles > div').children(':gt(2)').hide();
        $('#toolbar-experts > div').children(':gt(1)').hide();

        $('#toolbar-container a.close').click(function(){
            $(this).stop();
            var div = $(this).parent().parent();
            var el = $(this).parent()
            $(this).parent().hide('slow', function(){
                el.appendTo(div);
                var id = div.children(':visible').length;
                div.children(':eq(' + id + ')').show('slow');
            });
            return false;
        })
    },
    showArticles : function(e) {
        Toolbar.show(e);
        $('#toolbar .b2 a').removeClass('active');
        $('#toolbar .b1 a').addClass('active');
        $('#toolbar').next().next().hide();
        $('#toolbar').next().show();
        Toolbar.currentExpert = false;
        return false;
    },
    showExperts : function(e) {
        Toolbar.show(e);
        $('#toolbar .b1 a').removeClass('active');
        $('#toolbar .b2 a').addClass('active');
        $('#toolbar').next().hide();
        $('#toolbar').next().next().show();
        Toolbar.currentExpert = true;
        return false;
    },
    show: function(e) {
        $(e).stop();
        $('#toolbar .arrow a').unbind()
        $('#toolbar .arrow a').bind('click', Toolbar.hide);
        $('#toolbar .arrow a').addClass('displayed');
        return false;
    },
    hide: function(e) {
        $(e).stop();
        var toolbarArrow = $('#toolbar .arrow a');
        toolbarArrow.unbind().bind('click', Toolbar.currentExpert ? Toolbar.showExperts : Toolbar.showArticles);
        toolbarArrow.removeClass('displayed');
        $('#toolbar').next().hide();
        $('#toolbar').next().next().hide();
        return false;
    }
}

/**
* Popup z informacjami.
*
* @author Sebastian Bielawski
*/
var PopupInfo = {
    _modalInitialized: false,

    // Inicjalizajca
    init: function(response) {

        try {

        if (response == -1) {
            alert("B\u0142ąd");
        }

        if ($("#" + Modal.id).width() == 0) {
            this._modalInitialized = false;
            Modal.bind("click", this.hide);
            Modal.show();
        } else {
            this._modalInitialized = true;
        }

        if ($("#popup-info") != " ") {
            $("#popup-info").hide().remove();
        }

        $("body").append(response);
        var popup = $("#popup-info");

        $("#btn-close-popup").click(this.hide);
        popup.css("top", parseInt((window.innerHeight - popup.height()) / 2) + "px")
        .css("left", parseInt((window.innerWidth - popup.width()) / 2) + "px")
        .show();

        } catch (err) {
            $('body').append('<span class="debug" style="display:none;">'+err+'</span>');
        }
    },

    // Chowanie okna
    hide : function() {
        Modal.hide();

        var href = $("#btn-close-popup").attr("href");
        $("#popup-info").hide().remove();

        if (href != "#" && href != "anuluj") {
            return true;
        }

        return false;
    }
}

var Confirm = {
    html : null ,
    result: false,
    endoftime: new Date().getTime(),
    test : function( txt, title ){
        var html = '<div id="popup-info" style="display:none;"><div class="popup-top">' +
        '<p>'+title+'</p></div><div class="popup-middle"><div><p class="message">' +
        txt + '</p></div></div><div class="popup-bottom"><div>' +
        '<a  id="btn-close-popup"><img src="/images/popup-btn-anuluj.png"/></a>' +
        '<a  id="btn-close-confirm"><img src="/images/popup-btn-wyslij.png"/></a>' +
        '</div></div></div>';
        this.html = $(html).appendTo('body');
        $('#btn-close-popup').click(this.returnFalse)
        $('#btn-close-confirm').click(this.returnTrue)
        Modal.bind('click', this.returnFalse)
        Modal.show()
        this.html.show()
        while ((new Date().getTime()) > this.endoftime){
        //do nothing
        }
        html.remove()
        Modal.hide();
        return this.result;

    },

    returnTrue : function() {
        this.result = true;
        this.endoftime = Date().getTime() + 1000;
    },
    returnFalse: function() {
        this.result = false;
        this.endoftime = Date().getTime() + 1000;
    }
}

var YouTubeFilter = {
    init : function() {
        $.fn.tagName = function() {
            return this.get(0).tagName.toLowerCase();
        }

        $('embed').each(function(){
            if ($(this).parent().tagName()!='object'){
                var obj = $('object');
                obj.attr('application','application/x-shockwave-flash');
                obj.attr('data',$(this).attr('src'));
                obj.css('width',$(this).attr('width')+'px');
                obj.css('height',$(this).attr('height')+'px');
                $(this).attr('wmode','transparent');
                $(this).clone().appendTo(obj);
                obj.insertBefore(this)
                $(this).remove();
            } else {

        }
        })
    }

}


$(document).ready(function(){
    function getFbByAjax() {
        $.get('/default/facebook/index/',{ajaxian:1},function(data){
            $('#fb-ajax-wall-loader').children().remove();
            $(data).appendTo($('#fb-ajax-wall-loader'));
            FB.XFBML.parse(document.getElementById('fb-ajax-wall-loader'))
        })
    }
    if ($('#fb-ajax-wall-loader').length) {
        setTimeout(getFbByAjax, 200);
    }
    $('#accordion').accordion({
			autoHeight: false,
			navigation: true,
                        icons: {},
                        collapsible: true
		});
});

$(function(){
    
    // eventy GA
    $("a").click(function(){
        if (_gaq && /^http.*/.test($(this).attr('href'))) {
            _gaq.push(['_trackEvent', 'Link', 'outgoing', $(this).attr('href')]);
        }
        if (_gaq && /(zip|pdf)$/.test($(this).attr('href'))) {
            _gaq.push(['_trackEvent', 'Link', 'download', $(this).attr('href')]);
        }
    });

    // Feedback - "zgłoś błąd"
    var dialog = $("<div></div>").hide().appendTo("#holder").css("z-index", 667);
    $('.feedback a').click(function(e){
        e.preventDefault();
        $.ajax({
            url: $(this).attr('href'),
            async: false,
            dataType: 'html',
            timeout: 3000,
            success: function(data) {
                var popup = $('<div id="popup-info" class="feedbackWrapper">').html(data);
                PopupInfo.init(popup);
                $('#popup-info h1').append( $('<a>').text('Zamknij').click(function(e){e.preventDefault();PopupInfo.hide();}));
                $('#popup-info form').append('<input type="hidden" name="page" value="">');
                $('#popup-info form').submit(function(e){
                    e.preventDefault();
                    var formObj = $(this);
                    formObj.find('input[name=page]').val(document.location);
                    if (formObj.find('textarea').val() === '') {
                        alert('Wprowadź opis błędu');
                        return false;
                    }
                    var email = formObj.find('input[name=adres]');
                    if (email.length > 0 && !/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}/.test( email.val() )) {
                        alert('Wprowadź poprawny adres e-mail');
                        return false;
                    }
                    formObj.ajaxSubmit({
                        success: function(){
                            $('#popup-info .ftr').remove();
                            $('#popup-info h1').text('Dziękujemy za Twoją pomoc').append( $('<a>').text('Zamknij').click(function(e){e.preventDefault();PopupInfo.hide();}));
                            $('#popup-info .bdy').html('<p>Cały czas usprawniamy działanie portalu dlatego każda opinia i każde zgłoszenie błędów jest dla nas ważne. Nie możemy odpowiedzieć na wszystkie zgłoszenia indywidualne, ale każde jest sprawdzane przez nasz dział wsparcia technicznego.</p>');
                        }
                    });

                });
            }
        });
    });
});

