/* Main Javascript library for ZipRecruiter */

$(document).ready(function () {

    $('textarea.resizable:not(.processed)').TextAreaResizer();
    
    $("#save_answer").click(function (event) {
        $.post("/multiple-choice-option", $("#multiple_choice").serialize(), function (data) {
            console.log('ajax returned' + data.option_text);
            var list_elem = '<li>' + data.option_text + '</li>';
            $("#new_option").before(list_elem);
        },
        "json");
	    });

        // By suppling no content attribute, the library uses each elements title attribute by default
        $('a[href][title]').qtip({
            content: {
                text: false // Use each elements title attribute
            },
            show: {
                delay: 150
            },
            style: {
                backgroundColor: '#393939',
                color: '#ffffff',
                width: 125,
                textAlign: 'center',
                fontSize: 11,
                padding: 5,
                tip: { 
                		size: { x: 13, y: 8 },
                		corner: 'topMiddle'
                },
                border: {
                    width: 1,
                    radius: 4,
                    color: '#393939'
                }
            },
            // Give it some style
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            }
        });
		    
		     // Get Link popup box
		   $('.getLink').each(function()
		   {
		      $(this).qtip(
		      {
		         content: '<p class="padBottom8">Paste this interview url into a job posting or email:</p><p><input type="text" class="inputText text12 textCenter widthFull" onclick="selectAll();" value="' + this.href + '" readonly="true"/></p>', // Give it some content
		         show: { 
            		delay: 0 
        		 	},
				     hide: {
		            fixed: true // Make it fixed so it can be hovered over
		         },
		         style: {
                backgroundColor: '#393939',
                color: '#ffffff',
                width: 400,
                textAlign: 'center',
                fontSize: 11,
                lineHeight:2.6,
                padding: 5,
               	tip: { 
                		size: { x: 13, y: 8 },
                		corner: 'topMiddle'
                },
                border: {
                    width: 1,
                    radius: 4,
                    color: '#393939'
                }
            },
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                },
                adjust: {
               			screen: false // Keep the tooltip on-screen at all times
            		}
            }
		      });
		      $(this).attr('href','javascript:void(0);');

		   });
        //Table striping 
         $(".stripeMe tr:odd").addClass("even");
         
        //Table row hover effect
        $('table tr').hover(function () {
            $(this).find('td').addClass('hovered');
        },

        function () {
            $(this).find('td').removeClass('hovered');
        });
        //homepage module hover effect
        $('.blueBorderBox').hover(function () {
            $(this).addClass('hovered');
        },
        function () {
            $(this).removeClass('hovered');
        });
        //focus on interviewtitle
        $('.inlineCreateInterview').click(function () {
            setTimeout(function(){$("#quiz_name").focus();}, 400);
        });

    toggle_multi_choice_form('text');

    $("#show_hidden_id").click(function (event) {
        $("#hidden_responses_toggle").submit();
    });

    $("#qtypeSubmit").click(function (event) {
        $('#qtypeWrapper').hide();
        $("#question_input_new").css("display", "block");
        $("#save_buttons_new").css("display", "block");
        $("#close_add_question").css("display", "block");
        $("#add_question").css("display", "none");
        $("#preview_button").css("display", "none");
        $("#actionButtons").css("display", "none");
        $("#add_question_header").css("display", "block");
        $('#question_input_new').focus();
        $('#question_form_new').show();


        var question_type = $("#qtype").val();

        if (question_type != 'text') {
            toggle_multi_choice_form(question_type);
        }

        $("input[name='question_type']").val(question_type);

        return false;
    });

    $("#close_add_question").click(function (event) {
        reset_add_question();
        $('#question_form_new').hide();
        toggle_multi_choice_form('text');

        return false;
    });

    $("input[class='option_correct']").change(function (event) {
        // TBD uncheck all checkboxes in this class, except for this one
    });

    function set_location_from_pulldown() {
        location.href = $(this).val();
    }

    $("select[name='jump_response']").change(set_location_from_pulldown);

    $("select[name='jump_interviews']").change(set_location_from_pulldown);

    $("select[name='jump_ratings']").change(set_location_from_pulldown);

    $("select[name='jump_ratings_user']").change(set_location_from_pulldown);

    setup_answer_buttons();
    setup_remove_button();
    setup_edit_button();

    $("#save_and_finish").click(function (event) {

        return false;
    });

    $("#answersTab").click(function (event) {
        $("#responses").css("display", "block");
        $("#resume").css("display", "none");
        $("body").addClass("answers");
        $("body").removeClass("resume");
 
        return false;
    });

    $("#resumeTab").click(function (event) {
        $("#responses").css("display", "none");
        $("#resume").css("display", "block");
        $("body").removeClass("answers");
        $("body").addClass("resume");

        return false;
    });

    $(".inlinePreview").click(function (event) {
        $("#quiz_preview_iframe").attr("src", this.href);
        $("#quiz_preview_url").text("URL: " + this.href);
        return false;
    });

    $(".addUser.inputBtnLarge").click(function (event) {
        //TBD: this handler is called, but we're still taken to
        //the submit result page.
        $.post(this.form.href, this.form.serialize(), function (data) {
            $('#sent_invitation').css('visibility', 'visible');
        });

        return false;
    });

    $(".editInterviewTitle").click(function (event) {
        var title_link_id = this.id;
        var title_id = title_link_id.replace('interview_title_link', 'interview_title');
        var quiz_id = title_link_id.replace('interview_title_link_', '');
        var title = $('#' + title_id).text();
        $.alerts.okButton="Save";
        $.alerts.cancelButton="Cancel";
        jPrompt('Enter New Title:', title, 'Rename Job', function (quiz_name) {
            if (quiz_name) {
                $.post('/quiz/update-name/' + quiz_id, {
                    name: quiz_name
                },


                function (data) {
                    $('#' + title_id).text(data);
                });
            }
        });
        return false;
    });
    $("#orgName").hover(function() {
   		$(this).addClass("hidden");
	  	$(this).next("span").removeClass("hidden");
		});
		 $("#userEmail").mouseout(function() {
   		$(this).addClass("hidden");
	  	$(this).prev("span").removeClass("hidden");
		});

});

