var F = {

    container : null,
    commentLabel : 'Write comment...',
    formObj : null,

    init : function() {
        if ($('comment_form')) {
            this.formObj = $('comment_form');
        }
        if ($('diary_comments')) {
            this.container = $('diary_comments');
        }
        // Set part box height
        this.partBoxHeight();

        $$('.evt').each(function(obj) {
            $(obj).observe("click", function(event) {
                event.stop();
            });
        });

        $$('#act_btn .med_button').each(function(obj) {
            $(obj).observe("click", function() {
                F.sendQuery('', this.href, this, '', 'post');
            });
        });

        if (this.formObj) {
            this.setForm(this.formObj);
        }

        $$('.slider_content').each(function(obj) {
            obj = $(obj);
            if (obj.getElementsByTagName("li").length > 0)
                new UI.Carousel(obj);
        });

        $$('.part .slider_content a, #film_sb .slider_content a').each(
                function(obj) {
                    $(obj).observe("click", function(event) {
                        event.stop();
                        var img = this.childElements()[0];
                        var newSrc = img.src.replace("_Small.", "_Large.");
                        if (this.rel == "flickr")
                            newSrc = img.src.replace("_s.", "_m.");
                        var previewObj = $(this.rel);
                        previewObj.setOpacity(0.3);
                        var dummyImage = new Image();
                        dummyImage.src = newSrc;
                        dummyImage.onload = function() {
                            previewObj.src = newSrc;
                            previewObj.setOpacity(1);
                        };
                        var allChild = this.up("ul").childElements();
                        $A(allChild).each(function(ele) {
                            $(ele).removeClassName("selected");
                        });
                        $(this.parentNode).addClassName("selected");
                    });
                });

        $$('#contentarea .apply').each(function(obj) {
            $(obj).observe("click", function(event) {
                event.stop();
                F.sendQuery('', this.href, this, '', 'post');
            });
        });
        this.loadSection();
    },

    setViewEvent : function() {
        $$('.comments_num').each(
                function(obj) {
                    $(obj).stopObserving();
                    $(obj).observe(
                            "click",
                            function(event) {
                                event.stop();
                                var updater = this.parentNode.parentNode
                                        .getElementsByClassName("childs")[0];
                                F.sendQuery(updater, this.href, this);
                            });
                });
    },

    setParentEvents : function() {
        // for paging event and show comments
        $$('.pagination a, .comments_num').each(function(obj) {

            $(obj).stopObserving();
            $(obj).observe("click", function(event) {
                event.stop();
                if (this.hasClassName('comments_num')) {
                    var updater = F.getUpdater(this);
                    if (updater != F.container) {
                        if (updater.getElementsBySelector("ul").length > 0) {
                            updater.toggle();
                            return false;
                        }
                        if (this.rel == 0)
                            return false;
                    }
                    F.sendQuery(updater, this.href, this);
                } else {
                    F.getPages(this);
                }
            });
        });

        $$('.reply').each(function(obj) {
            $(obj).stopObserving();
            $(obj).observe("click", function(event) {
                event.stop();
                F.setCommentForm(this);
            });
        });
    },

    getPages : function(thisObj) {
        HistoryManager.setHash( {
            'page' : thisObj.rel
        });
    },

    getData : function() {
        var updater = this.container;
        var url = window.location.href;
        var hash = window.location.hash;
        url = url.replace('#', "?");

        /*
         * if(updater != F.container) {
         * if(updater.getElementsBySelector("ul").length>0) { updater.toggle();
         * return false; } if(thisObj.rel==0) return false; }
         */

        // F.sendQuery(updater, url, thisObj);
        F.sendQuery(updater, url);

    },

    setCommentForm : function(thisObj) {
        var parentObj = $(thisObj.parentNode);
        var relObj = parentObj.next(0);
        if ($(parentObj.parentNode).getElementsBySelector("form").length == 0) {
            var newForm = this.formObj.cloneNode(true);
            newForm = $(newForm);
            newForm.id = "";
            Element.insert(relObj, {
                'before' : newForm
            });
            new Insertion.Top(
                    newForm,
                    '<input name="parent_id" type="hidden" value="' + thisObj.rel + '" />');

            var textareaObj = newForm.getElementsByTagName("textarea")[0];
            textareaObj.value = "";
            this.setForm(newForm);
            newForm.focusFirstElement();
            return false;
        }
    },

    setForm : function(form) {
        form.stopObserving();
        form.observe("submit", function(event) {
            event.stop();
            F.submit(this);
        });
        this.setLabel(form);
    },

    setLabel : function(form) {
        var textareaObj = form.getElementsByTagName("textarea")[0];
        textareaObj = $(textareaObj);
        textareaObj.stopObserving();
        if (form == this.formObj) {
            textareaObj.value = this.commentLabel;
            textareaObj.observe("focus", function() {
                if (this.value == F.commentLabel)
                    F.showForm(form);
            });
        }
        textareaObj.observe("blur", function(event) {
            setTimeout(function() {
                if (!textareaObj.value)
                    F.hideForm(form);
            }, 100);
        });
    },

    submit : function(form) {
        form.request( {
            parameters : Form.serialize(form),
            onLoading : F.onSubmit(form),
            onComplete : function(request) {
                F.afterSubmit(request, form)
            }
        });
    },

    onSubmit : function(form) {
        this.isRequesting(true, form);
        form.disable();
    },

    afterSubmit : function(request, form) {
        this.isRequesting(false, form);
        var resp = request.responseText.evalJSON(true);
        form.enable();
        var updater = this.getUpdater(form);
        if (resp['errors'] == 0) {
            updater.update(resp['text']);
            this.hideForm(form);
            if (updater == this.container)
                this.setParentEvents();
            else
                this.updateCommentNum(updater);
        }
    },

    updateCommentNum : function(updater) {
        var num = updater.getElementsBySelector("li").length;
        updater.parentNode.getElementsByClassName("c_num")[0].update(num);
    },

    getUpdater : function(thisObj) {
        var updater = this.container;
        if (thisObj != this.formObj
                && (!thisObj.parentNode.hasClassName("pagination"))) {
            updater = thisObj.next(0);
            var parentObj = thisObj.parentNode;
            if (thisObj.hasClassName("comments_num"))
                parentObj = parentObj.parentNode;
            updater = parentObj.getElementsByClassName("childs")[0];
        }
        return updater;
    },

    hideForm : function(form) {
        if (form == this.formObj) {
            form.removeClassName('active');
            this.setLabel(form);
        } else {
            form.remove();
        }
    },

    showForm : function(form) {
        var textareaObj = form.getElementsByTagName("textarea")[0];
        form.addClassName('active');
        textareaObj.value = "";
    },

    sendQuery : function(updater, url, thisObj, params, method) {
        if (!method)
            method = 'get';
        if (!params)
            params = false;
        this.isRequesting(true, updater);
        new Ajax.Updater(updater, url, {
            method : method,
            parameters : params,
            onComplete : function(request) {
                F.afterResponse(request, updater, thisObj);
            }
        });
    },

    afterResponse : function(response, updater, thisObj) {
        this.isRequesting(false, updater);
        if (thisObj) {
            if (thisObj.hasClassName("apply")) {
                thisObj
                        .replace('<div class="right">' + response.responseText + '</div>');
                return false;
            }
            if (thisObj.hasClassName("med_button")) {
                var child = thisObj.childElements()[0];
                var resp = response.responseText.evalJSON(true);
                var followText = resp['text'];
                var supporters_list = resp['supporters_list'];
                child.update(followText);
                $('supporters').innerHTML = supporters_list;
                return false;
            }
        }
        if (updater == this.container) {
            this.setParentEvents();
        }
    },

    isRequesting : function(opt, obj) {
        if (opt) {
            $('ajax_working').show();
            if (obj)
                obj.setOpacity(0.3);
        } else {
            $('ajax_working').hide();
            if (obj)
                obj.setOpacity(1);
        }
    },

    partBoxHeight : function() {
        var auto = true;
        $$('.part').each(function(obj) {
            obj = $(obj);
            if (obj.down('li')) {
                auto = false;
            }
        });
        if (auto) {
            $$('.part').each(function(obj) {
                if ($(obj).down('.content')) {
                    $(obj).down('.content').addClassName('auto');
                }
            });
        }
    },

    afterUrlUpdate : function(val) {
        F.getData();
    },

    loadSection : function() {
        if (typeof HistoryManager != "undefined") {
            if (!window.location.hash) {
                F.getData();
            }
            HistoryManager.init( {
                onUrlUpdate : F.afterUrlUpdate
            });
        }
    }

};

