$(document).ready(function() {
  $("tr.address_row").hover(
    function() {
      $(this).addClass("highlight");
      $(this).find(".controlbox").show();
    },
    function() {
      $(this).removeClass("highlight");
      $(this).find(".controlbox").hide();
    }
  );

  $("#button_card_view").click(function() {
    //$(this).toggle();
    //$(".tableview").toggle();
    $("#tableview").hide();
    //hides bulk actions for card view and disables clicking
    $("#bulk_action_panel").css('opacity','0');
    $("#button_list_view").removeClass('activelistview');
    $("#cards").show();
    $("#button_card_view").addClass('activecardview');
    $.cookie("address_view", "cardview");
  });
  $("#button_list_view").click(function() {
    //$(this).toggle();
    //$(".cardview").toggle();
    $("#tableview").show();
    $("#bulk_action_panel").css('opacity','1');
    $("#button_list_view").addClass('activelistview');
    // $('table.addressbook').Scrollable(300, 700);
    $("#cards").hide();
    $("#button_card_view").removeClass('activecardview');
    $.cookie("address_view", "tableview");
  });
  
  if($.cookie("address_view") == "cardview") {
		$("#button_card_view").addClass('activecardview');
    $("#bulk_action_panel").css('opacity','0');
  }
  else {
    $("#tableview").show();
    $("#button_list_view").addClass('activelistview');
    $("#cards").hide();
    $("#bulk_action_panel").css('opacity','1');
    $("#button_card_view").removeClass('activecardview');
  }
})

// add Accept:text/javascript header to jQuery ajax requests
$.ajaxSetup({
  // need to add to accepts:html to fix Safari
  'accepts': {
    html: 'text/javascript, text/html',
    xml: "application/xml, text/xml",
    script: "text/javascript, application/javascript",
    json: "application/json, text/javascript",
    text: "text/javascript,text/plain",
    _default: "text/javascript,*/*"
  },
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "application/json, text/javascript") }
});

// send the csrf prevention token for non-GET ajax requests
$(document).ajaxSend(function(event, xhr, settings) {
  // skip if GET request or the token isn't defined on the page
  if (settings.type == 'GET' || settings.type == 'get' || typeof(AUTH_TOKEN) == 'undefined') {
    return;
  }

  // force proper content-type. jquery doesn't set it if there are no params (see line 3522 of jquery-1.3.2.js)
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  // append the token to the outgoing parameter data string
  settings.data = (settings.data ? settings.data + "&" : "") + $.param({ authenticity_token : AUTH_TOKEN });
});

