/* Main Javascript library for ZipRecruiter */

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

$(document).ready(function () {
  //Dropdown confirmation message bar (enabled in controller)
  setTimeout(function(){$('#flash_messages').slideDown('fast');}, 100);
  //closeable message link
  $('.close_link').click(function(e) {
    e.preventDefault();
    $(this).closest('.closable').hide();
    return false;
  });

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

  //No special characters method
  $.validator.addMethod("noSpecialChars", function(value, element) {
      return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
  }, "Enter only letters, numbers or dashes");
  //Add HTTP to URLs automatically
  $.validator.addMethod("complete_url", function(val, elem) {
      // if no url, don't do anything
      if (val.length == 0) { return true; }

      // if user has not entered http:// https:// or ftp:// assume they mean http://
      if(!/^(https?|ftp):\/\//i.test(val)) {
          val = 'http://'+val; // set both the value
          $(elem).val(val); // also update the form element
      }
      // now check if valid url
      // http://docs.jquery.com/Plugins/Validation/Methods/url
      // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
      return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val);
  });

    //textarea focus color
    $('textarea.textarea').focus(function () {
        $(this).addClass('focused');
    });
    $('textarea.textarea').blur(function () {
        $(this).removeClass('focused');
    });
    //Joblist row hover effect
    $('.row').live('mouseover', function() { $(this).addClass('hovered'); });
    $('.row').live('mouseout', function() { $(this).removeClass('hovered'); });
    //Joblist row hover effect
    $('#mainTabs li a').hover(function () {
        $(this).parent().addClass('hovered');
    },
    function () {
        $(this).parent().removeClass('hovered');
    });
    //jobStatus Bar row hover effect
    $('.jobStatusBar').live('mouseover', function() { $(this).addClass('hovered'); });
    $('.jobStatusBar').live('mouseout', function() { $(this).removeClass('hovered'); });

    //disable form buttons after form submit - COMMENTING OUT BECAUSE OF INTERFERENCE WITH JS VALIDATION
    //$('form').submit(function() {
      //$('input[type=submit]', this).addClass("disable");
    //});
        //Expand and collapse sections
    $(".msg_body").hide();
    $(".msg_head").click(function()
    {
      $(this).next(".msg_body").slideToggle(200);
    });

    $('textarea.resizable:not(.processed)').TextAreaResizer();

        // By suppling no content attribute, the library uses each elements title attribute by default
        $('.titleTip').each(function() {
          $(this).qtip({
              content: this.title, // Give it some content
              show: {
                  delay: 0
              },
              style: {
                  backgroundColor: '#222',
                  color: '#fff',
                  width: 155,
                  textAlign: 'center',
                  fontSize: 11,
                  padding: 3,
                  lineHeight:1.4,
                  tip: {
                      size: { x: 13, y: 8 },
                      corner: 'topMiddle'
                  },
                  border: {
                      width: 0,
                      radius: 6,
                      color: '#222'
                  }
              },
              // Give it some style
              position: {
                  corner: {
                      target: 'bottomMiddle',
                      tooltip: 'topMiddle'
                  }
              }
          });
          $(this).removeAttr('title'); //needed to not show defaut yellow title
        });
         // Get Link popup box
       $('.answerTip').each(function()
       {
          $(this).qtip(
          {
             content: this.rel, // Give it some content
             show: {
                delay: 0
               },
             hide: {
                fixed: false // Make it fixed so it can be hovered over
             },
             style: {
                backgroundColor: '#FFFADD',
                color: '#333333',
                width: 220,
                textAlign: 'left',
                fontSize: 12,
                lineHeight:1.4,
                padding: 8,
                 tip: {
                    size: { x: 8, y: 13 },
                    corner: 'rightMiddle'
                },
                border: {
                    width: 1,
                    radius: 4,
                    color: '#ffcd6b'
                }
            },
            position: {
                corner: {
                    target: 'leftMiddle',
                    tooltip: 'rightMiddle'
                },
                adjust: {
                     screen: false // Keep the tooltip on-screen at all times
                }
            }
          });
          $(this).attr('href','javascript:void(0);');

       });
         // Get Link popup box
       $('.answerTipRight').each(function()
       {
          $(this).qtip(
          {
             content: this.rel, // Give it some content
             show: {
                delay: 0
               },
             hide: {
                fixed: false // Make it fixed so it can be hovered over
             },
             style: {
                backgroundColor: '#FFFADD',
                color: '#333333',
                width: 220,
                textAlign: 'left',
                fontSize: 12,
                lineHeight:1.4,
                padding: 8,
                 tip: {
                    size: { x: 8, y: 13 },
                    corner: 'leftMiddle'
                },
                border: {
                    width: 1,
                    radius: 4,
                    color: '#ffcd6b'
                }
            },
            position: {
                corner: {
                    target: 'rightMiddle',
                    tooltip: 'leftMiddle'
                },
                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');

    $("#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
    });

    $("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_remove_button();
    setup_edit_button();

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

        return false;
    });

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

        return false;
    });

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

        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");
    });

});

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").unbind('click').click(function (event) {
        var link_id = this.id;
        var hidden_id = link_id.replace('another_answer', 'first_hidden_option');
        var container_id = link_id.replace('another_answer', 'option_container');

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

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

        return false;
    });

    $(".answerBtn.removeAnswer.newAnswer").unbind('click').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").unbind('click').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").unbind('click').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? This will also delete any responses you have already received.', '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' || question_type == 'yes-no') {
        $("#multiple_choice_form_new").css("display", "block");

        $(".answerText").val("");

        if (question_type == 'yes-no') {
          $("input[name='option_text_1']").val("Yes");
          $("input[name='option_text_2']").val("No");
        }

        $(".option_correct").attr("checked",0);

        for (var i=3; i<=10; i++) {
          $("#option_container_new_"+i).css("display", "none");
        }

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

