//Main Event Careers Center 2010
//
//mec.js

  $(document).ready(function(){
    $(".post_add").click(addCart);
    $(".post_remove").click(removeCart);
    if($(document).hasOwnProperty('postId'))
      refreshCartSingle();
    
    $(".typeSelect").change(refreshSubTypeSelect);
  });

  function refreshSubTypeSelect(e) {
    if($(".subTypeSelect").length > 0) {
      var postString = './ajax.php?action=subTypes';
      if($(".typeSelect").val() != "") {
        postString += '&type=' + $(".typeSelect").val();
      }
      $.getJSON(postString, function(data){
        //replaces options with new ones
        var newOptions = "<option value=\"\">Any</option>\n";
        for(o in data) {
          newOptions += "<option value=\"" + o + "\">" + data[o] + "</option>\n";
        }
        $(".subTypeSelect").html(newOptions);
      });
    }
  }
      
  function addCart(e) {
    if($(this).length == 0)
      return;
    var id = $(this)[0].id.substring(4);
    var queryString = './ajax.php?action=addCart&id=' + id;
    $.getJSON(queryString, function(data) {
      if(data.addCart) {
        refreshCartShort(data);
        refreshCartSingle(data, id);
        $("#remove_" + id).click(removeCart);
      }
    });
  }

  function removeCart(e) {
    if($(this).length == 0)
      return;
    var id = $(this)[0].id.substring(7);
    var queryString = './ajax.php?action=removeCart&id=' + id;
    $.getJSON(queryString, function(data) {
      if(data.removeCart) {
        refreshCartShort(data);
        refreshCartSingle(data, id);
        $("#add_" + id).click(addCart);
      }
    });
  }

  function refreshCartShort(data) {
    //refreshes html for cart display "X items in cart"
    
    //counting objects is hard
    var l = 0;
    for (p in data.cart) if(data.cart.hasOwnProperty(p)) l++;

    if(l > 0) {
      $("p.cart_short").html("You have " + l + " job" + ((l>1)?"s":"") + " in cart. <a href=\"cart.php\">View Job Cart</a>"
		+ "&nbsp;&nbsp;<em><a href=\"apply.php\">Please click here to Start Applying</a></em>");
      //console.log('on');
    }
    else {
      $("p.cart_short").html("");
    }
  }
  
  function refreshCartSingle(data, postId) {
    //refreshes html for cart info on post-detail page "This job is/isn't in your cart"
    if(typeof(postId) == 'undefined'){
      //console.log("skipping single");
      return false;
    }
    if(data.cart.hasOwnProperty(postId)) {
      $("span.cart_single").html("This job is in your cart. <a id=\"remove_" + postId + "\" href=\"javascript:void(0)\" class=\"post_remove\">Remove From Cart</a>");
    }
    else {
      $("span.cart_single").html("This job is not in your cart. <a id=\"add_" + postId + "\" href=\"javascript:void(0)\" class=\"post_add\">Add This Job To Your Cart</a>");
    }
  }

