function strip_tags(g,h){var m="",j=false;var f=[];var a=[];var l="";var d=0;var c="";var e="";var b=function(k,i,n){return n.split(k).join(i);};if(h){a=h.match(/([a-zA-Z0-9]+)/gi);}g+="";f=g.match(/(<\/?[\S][^>]*>)/gi);for(m in f){if(isNaN(m)){continue;}e=f[m].toString();j=false;for(c in a){l=a[c];d=-1;if(d!=0){d=e.toLowerCase().indexOf("<"+l+">");}if(d!=0){d=e.toLowerCase().indexOf("<"+l+" ");}if(d!=0){d=e.toLowerCase().indexOf("</"+l);}if(d==0){j=true;break;}}if(!j){g=b(e,"",g);}}return g;}
var j = jQuery.noConflict();

var count = 0;
var cloud = {
    'image': {
        'handler': '.library-image',
        'structure': '<a class="cloud cloud-image"><span class="add"></span></a>'
    },
    'content': {
        'handler': '.columnrow p, .contentrow p',
        'structure': '<a class="cloud cloud-text"></a>'
    },
    'header': {
        'handler': '#content h1, #articleinfo h2',
        'structure': '<a class="cloud cloud-header"><span class="add"></span></a>'
    }
}

var instance = '';

