/* NetAcad main javascript library. */

$(document).ready(function() {
  // what do we need to do when the page is loaded?

  $("#navTree").treeview({
    animated: "fast",
    collapsed: true,
    persist: "location"
  });

  $.session();
  $.listJobCountries();
  $.jobSearch();
  $.getUserCountry();

  if ( $("#cisco_articles").length > 0 || $("#gazeta").length > 0 ) {

    $("#cisco_articles").feedreader({
        targeturl: "/feeds/cisco.features.xml",
        items: 5
    });

    $("#cisco_videos").feedreader({
        targeturl: "/feeds/cisco.video.xml",
        items: 3,
        titleLength: 5
    });

	$("#gazeta").feedreader({
        targeturl: "/feeds/gazeta.pl.xml",
        items: 3,
        titleLength: 5
    });
  }

  $("#login").submit($.login);
  $("#logout").click($.logout);
  $("#register").submit(registerUser);
  $("#registerEmployer").submit(registerEmployer);
  $("#forgottenPassword").submit(forgottenPassword);
  $("#searchsave").submit(saveSearch);
  $("#changePassword").submit(changePassword);
  $("#userProfileForm").submit(updateProfile);
  $("#sendToFriend").submit(submitForm);
  $("#chooseYourCountry").change(showRecruiter);
  $("#competition").submit(submitForm);
  $("#questionnaire").submit(submitForm);
  $("#cms_request").submit(submitForm);
  // $("#register").submit(submitForm);

    if ( typeof articleID != "undefined" ) {
        if ( articleID.length > 0 ) {
            for ( i=0; i< articleID.length; i++ ) {
                var artID = articleID[i];
                var curval = 3;
                // get the rating
                $.ajax({
                  type: "POST",
                  url: '/api/cms/Rating',
                  dataType: "json",
                  async: false,
                  data: { aid : artID },
                  success: function(res) {
                    curval = res.score;
                  },
                  complete: function () {
                    $('#' + artID ).rating( '/api/cms/Vote', {maxvalue:5, curvalue:curval, id:''+artID+''} );
                  }
                });
            }
        }
    }

});