var VIMEO = {
    oEmbedCallback : 'VIMEO.embedVideo', // Tell Vimeo what function to call
    oEmbedUrl : 'http://www.vimeo.com/api/oembed.json', // Set up the URL
    loadFirst : true, // Load the first one in automatically?
    oWidth : 640,
    oHeight : 352,
    embedObj : null,

    init : function() {
        if ($('vimeo_thumbs')) {
            this.embedObj = $('vimeo_embed');
            var links = $('vimeo_thumbs').getElementsByClassName('vimeo_thumb');
            $A(links).each(function(aObj) {
                $(aObj).observe("click", function(event) {
                    event.stop();
                    F.isRequesting(true, this.embedObj);
                    VIMEO.getPlayer(this.href);
                });
            });
            if (this.loadFirst) {
                this.getPlayer(links[0].href);
            }
        }

    },

    getPlayer : function(url) {
        this.loadScript(this.oEmbedUrl + '?url=' + url + '&height='
                + this.oHeight + '&width=' + this.oWidth + '&callback='
                + this.oEmbedCallback);
    },

    embedVideo : function(video) {
        var videoEmbedCode = video.html;
        videoEmbedCode = videoEmbedCode.replace(/height="(\d+)"/,
                'height="' + VIMEO.oHeight + '"');
        F.isRequesting(false, this.embedObj);
        this.embedObj.update(unescape(videoEmbedCode));
    },

    loadScript : function(url) {
        var js = document.createElement('script');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', url);
        document.getElementsByTagName('head').item(0).appendChild(js);
    }

};