var procedPost = true;
var Discussion = {
    start: function() {
        this.decoration();
        this.moderate();
        this.scrollbar();
        this.thread();
        this.post();
        this.thumbnails();
    },
    
    thumbnails: function() {
        j('.post .right').each(function() {
            var list = '<ul class="thumbnail-list">';
            j(this).find('.preview-attachment').each(function() {
                var rel = j(this).attr('rel');
                var href = j(this).attr('href');
                var name = j(this).attr('class');
                list += '<li><a href="'+href+'" rel="'+rel+'" class="'+name+'"><img src="'+rel+'" /><span class="frame"></span></a></li>';        
            });
            list += '</ul>';
            j(this).append(list);
        });
    },

    moderate: function() {
        j('.moderate').click(function() {
            var Jself = j(this);
            var proced = confirm("Czy na pewno chcesz zgłosić tą wiadomość moderatorowi?")
            if (proced) {
                var data = 'content='
                    + encodeURIComponent(Jself.parent().parent().parent().find('p').html())
                    + '&discussion='
                    + encodeURIComponent(Jself.attr('rel'));
                var url = "/poradnik/moderacja/";
                j.post(url, data, function(data) {
                    Jself.html('Zgłoszono');
                }, "text");
            }
            return false;
        });
    },

    scrollbar: function() {
        try {
            j('.contento .scroll').jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 20, dragMinHeight: 15});
        } catch(e) {
            alert(e);
        }
    },
    
    thread: function() {
        var Layer = new Windows('#frame_new_thread', false);
        var self  = this;
        Layer.close('.cancel', function() {
            tinyMCE.execCommand('mceRemoveControl', false, 'new_thread_content');
        });
        Layer.open('#new_thread',
            function() {
                var tutorial  = tutorial_id;
                tutorial = '<input type="hidden" name="data[post][tutorial]" value="' + tutorial + '" />';
                tutorial_url = '<input type="hidden" name="tutorial_url" value="' + j(Layer.openElement).attr('rel') + '" />';
                var content = ''
                content += '<div class="frame_discussion" id="frame_new_thread">';
                content += '<div class="open"></div>';
                content += '<div class="body">';
                content += '<div class="content">';
                content += '<form action="/threads/add" id="new_thread_form" method="post" accept-charset="utf-8">';
                content += '<fieldset>';
                content += tutorial;
                content += tutorial_url;
                content += '<p><input id="new_thread_title" type="text" name="data[post][title]" value="Tutaj wpisz temat rozpoczynanej dyskusji."/></p>';
                content += '<p><textarea id="new_thread_content" class="new_thread_content" name="data[post][content]" rows="8" cols="40">Tutaj wpisz treść pierwszego posta w dyskusji.</textarea></p>';
                content += '</fieldset>';
                content += '</form>';
                content += '<p class="buttons action"><a class="cancel" href="#cancel">Anuluj</a><a class="submit" href="#submit">Gotowe</a></p>';
                content += '</div>';
                content += '</div>';
                content += '<div class="close"></div>'
                content += '</div>';
                Layer.init(content);
            }, function() {
                instance = 'thread';
                self.manage('thread');
                var position = j('#new_thread').position();
                var b = j('body').height() - Math.round(position.top + 8);
                j('#frame_new_thread').css({bottom: b});
                self.buttons();
                self.decoration();
            }
        );
    },
    
    post: function() {
        var Layer = new Windows('#frame_new_post', false);
        var self  = this;
        Layer.close('.cancel');
        Layer.open('#new_post',
            function() {
                var thread  = j(Layer.openElement).attr('rel');
                thread = '<input type="hidden" name="data[post][thread]" value="' + thread + '" />';
                var content = ''
                content += '<div class="frame_discussion" id="frame_new_post">';
                content += '<div class="open"></div>';
                content += '<div class="body">';
                content += '<div class="content">';
                content += '<form action="/threads/add" id="new_post_form" method="post" accept-charset="utf-8">';
                content += '<fieldset>';
                content += thread;
                content += '<p><textarea id="new_post_content" class="new_post_content" name="data[post][content]" rows="8" cols="40">Tutaj wpisz treść posta.</textarea></p>';
                content += '</fieldset>';
                content += '</form>';
                content += '<p class="buttons action"><a class="cancel" href="#cancel">Anuluj</a><a class="submit" href="#submit">Gotowe</a></p>';
                content += '</div>';
                content += '</div>';
                content += '<div class="close"></div>'
                content += '</div>';
                Layer.init(content);
            }, function() {
                instance = 'post';
                self.manage('post');
                var position = j('#new_post').position();
                var b = j('body').height() - Math.round(position.top - 28);
                j('#frame_new_post').css({bottom: b});
                self.buttons();
                self.decoration();
            }
        );
    },
    
    attach: function(editor) {
        
        j('#new_'+instance+'_content_attach').after('<span id="attach-loader"></span>');

        var position = j.browser.msie ? editor.selection.getBookmark(false) : false;
        if (position) editor.selection.moveToBookmark(position);

        var frame = j('.frame_discussion');

        function terminate() {
            j('#frame_new_attachment').fadeOut('120', function() {
                j(this).remove();
            });
        }

        function paste(filetype, src, rel) {
            count++;
            var link = {};
            switch (filetype) {
                case 'flickr':
                    link.src = src;
                    link.rel = rel;
                break;
                case 'normal':
                    link.rel = '/files/attachments/' + src;
                    link.src = '/files/attachments/thumb_' + src;
                break;
            }
                    
            var container = j('.frame_discussion .content');
            if (!document.getElementById('frame_thumbnail'))
                container.append('<ul id="frame_thumbnail"></ul>');
            container.find('#frame_thumbnail').append('<li><span><em>usuń</em></span> <a class="preview-attachment open-'+filetype+'" href="'+link.rel+'" rel="'+link.src+'">zdjęcie '+count+'</a></li>');
            editor.execCommand('mceInsertContent', false, '<a class="preview-attachment open-'+filetype+'" href="'+link.rel+'" rel="'+link.src+'">[zdjęcie '+count+']</a>');
        };

        j('#frame_thumbnail li span').live('click', function() {
            var element = j(this).parent().find('a').attr('href');
            j('iframe').contents().find("a[href='"+element+"']").remove();
            tinyMCE.triggerSave();
            j(this).parent().remove();
        })
        
        j.ajax({
            url: '/request/attachment/view/',
            cache: true,
            success: function(content) {
                var c = j('#new_'+instance+'_content_attach').position().top - 225;
                j(content).animate({opacity: 0}, 0).css('top', c).prependTo(frame).animate({opacity: 1}, 120, function() {
                    j('#attach-loader').fadeOut(100, function() { j(this).remove(); });
                    if (j.browser.msie)
                        this.style.removeAttribute('filter');
                    Scroller('.flickr');
                    j('#frame_new_attachment .flickr a').click(function() {
                        if (j(this).is('.active')) {
                            j(this).removeClass('active');
                        } else {
                            j('.flickr a').removeClass('active');
                            j(this).toggleClass('active');
                        }
                        return false;
                    });
                    var proced = false;
                    j('#frame_new_attachment .insert').click(function() {
                        if (proced)
                            return false;
                        proced = true;
                        var src = j('#frame_new_attachment .flickr .active').find('img').attr('src');
                        var href = j('#frame_new_attachment .flickr .active').attr('href');
                        var file = j("#frame_new_attachment input[name='data[post][file]']").val();
                        if (src && file) {
                            Message('Możesz wybrać tylko jeden obrazek.', 'attachment');
                            return false;
                        }

                        if (href || file) {
                            if (href) {
                                proced = false;
                                paste('flickr', src, href);
                                terminate();
                            }
                            if (file) {                                                     
                                j('#new_attachment_form').ajaxSubmit({
                                    dataType: 'json',
                                    success: function(e) {
                                        proced = false;
                                        if (e.status == true) {
                                            paste('normal', e.file);
                                            terminate();
                                        } else {
                                            Message(e.msg, 'attachment')
                                        }
                                    }
                                });
                            }
                        } else {
                            proced = false;
                            Message('Nie wybrano obrazka.', 'attachment');
                        }
                        return false;
                    })
                    j('input.file').filestyle({
                        imageheight : 30,
                        width: 128,
                        imagewidth : 63
                    });
                    j('#underoverlay, #frame_new_attachment .cancel').click(function() {
                        terminate();
                        return false;
                    });
                });
            }
        });
    },
    
    proced: function(type) {
        tinyMCE.triggerSave();
        if (procedPost) {
            var options = { 
                dataType: 'json',
                success: function(d) {
                    if (d.status == false) {
                        var message = '';
                        j(d.message).each(function(i, e) {
                            message += '<li>' + e + '</li>'; 
                        });
                        Message(message, type);
                    } else {
                        if (d.redirect) {
                            j('#frame_new_' + type).fadeOut(120);
                            window.location.href = d.redirect;
                        }
                    }
                    procedPost = true;
                }
            }
            j('#new_' + type + '_form').ajaxSubmit(options);
        }
        return false;
    },

    manage: function(type) {
        count = 0;
        j('#frame_new_' + type + ' .submit').click(function() {
            Discussion.proced(type);
            procedPost = false;
        });
        function removeDefault(editor) {
            var content = tinyMCE.activeEditor.getContent();
            if (content && content.length > 0) {
                if (strip_tags(content) === 'Tutaj wpisz treść pierwszego posta w dyskusji.'
                || strip_tags(content) === 'Tutaj wpisz treść posta.') {
                    tinyMCE.activeEditor.setContent('');
                }
            }
        }
        j('.new_' + type + '_content').tinymce({
            script_url : '/template/script/tiny_mce/tiny_mce_src.js',
            mode : "textareas",
            theme : "advanced",
            plugins : "safari,autoresize,paste",
            theme_advanced_buttons1 : "bold,italic,attach",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_buttons4 : "",
            entities : "",
            apply_source_formatting : true,
            remove_trailing_nbsp : true,
            forced_root_block : '',
            force_br_newlines: true,
            auto_resize : true,
            remove_script_host : false,
            convert_urls : false,
            paste_use_dialog : false,
            paste_auto_cleanup_on_paste : true,
            theme_advanced_toolbar_location : "bottom",
            theme_advanced_toolbar_align : "left",
            extended_valid_elements : "a[name|href|target|title|rel|class],img[class|src|alt|rel]",
            setup: function(e) {
                e.addButton('attach', {
                    title : 'Wstaw obrazek',
                    onclick : function() {
                        Discussion.attach(e);
                    }
                });
                e.onEvent.add(function(e) {
                    removeDefault(e);
                });
            }
        });
    },
    
    buttons: function() {
        j('.mceButton').hover(function(element) {
            var name = j(this).attr('class');
            j(this).parent().parent().find('.label').addClass('label-' + name).show();
        }, function() {
            var name = j(this).attr('class');
            j(this).parent().parent().find('.label').removeClass('label-' + name).hide();
        });
        j('.frame_discussion input').one('focus', function() {
            j(this).val('');
        });        
    },
    
    decoration: function() {
        j('.open-normal').live('click', function(){
            var content = j('<div id="image_window" class="wimage"></div>');
            content.append('<div class="content"><a class="image" href="#image" title=""></a></div>');
            content.append('<div class="close"><a class="terminate" href="#close"></a></div>');
            var values = {
                'height' : j('body').height(),
                'width'  : j('body').width()
            };
            var source = { 'src' : j(this).attr('href') };
            j('<div id="image_overlay"></div>').animate({opacity: 0}, 0).prependTo('body').css(values).animate({opacity: 0.6}, 180, function() {
                j(content).animate({opacity: 0}, 0).prependTo('body').animate({opacity: 1}, 260, function() {
                    new Loader(source, '#image_window');
                    Close();
                    j('#image_window .image').click(function() { return false });
                }).center();
            });
            return false;
        });  
        j('.open-flickr').live('click', function(){
            var target = {
                'src': j(this).attr('rel').replace("_s", ""),
                'href': j(this).attr('href')
            }
            Flickr(target);
            return false;
        });
    }
};