jQuery.extend({

  login: function ()
  {
    // user login attempt
    document.body.style.cursor = 'wait';
    var queryString = $(this).serialize();
    $.ajax({
      type: "POST",
      url: '/api/users/Session',
      dataType: "json",
      data: queryString,
      success: function(data) {
        if (data.status == 'error') {
          $.prompt('Login Failed. Please enter your email and password and try again');
          $.cookie('session',null); // clear invalid session key
        }
        else {
          $.cookie('session',data.session_key);
          $.user = data;
          var page = location.pathname.substring(1);
          if (page == 'job_register.htm') {
            location.replace('http://'+location.host+'/job_member_summary.htm');
          }
          else {
            $.listTaggedJobs();
            $("#loginBox").slideUp("fast", function () {
              var numSearches = (data.searches) ? data.searches.length : 0;
              $("#saved_searches_count").text(numSearches);
              $("#memberSummaryBox").slideDown('fast');
            });

            if ($("#userProfileForm").length > 0) {
              for (i in data) {
                $("#"+i).attr('value',$.user[i]);
              }
            }
            $(".first_name").text($.user.first_name);
          }
        }
      },
      complete: function () {
        $.refreshJobTagLinks();
        document.body.style.cursor = 'default';
      }

    });
    return false;
  },

  logout: function () {
    // user logs out
    $.cookie('session',null);
    $.user = null;
    $.removeJobTagLinks();
    $.toggleUserSummary();

    $.ajax({
        url: '/api/users/Session/End',
        data: null,
        dataType: 'json',
        complete: function () {

          var page = location.pathname.substring(1);
          if (page == 'job_member_summary.htm') {
            location.replace('http://'+location.host+'/jobs.htm');
          }
        }

    });

    return false;
  },

  session: function (callback) {
    // authenticate using session key
    if( $.cookie('session') == null ) return this;

    $("#memberSummaryLoading").show();

    // IE7 just refuses to stop caching
    var d = new Date().getTime();

    $.ajax({
      type: "POST",
      url: '/api/users/Session',
      dataType: "json",
      data: { 'd': d },
      success: function(user) {
        if (user.status == 'error') {
          $.user = null;
          $.cookie('session',null);
        }
        else {
          $.user = user;
          var page = location.pathname.substring(1);
          if (page == 'job_register.htm') {
            location.replace('http://'+location.host+'/job_member_summary.htm');
          }
        }
      },
      complete: function () {
        $("#memberSummaryLoading").hide();
        $.showUserInfo().toggleUserSummary().refreshJobTagLinks('session');
        $.listSavedSearches();
      }
    });

    return this;
  },

  // bucket for user info
  user: null,

  showUserInfo: function ()
  {
    // load a users basic info, tagged jobs and saved searches
    if (!$.user || $("#userProfileForm").length < 1) return this;

    // fill in the user profile form
    for (i in $.user) {
      $("#"+i).val($.user[i]);
    }

    var page = location.pathname.substring(1);
    if (page == 'job_member_summary.htm') {

      $(".jobDetailsBox").hide();

      // get details of my saved jobs
      var jobIds = new Array();
      for (i in $.user.jobs) {
        jobIds[jobIds.length] = $.user.jobs[i].job_id;
      }

      if (jobIds.length > 0) {
        var queryString = 'ids=' + jobIds.join(',');
        $.jobSearch(queryString);
      }
    }

    return this;
  },


  jobSearch: function (queryString) {
    // search for jobs
    if ( !queryString ) queryString = window.location.search.substring(1);
    if ( !queryString ) {
      if ($("#noResults").length > 0)
        $("#noResults").customFadeIn('fast');
        $("#loading").hide();
      return this;
    }

    var criteria = $.qsObj(queryString);
    if (criteria.save) return this;

    $.Tache.Get({
      type: "GET",
      url: '/api/jobs/Search',
      data: queryString,
      dataType: 'json',
      success: function(results) {

        var criteria = $.qsObj();
        var jobs     = results.jobs;

        // display some meta data
        $.showSearchMetaData(criteria,results.rows);

        // and some pagination links if needed
        if (jobs.length) $.showPageLinks(results.pages,results.current_page);

        $(".jobDetailsBox").hide();

        // display the search results
        var numJobs = jobs.length;
        if ( numJobs < 1 ) {
          $("#loading").hide();
          if ($("#noResults").length > 0) $("#noResults").customFadeIn('fast');
          return this;
        }

        for (i in jobs) {
          numJobs--;
          var job = jobs[numJobs]; // reverse order
          var posted = $.makeDate(job.added);
          job.posted = posted;
          var tagLink = $.jobTagLink(job.id);
          $("#jobDetailsBox") .clone()
                              .find(".more_details_link").attr('href','/job_details.htm?id='+job.id).end()
                              .find(".job_title").html(job.job_title).end()
                              .find(".job_ref").html(job.id).end()
                              .find(".job_country").html(job.country).end()
                              .find(".job_synopsis").html(job.synopsis).end()
                              .find(".posted").html(job.posted).end()
                              .find("#description").html(job.description).end()
                              .find(".apply_link").attr('href',job.source_url).end()
                              .find(".tag_link")
                                .attr("id",job.id)
                                .attr("title",tagLink[1])
                                .attr("href",tagLink[0])
                                .click(tagLink[3])
                              .end()
                              .find("#tagJob").attr("src",'/images/'+tagLink[2]).end()
                              .find("#joblist").each(function() {
                                var $this = $(this);
                                $this.empty();
                                var details = { 'posted'       : 'Date Posted',
                                                'organisation' : 'Company' ,
                                                'location'     : 'Location',
                                                'salary'       : 'Salary' };
                                for (i in details) {
                                  var desc = details[i];
                                  if (job[i]) $this.append('<li><b>'+desc+':</b> '+job[i]+'</li>').end();
                                }
                              })
                              .end()
                              .find("#source_link").each(function () {
                                var $this = $(this);
                              })
                              .end()
                              .insertAfter("#jobSearchResultsTop")
                              .show();

          // these are job details page specific
          if ($("#optTop").length > 0) {
            if (job.location)       $("#optTop").append('<b>Location :</b> '+job.location+', '+job.country+'<br>');
            if (job.organisation)   $("#optTop").append('<b>Company :</b> '+job.organisation+'<br>');
            if (job.salary)         $("#optTop").append('<b>Salary :</b> '+job.salary+'<br>');
            if (job.contract_type)  $("#optTop").append('<b>Job Type:</b> '+job.contract_type);

            if (job.contact_name)   $("#optBot").append('<b>Contact :</b> '+job.contact_name+'<br>');
            if (job.contact_phone)  $("#optBot").append('<b>Contact Telephone :</b> '+job.contact_phone+'<br>');
            if (job.contact_email)  $("#optBot").append('<b>Contact Email :</b> '+job.contact_email);

            if (job.skill) {
              $("#skills").show();
              $("#skill").text(job.skill);
            }
          }

          if (job.source_img) {
            $("#job_source").attr('src','/images/'+job.source_img);
          }
          else {
            $("#job_source").remove();
          }

          $.refreshJobTagLinks();

        }
      },
      complete: function () {
        $("#loading").fadeOut("fast", function () {
          $("#results").customFadeIn("fast");
        });
      }
    });

    return this;
  },

  showPageLinks: function (totalPages,currentPage) {

    if ($(".pagination_links").length < 1) return;

    $(".pagination_links").empty();

    totalPages = parseInt(totalPages);
    if (totalPages < 2) return;
    currentPage = (currentPage) ? parseInt(currentPage) : 1;

    var totalLinks = (totalPages < 12) ? totalPages : 12;
    var pagesAr = new Array();

    var page;

    if (currentPage - parseInt(totalLinks/2) < 0) {
      page = 0;
    }
    else if ((currentPage + totalLinks) > totalPages) {
      page = totalPages - totalLinks;
    }
    else {
      page = currentPage - parseInt(totalLinks/2);
    }

    for (i=0; i<totalLinks; i++) {
      page++;
      if (page > totalPages || page < 1) continue;
      pagesAr[pagesAr.length] = page;
    }

    pagesAr.sort($.sortNumber);

    for (i=0; i<pagesAr.length; i++) {
      var pageNum = pagesAr[i];
      var page = (currentPage != pageNum) ?
                 '<a href="javascript: continueSearch('+pageNum+')">'+pageNum+'</a>' :
                 '<b>'+pageNum+'</b>';
      pagesAr[i] = page;
    }

    $(pagesAr.join(' : ')).appendTo(".pagination_links");
  },

  showSearchMetaData: function (criteria,numResults)
  {
    // show meta data about the job search
    if ($("#results_summary").length < 1) return;

    $("#results_summary").empty().text('Total jobs found: '+numResults);

    $("#date").val(criteria.date);
    $("#country_id").val(criteria.country_id);
    $("#keywords").val(criteria.keywords);
    $("#page").val(criteria.page);
    $("#contract_type").val(criteria.contact_type);

    var critString = new Array ();
    critString[critString.length] = "Date range: " + $("#date :selected").text();
    critString[critString.length] = (criteria.country_id) ? "Country: " + $("#country_id :selected").text() : "All countries";
    critString[critString.length] = (criteria.contract_type) ? "Type: " + $("#contract_type :selected").val() : "Any contract";
    critString[critString.length] = (criteria.keywords) ? "Keywords: " + criteria.keywords : "No keywords";

    $("#searchCriteriaDetails").empty().html(critString.join(' | '));
  },

  jobTagLink: function (jobId) {
    // determine which link and image to use on the tag this job button
    var response = new Array ('/job_register.htm?save=1&id='+jobId,'Tag This Job','button_tag_job.png','');

    if ($.user) {
      response[0] = '';
      response[3] = tagJob;

      var taggedJobs = $.user.jobs;
      for (i in taggedJobs) {
        if (taggedJobs[i].job_id == jobId) {
          response = new Array ('','Untag This Job','button_tag_remove.png',unTagJob);
          break;
        }
      }
    }

    return response;

  },

  refreshJobTagLinks: function () {
    /* set the Tag This Job button to the right value as according
       to the users jobs from getUserInfo and() jobSearch() */
    $(".tag_link").each(function() {
      if (this.id) {
        var tagLink = $.jobTagLink(this.id);
        $(this).attr("title",tagLink[1])
               .attr("href",tagLink[0])
               .click(tagLink[3])
               .children("img").attr("src",'/images/'+tagLink[2]).end();
      }
    }).end
  },

  removeJobTagLinks: function () {

    $(".tag_link").each(function() {
      if (this.id) {
        var tagLink = $.jobTagLink(this.id);
        $(this).attr("title",'Tag this job')
               .unbind()
               .attr("href",'/job_register.htm?save=1&id='+this.id)
               .children("img").attr("src",'/images/button_tag_job.png').end();
      }
    }).end

  },

  toggleUserSummary: function ()
  {
    // show or remove the summary of my tagged jobs and saved
    // searches depending on whether or not I am logged in
    if (! $.user ) {
      $("#loginBox").slideDown("fast");
      $("#memberSummaryBox").slideUp('fast');
    }
    else {
      $(".first_name").text($.user.first_name);
      $("#saved_searches_count").text($.user.searches.length || 0);

      $("#loginBox").slideUp("fast");
      $.listTaggedJobs();
      $("#memberSummaryBox").slideDown('fast');
    }

    return this;
  },

  listJobCountries: function ()
  {
    // get and display a list of countries we have jobs for
    if ( $(".countrymenu").length < 1) return this;

    $.ajax({
      url: '/js/countries.js',
      dataType: "json",
      data: null,
      success: function(json) {
        var countries = json.countries
        for (i in countries) {
          var country   = countries[i];
          var thisOpt   = document.createElement('option');
          thisOpt.value = country[0];
          thisOpt.appendChild(document.createTextNode(country[1]));
          $(".countrymenu").append(thisOpt);
        }
      }
    });

    return this;
  },

  listTaggedJobs: function ()
  {
    // display this user's tagged jobs
    $("#jobs_list > p.jobs_list").remove();
    if ( !$.user ) return this;

    var jobs = $.user.jobs;
    $("#saved_jobs_count").text(jobs.length);

    if (jobs.length < 1) return this;

    for (i in jobs) {
      var job = jobs[i];
      $("#jobs_list").append('<p class="jobs_list"><a href="/job_details.htm?id='+job.job_id+'">&raquo; '+job.job_title+'</a></p>');
      if (i > 4) {
        $("#jobs_list").append('<p class="jobs_list"><a href="/job_member_summary.htm" title="See all your saved jobs">More...</a></p>');
        break;
      }
    }

    return this;
  },

  date_ranges: { 1: 'Last 3 days', 2: 'Last week', 3: 'Last month' },

  listSavedSearches: function ()
  {
    // get and display this users saved searches
    if (!$.user|| $("#searchSavedBox").length < 1) return this;

    $(".searchSavedBox").hide();

    var searches = $.user.searches;
    for (i in searches) {
      var thisSearch = searches[i];
      var updates = ( thisSearch.updates == 1 ) ? true : false
      var countryName = $.getCountryName(thisSearch.country_id);
      $("#searchSavedBox").clone()
                          .find("#searchName").html('<b>&raquo; '+thisSearch.name+'</b>').click(toggleSearchName).end()
                          .find("#search_name").val(thisSearch.name).end()
                          .find("#renameSearch").submit(renameSearch).end()
                          .find("#search_id").val(thisSearch.id).end()
                          .find("#searchUpdates")
                            .attr('checked', updates )
                            .attr('value',thisSearch.id)
                            .click(toggleSearchUpdates)
                          .end()
                          .find(".removeSavedSearch")
                            .attr("id",thisSearch.id)
                            .attr("title",'Remove '+thisSearch.name)
                            .click(removeSavedSearch)
                          .end()
                          .find("#country").text(countryName).end()
                          .find("#keywords").text(thisSearch.keywords ? thisSearch.keywords : 'None').end()
                          .find("#contract").text(thisSearch.contract_type ? thisSearch.contract_type : 'Any').end()
                          .find("#date").text($.date_ranges[thisSearch.date] ? $.date_ranges[thisSearch.date] : 'All time').end()
                          .insertAfter("#userSavedSearches")
                          .show();
    }

    return this;
  },

  getCountryName: function(countryId) {
    for (i in $.countries) {
      if ($.countries[i][1] == countryId) {
        return $.countries[i][0];
      }
    }
    return 'Any';
  },

  qsObj: function (queryString) {
    // return the URL query string as an object
    if (!queryString) queryString = window.location.search.substring(1);
    var qsobj = {};

		if ( queryString ) {
			var pairs = queryString.split('&');
			for ( i=0;i<pairs.length;i++ ) {
				var pair = pairs[i].split('=');
				qsobj[pair[0]] = pair[1] ? unescape(pair[1].replace(/\+/g," ")) : '';
			}
		}
		return qsobj;
	},

  sortNumber: function(a,b) {
    return a - b;
  },

  makeDate: function(d) {
    var month = parseInt(d.month * 1) - 1;
    var months = new Array ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );

    var dateAr = new Array(d.day,months[month],d.year);
    return dateAr.join('-');
  },

  getUserCountry: function () {
    // try and determine the user's country

    if ($("#register").length < 1 && $("#registerEmployer").length < 1 && $("#competition").length < 1 ) return this;

    $.ajax({
        url: '/api/users/Country',
        dataType: "json",
        success: function(data) {
          if (data.country_code != '') {
            $("#country").val(data.country_code);
          }
        }
    });

    return this;
  }


})(jQuery);