/**
 * 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 setupPlaceholder() {
  $("input[type=text][title],textarea[title]")
      .each( showPlaceholder ) // initialize each control on page load
      .blur( showPlaceholder )
      .focus( 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("");
    }
}
$( function() {

    setupPlaceholder();
    $("form").submit( function() {
      $( "input[type=text][title],textarea[title]", this ).each( hidePlaceholder );
    } );

});

//Get URL parameters
//http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

function popupDuplicate (e,quizType) {
  var popupDuplicateUrl = e.attr('href') + "ajax";
  function setupForSubmit() { $('.ajaxPost').click(function (ev) { var t = $(ev.target); var set_submit_value = t.attr('name')+'='+t.val(); $.post(popupDuplicateUrl, $("#job_duplicate_form").serialize()+'&'+set_submit_value, function (d,ts) { if (d.charAt(0) === '/') { window.location = d; } else { $('#duplicatePop').replaceWith(d); e.colorbox.resize(); setupForSubmit(); } } ); return false; }); };
  e.colorbox({width:"700px", href:function () { return popupDuplicateUrl; }, onComplete:function () { setupForSubmit() } });
}

function getIndeedJobs(url, container_id, hide_id, callback) {
  $.ajax({
    type: "GET",
    url: url,
    dataType: "xml",
    success: function(xml) {
      var results = $(xml).find('result');
      var sponsored = $('<div id="sponsored"><div id="sponsored_by" class="text12"><div id="sponsored_inner"><strong><a href="http://www.indeed.com/" rel="nofollow" target="_blank" class="black noUnderline">Jobs</a> by</strong></div><a title="Job Search" id="sponsored_logo" href="http://www.indeed.com/" rel="nofollow" target="_blank"><img alt="Indeed job search" src="http://www.indeed.com/p/jobsearch.gif" /></a><div class="clear"></div></div><div class="clear"></div></div>');
      results.each(function() {
        var $this = $(this);
        var jobtitle = $this.find('jobtitle').text();
        var url = $this.find('url').text();
        var company = $this.find('company').text();
        var formattedDate = $this.find('formattedRelativeTime').text();
        var formattedLocation = $this.find('formattedLocation').text();
        var source = $this.find('source').text();
        var onmousedown = $this.find('onmousedown').text();
        var snippet = $this.find('snippet').text();

        var logo = '<div class="logo"><img src="//d2jutb8bry7gi8.cloudfront.net/zrs/343ccf82/img/chair-icon-gray.png" alt="' + company + '"/></div>';
        var info = $('<div class="info"></div>')
          .append('<h6><a href="'+url+'" onmousedown="' + onmousedown + '" class="block showVisited">' + jobtitle + '</a></h6>')
          .append('<p class="company">' + company + ' - <span class="location">' + formattedLocation + '</span></p>')
          //.append('<p class="snippet">' + snippet + '</p>')
          .append('<p class="category">' + source + '<span class="date"> - ' + formattedDate + '</span></p>');
        var row = $('<li class="indeed row"></li>')
          .append('<div class="flRight button text12"><p><a class="btn grayBtn small"' + onmousedown + ' href="'+url+'">View Job</a></p></div>')
          .append(logo)
          .append(info)
          .append('<div class="clear"></div>');
        sponsored.append(row);
      });
      sponsored.prependTo(container_id);
      if ($(xml).find('resultsSource').text() == 'ziprecruiter') {
        $('#indeed_at').addClass('hidden');
      }
      if (results.size() > 0) {
        $(hide_id).removeClass('hidden');
        $('#related_jobs').removeClass('hidden');
      }

      if ( typeof callback == 'function' ) {
        callback();
      }
    }
  });
}
jQuery.validator.addMethod(
    "company_name",
    function(value, element) {
        var check = false;
        var re = /\b(confidential|private|na|n\/a|anonymous|none|self)\b/
        value = value.toLowerCase();
        if( re.test(value)){
            check = false;
        } else {
            check = true;
        }
        return this.optional(element) || check;
    },
    "Some job boards will not accept job ads with this as the company name. Please enter a company name, your recruiting firm name or another descriptive phrase."
);

