$(document).ready(function () {

  // FB init
  window.fbAsyncInit = function () {
    FB.init({
      appId : fb_app_id,
      status : true,
      cookie : true,
      xfbml  : true
    });
  };

 	//Homepage CTA effects
 	$('.homepage_cta').hover(
 		function () {
 			if (Modernizr.borderradius) {
 				$('.cta_circle', this).stop().animate({scale: [1.1, 1.1]}, 200, 'easeOutExpo');
 			}
 		},
 		function () {
 			if (Modernizr.borderradius) {
 				$('.cta_circle', this).stop().animate({scale: [1, 1]}, 200, 'easeOutExpo');
 			}
 		}
 	);

   //Homepage slider
   $('#homepage_slider').camm_slider();

   //contact
   $("body.contact_us").contact_us();


   //Newsletter
 	var newsletter_form = $('#newsletter_signup_form');
 	var newsletter_input = $('#newsletter_signup_input');

 	newsletter_input.focus(function() {
 		newsletter_input.removeClass('newsletter_invalid');
 	});

 	newsletter_form.submit(function () {
 		$(newsletter_input).removeClass('newsletter_invalid');
 		var reg = new RegExp("^[a-zA-Z0-9_.-]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
 		if (newsletter_input.val() !== "" && reg.test(newsletter_input.val())) {
 			$.ajax({
 				type:'post',
 				url : $(this).attr('action'),
 				data : {
 					newsletter_input : newsletter_input.val()
 				},
 				success: function () {
 					newsletter_form.fadeOut(400, function () {
 						$(this)
 							.html('<p><strong>Thanks!</strong> You are now added to our mailing list.</p>')
 							.fadeIn(400);
 					});
 				}
 			});
 		} else {
 			$(newsletter_input).addClass('newsletter_invalid');
 		}
 		return false;
 	});

 	// Homepage tweets
 	if ($('#twitter_container').size())
 	{
 			$("#twitter_container").html('').tweet({
 				username: "connectminds",
 				retweets: false,
 				fetch: 10,
 				join_text: null,
 				count: 1,
 				loading_text: "loading tweets...",
 				template: '<p>{text}</p><span class="twitter_date"><strong>{tweet_relative_time}</strong> from Twitter</span><div class="arrow-down"></div>'
 			});

 	}
 });

//CAMM Homepage slider with timer, by FreeAssociation
//Thanks to whoever did the IWC.com slider for the inspiration!
$.fn.camm_slider = function(options) {

    var timer = null;

    var defaults = {
      height: 375,
      easing_method: 'easeOutExpo',
      duration: 750,
      speed: 4000,
      timer: true,
	    container_width: 960
    };

    var options = $.extend(defaults, options);

    var container    = this;
    var wrapper      = $('<div class="camm_slider"></div>');
    var slide_holder = $('<div class="slide_holder"></div>');
    var slides       = $('.slide', container);
    var nav_items    = $('li', container);
    var titles       = $('h3', nav_items);
    var nav_holder   = $('<ul class="nav_holder"></ul>');
    var animating    = 0;
    var index        = 0;

    var progress_width = 500; //width of progress bg image
    var progress_pos = -progress_width;
		var base = $(this);


    var init = function() {

      container.wrap(wrapper);

      $.each(slides, function(i,e) {
         $(e).attr('id','slide'+i).css({'position':'absolute', 'top':0, 'left':i*options.container_width});
      });

      slide_holder.height(options.height).html(slides);

      $.each(nav_items, function(i, e) {

        var nav_item = $(e);
        nav_item.attr('id', 'nav' + i);
        nav_item.data('index', i);

        if (i === 0) {
          nav_item.addClass('selected');
        }

        //var li_header = $('h3',nav_item);
        //li_header.replaceWith(li_header.text());

        nav_item.click(function () {
          if (index != $(this).data('index') && animating === 0) {
    				stop_timer();
            step_to($(this).data('index'), false);
          }
        });

      });


      nav_holder.html(nav_items)
				.css({
					width : nav_items.size() * (16+8)
					// force the container to a specific width so that margin: 0 auto will center it
					// the formula is the number of nav items time one nav item's width+margin
				});

      container.before(slide_holder);

			$('#homepage_message').before(nav_holder);

      container.remove();
      //start_timer();

    };

  	var start_timer = function(){
  		timer = setInterval(function(){
              if (index != (nav_items.length-1)) {
                  step_to(index+1);
              } else {
                  step_to(0);
              }

  		},options.speed);
  	}

  	var stop_timer = function(){
          progress_pos = -progress_width;
  		clearInterval(timer);
  	}

    var step_to = function(li_index, restart_timer) {
        animating = 1;

		$('#nav'+index).removeClass('selected');
		$('#nav'+li_index).addClass('selected');

        var direction = (li_index > index || (index === nav_items.length-1 && li_index ==0)?'left':'right');

        old_slide = $('#slide'+index);
        new_slide = $('#slide'+li_index);

        current_pos = parseInt(old_slide.css('left'));

        new_slide.show().css({'top':0,'left':(direction=='left'?current_pos+options.container_width:current_pos-options.container_width)});

		index = li_index;

        slide_holder.animate(
            {'left': (direction=='left'?'-=':'+=')+options.container_width},
            options.duration,
            options.easing_method,
            function() {
                animating=0;
                old_slide.css({'top':600});
                slide_holder.css({'left':0});
                new_slide.css({'left':0});
				if (restart_timer == true) {
					start_timer();
				}
            }
        );
    }

	init();

	return this.each(function(){});
}

//get latest activity or nearest opportunities
$.fn.get_nearest_opportunities = function() {
  var module = $(this);
  $.ajax({
		type:'get',
		dataType: 'html',
		url : "/home/get_nearest_opportunities/",
		success: function (content) {
      var replacedContent = module.find("p.loading");

      replacedContent.fadeOut('300', function() {
        replacedContent.replaceWith(content);
        replacedContent.fadeIn();
      });
		}
	});

}

$.fn.get_activity = function() {
  var module = $(this);
  $.ajax({
		type:'get',
		dataType: 'html',
		url : "/home/get_activity/",
		success: function (content) {
      var replacedContent = module.find("p.loading");
      replacedContent.fadeOut('300', function() {
        replacedContent.replaceWith(content);
        replacedContent.fadeIn();
      });
		}
	});
}


$.fn.contact_us = function() {

  function setupForm() {

    $("#contact_form select[id=reason]").change(function(event){
  		//show/hide location dropdown depending on reason drop down
  		var selected = $("#contact_form select[id=reason] option:selected");
  		var locationBox = $("#contact_form select[id=state]");
  		var locationLabel = $("#contact_form label[for=state]");
  		var errorMessage = $("#contact_form p.state_error");
  		if(selected.hasClass("needsLocation")) {
  			locationBox.fadeIn(250);
  			locationLabel.fadeIn(250);
  			if(errorMessage.size()) {
  			  errorMessage.fadeIn(250);
  			}
  			locationBox.addClass("notBlank");
  		} else {
  			locationLabel.fadeOut(250);
  			locationBox.removeClass("notBlank");
  			locationBox.fadeOut(250, function(){
  				locationBox.val("");
  			});
  			if(errorMessage.size()) {
  			  errorMessage.fadeOut(250);
  			}


  		}
  	})
  }

  setupForm();

}