// fixes for the IE7 ClearType issue when using fade
(function($) {
	$.fn.customFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
})(jQuery);

function continueSearch(page) {
  $(".page").attr("value",page);
  $("#jobsearchside").submit();
}

function tagJob () {
  var $this = $(this);
  toggleTaggedJob('add',this);
  $this.unbind().click(unTagJob);
  return false;
}

function unTagJob () {
  var $this = $(this);
  toggleTaggedJob('remove',this);
  $this.unbind().click(tagJob);
  return false;
}

function toggleTaggedJob(direction,linkObj) {
  var params = {
     add:    { image: 'button_tag_remove.png', methodNm: 'SaveJob' },
     remove: { image: 'button_tag_job.png',    methodNm: 'RemoveJob' }
  };

  var myParams = params[direction];
  var $linkObj = $(linkObj);
  $linkObj.children("img").attr('src','/images/'+myParams.image);
  var jobId = $linkObj.attr('id');
  var queryString = 'job_id='+jobId;

  $.ajax({
    url: '/api/users/'+myParams.methodNm,
    dataType: "json",
    data: queryString,
    success: function(data) {
      $.session();
    }
  });

  return false;
}

function removeSavedSearch () {
  $.ajax({
    url: '/api/users/RemoveSearch',
    dataType: "json",
    data: { search_id: this.id },
    success: function(data) {
      $.session();
    }
  });
  return false;
}