function show_title_form() {
    $("#title_form").css("display", "block");
    $("#title_static").css("display", "none");
    $("#edit_title_link").css("display", "none");

    return false; // prevents pseudo-url from refreshing page
}

function submit_edit_ajax(input_element) {
    var form_id = input_element.form.id;
    var container_id = form_id.replace('question_form', 'question');
    var display_function;

    if (form_id == 'question_form_new') {
        display_function = function (data) {
            $('.questionList').append(data);
            setup_edit_button();
            setup_remove_button();
        };
    } else {
        display_function = function (data) {
            $('#' + container_id).replaceWith(data);
            setup_edit_button();
            setup_remove_button();
        };
    }

    var save_url = input_element.form.action + 'ajax/';
    $.post(save_url, $('#' + form_id).serialize(), display_function);

    $(".noQuestionMessage").css("display", "none");
    $("#actionButtons").css("display", "block");

    reset_add_question();
    toggle_multi_choice_form('text');

}

function reset_add_question() {
    $("#qtypeWrapper").show();
    $("#question_input_new").css("display", "none");
    $("#save_buttons_new").css("display", "none");
    $("#close_add_question").css("display", "none");
    $("#add_question").css("display", "inline");
    $("#preview_button").css("display", "inline");
    $("#actionButtons").css("display", "block");
    $("#add_question_header").css("display", "none");
    $('#question_form_new').show();

    $("#qtype").val("");
    $("#question_input_new").val("");
}

function setup_answer_buttons() {

    $(".anotherAnswer").click(function (event) {
        var link_id = this.id;
        var hidden_id = link_id.replace('another_answer', 'start_hidden_options');
        var container_id = link_id.replace('another_answer', 'option_container');

        var start_hidden_options = $("input[name='" + hidden_id + "']").val();
        var container = container_id + '_' + start_hidden_options;

        $("#" + container).removeAttr('style');
        start_hidden_options++;
        $("input[name='" + hidden_id + "']").val(start_hidden_options);

        return false;
    });

    $(".answerBtn.removeAnswer.newAnswer").click(function (event) {
        var link_id = this.id;
        var container_id = link_id.replace('remove_answer', 'option_container');
        $("#" + container_id).remove();

        return false;
    });

}

