$(document).ready(function(){ 
  
  $('.profile_image').tipsy({gravity: 's'});
  
  $('.ui-dialog').dialog({ autoOpen: false, height: "auto", width: "auto"});
  
  $('.donation_amount_option').change(function(){
    $('#donation_amount').val('');
  });
  $('#donation_amount').change(function(){
    $('.donation_amount_option').attr("checked", false);
  });
  
  $('.donation_form').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
  });

  $('.pledge_amount_option').change(function(){
    $('#pledge_amount').val('');
  });
  $('#pledge_amount').change(function(){
    $('.pledge_amount_option').attr("checked", false);
  });
  
  $('.truncate-1000').truncate({max_length: 1000});
  $('.truncate-500').truncate({max_length: 500});  
  $('.truncate-200').truncate({max_length: 200});
  $('.truncate-90').truncate({max_length: 90});
  
  // for mega drop downs
  var config = {
       sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
       interval: 100, // number = milliseconds for onMouseOver polling interval
       over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
       timeout: 300, // number = milliseconds delay before onMouseOut
       out: megaHoverOut // function = onMouseOut callback (REQUIRED)
  };
  $("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
  $("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations
  
  $("ul#subnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
  $("ul#subnav li").hoverIntent(config); //Trigger Hover intent with custom configurations
  
  afterAjaxForm();
  
  $('.fancyzoom').fancyZoom({directory: "/images/fancyzoom", scaleImg:true, closeOnClick: true});
  
  if ((Modernizr.video && Modernizr.video.h264) == false) {
		$("video").each( function(i, e) { 
		    jwplayer(jQuery(e).attr("id")).setup({
		        flashplayer: "/jwplayer/player.swf",
						skin: "/jwplayer/glow.zip"
		    });
		});
  }

  $("#slides").slides({
      preload: true,
      generatePagination: false,
      play: 5000,
      effect: 'fade',
      fadeSpeed: 700,
      crossfade: true,
      pagination: true,
			paginationClass: 'features_pagination'

  });
	
	var countries = ['US','CA']

  if (jQuery.inArray($('#donation_billing_address_country_code, #invoice_payment_billing_address_country_code').val(), countries) > -1) {
    $('.us_or_canada').show();  
    $('.not_us_or_canada').hide();  
  } else {
		$('.us_or_canada').hide();
    $('.not_us_or_canada').show();
	}

	$('#donation_billing_address_country_code, #invoice_payment_billing_address_country_code').change(function() {
		if (jQuery.inArray($('#donation_billing_address_country_code, #invoice_payment_billing_address_country_code').val(), countries) > -1) {
	    $('.us_or_canada').show();  
	    $('.not_us_or_canada').hide();
	  } else {
			$('.us_or_canada').hide();
	    $('.not_us_or_canada').show();			
		}
	});
	
	if (jQuery.inArray($('#donation_work_address_country_code').val(), countries) > -1) {
    $('.work_us_or_canada').show();  
    $('.work_not_us_or_canada').hide();  
  } else {
		$('.work_us_or_canada').hide();
    $('.work_not_us_or_canada').show();
	}

	$('#donation_work_address_country_code').change(function() {
		if (jQuery.inArray($('#donation_work_address_country_code').val(), countries) > -1) {
	    $('.work_us_or_canada').show();  
	    $('.work_not_us_or_canada').hide();
	  } else {
			$('.work_us_or_canada').hide();
	    $('.work_not_us_or_canada').show();			
		}
	});

  if ($('#nation_signup_is_voter_intelligence').attr('checked') == false) {
    $('#voter_file_additions').hide();   
  }
  $('#nation_signup_is_voter_intelligence').change(function() {
    if ($('#nation_signup_is_voter_intelligence').attr('checked')) {
      $('#voter_file_additions').show();
    } else {
      $('#voter_file_additions').hide();
    }
  });

  $(".textarea-tinymce").tinymce({
  			// Location of TinyMCE script
  			script_url : '/javascripts/tiny_mce/tiny_mce.js',

  			// General options
  			theme : "advanced",
  			skin : "thebigreason",
  			plugins : "fullscreen,paste",
  			// Theme options
  			theme_advanced_buttons1 : "formatselect,bold,italic,underline,strikethrough,|,bullist,numlist,|,outdent,indent,|,link,unlink,|,undo,redo,|,code,pastetext,pasteword",
  			theme_advanced_buttons2 : "",
  			theme_advanced_buttons3 : "",
  			theme_advanced_buttons4 : "",
  			theme_advanced_toolbar_location : "top",
  			theme_advanced_toolbar_align : "left",
  			theme_advanced_statusbar_location : "bottom",
  			theme_advanced_resizing : true,
				theme_advanced_resize_horizontal : false,
  			
  			fix_list_elements : true,
  			forced_root_block : false,
  			// valid_elements : "",
  			// convert_newlines_to_brs : true,
  			convert_urls : false,
        relative_urls : false,
        
        valid_elements : "@[id|align|class|style|title|dir<ltr?rtl|lang|xml::lang],"
        + "a[rel|rev|charset|hreflang|tabindex|accesskey|type|name|href|target|title|class],"
        + "strong/b,em/i,strike,u,div,-div,span,-span,"
        + "#p,-ol[type|compact],-ul[type|compact],-li,br,-sub,-sup,-blockquote,"
        + "img[longdesc|usemap|src|border|alt=|title|hspace|vspace|width|height|align],"
        + "-table[border|cellspacing|cellpadding|width|frame|rules|height|align|summary|bgcolor|background|bordercolor],"
        + "-tr[rowspan|width|height|align|valign|bgcolor|background|bordercolor],tbody,thead,tfoot,"
        + "#td[colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor|scope],"
        + "#th[colspan|rowspan|width|height|align|valign|scope],"
        + "-code,-pre,address,-h1,-h2,-h3,-h4,-h5,-h6,hr[size|noshade],-font[face|size|color],"
        + "caption,dd,dl,dt,cite,abbr,acronym,del[datetime|cite],ins[datetime|cite],"
        + "map[name],area[shape|coords|href|alt|target],bdo,"
        + "button,col[align|char|charoff|span|valign|width],colgroup[align|char|charoff|span|valign|width],"
        + "kbd,label[for],legend,noscript,q[cite],samp,small,tt,var,big",
        
  			// Example content CSS (should be your site CSS)
  			content_css : "/stylesheets/tiny_mce.css",

  		});
  
});

function afterAjaxForm() {
  
  if (!($.browser.msie && $.browser.version=="6.0")) {
    $("abbr.timeago").timeago();	
  }
  
  // http://www.tomdeater.com/jquery/character_counter/
  $("#face_tweet_content").charCounter(140, {container: "#face_tweet_content_charsleft", format: "%1", pulse: false, delay: 100});

	$("#flash a.close").click(function() {
	  $("#flash").remove();
	  return false;
	});
	
	$(".share_close").click(function() {
	  $(".share_container").fadeOut("slow");
	  return false;
	});
	
	$('.facebook_share_link').click(function() {
    u = this.href.split('=').last;
    var share = { method: "stream.share", u: u, display: "dialog"};
    FB.ui(share, function(response) { return false; });
    return false;
  });

	$('.petition_signature_form').submit(function() {
		$(this).find(".form_submit").html("<div class='form_submitting'><img src='/images/bert-loader-small.gif' width='16' height='11' border='0'> Saving...</div>")
	});
  
  $('#comment_content, #petition_signature_content, #feedback_content, #flag_content, #volunteer_signup_content, #profile_note_content').autogrow();
	
	$("#address_change_submitted_address").DefaultValue("City, State, Address, or Post Code")
  
  $(".share_signup #signup_first_name").DefaultValue("First Name");
  $(".share_signup #signup_last_name").DefaultValue("Last Name"); 
  $(".share_signup #signup_email").DefaultValue("Email address");
  $("#email_signin #signup_email").DefaultValue("Email address");
  $("#wide #event_rsvp_first_name").DefaultValue("First name");
  $("#wide #event_rsvp_last_name").DefaultValue("Last name");
  $("#wide #event_rsvp_email").DefaultValue("Email");
  $("#wide #event_rsvp_mobile_number").DefaultValue("Cell (Optional)");
  $("#wide #event_rsvp_phone_number").DefaultValue("Phone");
  $("#wide #event_rsvp_submitted_address").DefaultValue("City, State, Address, or Post Code");
  $("#wide #petition_signature_content").DefaultValue("Your comment (optional)");
  $("#wide #petition_signature_first_name").DefaultValue("First name");
  $("#wide #petition_signature_last_name").DefaultValue("Last name");
  $("#wide #petition_signature_email").DefaultValue("Email");
  $("#wide #petition_signature_mobile_number").DefaultValue("Cell (Optional)");
  $("#wide #petition_signature_submitted_address").DefaultValue("City, State, Address, or Post Code");
	
  ajaxLinks();	
}

// this is for the mega drop downs in the nav
function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo(0, 1).show(); //Find sub and fade it in
    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 

    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;  

        $(this).find(".row").each(function() {  //for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        
        if ( $(this).find(".sub").length > 0 ) {
              var o = $(this).find('.sub').offset();     
              var p = $('#topnav_container').offset();
              var pw = document.getElementById('topnav_container').clientWidth;
              var tw = rowWidth;
              var tml = (tw + (o.left - p.left)) - pw;
              
              $(this).find(".sub").css({'width' : rowWidth}).css({'margin-left':'-' + tml + 'px'});
        }
        $(this).find(".sub").css({'width' : rowWidth})
        
    }
}

function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo(0, 0, function() { //Fade to 0 opactiy
      $(this).css({'margin-left':'0'});
      $(this).hide();  //after fading, hide it
  });
}
