jQuery.ajaxSetup({
    'beforeSend': function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript")
    }
})

$(function() {

	$(".dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 340,
		width: 500,
		modal: true,
		buttons: {
         Cancel: function() {
			$(this).dialog('close');
		 },
		'Process Import': function() {
		    var import_id = $(this).attr('id').split("_")[1];
		    var container = $(this)
            var form = $(this).children('form');
            var valid = true
            form.find('input:not(:hidden)').each(function(i, v){
               if($(v).attr('name').match(/card_number|cvv/)) {
                 number = $(v).val()
                 if(!number.match(/[0-9]/))
                   valid = false;
               }
            });
            if(valid) {
                $("p#validation-tips").html("");
                //$("#process-purchase").dialog('open');
                $('.ui-dialog-titlebar-close').hide();
                var button_pane =  $("div.ui-dialog-buttonpane")
                button_pane.find('button').hide();
                $("div#process-purchase").clone().prependTo(button_pane)
                $.post(form.attr('action'), form.serialize(), function(response) {
                   button_pane.find("div#process-purchase").remove();
                   button_pane.find('button').show();
	               //$("#process-purchase").dialog('close');
                   response = eval("(" + response + ")");

	               if(response['result'] == 'pass') {
                     $("#cta_" + import_id).remove();
                     $("#dialog_" + import_id).dialog('close');
                     $("#response").dialog('open')
                     $("#response").html(response["message"])
                   } else {
                     $("p#validation-tips").html(response["message"])
                   }
                   $('.ui-dialog-titlebar-close').show();
	               return
                });
             } else {
                $("p#validation-tips").html("Invalid credit card information.");
                return;
             }
	     }
        },
        beforeclose: function() {
            form = $(this).children('form');
            if(form.length > 0)
                $(this).children('form')[0].reset();
            $("p#validation-tips").html("");
        }
	});

	$("#cvv").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 225,
		width: 375,
		modal: true
	});

	$("#response").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 225,
		width: 400,
		modal: true,
		buttons: {
         Close: function() {
			$(this).dialog('close');
			location.reload(true);
		 }
		}
	});

	$("#process-purchase").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 25,
		width: 300,
		modal: true
	});

    $('#show-cvv').live('click', function(e) {
	    e.preventDefault();
		$('#cvv').dialog('open');
	});

	$('.buy-credits').live('click', function(e) {
	    e.preventDefault();
		$('#dialog_' + $(this).attr("id").split("_")[1]).dialog('open');
	});



	$('a#no-key-mc').live('click', function(e) {
    e.preventDefault();
	  $('div#mailchimp-login').show();
	  $('div#mailchimp-key').hide();
	});
	$('a#key-mc').live('click', function(e) {
	  e.preventDefault();
	  $('div#mailchimp-login').hide();
	  $('div#mailchimp-key').show();
	});
	$('a#discount-code').click(function(e){
		e.preventDefault();
		$(this).fadeOut('fast', function() {
			$("p#discount-entry").fadeIn('fast');
		});

	})
	//tab management
	$('ul.jtabs li>a').click(function() {
		$('li.selected-tab').removeClass('selected-tab')
		$('div.tab-content').hide()
		$(this).parent('li').addClass('selected-tab')
		$("div#" + this.href.split("#")[1] + "-import-tab").show()
		$('input[type="hidden"]#import_import_type').val(this.href.split("#")[1])
	})


	if($('div.tab-content').length > 0 && window.location.hash != '') {
		$('a[href="' + window.location.hash + '"]').trigger('click');
	} else if($('input[type="hidden"]#import_import_type').length > 0) {
		$('a[href="#' + $('input[type="hidden"]#import_import_type').val() + '"]').trigger('click');
	}

	$('a.sortable').live('click', function() {
		var container = $("table.contacts");
		var group_id = current_group ? current_group : ''
		var order = ''
		if($(this).hasClass('sorted-up'))
			order = "down"
		else if($(this).hasClass('sorted-down'))
			order = "up"
		else
			order = "down"

		$.get('/dashboard', {sort: $(this).attr('id'), id: group_id, order: order}, function(result){
			container.html(result)
			$('a.trash-delete').fancyZoom();
			handle_trash();
		})
		return false;
	})

	$('.pagination a').live('click', function() {
		if($(this).parents("div#groups-container").length > 0){
			var container = $("div#groups-container")
			$.get($(this).attr('href'), function(result){
				container.html(result)
				handle_group_menu();
			})
		}
		if($(this).parents("table.contacts").length > 0){
			var container = $("table.contacts")
			$.get($(this).attr('href'), function(result){
				container.html(result)
				$('a.trash-delete').fancyZoom();
				handle_trash();
			})
		}
		return false
	})
	current_group = null
	$("a.contact-group").live('click', function() {
		$("a.contact-group-selected").removeClass('contact-group-selected')
		$(this).addClass("contact-group-selected")
		var container = $("table.contacts")
		if($(this).html() == "All Contacts")
			current_group = null;
		else
			current_group = $(this).attr("id").split("_")[1];
		$.get($(this).attr('href'), function(result){
			container.html(result)
			$('a.trash-delete').fancyZoom();
			handle_trash();
		})
		return false;
	})

	$("a#seek-insight").click(function(e) {
		e.preventDefault()
		var container = $("table.contacts")
		if(current_group) {
			//Insights for a specific group
			$.get($(this).attr('href'),{ group_id: current_group}, function(result){
				container.html(result)
			})
		}
		else {
		 //Insights for all contacts
			$.get($(this).attr('href'),{ group_id: current_group}, function(result){
				container.html(result)
			})
		}
	})

	$("a.close-msg").click(function() {
		$("div.edit").hide();
		$("div.closed-message").show();
	})


	handle_trash();
	handle_group_menu();

})

