﻿var yooskControls = {

    //////////////////////////////////////////////////////////////////////////////////////////////
    //

    answer: {
        /// <summary>
        /// ~/Controls/Answers/Answer.ascx
        /// </summary>

        playVideo: function(videoUrl) {
            /// <summary>
            /// Plays the given video in a popup.
            /// </summary>

            // Display video using fancybox overlay
            $.fancybox('', {
                'padding': 0,
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none',
                'title': this.title,
                'width': 680,
                'height': 385,
                'href': videoUrl.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                'type': 'swf',
                'swf': {
                    'wmode': 'transparent',
                    'allowfullscreen': 'true'
                },
                onComplete: function() {
                    // We want the borders in this popup
                    $("#fancybox-wrap").removeClass("fancybox-noborder");
                }
            });
        },

        rate: function(answerId, goodRating, numGood, numBad, el) {
            /// <summary>
            /// Rates the passed answer as good or bad.
            /// </summary>

            // Update container to show rating
            $(el).parent().children('a').hide();
            $(el).parent().children('span.spinner').show();

            // Issue the rating
            yoosk.answers.rate(answerId, goodRating, function() {
                // Show that the vote was registered
                $(el).parent().children('span.spinner').hide();
                $(el).parent().children('span.voted').show().html("You voted " + (goodRating ? "Yes" : "No") + ".");
                // Update the voting counts
                if(goodRating) numGood ++;
                else numBad ++;
                $(el).siblings("span.currentRating").find("span.votePerc").html(
                    ((numGood / (numGood + numBad)) * 100).toFixed(0));
                $(el).siblings("span.currentRating").find("span.totalVotes").html(numGood + numBad);
            });
        }
    },

    //////////////////////////////////////////////////////////////////////////////////////////////
    //

    question: {
        /// <summary>
        /// ~/Controls/Question/Question.ascx
        /// </summary>

        vote: function(questionId, voteLink) {
            /// <summary>
            /// Votes for the given question and updates the display.
            /// </summary>

            // Show spinner whilst vote is processed            
            $(voteLink).children("span.action").hide();
            $(voteLink).children("span.spinner").show();

            // Register the vote with Yoosk
            yoosk.questions.vote(questionId,
                function() {
                    // Update display to show we have now voted
                    $(voteLink).children("span.spinner").hide();
                    $(voteLink).children("span.voted").show();
                    // Increase number of displayed votes
                    var numEl = $(voteLink).parentsUntil("div.clearfix").parent().find("span.voteCount");
                    numEl.html(parseInt(numEl.first().html()) + 1);
                    // Disable the onclick
                    $(voteLink).attr('onclick', 'return false;');
                }
            );
        },

        report: function(questionId) {
            /// <summary>
            /// Opens a window to report the given question.
            /// </summary>

            // Display popup with report options.
            $.fancybox(
                '<div class="popup">' +
                    '<div class="box" id="report">' +
                        '<h2>Report Abuse</h2>' +
                        '<div class="boxBody">' +
                            '<div>' +
                                '<p>Please tell us below why you think this question has breached the ' +
                                    '<a href="' + yoosk.api.siteBase + 'terms-of-service.aspx">Yoosk Terms of Service</a>. ' +
                                    'The question you complain about will be sent to a moderator who will decide whether the question ' +
                                    'should be removed. If you enter your email below, you will be informed of the decision.' +
                                '</p>' +
                                '<textarea id="reportText" cols="30" rows="4"></textarea>' +
                                '<p>Your email address (optional):</p>' +
                                '<input id="reportEmail" type="text" />' +
                                '<input id="reportQuestionId" type="hidden" value="' + questionId + '" />' +
                                '<a class="send" href="#" onclick="yooskControls.question.sendReport(); return false;">Send Report</a>' +
                                '<span class="spinner" style="display: none">Sending ...</span>' +
                            '</div>' +
                        '</div>' +
                        '<div class="boxFooter"></div>' +
                    '</div>' +
                '</div>',
                {
                    'padding': 0,
                    'autoScale': false,
                    'transitionIn': 'none',
                    'transitionOut': 'none',
                    'width': 680,
                    'height': 385,
                    onComplete: function() {
                        // Remove borders
                        $("#fancybox-wrap").addClass("fancybox-noborder");
                    }
                }
             );
        },

        sendReport: function() {
            /// <summary>
            /// Sends a report from a filled out report popup window.
            /// </summary>

            // Grab our content
            var content = $("#reportText").val();
            var email = $("#reportEmail").val();

            // Question filled out?
            if (content.length < 1)
                alert("Please enter some text explaining why this question has breached the terms of service.");
            else if (email.length > 1 && email.search("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$") == -1)
                alert("The email address you have entered is not valid.");
            else {
                // Spinner whilst sending
                $("#report a.send").hide();
                $("#report span.spinner").show();

                // Send the report
                yoosk.questions.report(
                    $("#reportQuestionId").val(), content, email,
                    function() {
                        // Cancel spinner and tell user
                        alert("Your report has been sent for review. Thank you.");
                        $("#report span.spinner").hide();
                        $("#report a.send").show();
                        // Clear box content, and hide
                        $("#report textarea").val('');
                        $.fancybox.close();
                    }
                );
            }
        }

    },

    //////////////////////////////////////////////////////////////////////////////////////////////
    //

    askQuestion: {
        /// <summary>
        /// ~/Controls/Questions/AskQuestion.ascx
        /// </summary>
        
        // The askQuesiton flexbox instance.
        flexbox: null,

        init: function(id, name) {
            /// <summary>
            /// Initialise the ask question control
            /// </summary>
            $(function() {
                // Hiding and showing via the pop over box messes with the init. We manually check
                if ($("#askQuestion div.findBox > div input").length == 0) {
                    // Setup typeahead
                    var flexBox = $("#askQuestion div.findBox > div").flexbox(yoosk.api.ajaxBase + "get-cele-list.aspx",
                    {
                        showArrow: false, watermark: "Type a public figure name here", width: 270, paging: false,
                        resultsProperty: "yooskeeArray", displayValue: "ItemName", hiddenValue: "ItemId",
                        resultTemplate: "{ItemName}"
                    });
                    // Apply watermark to text area
                    yoosk.ui.textbox.watermark($("#askQuestion_question"));
                    // If we were given an ID, set the initial value
                    if(id != null && id > 0 && name != null) {
                        flexBox.setValue(name);
                        $('#askQuestion div.findBox input:hidden:first').val(id);
                    }
                    // Remember instance incase we need it
                    yooskControls.askQuestion.flexbox = flexBox;
                }
            });
        },

        reset: function() {
            /// <summary>
            /// Resets the ask question control back to being blank and the first page.
            /// </summary>

            // Clear first page form
            $('#askQuestion_question').val('');
            $('#askQuestion_categories').val('noTopic');

            // Move to first page
            yooskControls.askQuestion.changePage(0);
        },

        submit: function() {
            /// <summary>
            /// Validates and submits the entered question.
            /// </summary>
            
            // Grab width if first time, we should be visible (needed for later anim)
            if (yooskControls.askQuestion._pageWidth == 0)
                yooskControls.askQuestion._pageWidth = $('#askQuestion_start').width();

            // Hide any previous errors
            $('#askQuestion .errorContainer').hide();
            $('#askQuestion .error').hide();
            $('#askQuestion .top').show();
            $('#askQuestion .errorHighlight').removeClass("errorHighlight");

            // Check content is selected
            var isValid = true;
            if ($('#askQuestion_question').val().length < 1) {
                $('#questionTooShort').show();
                $('#askQuestion_question').addClass("errorHighlight");
                isValid = false;
            }
            else if ($('#askQuestion_categories').val() == 'noTopic') {   // No topic selected?
                $('#noCategory').show();
                $('#askQuestion_categories').addClass("errorHighlight");
                isValid = false;
            }
            else if ($('#askQuestion div.findBox input:hidden:first').val().length < 1) {   // Leader selected?
                // Maybe we have a select instead?
                if($("#askQuestion_themePF").length == 0) {
                    $('#noLeader').show();
                    isValid = false;
                }
            }

            // All ok?
            if (isValid) {

                // Are we authenticated? If not we need to show the login box instead
                if (!yoosk.user.isAuthenticated) {
                    $("#loginLink").trigger('click');
                    // When it gets closed, pop our window back up
                    loginTab.onClosed = function() {
                        // Stop listening
                        loginTab.onClosed = null;
                        // Display question popup again (only if this was from the ask popup)
                        if ($("#askTab") != null && $("#askTab").length == 1) {
                            // The popup doesnt like being reactivated on a cancel. We need to wait for some JS
                            setTimeout(function() {
                                // Bit hacky with the box, it doesnt overlay properly
                                $("#askTab").trigger('click');
                                $("#fancybox-overlay").css('display', 'block');
                            }, 100);
                        }
                        // Resubmit form if we are now logged in
                        if (yoosk.user.isAuthenticated)
                            yooskControls.askQuestion.submit()
                    }
                } else {

                    // Hide yoosk button and replace with spinner
                    $("#askQuestion_start div.sendIt a").hide();
                    $("#askQuestion_start div.sendIt .spinner").show();

                    // Post the question
                    var pfId = $('#askQuestion div.findBox input:hidden:first').val();
                    if($("#askQuestion_themePF").length > 0)
                        pfId = $("#askQuestion_themePF").val();
                    yoosk.questions.ask(pfId, $('#askQuestion_question').val(), $('#askQuestion_categories').val(),
                        $('#askQuestion_panel').val(),
                        function(questionId) {
                            // Question submitted ok
                            yooskControls.askQuestion.changePageForward();
                            // Remove spinner and clear question content incase user goes back to repost
                            $("#askQuestion_start div.sendIt .spinner").hide();
                            $("#askQuestion_start div.sendIt a").show();
                            $('#askQuestion_question').val('');
                            
                            // Setup link on last page to point to PF
                            $('#askQuestion_finished a.support').attr('href',
                                yoosk.api.siteBase + 'celebrity/' + pfId + '/' + 
                                $("#askQuestion div.findBox input.ffb-input").val().replace(" ", "_") + '.aspx');
                            
                            // Check if we have rated this PF before
                            $('#askQuestion_finished .rating').hide();
                            $('#askQuestion_finished .haveRated').show();
                            yoosk.leaders.haveRated(pfId, 
                                function (haveRated) {
                                    // Reveal ratings panel if we havent rated before
                                    if(!haveRated) {
                                        // Reset panel first
                                        $('#askQuestion_finished span.ok').hide();
                                        $('#askQuestion_finished a.button').show();
                                        $('#askQuestion_finished input:checked').attr("checked", false); 
                                        $('#askQuestion_finished input').attr('disabled', false);
                                        // Now show the panel
                                        $('#askQuestion_finished .rating').show();
                                    }
                                }
                            );
                            // Update the page to show our newly asked question (supported pages only)
                            yooskControls.askQuestion.showLatestQuestion(questionId);
                        }
                    );
                }

            } else {
                // We had errors, show the error container in place of the top
                $('#askQuestion .errorContainer').show();
                $('#askQuestion .top').hide();
            }

        },

        // The index of the current page
        _currentPage: 0,
        // The width of the first page (used for anim)
        _pageWidth: 0,

        changePage: function(num) {
            /// <summary>
            /// Moves the ask question widget to the specific page.
            /// </summary>

            // Grab width if first time
            if (yooskControls.askQuestion._pageWidth == 0)
                yooskControls.askQuestion._pageWidth = $('#askQuestion_start').width();

            // How far do we need to move?
            var distance = 0 - (num * yooskControls.askQuestion._pageWidth);
            // If we are hidden, animate doesnt work, need to check
            if ($('#askQuestionWrapper').parents(':hidden').length == 0)
                $('#askQuestionWrapper').animate({ left: distance }, 250, "linear");
            else
                $('#askQuestionWrapper').css('left', distance + "px");
                
            // Update page index
            yooskControls.askQuestion._currentPage = num;
        },

        changePageForward: function() {
            /// <summary>
            /// Moves the ask question widget forwards one page.
            /// </summary>
            yooskControls.askQuestion.changePage(yooskControls.askQuestion._currentPage + 1);
        },
        
        rate: function() {
            /// <summary>
            /// Submits ratings for the current PF.
            /// </summary>
            
            // Have all the items been ticked?
            if($('#askQuestion_finished input:checked').length != 6) {
                alert("Please select either yes or no for all qualities before submitting your ratings.");
            } else {
                // Replace button with spinner
                $('#askQuestion_finished a.button').hide();
                $('#askQuestion_finished .spinner').show();
                
                // Who are we rating?
                var pfId = $('#askQuestion div.findBox input:hidden:first').val();
                if($("#askQuestion_themePF").length > 0)
                    pfId = $("#askQuestion_themePF").val();
                // Submit the ratings
                yoosk.leaders.rate(pfId,
                    $('#askQuestion_finished input[name=rateHonest]:checked').val(),
                    $('#askQuestion_finished input[name=rateClear]:checked').val(),
                    $('#askQuestion_finished input[name=rateWellInformed]:checked').val(),
                    $('#askQuestion_finished input[name=rateInspiring]:checked').val(),
                    $('#askQuestion_finished input[name=rateConsistent]:checked').val(),
                    $('#askQuestion_finished input[name=rateWellIntentioned]:checked').val(),
                    function () {
                        // Tell user the rating was submitted
                        $('#askQuestion_finished .spinner').hide();
                        $('#askQuestion_finished span.ok').show();
                        // Lock the radio boxes in place
                        $('#askQuestion_finished input').attr('disabled', 'disabled');
                    }
                );
            }
            
        },
        
        popup: function(pfId, pfName, topicName) {
            /// <summary>
            /// Opens the ask question popup (if on page) with the preset info.
            /// </summary>
            
            // Set the defaults if given
            if(pfName != null && pfId != null) {
                // Do we have a select box?
                if($("#askQuestion_themePF").length > 0) {
                    $("#askQuestion_themePF").val(pfId);
                } else {
                    yooskControls.askQuestion.flexbox.setValue(pfName);
                    $('#askQuestion div.findBox input:hidden:first').val(pfId);
                }
                // Set topic if given
                if(topicName != null)
                    $('#askQuestion_categories').val(topicName);
            }

            // Popup ask question dialog
            $("#askTab").trigger("click");
        },
        
        showLatestQuestion: function(questionId) {
            /// <summary>
            /// Adds this new question to the list of recent questions
            /// </summary>
            
            // Grab the latest question content
            yoosk.questions.getFormatted(questionId, function(html) {
                    // Update any recent questions carousels
                    yooskControls.questionsCarousel.addToRecent(html);
                });
        }
        
    },
    
    //////////////////////////////////////////////////////////////////////////////////////////////
    //
    
    questionsCarousel: {
        /// <summary>
        /// ~/Controls/Questions/RecentQuestionsCarousel.ascx
        /// </summary>
        
        // List of recent questions carousels (so we can add to them)
        recentQuestionInstances: [],
        
        init: function (container) {
            /// <summary>
            /// Inits the carousel from the given container.
            /// </summary>
            
            // Init carousel when JS loaded
            $(function() {
                // Create carousel
                $(container).find("ul:first").jcarousel({
                    initCallback: function(carousel, state) {
                        // Bind forward
                        $(container).find('div.carouselNav a:first').bind('click', function() {
                            carousel.prev();
                        });
                        // Bind back
                        $(container).find('div.carouselNav a:last').bind('click', function() {
                            carousel.next();
                        });
                        // Bind top question / answer
                        var topPage = 0;
                        $(container).find('div.carouselNav a.top').bind('click', function() {
                            // Have we inserted this question already?
                            if(topPage == 0) {
                                // Need to insert the question into carousel
                                var length = $(container).find("ul li").length;
                                carousel.add(length + 1, $(container).find('div.top').children());
                                carousel.size(length + 1);
                                topPage = length + 1;
                            }
                            // Jump to this item
                            carousel.scroll(topPage);
                        });
                        // Remeber this carousel
                        if($(container).hasClass("recentQuestions"))
                            yooskControls.questionsCarousel.recentQuestionInstances.push(
                                { carousel: carousel, container: $(container) }
                            );
                    },
                    scroll: 1,
                    wrap: "circular",
                    buttonNextHTML: null,
                    buttonPrevHTML: null
                });    
            });
        },
        
        addToRecent: function (html) {
            /// <summary>
            /// Adds th given content as a page in all recent carousels
            /// </summary>

            for(var n = 0; n < yooskControls.questionsCarousel.recentQuestionInstances.length; n++) {
                // Grab this carousel instance
                var carousel = yooskControls.questionsCarousel.recentQuestionInstances[n].carousel;
                var container = yooskControls.questionsCarousel.recentQuestionInstances[n].container;
                // Add the new content to it
                var length = $(container).find("ul li").length;
                carousel.add(length + 1, $(html));
                carousel.size(length + 1);
                carousel.scroll(length + 1);
            }
        }
        
    },

    //////////////////////////////////////////////////////////////////////////////////////////////
    //

    signIn: {
        /// <summary>
        /// ~/Controls/Users/SignIn.ascx
        /// </summary>

        init: function() {
            /// <summary>
            /// Inits the sign in control
            /// <summary>
            
            // Watermark textboxes
            yoosk.ui.textbox.watermark($("#loginUsername"));
            yoosk.ui.textbox.watermark($("#twitterUsername"));
        },

        login: function() {
            /// <summary>
            /// Attempts to log the user in with the given credentials.
            /// <summary>

            // Reset any previous errors
            $("#signIn div.page:first .error").hide();
            $("#register .error").hide();
            
            // Are the username / password filled?
            var username = $("#loginUsername").val();
            var password = $("#loginPassword").val();
            if (username.length < 1 || password.length < 1) {
                // Details not entered
                $("#loginNotGiven").show();
            } else {
                // Checks passed. Try to login

                // Replace login button with spinner
                $("#mainLogin a.button").hide();
                $("#mainLogin span.spinner").show();

                // Do the login
                yoosk.user.login(username, password, $("#loginRemember").is(":checked"),
                    function(validLogin) {
                       // Were we valid?
                       if (validLogin == "success") {
                           // Close the popup, we logged in
                           $.fancybox.close();
                           // Update the page header with the logged in user information
                           yoosk.user.isAuthenticated = true;
                           yooskControls.signIn.updateHeader(username);
                           //window.location=yoosk.api.siteBase;
                       } else if (validLogin == "requestemail"){    
                           // Login was not valid
                           $("#loginRequestEmail").show();
                           // Put login button back
                           $("#mainLogin span.spinner").hide();
                           $("#mainLogin a.button").show();
                       } else if (validLogin == "landingpage") {
                           // Close the popup, we logged in
                           $.fancybox.close();
                           // Update the page header with the logged in user information
                           yoosk.user.isAuthenticated = true;
                           yooskControls.signIn.updateHeader(username);
                           window.location= yoosk.api.siteBase;
                       } else {
                           // Login was not valid
                           $("#loginInvalid").show();
                           // Put login button back
                           $("#mainLogin span.spinner").hide();
                           $("#mainLogin a.button").show();
                       }
                    }
                );
            }
        },
        
        updateHeader: function(username) {
            /// <summary>
            /// Updates the page header with the new login information.
            /// <summary>
            
            // Logged in? Or out
            if(username != null) {
                // Hide login links, repalce with username
                $("#loginLink").hide();
                $("#loginRegisterSearch a.username").show().html(username);
                $("#loginRegisterSearch a.logout").show();
                
            } else {
                $("#loginRegisterSearch a.username").hide();
                $("#loginRegisterSearch a.logout").hide();
                $("#loginLink").show();
            }
        },
        
        loginWithFacebook: function() {
            /// <summary>
            /// Attempts to log the user in using Facebook.
            /// <summary>
            
            // Ensure we have (or prompt for) a Facebook session
            FB.login(function(response) {
                if (response.session) {
                    // We have a session to auth with
                    var session = FB.copy({}, FB.getSession());
                    // Encode session
                    var tempSession = FB.copy({}, FB.getSession());
                    delete tempSession.sig;
                    var sigEncode = FB.QS.encode(tempSession, '', false);
                    // Show we are logging in
                    $("#facebookAuth img").hide();
                    $("#facebookAuth .spinner").show();
                    // Call the login script with these details
                    yoosk.user.loginWithFacebook(sigEncode, session.uid, session.sig,
                        function(isValid) {
                           if(isValid) {
                               // Close the popup, we logged in
                               $.fancybox.close();
                               // Update the page header with the logged in user information
                               yoosk.user.isAuthenticated = true;
                               yooskControls.signIn.updateHeader("<fb:name uid=\"" + session.uid + "\" linked=\"false\" useyou=\"false\"></fb:name>");FB.XFBML.parse();
                               // Tell FB to parse the new header
                               FB.XFBML.parse(document.getElementById('welcomeHeader'));
                            } else {
                                alert("Sorry, we were unable to validate your Facebook credentials.");
                            }
                        }
                    );
                }
            });
        },
        
        toggleTwitterLogin: function() {
            /// <summary>
            /// Shows or hides the Twitter login options.
            /// <summary>
            
            // Need to show? or hide?
            if($("#signIn div.page:first").is(":visible")) {
                // Hide existing login options
                $("#signIn div.page:first").fadeOut(300, function () {
                    $("#twitterPage").fadeIn(300);
                });
            } else {
                // Twitter login, replace with original
                $("#twitterPage").fadeOut(300, function () {
                    $("#signIn div.page:first").fadeIn(300);
                });
            }
        },
        
        loginWithTwitter: function() {
            /// <summary>
            /// Attempts to log the user in using Twitter.
            /// <summary>
            
            // Replace login button with spinner
            $("#twitterPage a.button").hide();
            $("#twitterPage span.spinner").show();
            
            // Grab credentials
            var username = $("#twitterUsername").val();
            var password = $("#twitterPassword").val();

            // Do the login
            yoosk.user.loginWithTwitter(username, password,
                function(validLogin) {
                   // Were we valid?
                   if (validLogin) {                                           
                       // Close the popup, we logged in
                       $.fancybox.close();
                       // Update the page header with the logged in user information
                       yoosk.user.isAuthenticated = true;
                       yooskControls.signIn.updateHeader("Twitter_" + username);
                   } else {                        
                       // Login was not valid
                       $("#twitterLoginInvalid").show();
                       // Put login button back
                       $("#twitterPage span.spinner").hide();
                       $("#twitterPage a.button").show();
                   }
                }
            );
        }
    },
    
    //////////////////////////////////////////////////////////////////////////////////////////////
    //

    register: {
        /// <summary>
        /// ~/Controls/Users/Registration.ascx
        /// </summary>
        
        init: function() {
            /// <summary>
            /// Inits the register in control
            /// <summary>
            
            // Watermark textboxes
            yoosk.ui.textbox.watermark($("#registerUsername"));
            yoosk.ui.textbox.watermark($("#registerEmail"));
        },
        
        reset: function() {
            $("#registerUsername").val("Your name");
            $("#registerEmail").val("Your email address");
            $("#registerPassword").val("");            
            $("#registerPasswordRetype").val("");
        },
        
        register: function() {
            /// <summary>
            /// Attempts to register a new user.
            /// <summary>

            // Reset any previous errors
            $("#register .error").hide();
            $("#signIn div.page:first .error").hide();
            
            // Are the username / password / email filled?
            var username = $("#registerUsername").val();
            var password = $("#registerPassword").val();
            var email = $("#registerEmail").val();
            if (username.length < 1 || password.length < 1 || email.length < 1) {
                // Details not entered
                $("#registerNotFilled").show();
            } else if (email.search("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$") == -1) {
                // Details not entered
                $("#registerEmailInvalid").show();
            } else if(password != $("#registerPasswordRetype").val()) {
                // Passwords do not match
                $("#registerPasswordNoMatch").show();
            } else {
                // Checks passed. Try to register

                // Replace login button with spinner
                $("#register a.button").hide();
                $("#register span.spinner").show();

                // Do the registration
                yoosk.user.register(username, email, password,
                    function(result) {
                       // Were we valid?
                       if (result == "OK") {
                           // Close the popup, we registered
                           $.fancybox.close();
                           // Update the page header with the logged in user information
                           yoosk.user.isAuthenticated = true;
                           yooskControls.signIn.updateHeader(username);
                       } else if( result == "ActiveEmail" ) {                           
                           alert ("Thank you, you have successfully registered with Yoosk. Please go to your email account to activate your registration. Have fun and contact us if you have any problems.");
                           // Close the popup, we registered
                           $("#register span.spinner").hide();
                           $("#register a.button").show();
                           yooskControls.register.reset();
                           $.fancybox.close();                                                      
                       } else {
                           // Dupe email?
                           if(result == "DuplicateEmail")
                               $("#registerDupeEmail").show();
                           else if (result == "EmailRequest")
                               $("#registerEmailRequest").show();
                           else
                               $("#registerDupeUsername").show();
                           // Put register button back
                           $("#register span.spinner").hide();
                           $("#register a.button").show();
                       }
                    }
                );
            }
        }
    },
    
    //////////////////////////////////////////////////////////////////////////////////////////////
    //
    
    generic: {
        /// <summary>
        /// Reusable functions common to several controls.
        /// </summary>
        
        autoAuth: function (el) {
            /// <summary>
            /// Checks if we are authed when clicking a link. Prompts if not.
            /// </summary>  
            
            // Authed already?
            if(yoosk.user.isAuthenticated) return true;
            
            // Popup as not authed
            $("#loginLink").trigger('click');
            // When it gets closed, activate the link
            loginTab.onClosed = function() {
                // Stop listening
                loginTab.onClosed = null;
                // Click the link if authed
                if (yoosk.user.isAuthenticated)
                    window.location = $(el).attr('href');
            }
            
            // Block default action
            return false;
        }
        
    },
    
    //////////////////////////////////////////////////////////////////////////////////////////////
    //
    createFeature: {
        /// <summary>
        /// ~/Controls/Feature/Feature-createdbyuser.ascx
        /// </summary>
        
        reset: function() {
             // reset field
             $("#livedate").val("");                         
             $("#closedate").val("");
             $("#featuretitle").val("");
             $("#featureimage").val("");
             $("#featurethumbnail").val("");
             $("#introduction").val("");            
             $("#featureimage").removeAttr("disabled");  
             $("#featureimage").removeClass("gray");              
             $("#featurethumbnail").removeAttr("disabled");  
             $("#featurethumbnail").removeClass("gray");
             $('#imageuploadlink').show();
             $('#imageupload').html("");
             $('#imagecheck').html("");
             $('#thumbuploadlink').show();
             $('#thumbupload').html("");
             $('#thumbcheck').html("");
             
             $("#_input1").val("");
             $('#divmemberpanel').html("");
             themeId = "";
             
        },
                            
        submit: function() {
             // Are we authenticated? If not we need to show the login box instead
                if (!yoosk.user.isAuthenticated) {                   
                    // Hide start button and replace with login or register button
                    $("#createFeatureTabContent div.createFright div.conversation").hide();
                    $("#createFeatureTabContent div.createFright div.loginRegister").show();
                } else {
                   // Hide Start page and replace with Building Your Feature page
                   $("#StartAConversation").hide();
                   yooskControls.createFeature.reset();
                   yoosk.feature.resetfiled();
                   $("#BuildingYourFeature").show();
                  
                }                 
        },       
               
        loginorregister: function () {
            if (!yoosk.user.isAuthenticated) { 
                $("#loginLink").trigger('click');            
                
                // When it gets closed, pop our window back up
                loginTab.onClosed = function() { 
                    // Return Start Conversation page.    
                    $("#createFeatureTabContent div.createFright div.conversation").show();
                    $("#createFeatureTabContent div.createFright div.loginRegister").hide();  
                                               
                    if (yoosk.user.isAuthenticated) { 
                        // Display buliding create your feature popup again (only if this was from the ask popup)
                        if ($("#createFeatureTab") != null && $("#createFeatureTab").length == 1) {
                            // The popup doesnt like being reactivated on a cancel. We need to wait for some JS
                            setTimeout(function() {
                                // Bit hacky with the box, it doesnt overlay properly
                                $("#createFeatureTab").trigger('click');
                                $("#StartAConversation").hide();                                                              
                                yooskControls.createFeature.reset(); 
                                 $("#BuildingYourFeature").show();                             
                            }, 100);
                        }
                    }                   
                    
                }
            } 
        }, 
        
        saveandcontinuestepone: function () {  
              
            // Hide any previous errors
            $('#buildingFeature .errorContainer').hide();
            $('#buildingFeature .error').hide();           

            // Check content is selected
            var isValid = true;
            if ($('#livedate').val().length < 1) { // No live date selected?
                $('#noLiveDate').show();
                isValid = false;
            } 
            
            if ($('#closedate').val().length < 1) {   // No closing date selected?
                $('#noClsoingDate').show();
                isValid = false;
            } 
            if ($('#featuretitle').val().length < 1) {   // No feature title selected?
                $('#noFeatureTitle').show();
                isValid = false;
            }
             
            // All ok?
            if (isValid) {  
               
                if (themeId > 0)
                {
                    //update Feature
                    yoosk.feature.update(themeId, $('#livedate').val(), $('#closedate').val(), $('#featuretitle').val(), $('#txtFeatureImage').val(), $('#introduction').val() );                   
                } 
                else
                {    
                     // Create Feature         
                     yoosk.feature.create( $('#livedate').val(), $('#closedate').val(), $('#featuretitle').val(), $('#txtFeatureImage').val(), $('#introduction').val() );                   
                }
                
                 // Hide Start, Building Your Feature page and replace with Add Some Interviewee to Question page 
                 $("#StartAConversation").hide();
                 $("#BuildingYourFeature").hide();              
                 $("#AddInterviewee").show(); 
                 
            } else {
                // We had errors, show the error container in place of the top
                $('#buildingFeature .errorContainer').show(); 
            }   
                         
        },
        
        saveandcontinuesteptwo: function () {
              // Hide Start, Building Your Feature, Add Interviewee page and replace with Add Your Own Branding    
              $("#StartAConversation").hide();
              $("#BuildingYourFeature").hide(); 
              $("#AddInterviewee").hide();
              $("#AddBranding").show();
              yoosk.feature.sendemail(themeId);              
              
        },
        
        saveandcontinuestepthree: function () {                           
              var chkmail = ( $("#chkemailme").is(':checked') );
              yoosk.feature.emailme(chkmail);
                            
              // Hide Start, Building Your Feature, Add Interviewee, Add Your Own Branding and replace with Publish Feature
              $("#StartAConversation").hide();
              $("#BuildingYourFeature").hide(); 
              $("#AddInterviewee").hide();
              $("#AddBranding").hide();
              $("#PublishFeature").show();
        },
        
        finished: function () 
        {            
             $("#PublishFeature").hide();
             $.fancybox.close();
             
             themeId = "";
        },
        
        backstep3: function () {
            $("#PublishFeature").hide();
            $("#AddBranding").show();             
        },
        
        backstep2: function () {
            $("#AddBranding").hide();
            $("#AddInterviewee").show();             
        },
        
        backstep1: function () {
            $("#AddInterviewee").hide();
            $("#BuildingYourFeature").show();
            
            //reset image and thumbnail fields
            $("#featureimage").val(""); 
            $("#featurethumbnail").val("");
            $("#featureimage").removeAttr("disabled");  
            $("#featureimage").removeClass("gray");              
            $("#featurethumbnail").removeAttr("disabled");  
            $("#featurethumbnail").removeClass("gray");
            $('#imageuploadlink').show();
            $('#imageupload').html("");
            $('#imagecheck').html("");
            $('#thumbuploadlink').show();
            $('#thumbupload').html("");
            $('#thumbcheck').html("");
        },
       
        uploadimage: function () {            
            // Check content is selected
            var isValid = true;           
                                   
            if ($('#featureimage').val().length < 1) { 
                alert ("Please, select image!");
                isValid = false;
            }
            if (isValid) {
                // Upload Image
                yoosk.feature.uploadimage();
            }
        }, 
        
        uploadthumbnail: function () {
            var isValid = true;           
                              
            if ($('#featurethumbnail').val().length < 1) { 
                alert ("Please, select thumbnail!");
                isValid = false;
            }
            
            if (isValid) {
                // Upload Thumbnail
                yoosk.feature.uploadthumbnail();
            }
        },
        
        uploadphoto: function () {            
            // Check content is selected
            var isValid = true;           
                                   
            if ($('#addinterphoto').val().length < 1) { 
                alert ("Please, select photo!");
                isValid = false;
            }
            
            if (isValid) {
                // Upload Image
                yoosk.feature.uploadphoto();
            }
        }, 
        
         // The Add Interviewee flexbox instance.
        flexbox1: null,

        init: function(id, name) {
            /// <summary>
            /// Initialise the create feature control
            /// </summary>
   
            $(function() {
                // Hiding and showing via the pop over box messes with the init. We manually check
                if ($("#addInterviewee div.findBox1 > div input").length == 0) {
                    // Setup typeahead
                    var flexBox = $("#addInterviewee div.findBox1 > div").flexbox1(yoosk.api.ajaxBase + "get-cele-list.aspx",
                    {
                        showArrow: false, watermark: "", width: 220, paging: false,
                        resultsProperty: "yooskeeArray", displayValue: "ItemName", hiddenValue: "ItemId",
                        resultTemplate: "{ItemName}"
                    });
                                    
               }
            });
        }         
    }    
};