$(document).ready(function($) {
  // enable facebox links
  $('a[rel*=facebox]').facebox();

  // remove default facebox footer
  $(document).bind('beforeReveal.facebox', function() {
    $('#facebox .footer').remove();
  });

  // enable cancel button actions in lightboxes
  $('#facebox #cancel, #facebox .cancel').live('click', function() {
    $(document).trigger('close.facebox');
    return false;
  });

  // add tooltips
  $('.tip').each(function() {
    $(this).cluetip({
      width: 400,
      dropShadow: true,
      arrows: true,
      cluezIndex: 599
    });
  });

  // enable tabs
  $('#stats > ul').tabs({ fx: { opacity: 'toggle' } });

  // front page button hovers
  function toggleHover() {
    $(this).toggleClass('hover');
    $('#overlay').toggleClass($(this).attr("id") + '_overlay');
  }
  $('#homepagetabs li#what_is_vowdoo').hover(toggleHover, toggleHover);
  $('#homepagetabs li#say_i_do').hover(toggleHover, toggleHover);
  $('#homepagetabs li#how_to_vowdoo').hover(toggleHover, toggleHover);
  $('#homepagetabs li#what_vowdoo_costs').hover(toggleHover, toggleHover);

  // autocomplete email functionality on dashboard new guest form
  search_fields = $('#guest_first_name, #guest_last_name');
  search_fields.change(function() {
    $.get('/autocomplete_contacts/search.js', search_fields.fieldSerialize(), function(data, textStatus) {
      if (data && data.length > 0 && textStatus == 'success') {
        $('#guest_email').val(data);
        // todo: add more ui around this so user knows autocomplete is working or not.
      }
    });
  });

  // edit guest lightbox: children guests nested forms add blank row functionality
  $('#guests_info a.add_child').live('click', function() {
    var assoc   = $(this).attr('data-association');
    var regexp  = new RegExp('new_' + assoc, 'g');
    var new_id  = new Date().getTime();

    $("#guests_info table > tbody:last").append("<tr>" + NEW_CHILD_FORM.replace(regexp, new_id) + "</tr>");
    return false;
  });

  // additional family lightbox from dashboard new guest form
  $("form.new_guest select[id$='guest_type']").change(function(elem) {
    if ($(elem).val() != "Single") {
      $.facebox({ div: '#additional_family'});
    }
  });
  // copy form values from additional family lightbox to fields in form when closing
  $(document).bind('close.facebox', function() {
     $('#facebox #additional_family :input').each(function() {
       if ($(this).attr('id')) {
         if($(this).is(':checked')) {
           $('#' + $(this).attr('id')).attr('checked', true);
         } else {
           $('#' + $(this).attr('id')).val($(this).val());
         }
       }
     });
  });

  // confirm edit templates lightbox on dashboard request button
  $('.question_link').click(function() {
    $('#edit_template_confirmation a#send').attr('href', $(this).attr('rel'));
    $.facebox({ div: '#edit_template_confirmation'});
    return false;
  });

  // show the assignable contacts part of the new guest form in a lightbox
  if ($('.do_assign_lightbox').length > 0) {
    $.facebox({ ajax: '/guests/0/assign' });
  }
  
  // dashboard video
  if ($('.show_video').length > 0) {
    $.facebox({ div: '#video' });
  }
  $('a.open_video').click(function() {
    $.facebox({ div: '#video'});
    return false;
  });
  $(document).bind('close.facebox', function() {
    if ($('#video:visible').length > 0) {
      $.post('/users/watched_video');
    }
  });
  
  if ($('.show_offer').length > 0) {
    $.facebox({ div: '#offer' });
  }
  
  if ($('.show_facebook_share').length > 0) {
    $.facebox({ div: '#facebook-share' });
  }

  // add email for first guest lightbox
  if ($('#first_guest_email').length > 0) {
    $.facebox({ div: '#first_guest_email' });
  }

  var parseOptionTree = function(element) {
    // this is a pretty inefficient implementation, but the data set is small
    var result = {};

    var getDepth = function(option) {
      var classes = option.attr('class').split(' ');
      for (var i = 0; i < classes.length; i++) {
        if (classes[i].indexOf('depth_') == 0) {
          return parseInt(classes[i].substr(6));
        }
      }
      return null;
    };

    var getParents = function(option) {
      var parents = [];
      for (depth = getDepth(option) - 1; depth > 0; depth--) {
        parents.unshift(option.prevAll('.depth_' + depth + ':first'));
      }
      return parents;
    };

    element.find('option:enabled').each(function() {
      var leaf = $(this);

      var node = result;
      $(getParents(leaf)).each(function() {
        var name = this.text();
        if (node[name]) {
          node = node[name];
        } else {
          node = (node[name] = {});
        }
      });
      node[leaf.text()] = leaf.attr('value');
    });

    return result;
  };

  $('.option_tree').each(function() {
    var tree = $(this);

    $('<input type="hidden"/>').replaceAll(tree)
      .attr('name', tree.attr('name'))
      .optionTree(parseOptionTree(tree));
  });


  // Toggle row of buttons on a guest card on hover.
  $("div.card").hover(
    function () {
      var button_bar = $(this).children(".actions")
      if (button_bar.is(":hidden")) {
         button_bar.show(300);
       }
    }, 
    function () {
      $(this).children(".actions").slideUp();
    }
  );

  // Toggle row of actions on gatherings pages.
  $("td.rsvp_action").hover(
    function () {
      var button_bar = $(this).children(".rsvp_actions")
      if (button_bar.is(":hidden")) {
         button_bar.show(300);
       }
    }, 
    function () {
      $(this).children(".rsvp_actions").slideUp();
    }
  );

  Date.firstDayOfWeek = 0;
  Date.format = 'mm/dd/yyyy';

  $("#event_ceremony_on").datePicker();

  $('.template').hide();
  $('.template:first').show();

  if ($("#rsvpStats").length != 0) {
    $.plot($("#rsvpStats"), rsvpStats, pie_graph_options);
  }

});

$(document).ready(function() {
  $("tr.rsvp_row").hover(
    function() {
      $(this).addClass("highlight");
      $(this).find(".rsvp_actions").show();      
    },
    function() {
      $(this).removeClass("highlight");
      $(this).find(".rsvp_actions").hide();
    }
  );
});

function switch_to_template(obj) {
  var selected = obj.selectedIndex;
  $('.template').hide();
  $('#'+obj.options[selected].value).show();
}

// post-import callback for plaxo importer on event settings page
function onABCommComplete(data) {
  $('#plaxo_success').show();
  if (data) {
    $('#contacts').val($.toJSON(data));
    $('#plaxo_count').text(data.length);
  } else {
    $('#plaxo_success button').hide();
    $('#plaxo_count').text("No");
  }
}

// Select all button
$(document).ready(function(){

 $("#select_all").click(function()
  {
   var checked_status = this.checked;
   $("input[name=guests[]]").each(function() {
    this.checked = checked_status;
   });
  });

});