function setup_edit_button() {

    $(".editQuestionInline").click(function (event) {
        var edit_question_id = this.id;
        var question_container_id = edit_question_id.replace('edit_question_text', 'question').replace('edit_question', 'question');
        var url = this.href + 'ajax/';
        $.get(url, {},
              function (data) {
                $("#" + question_container_id).replaceWith(data);
              }
        );

        return false;
    });

}

function setup_remove_button() {

    $(".btnRemoveQuestion").click(function (event) {
        var link_id = this.id;
        var question_container_id = link_id.replace('remove_question', 'question');
        var remove_url = this.href;

        jConfirm('Are you sure you want to remove this question?', 'Warning', function (result) {
            if (result) {
                $.get(remove_url, {},

                function (data) {
                    $("#" + question_container_id).remove();
                });
            }
        });

        return false;
    });

}

function toggle_multi_choice_form(question_type) {
    if (question_type == 'multiple-choice') {
        $("#multiple_choice_form_new").css("display", "block");

        for (var i=1; i<=4; i++) {
          $("input[name='option_text_" + i + "']").val("");
          $("input[name='option_correct_" + i + "']").val("");
        }

        // TBD: firefox does something odd with display:block, this seems to work
        // better, but is non-standard.
        $("#option_container_new_3").css("display", "");
        $("#option_container_new_4").css("display", "");
    } else if (question_type == 'yes-no') {
        $("#multiple_choice_form_new").css("display", "block");

        $("input[name='option_text_1']").val("Yes");
        $("input[name='option_text_2']").val("No");
        $("input[name='option_correct_1']").val("");
        $("input[name='option_correct_2']").val("");

        $("#option_container_new_3").css("display", "none");
        $("#option_container_new_4").css("display", "none");

        $("input[name='start_hidden_options']").val("2");
    } else {
        $("#multiple_choice_form_new").css("display", "none");
    }
}

function edit_interview() {
    var default_name = $("#interview_name").text();
    var input_elem = '<input type="text" id="interview_input" name="itv_name" value="' + default_name + '"/>';

    $("#interview_name").replaceWith(input_elem);

    $("#save_interview").css("display", "inline");
    $("#edit_interview").css("display", "none");
}

function save_interview() {
    var interview_name = 'My Interview';
    var interview_span = '<span id="interview_name">' + interview_name + '</span>';

    $("#interview_input").replaceWith(interview_span);

    $("#save_interview").css("display", "none");
    $("#edit_interview").css("display", "inline");
}

//Select text in textarea on click
function selectAll() {
    $(this).select();
}

//Focus on interview title on new interview creation

function focusField(id) {
    document.getElementById(id).focus();
}
// Coming Soon 


function comingSoon() {
    alert("This feature is coming soon!");
}
/**
 * Unobtrusively set up placeholder behaviors on all text inputs for which
 * the title attribute has been set. The title text will be used as the
 * placeholder text.
 * @author Travis Miller
 * @link http://www.electrumdigital.com/
 */
$( function() {
 
    $("input[type=text][title],textarea[title]")
        .each( showPlaceholder ) // initialize each control on page load
        .blur( showPlaceholder )
        .focus( hidePlaceholder );
 
    $("form").submit( function() {
    	$( "input[type=text][title],textarea[title]", this ).each( hidePlaceholder );
    } );
 
    function showPlaceholder() {
    	var $control = $(this);
        var placeholderText = $control.attr("title");
        if ( $control.val() === "" || $control.val() === placeholderText ) {
        	$control.addClass("placeholder");
            $control.val(placeholderText);
        }
    };
 
    function hidePlaceholder() {
    	var $control = $(this);
        if ( $control.val() === $control.attr("title") ) {
        	$control.removeClass("placeholder");
        	$control.val("");
        }
    }
 
} );