function registerUser () {
  var qsObj = $.qsObj;
  var query_string = $(this).serialize();
  if (qsObj.job_id) query_string += '&job_id='+qsObj.job_id;

  $("#message").hide('fast', function () {
    $(".error").hide();
    $("#registering").show('fast', function() {
      $.ajax({
        url: '/api/users/Register',
        dataType: "json",
        data: query_string,
        success: function(data) {
          if (data.status == 'error') {
            var errors  = data.errors;
            var missing = data.missing;
            var enflect = (errors.length + missing.length > 1) ? 'errors' : 'error';
            for (i in missing.sort()) {
              $("#"+missing[i]+"_error").customFadeIn();
            }
            for (i in errors) {
              $("#"+i+"_error").text(errors[i]).customFadeIn();
            }

            $("#message").addClass('error').html('<b>The following errors occurred:</b>').customFadeIn();
            return false;
          }
          $.cookie('session',data.session_key);
          /*alert(data.session_key);*/
          window.location = "/job_member_summary.htm";
          $("#message").removeClass("error");
          $("#message").text('Congratulations, you are now registered!').customFadeIn();
        },
        complete: function () { $("#registering").toggle();}
      });
    });
  });

  return false;

}

function registerEmployer () {
  var query_string = $(this).serialize();
  $("#message").hide('fast', function () {
    $(".error").hide();
    $.ajax({
      url: '/api/users/RegisterEmployer',
      dataType: "json",
      data: query_string,
      success: function(data) {
        if (data.status == 'error') {
          var errors  = data.errors;
          var missing = data.missing;
          var enflect = (errors.length + missing.length > 1) ? 'errors' : 'error';
          for (i in missing.sort()) {
            $("#"+missing[i]+"_error").customFadeIn();
          }
          for (i in errors) {
            $("#"+i+"_error").text(errors[i]).customFadeIn();
          }
          $("#message").addClass('error').html('<b>The following errors occurred:</b>').customFadeIn();
          return false;
        }

        $.cookie('session',data.session_key);
        $("#form").load("/inc/en/employer-registered.htm");
      },
      complete: function () { $("#registering").toggle();}
    });
  });

  return false;

}