var Profiler={flickr:function(){j('.flickr .image').bind('click',function(){var target={'src':j(this).attr('rel'),'href':j(this).attr('href')}
Flickr(target);return false;});},construct:function(){var Layer=new Windows();Layer.close('.close');Layer.open('.user-profile',function(){var id=j(Layer.openElement).attr('rel');j.ajax({url:'/request/profile/view/'+id+'/window/',cache:false,success:function(content){Layer.init(content);}});},function(){j('.wpublic .list dt').bind('click',function(){j(this).toggleClass('active').next().slideToggle(300);});Scroller('.flickr');Profiler.flickr();});j('.spy .email').click(function(){return false;})
j('.rss').attr('target','_blank');j('.spy .email').click(function(){var type=j(this).attr('rel');var self=this;j.getJSON('/poradnik/sledzenieprzezemail/'+type,function(data){if(data.result==0)
alert('Musisz się zalogować aby śledzić dyskusję przez e-mail');else
j(self).toggleClass('follow').find('em').toggle();})
return false;})}};

var imagebox = {
    show: function() {
        imagebox.display(j(this).attr('href'));
        return false;
    },

    open: function(target) {
        imagebox.display(target);
    },
    
    display: function(target) {
        var source = {src: target, 'title': 'Kliknij aby zamknąć zdjęcie.'};
        var content = j('<div id="image_window" class="wimage"></div>');
        content.append('<div class="content"><a class="image" href="" title=""></a></div><div class="close"><a class="terminate" href="#"></a></div>');
        var values = {'height' : j('body').height(), 'width'  : j('body').width()};
        j('<div id="image_overlay"></div>').animate({opacity: 0}, 0).prependTo('body').css(values).animate({opacity: 0.6}, 180, function() {
            j(content).animate({opacity: 0}, 0).prependTo('body').animate({opacity: 1}, 260, function() {
                new Loader(source, '#image_window');
                imagebox.bind();
            }).center();
        });
        return false;
    },
    
    addition: function() {
        var target = this;
        jQuery.ajax({
            url: j(target).attr('href'),
            cache: false,
            success: function(content){
                j('<div id="overlay"></div>').animate({opacity: 0}, 0).prependTo('body').css({'width': j('body').width(), 'height': j('body').height()}).animate({'opacity': 0.6}, 180, function() {
                    j(content).animate({opacity: 0}, 0).prependTo('body').animate({opacity: 1}, 260, function() {
                        Cufon.replace('#guide h1', {fontFamily: 'GlasgowPl RR ExtraBold'});
                        Cufon.replace('#guide h3 span', {fontFamily: 'GlasgowPl RR Light'});
                        imagebox.bind();                    
                    }).center();
                });
            }
        });
        return false;
    },
    
    flash: function(target) {
        jQuery.ajax({
            url: j(target).attr('href'),
            cache: false,
            success: function(content){
                j('body').append(content);
                var w = {'width': j('#windowsize').width(), 'height': j('#windowsize').height()};
                j('#image_overlay').animate({opacity: 0}, 0).css({'width': j('body').width(), 'height': j('body').height()}).animate({'opacity': 0.6}, 180, function() {
                    j('#image_window').css({'marginLeft': - (w.width / 2), 'width': w.width, 'height': w.height, 'visibility': 'visible'}).center();
                    imagebox.bind();                    
                });
            }
        });
        return false;
    },

    bind: function() {
        j('#image_overlay, #image_window .close, #image_window .image, #window .terminate, #overlay').click(imagebox.hide);
    },
    
    hide: function() {
        j('#image_window, #window').fadeOut('120', function() {
            j('#image_overlay, #overlay').fadeOut('60', function() {
                j('#image_window, #image_overlay, #overlay, #window').remove();
            });
        });
        return false;
    }
}

