jQuery(document).ready(function($){
  document.fbfriend = {};
  $('.fb_mutual_pics_dots').live('mouseenter', function(ev) {
    if (!$(this).data('info')) {
      var num = this.title.match(/\d+/);
      $(this).data('name', 'You have ' + num);
      $(this).data('info', 'more mutual friend' + (num > 1 ? 's' : ''));
      this.title = null;
    }
    $('#fb-tip').remove();
    var p = $(this).after('<div id="fb-tip"><dl><dt>'+$(this).data('name')+'</dt><dd>'+$(this).data('info')+'</dd></dl></div>').position();
    $('#fb-tip').css({'top':'21px', 'left':p.left});
  }).live('mouseout', function(ev){
    $('#fb-tip').remove();
  });
  $('.fbpic').live('mouseenter', function(ev) {
    $('#fb-tip').remove();
    var p = $(this).after('<div id="fb-tip"><dl><dt><img src="'+document.base_url+'images/fb_tip.gif" alt="loading..." /></dt><dd></dd></dl></div>').position();
    $('#fb-tip').css({'top':'21px', 'left':p.left});
    if(!document.fbfriend[$(this).attr('longdesc').substr(26)]) {
      $.getJSON($(this).attr('longdesc')+'?callback=?', function(data){
        if (document.fbuid && document.fbuid == data.id) {
          document.fbfriend[document.fbuid] = {'name':data.name, 'info':'you two are friends'};
        } else {
          document.fbfriend[data.id] = {'name':data.name, 'info':'is a mutual friend'};
        }
        $("#fb-tip dt").text(document.fbfriend[data.id].name);
        $("#fb-tip dd").text(document.fbfriend[data.id].info);
      })
    } else {
      $("#fb-tip dt").text(document.fbfriend[$(this).attr('longdesc').substr(26)].name);
      $("#fb-tip dd").text(document.fbfriend[$(this).attr('longdesc').substr(26)].info);
    }
  }).live('mouseout', function(ev){
    $('#fb-tip').remove();
  });
  function browseFb() {
    $("#facebook_connected").removeClass("box_inactive_2").addClass("box_active_2");
    $("#friends").attr('checked', true);
    $("#pagination").hide();
    $("#resultset").hide();
    $("#progress").show();    
    updateResults();
  }
  if('#fb' == location.hash) {
    browseFb();
  }
  /*$("#fb-browse").attr('href', location.protocol+'//'+location.hostname+location.pathname+'?js=1#fb').bind("click", function(){
    browseFb();
  });*/
  $("#fb-browse").attr('href', document.base_url+'find/?js=1#fb');
  $("#btn_connect, #btn_connect_med").live('click', function() {
    FB.login(function(response){
      if("connected" == response.status) {
        $.ajax({
          url: document.base_url+'fb/check',
          type: "POST",
          dataType:"json",
          success: function(data) {
            if('login' == data.state || 'added' == data.state) {
              location.reload(true);
            } else if('exist' == data.state) {
              fb.loadAnchor(document.base_url+'fb/merge', 'theme:custom width:470 height:360 scrolling:no outerBorder=0 innerBorder=1 showClose:false modal:true padding:15 innerBorder:0 disableScroll:false shadowType=halo overlayOpacity:0.001');
            } else if('linked' == data.state) {
              $.alerts.dialogClass = "confirmed"; // set custom style class
			        jAlert('We have successfully linked your Facebook profile to your Tischen account.',
			               'Success!',
			               function() {
                       location.href = document.base_url + 'account';
			               });
			        $.alerts.dialogClass = null; // reset to default
            }
          }
        });  
      }
    },
    {perms:'email'});
  });
  $("#fb_invite, #fb-invite").bind("click", function(){
    fb.loadAnchor(document.base_url+'fb/invite', 'theme:custom width:660 height:593 scrolling:no showClose:false modal:true padding:15 innerBorder:1 outerBorder:0 disableScroll:false shadowType=halo overlayOpacity:0');
  });
  $(".updating-results").hide();
  $("#field_rate_from, #field_rate_to").live("focus", function(){
    $("#field_rate").attr("checked", "checked");
    $("#box_rate").addClass("box_active");
  });
  $("#field_gender_female, #field_gender_male").live("change", function(){
    $("#box_gender").addClass("box_active");
    $("#field_gender").attr("checked", "checked");
    updateResults();
  });
  $("#field_rate, #field_cp, #field_ws, #field_gender, #field_gender_female, #field_gender_male, #friends").live("click", function(ev){
    if ($("#field_ws").is(":checked")) {
      $("#box_ws").addClass("box_active");
    } else {
      $("#box_ws").removeClass("box_active");
    }
    if ($("#field_cp").is(":checked")) {
      $("#box_cp").addClass("box_active");
    } else {
      $("#box_cp").removeClass("box_active");
    }
    if ($("#field_gender").is(":checked")) {
      $("#box_gender").addClass("box_active");
    } else {
      $("#box_gender").removeClass("box_active");
    }
    if ($("#friends").is(":checked")) {
      $("#facebook_connected").removeClass("box_inactive_2");
      $("#facebook_connected").addClass("box_active_2");
    } else {
      $("#facebook_connected").removeClass("box_active_2");
      $("#facebook_connected").addClass("box_inactive_2");
    }
    updateResults();
  });
  $("#field_rate_from, #field_rate_to").live("change", function(){
    if ($("#field_rate").is(":checked")) {
      $("#box_rate").addClass("box_active");
    } else {
      $("#box_rate").removeClass("box_active");
    }
  });
  $("#field_rate_from, #field_rate_to").live("blur", function(){
    if ($("#field_rate").is(":checked")) {
      $("#box_rate").addClass("box_active");
      updateResults();
    } else {
      $("#box_rate").removeClass("box_active");
    }
  });
  document.geocode = false;
  document.centerlat = false;
  document.centerlng = false;
  document.formatted = false;
  var address;
  var geocoder;
  address = ($("#field_place").is(".inactive") ? "" : $("#field_place").val());
  if (address && address != 'anywhere' && address != 'earth' && address != 'world' && 0 == $("#place_formatted").length) {
    $("#progress").show();
    document.geocode = true;
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        //console.log(results);
        document.centerlat = results[0].geometry.location.lat();
        document.centerlng = results[0].geometry.location.lng();
        document.formatted = results[0].formatted_address;
        updateResults(-1);
      } else {
        $("#results").hide();
        $("#results_container").empty();
        $("#search_error_message").html("We couldn&#39;t locate <em>&#34;"+$("#field_place").val()+"&#34;</em>. Please try another location or leave the field empty.");
        $("#no_results").show();
      }
    });
  }
  function updateResults(page) {
    //alert($("#friends").val());
    $("#no_results").hide();
    $(".updating-results").show();
    if (document.xhr && document.xhr.abort) { 
      document.xhr.abort(); 
    }
    document.xhr = $.ajax({
      url: document.base_url+'fetch/',
      type: "POST",
      data:({
        "o":($("#friends").is(":checked") ? $("#friends").val() : ""),
        "s":($("#field_search").is(".inactive") ? "" : $("#field_search").val()),
        "a":($("#field_place").is(".inactive") ? "" : $("#field_place").val()),
        "m":(document.formatted ? document.formatted : ($("#field_place").is(".inactive") ? "" : $("#field_place").val())),
        "p":(undefined === page || -1 == page ? 0 : page),
        "i":(undefined !== page && -1 == page ? 1 : 0),
        "f":($("#field_rate").is(":checked") ? $("#field_rate_from").val() : ""),
        "t":($("#field_rate").is(":checked") ? $("#field_rate_to").val() : ""),
        "d":($("#field_location_miles") ? $("#field_location_miles").val() : ""),
        "w":($("#field_ws").is(":checked") ? "1" : ""),
        "c":($("#field_cp").is(":checked") ? "1" : ""),
        "j":(document.ta),
        "g":(jQuery("#field_gender").is(":checked") ? ( jQuery("#field_gender_female").is(":checked") ? "2" : ( jQuery("#field_gender_male").is(":checked") ? "1" : "") ) : ""),
        "x":(false===document.centerlng ? "" : document.centerlng),
        "y":(false===document.centerlat ? "" : document.centerlat)
      }),
      dataType:"json",
      success: function(data) {
        document.xhr = null;
        document.ta = false;
        if(data) {
          if(data.total && (1 == document.ss || 1 == data.friends)) {
            $("#mass").show();
          } else {
            $("#mass").hide();
          }
          if (undefined !== data.force_filter_complete_profile && true == data.force_filter_complete_profile) {
            $("#field_cp").attr("checked", "checked");
            $("#box_cp").addClass("box_active");
          };
          if (undefined != data.showing_from) {
            $("#showing_from").text(data.showing_from);
            $("#showing_to").text(data.showing_to);
            $("#total_rows").text(data.total);
            $("#showing").show();
          } else {
            $("#showing_from").text("");
            $("#showing_to").text("");
            $("#total_rows").text("");
            $("#showing").hide();
          }
          $("#progress").hide();
          
          if (data.showmap) {
            $("#box_location").html(data.place).show();
          } else {
            $("#box_location").html(data.place).hide();
          }
          
          if (data.results) {
            $("#no_results").hide();
            $("#results_container").html(data.results);
            $("#results").show();
            $("#resultset").show();
            $("#pagination").show();
          } else {
            $("#results").hide();
            $("#results_container").empty();
            if (document.geocode) {
              if (false === document.centerlat && false === document.centerlng) {
                $("#search_error_message").html("We couldn&#39;t locate <em>&#34;"+$("#field_place").val()+"&#34;</em>. Please try another location or leave the field empty.");
              } else {
                if(100 == $("#field_location_miles").val()) {
                  $("#search_error_message").html("Your search did not match any profiles in "+$("#place_formatted").attr("title")+".");
                } else if(1 == $("#field_location_miles").val()) {
                  $("#search_error_message").html("Your search did not match any profiles within a mile of<br />"+$("#place_formatted").attr("title")+".");
                } else {
                  $("#search_error_message").html("Your search did not match any profiles within "+$("#field_location_miles").val()+" miles of<br /> "+$("#place_formatted").attr("title")+".");
                }
              }
            } else {
              $("#search_error_message").html("Your search did not match any profiles.");
            }
            $("#no_results").show();
            $("#mass").hide();
          }
          $(".updating-results").hide();
        } 
      },
      error:function (xhr, ajaxOptions, thrownError) {
          alert('error');
      }
    });  
  }
  $("#field_location_miles").live("change", function(ev){
    updateResults();
  });
  $("#pagination a").live("click", function(ev){
    $(window).scrollTo("#wrapper", "slow");
    updateResults(this.href.substr(this.href.lastIndexOf('/')+1));
    if (!ev) var ev = window.event;
    ev.cancelBubble = true;
    if (ev.stopPropagation) ev.stopPropagation();
    if (ev.preventDefault) ev.preventDefault();
    return false;
  });

  $("#mass").live('click', function() {
    if (!$("#friends") || !$("#friends").is(":checked")) {
      if ($("#field_search").hasClass("inactive") || !$.trim($("#field_search").val())) {
        jAlert('Please search for a job title or skill first before sending a job request.');
        return false;
      }
    }
    
    var dynamic_url = document.base_url + 'mass_jobrequest?';
    if ($("#field_search").val() != '"What"- e.g. babysitter') {
        dynamic_url += 'jobtitle=' + $("#field_search").val() + '&';
    }
    if ($("#field_place").val() != '"Where"- e.g. Brooklyn') {
        dynamic_url += 'where=' + $("#field_place").val() + '&';
        dynamic_url += 'distance= '+ $("#field_location_miles").val() + '&'
    }
    if ($("#field_rate").is(":checked")) {
        if ($("#field_rate_from").val() >= 0) {
            dynamic_url += 'rate_from=' + $("#field_rate_from").val() + '&';
        }
        if ($("#field_rate_to").val() >= 0) {
            dynamic_url += 'rate_to=' + $("#field_rate_to").val() + '&';
        }
    }
    if ($("#field_cp").is(":checked"))
    {
        dynamic_url += 'completeprofile=1&';
    }
    else {
        dynamic_url += 'completeprofile=&';
    }
    if ($("#field_ws").is(":checked")) {
       dynamic_url += 'worksample=1&';
    }
    if ($("#field_gender").is(":checked")) {
        if ($("#field_gender_female").is(":checked")) {
            dynamic_url += 'gender=2&';
        }
        else if ($("#field_gender_male").is(":checked")){
            dynamic_url += 'gender=1&';
        }
    }
    if ($("#friends").is(":checked")) {
        dynamic_url += 'facebook=1';
    }

    if ($(this).attr('class') != 'loggedin') {
        fb.loadAnchor(dynamic_url, 'theme:custom width:800 height:440 scrolling:no showClose:false modal:true padding:15 outerBorder:0 innerBorder:0 disableScroll:false shadowSize=16 shadowType=halo overlayOpacity:0 loadPageOnClose: self');
    }
    else {
        fb.loadAnchor(dynamic_url, 'theme:custom width:800 height:440 scrolling:no showClose:false modal:true padding:15 outerBorder:0 innerBorder:0 disableScroll:false shadowSize=16 shadowType=halo overlayOpacity:0');
    }

    
  });

});