function forgottenPassword () {
  var queryString = $(this).serialize();
  $.ajax({
    type: "POST",
    url: '/api/users/ForgotPassword',
    dataType: "json",
    data: queryString,
    success: function(response) {
      if (response.status == 'error') {
        $("#msg").text('There was a problem submitting this form. Please try again');
      }
      else {
        $("#msg").html('A new password has been emailed to you.<br><br>Please use this password to login. Once logged in you can change your password on your profile page.');
		$("#forgotPasswordForm").hide();
      }
    }
  });
  return false;
}

function changePassword () {
  var queryString = $(this).serialize();
  $.ajax({
    type: "POST",
    url: '/api/users/ChangePassword',
    dataType: "json",
    data: queryString,
    success: function(response) {
      if (response.status == 'error') {
        $("#msg").text('There was a problem submitting this form. Please try again');
      }
      else {
        $("#msg").html('Your password has been updated');
		    $("#changePassword").hide();
      }
    }
  });
  return false;
}

function updateProfile () {
  var $this = $(this);
  var queryString = $this.serialize();
  $.ajax({
    type: "POST",
    url: '/api/users/Update',
    dataType: "json",
    data: queryString,
    success: function(response) {
      if (response.status == 'error') {
        $("#message").text('There was a problem submitting this form. Please try again');
      }
      else {
        $("#message").html('Details updated');
      }
    }
  });
  return false;
}