var Librarian = {
    Start: function() {
        j('img').addClass('library-image');
        this.Images();
        this.Selection();
        this.Topic();
        this.Header();
    },
    
    Flash: function(value) {
        j.get('/request/flash/add/' + value + '/json/');
    },

    Selection: function() {
        var range = true;
        var time = 0;
        var fade = 500;
        j(cloud.content.handler).mouseup(function(e) {
            function removeThumbler() {
                clearTimeout(time);
                j('.cloud-text').hide().remove();
            }
            removeThumbler();
            j(cloud.content.handler + ':not(.cloud)').bind('click', removeThumbler);
            var userSelection;
            var selection = '';
            if (window.getSelection) {
                userSelection = window.getSelection();
                if (userSelection.getRangeAt) {
                    try {
                        selection = userSelection.getRangeAt(0);
                    } catch(e) {}
                } else {
                    userSelection = document.selection.createRange();
                    userSelection.setStart(userSelection.anchorNode,userSelection.anchorOffset);
                    userSelection.setEnd(userSelection.focusNode,userSelection.focusOffset);
                    selection = userSelection;
                }
            } else if (document.selection && document.selection.createRange) {
                var range = document.selection.createRange();
                selection = range.text;
            }
            selection = '' + selection;
            // alert(alert(selection.length));
            if (selection.length > 3) {
                var date = new Date();
                var id = 'selection' + date.getTime();
                var css = {
                    'top' : e.pageY + 15,
                    'left': e.pageX + 15
                }
                j(cloud.content.structure).appendTo('body').css(css).attr('id', id).click(function() {
                    var self = j(this);
                    var data = 'data[Snippet][source_section]=tutorials&data[Snippet][source_id]='
                            + encodeURIComponent(tutorial_id)
                            + '&data[Snippet][contents]='
                            + encodeURIComponent(selection);
                    var url = "/snippets/addToLibrary/";
                    j.post(url, data, function(data) {
                        self.addClass('cloud-text-added');
                        time = setTimeout(function() {
                            self.hide();
                        }, 600);
                    }, "text");
                });
            }

            time = setTimeout(function() {
                j('#' + id).hide();
            }, 30000);
        });
    },

    Images: function() {
        var range = true;
        var time = 0;
        var fade = 500;
        j(cloud.image.handler).not('.disabled').mouseover(function() {
            var rel = j(this).attr('rel');
            var thumbler = 'thumbler' + rel;
            if (document.getElementById(thumbler)) {
                var thumbler = j('#' + thumbler);
                if (!(thumbler.hasClass('cloud-image-added')))
                    thumbler.show();
            } else {
                j(cloud.image.structure).insertAfter(this).attr('id', thumbler);
                var thumbler = j('#' + thumbler);
                thumbler.hover(
                    function() {
                        range = false;
                    }, function() {
                        range = true;
                    }
                );
                thumbler.click(function() {
                    var self = j(this);
                    self.addClass('cloud-image-added');
                    j.get('/illustrations/addToLibrary/' + rel, function() {
                        time = setTimeout(function() {
                            self.hide();
                        }, 600);
                    });
                    return false;
                })
            }
        });
        j(cloud.image.handler).mouseout(function() {
            var rel = j(this).attr('rel');
            time = setTimeout(function() {
                if (range) {
                    var thumbler = 'thumbler' + rel;
                    j('#' + thumbler).hide();
                }
            }, 600);
        });
    },
    
    Header: function() {
        var range = true;
        var time = 0;
        var fade = 500;
        j(cloud.header.handler).mouseover(function() {
            var element = this;
            var thumbler = 'thumbler-header';
            if (document.getElementById(thumbler)) {
                var thumbler = j('#' + thumbler);
                if (!(thumbler.hasClass('cloud-header-added')))
                    thumbler.show();
            } else {
                j(cloud.header.structure).appendTo(j(element).parent()).attr('id', thumbler);
                var thumbler = j('#' + thumbler);
                thumbler.hover(
                    function() {
                        range = false;
                    }, function() {
                        range = true;
                    }
                );
                thumbler.click(function() {
                    var self = j(this);
                    self.addClass('cloud-header-added');
                    j.get('/tutorials/ajaxAddToLibrary/' + tutorial_id, function() {
                        time = setTimeout(function() {
                            self.hide();
                        }, 600);
                    });
                    return false;
                })
            }
        });
        j(cloud.header.handler).mouseout(function() {

            time = setTimeout(function() {
                if (range) {
                    j('#thumbler-header').hide();
                }
            }, 600);
        });
    },

    Topic: function () {
        j('#contentbigbutton .button').click(function() {
            if ((typeof logged === 'undefined') == false) {
                j.get('/przeczytany/' + tutorial_id, function() {
                    j('#topicunknown').css({backgroundPosition: 'bottom center'});
                }, "html");
            }
            return false;
        });
    }
}

