MOBX.EventHandler.onDomReady(function () {
    MOBX.ContestBehavior.init();
});

MOBX.ContestEntry = function () {
    var publicObj = {};
    var agreesToTerms = null;
    var video_uid = null;
    var contest_id = null;
    publicObj.title = null;
    publicObj.description = null;
    publicObj.submitted = false;
    
    publicObj.video = null;
    publicObj.contestName = null;
    publicObj.allowedToSend = false;
    
    publicObj.contestEntryForm = "contest_entry_form";
    
    // as soon as all attributes are filled out, we're ready to actually submit a contest entry.
    var checkForAllowedToSend = function () {
        if (agreesToTerms && video_uid && contest_id) {
            publicObj.allowedToSend = true;
            MOBX.EventHandler.fireCustom(document.body, "contest_entry_ready");
        } else {
            publicObj.allowedToSend = false;
            MOBX.EventHandler.fireCustom(document.body, "contest_entry_not_ready");
        }
    };
    
    //fire events on attribute changes
    var afterSetAttribute = function () {
        checkForAllowedToSend();
        MOBX.EventHandler.fireCustom(document.body, "contest_entry_attributes_changed");
    };
    
    publicObj.setVideo = function (vid) {
        debug("setting video");
        publicObj.video = vid;
		publicObj.video.embed_url_hd = publicObj.video.embed_url_hd.sub(/width\s*=\s*"[^"]*"/, "width='100%'").sub(/height\s*=\s*"[^"]*"/, "height='100%'");
        debug("Embed url is: " + publicObj.video.embed_url_hd);
		publicObj.setVideoUid(vid.uid);
    };
    
    publicObj.setVideoUid = function (vidUid) {
        debug("setting video uid");
        
        $("contest_entry_video_uid").value = vidUid;
        video_uid = vidUid;
        afterSetAttribute();
    };
    
    publicObj.setTitle = function (titl) {
        debug("setting title");
        
        $("contest_entry_title").value = titl;
        publicObj.title = titl;
        afterSetAttribute();
    };
    
    publicObj.setDescription = function (desc) {
        debug("setting description");
        desc = desc || " ";
        $("contest_entry_description").value = desc;
        publicObj.description = desc;
        afterSetAttribute();
    };
    
    publicObj.setAgreesToTerms = function (bool) {
        debug("setting agrees to terms");
        
        if (bool) {
            $("contest_entry_agrees_to_terms").checked = "checked";
        } else {
            $("contest_entry_agrees_to_terms").checked = false;
        }
        agreesToTerms = bool;
        afterSetAttribute();
    };
    
    publicObj.submit = function () {
        MOBX.EventHandler.fireCustom(document.body, "contest_entry_submitting");
        
        var handleEntrySuccess = function (resp) {
            publicObj.submitted = true;
            MOBX.EventHandler.fireCustom(document.body, "contest_entry_submission_success");
        };
        
        var handleEntryFailure = function (resp) {
            MOBX.EventHandler.fireCustom(document.body, "contest_entry_submission_failure");
        };
        
        var url = $(publicObj.contestEntryForm).action;
        var ajx = new Ajax.Request(url, {
            parameters: Form.serialize($(publicObj.contestEntryForm)),
            onSuccess: handleEntrySuccess,
            onFailure: handleEntryFailure
        });
    };
    
    MOBX.EventHandler.onDomReady(function () {
        contest_id = $F("contest_entry_contest_id");
    });
    
    var debug = function (txt) {
        //console.log(txt);
    };
    
    return publicObj;
}();