function handle_trash() {
	$("table.contacts tbody > tr").hover(function() {
		$(this).find('td.zoom > a.trash-delete').show();
	},
	function() {
		$(this).find('td.zoom > a.trash-delete').hide();
	})
}

function	handle_group_menu() {
  $('.contact-group-container').each(function() {
    var container = $(this);
    var graphic = container.find('.view-menu');

    // Display the context menu graphic when hovering over the group name
    var hover_in = function() { graphic.show(); };
    var hover_out = function() { graphic.hide(); }
    container.hover(hover_in, hover_out);

    // Make sure that context menu graphic is visible while the context menu
    // is visible. That means disabling the hover-out hiding of the graphic
    // when opening the menu, and rebinding it when the menu is closed.
    // This would be much easier if show / hide were bindable events...
    var hide_context_graphic = function() {
      graphic.hide();
      container.bind('mouseleave', hover_out);
      $(document).unbind('click.hide_context_graphic');
    };
    graphic.click(function(e) {
      var output = container.unbind('mouseleave');
      // Stop the following document click event from being called straight away
      e.stopPropagation();

      $(document).bind('click.hide_context_graphic', hide_context_graphic);
    });


    // Bind the context menu to appear when the hovered graphic is clicked
    var context_menu = graphic.next('.contextMenu');
    graphic.contextMenu(
      { menu: context_menu.attr('id'), leftButton: true },
      function(action, el, pos) {
        group_id = el.attr('id').split("_")[2]
        if (action.match(/export|form/)) {
          window.location.href = "/groups/" + group_id + "/" + action
        } else if (action == 'delete') {
          $('#delete_group_' + group_id).fancyShow({xPos: pos.x, yPos: pos.y});
        } else if (action == 'rename') {
          // Stop the hover context menu graphic
          container.unbind('mouseenter mouseleave');
          $('#group_' + group_id).trigger("edit");
        }

        hide_context_graphic();
      }
    );

    // Jeditable isn't really set up to handle editing from another link.
    // We can set up a new event 'edit' and trigger that instead of the usual
    // click event.
    // We want to Because the text being replaced is a link
    var title = container.find(".contact-group");
    var group_id = title.attr('id').split("_")[1]
    var inner_link = title.find('a');
    title.editable("/groups/" + group_id, { 
      event : "edit", 
      name  : "group[name]",
      // we don't care what the element's ID is, and the default param 'id'
      // clashes with rails, so change it to something else
      id    : 'unicorns',
      submit: 'Save',
      cancel: 'Cancel',
      method: 'PUT',
      onblur: 'ignore',
      indicator: 'Saving <img src="/images/small-ajax-loader.gif" />',
      data: inner_link.text(),
      submitdata: {
        authenticity_token: FORM_AUTH_TOKEN
      },
      onreset: function() {
        container.hover(hover_in, hover_out);
      },
      callback: function(value, settings) {
        inner_link.text(value);
        $(this).html(inner_link);
        container.hover(hover_in, hover_out);
      }
    })
  }); 

	return false;
}