j(document).ready(function() {
    j('.image-zoom').click(imagebox.show);
    j('.flash-zoom').click(function() {
        imagebox.flash(this);
        return false;
    });
    
    j('.additions').click(imagebox.addition);

    if ((typeof logged === 'undefined') == false) { Librarian.Start(); }

    var Layer = new Windows();
    Layer.close('.terminate');
    Layer.open('.helper',
        function() {
            j.ajax({
                url: Layer.handler,
                cache: false,
                success: function(content){
                    Layer.init(content);
                }
            });
        }
    );
    j('.photo-zoom').click(function() {
        var source = {
            src: j(this).attr('href'),
            'title': 'Kliknij aby zamknąć zdjęcie.'
        };

        var content = j('<div id="image_window" class="wimage"></div>');
        content.append('<div class="content"><a class="image" href="" title=""></a></div>');
        content.append('<div class="close"><a class="terminate" href="#"></a></div>');
        var values = {
            'height' : j('body').height(),
            'width'  : j('body').width()
        };
        j('<div id="image_overlay"></div>').animate({opacity: 0}, 0).prependTo('body').css(values).animate({opacity: 0.6}, 180, function() {
            j(content).animate({opacity: 0}, 0).prependTo('body').animate({opacity: 1}, 260, function() {
                new Loader(source, '#image_window');
                j('#image_window .image').click(function() {
                    j('#image_window').fadeOut('120', function() {
                        j('#image_overlay').fadeOut('60', function() {
                            j('#image_window').remove();
                            j('#image_overlay').remove();
                        });
                    });
                    return false;
                })
                Close();
            }).center();
        });
        return false;
    });
    Profiler.construct();
    Discussion.start();
    Cufon.replace('#tutorial-header h2 strong, h2 span, h5.sub, .promotion span', {fontFamily: 'GlasgowPl RR Light'});
    Cufon.replace('#tutorial-header h1, h4, h2 > strong, h5.sub > strong, , .promotion strong', {fontFamily: 'GlasgowPl RR ExtraBold'});
});