MOBX.ContestBehavior = function () {
    var publicObj = {};
    var videoField = null;
    //this is to be set by rails
    var contestEntry = MOBX.ContestEntry;
        
    var handleVideoButtonClick = function (evt) {
        debug("handling the button click");
        var btn = $("pick_video_button");
        if (!btn.disabled) {
            MOBX.Navigation.goToPage("entry_form");
        }
    };
    
    var uidFromVideoElement = function (el) {
        return $(el).id.match(/video_(.+)/)[1];
    };
    
    var updateAllEntryDetails = function () {
        debug("attempting to update entry details");
        if (contestEntry.video) {
            debug("actually updating entry details");
            $("official_rules_contest_entry_details").updateFromJson(contestEntry);
            $("entry_preview_thank_you").updateFromJson(contestEntry);
			$("contest_entry_details").updateFromJson(contestEntry);
            $$("a.mobx_video_template").each(function (el) {
            	el.href = el.rel.gsub(/RRvideo_uidRR/, contestEntry.video.uid);
            });
        }
    };
    
    var updateEntryForm = function () {
        if (contestEntry.video) {
            $("entry_title").value = contestEntry.video.title || "";
            $("entry_description").value = contestEntry.video.description || "";
        }
    };

    var updateContestsForPreview = function () {
        if (!(contestEntry.video && contestEntry.video.streaming_flv)) {
            $("contests").addClassName("no_video_preview");
        } else {
            $("contests").removeClassName("no_video_preview");
        }
    };
    
    var handleVideoClick = function (vid) {
        debug("handling video click");
        contestEntry.setVideo(vid);
        updateEntryForm();
        updateContestsForPreview();
		currentPage = MOBX.Navigation.currentPage;
		if ( currentPage == 'pick_video_from_list') {
			MOBX.Navigation.goToPage("entry_form");
		}
    };
    
    //tabs above take the id of the page(s) they respond to as class names
    //loop through remove the class "active" from all except the one we care about
    var activateTab = function (pageName) {
        debug("activating tab: " + pageName);
        var activeTab = $$("#tabs li." + pageName).first();
        if (activeTab) {
            activeTab.addClassName("active");
            $$("#tabs li").each(function (el) {
                if (el != activeTab) {
                    el.removeClassName("active");
                }
            });
        }
    };
    
    // as a page activates it fires an event on itself
    // this function subscribes to those events.    If the page is the first one
    // then we go to the server and update the list of videos or not if
    // we started with a pre-selected video
    var handlePageActivation = function (evt) {
        debug("handling page activation");
        //scroll to the top of the page
        Element.scrollTo(document.body);
        activateTab(Event.element(evt).id);
    };
    
    var showUserElements = function () {
        $$(".non_user").invoke("hide");
        $$(".for_user").invoke("show");
    };
    
    var hideUserElements = function () {
        $$(".non_user").invoke("show");
        $$(".for_user").invoke("hide");
    };
    
    var handleSignupOrLoginSuccess = function (evt) {
        debug("signup or login success received");
        showUserElements();
        publicObj.user = evt.user;
        MOBX.Navigation.goToPage("pick_video_from_list");
    };
    
    var handleEntryFormClick = function (evt) {
        contestEntry.setTitle($F("entry_title"));
        contestEntry.setDescription($F("entry_description"));
    };
    
    var disableButtons = function () {
        MOBX.Button.disable("enter_contest_button");
    };
    
    var handleContestEntryReady = function () {
        MOBX.Button.enable("enter_contest_button");
    };
    
    var setAgreesToTerms = function (evt) {
        debug("firing agrees to terms");
        var el = $("contest_entry_agrees_to_terms");
        if (el.checked) {
            contestEntry.setAgreesToTerms(true);
        } else {
            contestEntry.setAgreesToTerms(false);
        }
    };
    
    var handleDisagreesToTermsClick = function (evt) {
        var el = Event.element(evt);
        if (el.checked) {
            $("contest_entry_agrees_to_terms").checked = false;
            contestEntry.setAgreesToTerms(false);
        }
    };
    
    // comes form the contest_entry_submission_success event
    var handleEntrySubmissionSuccess = function (evt) {
        var el = $("enter_contest_button");
        MOBX.Button.enable(el);
        MOBX.Navigation.goToPage("thank_you");
    };
    
    // comes from the contest_entry_submission_failure event
    var handleContestEntryFailure = function (evt) {
        MOBX.Navigation.goToPage("contest_info");
        // temporary debug code below
        $("contest_entry_error_holder").update("Oops... could not submit your entry").show();
    };
    
    //asks the contest entry to submit... success and failure are handled through events
    var enterContestOrDoNothing = function (evt) {
        Event.stop(evt);
        var el = $("enter_contest_button");

        if (!el.disabled) {
            MOBX.Button.setToLoading(el);
            contestEntry.submit();
        }
    };
    
    var subscribeToEvents = function () {
        debug("subscribing to events");
        MOBX.EventHandler.subscribe("#pick_video_button", "click", handleVideoButtonClick);
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "user_signup_success", handleSignupOrLoginSuccess);
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "user_login_success", handleSignupOrLoginSuccess);
        MOBX.EventHandler.subscribe("#continue_from_entry_form", "click", handleEntryFormClick);
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "contest_entry_ready", handleContestEntryReady);
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "contest_entry_not_ready", disableButtons);
        MOBX.EventHandler.subscribe("#contest_entry_agrees_to_terms", "click", setAgreesToTerms);
        MOBX.EventHandler.subscribe("#enter_contest_button", "click", enterContestOrDoNothing);
         
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "contest_entry_submission_success", handleEntrySubmissionSuccess);
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "contest_entry_submission_failure", handleContestEntryFailure);
        
        MOBX.EventHandler.subscribe(MOBX.cssNamespace, "contest_entry_attributes_changed", updateAllEntryDetails);
        
        MOBX.EventHandler.subscribe(".video_select_button", "click", function(evt) {
            Event.stop(evt);
        });
    };

    //these are outside of the usual init process just so they are active at page load
    
    MOBX.EventHandler.subscribe(".page", "activated", handlePageActivation);
    
    MOBX.EventHandler.subscribe(["#contest_info", "#entry_form", "#official_rules", "#thank_you", "#pick_video_from_list"], "activated", function (evt) {
        debug("function 1");
        if (contestEntry.submitted) {   
            MOBX.Navigation.goToPage("thank_you");
        } 
    });
    
    MOBX.EventHandler.subscribe(["#entry_form", "#official_rules", "#thank_you"], "activated", function (evt) {
        debug("function 2");
        debug('----------------------------------> page activated: ' + Event.element(evt).id);
        
        if (!publicObj.user) {
            MOBX.Navigation.goToPage("contest_info");
            return;
        }
        if (!contestEntry.video) {
            debug("a condition wasn't met");
            MOBX.Navigation.goToPage("pick_video_from_list");
        }
    });
    
    MOBX.EventHandler.subscribe("#thank_you", "activated", function (evt) {
        debug("thank you function");
        if (!contestEntry.submitted) {
            debug('oops... cant show thank you yet');
            MOBX.Navigation.goToPage("official_rules");
        }
    });
    
    MOBX.EventHandler.subscribe("#official_rules", "activated", function (evt) {
        debug("official rules function");
        if ($("contest_entry_agrees_to_terms").checked) {
            $("contest_entry_agrees_to_terms").checked = false;
        }
    });
    
    MOBX.EventHandler.subscribe("#pick_video_from_list", "activated", function (evt) {
        debug('firing pick video from list function');
        if (!publicObj.user) {
            MOBX.Navigation.goToPage("contest_info");
        } else {
            MOBX.VideoPicker.activate('video_picker', { 'onVideoClick': handleVideoClick, inlineUploader: true });
        }
    });
    
    //end event handlers that should remain not in the "subscribeToEvents function"
    
    publicObj.user = null;
    
    
    publicObj.init = function () {
        MOBX.Navigation.init({'initialPage': 'contest_info'});    
        
        subscribeToEvents();
        if (publicObj.user) {
            showUserElements();
        } else {
            hideUserElements();
        }
        disableButtons();
        debug('initing');
    };
    
    var debug = function (msg) {
       // console.log(msg);
    };
    
    return publicObj;
}();