function saveSearch(formObj) {
  // save these search criteria
  if (!$.user) {
    window.location = "/job_register.htm";
  }
  else {
    var updates = formObj.send_updates.checked ? 1 : 0;
    var queryString = $("#jobsearchside").serialize();
    queryString += '&name='+formObj.search_name.value+'&send_updates='+updates;
    $.ajax({
      type: "POST",
      url: '/api/users/SaveSearch',
      dataType: "json",
      data: queryString,
      success: function(response) {
        $.session();
      },
      complete: function() {
        tb_remove();
        $("#saveSearch").fadeOut('slow');
      }
    });

    return false;
  }
}

function toggleSearchName () {
  $(this).parent().children(".toggleable").toggle();
  return false;
}

function renameSearch () {
  var $this = $(this);
  var queryString = $this.serialize();
  $.ajax({
    type: 'POST',
    url: '/api/users/RenameSearch',
    dataType: 'json',
    data: queryString,
    success: function () {
      $this.parent().children("#searchName").html('<b>&raquo; '+$this.find("#search_name").val()+'</b>').click(toggleSearchName);
      $this.parent().children(".toggleable").toggle();
    }
  });
  return false;
}

function submitForm () {
  var $this    = $(this);
  var formData = $.qsObj($this.serialize());
  formData.url = parent.location.href;
  $.ajax({
    type: 'POST',
    url: '/api/users/Forms',
    dataType: 'json',
    data: { id: formData.form_id, form_data: $.toJSON(formData) },
    success: function (data) {
      $(".error").hide();
      if (data.status == 'error') {
        var errors  = data.errors  || [];
        var missing = data.missing || [];
        var enflect = (missing.length > 1) ? 'errors' : 'error';
        for (i in missing.sort()) {
          $("#"+missing[i]+"_error").customFadeIn();
        }
        for (i in errors) {
          $("#"+i+"_error").text(errors[i]).customFadeIn();
        }
      }
      else {
        $("#message").html(data.message);
        $this.hide();
      }
    }
  });
  return false;
}

function showRecruiter() {
  var page = $(this).val();
  $.get("/inc/recruiters/"+page+".htm", function(data) {
    $("#recruiterInfo").html(data);
  });
}

function toggleSearchUpdates () {

  var search_id = this.value;
  var updates   = this.checked ? 'yes' : 'no';
  var d = new Date().getTime();

  $.ajax({
    type: 'GET',
    url: '/api/users/ToggleSavedSearch',
    dataType: 'json',
    data: { 'search_id': search_id, 'search_updates': updates, 'd' : d },
    success: function () {
      var msg = (updates == 'yes') ? 'now' : 'no longer';
      $.session().prompt('Update complete: you will '+msg+' receive updates for this search');
    }
  });

  return false;
}

