var CAMPUSES = null;

// remap jQuery to $
(function($){
    jQuery("#toggle").click(function() {
       jQuery("#search_wrapper").toggle('blind');
       return false;
    });
	
	if(jQuery("#countdown").length)
    {
        var liftoffTime = new Date(jQuery("#countdown_until").val());
        jQuery('#countdown').countdown({until: liftoffTime,
        layout: '<span class="white">{dn}</span> days <span class="white">{hn}</span> hrs <span class="white">{mn}</span> mins <span class="white">{sn}</span> secs'});
    }
	
	if(jQuery("#cfonline_countdown").length && jQuery("#cfonline_until").length)
    {
        var liftoffTime = new Date(jQuery("#cfonline_until").val());
        jQuery('#cfonline_countdown').countdown({until: liftoffTime,
			layout: '<a href="http://online.cfmiami.org">CF Online starts in <span class="number">{dn}</span> days <span class="number">{hn}</span> hrs <span class="number">{mn}</span> mins <span class="number">{sn}</span> secs</a>',
			expiryText: '<div class="complete"><a href="http://online.cfmiami.org">Watch The Service Now!</a></div>',
			alwaysExpire: true
		});
    }
    
  // Tabify
  if($("#tabs").length) {
   $('#tabs').tabs();   
  }

    if($(".health-report iframe").length) {
        $(".health-report iframe").contents().find(".ss-form-entry").hide();
    }
	
    /* if($(".watch").length) {
            $(".play").click(function() {
                    var href = $(this).attr("href");
                    var src = "";

                    if(href.indexOf("vimeo") > 0) {
                            var parts = href.split("/");
                            src = "http://player.vimeo.com/video/" + parts[parts.length - 1] + "?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1";
                    }

                    $(this).parent().html('<iframe width="940" height="290" frameborder="0" allowfullscreen="" webkitallowfullscreen="" src="' + src + '"></iframe>');
                    return false;
            });
    } */

  //Devotionals
  if($("#devotionals").length) {
      $("#devotionals").change(function() { window.location = $(this).val(); });
  }
  
  if ($.browser.msie) {
	$("body").addClass("ie");
  }

  // Pretty Photos
  $("a[rel^='prettyPhoto']").prettyPhoto({
      default_width: 640,
      default_height: 360,
      show_title: false,
      allow_resize: false,
      theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
      modal: true /* If set to true, only the close button will close the window */
  });

  if($("#bible_studies").length) {
	$(".show").click(function() {
		var $element = $(this);
		var $answer = $("#answer_" + $element.data("number"));
		
		if($answer.is(":visible")) {
			$answer.fadeOut('slow');
			$element.html("view answer");
		} else {
			$answer.fadeIn('slow');
			$element.html("hide answer");
		}
		
		return false;
	});
  }
  
  var tabContainers = $('div.tabs > div.pane');

  $('div.tabs ul.tab-navigation a').click(function() {
    tabContainers.hide().filter(this.hash).show();

    $('div.tabs ul.tab-navigation a').removeClass('active');
    $(this).addClass('active');
    $(this).append('<span class="arrow"></span>');

    return false;
  }).filter(':first').click();

  // Check for campus-search section
  var searchBox = $('section.campus-search');
  if(searchBox.length > 0){
    CAMPUSES = [
      {id: 'cmp_dt', name: 'Downtown', coordinates:[25.778776,-80.192069]},
      {id: 'cmp_hs', name: 'Homestead', coordinates:[25.479101,-80.419841]},
      {id: 'cmp_pb', name: 'Palmetto Bay', coordinates:[25.613784,-80.337176]},
      {id: 'cmp_rd', name: 'Redland', coordinates:[25.535786,-80.457498]},
      {id: 'cmp_wk', name: 'West Kendall', coordinates:[25.687808,-80.394832]},
      {id: 'cmp_cg', name: 'Coral Gables', coordinates:[25.748964,-80.260414]}
    ];

    enagageAwesomeness();

    //$('li.campus').live('click', function(){
      //showCampusInfo(CAMPUSES[$(this).index()]);

    $('.find-campus button').bind('click', function(e){
        var zip = searchCue();
        findNearestCampusByZip(zip);
        e.preventDefault();
        return false;
    });

    $('#zip').bind('keydown', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) { //Enter keycode 
          var zip = searchCue();
          $('#zip').blur();
          findNearestCampusByZip(zip);
          e.preventDefault();
          return false;
        }
    });

    $('.find-campus form').submit(function(e){
      e.preventDefault();
      return false;
    });

    $('.info-box a.close').bind('click', function(e){
        $(this).parent().parent('.info-box').fadeOut('fast', function(){
          $('#zip').val('');
          $('#zip').prop('placeholder', 'Enter your Zipcode');

          $('div.find-campus').fadeIn('slow');
        });
        e.preventDefault();
        return false;
    })
  }
})(window.jQuery);

function enagageAwesomeness(){
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
  document.body.appendChild(script);
}

function initialize(){}

function backToSearch(){
  window.jQuery('.info-box:visible').fadeOut('slow', function(){
    window.jQuery('div.find-campus').fadeIn();
  });
}

function showCampusInfo(campusInfo){
  //window.jQuery('div.find-campus:visible').fadeOut();
  jQuery("#zip").val("");
  var infoBoxID = '#' + campusInfo.id + '_info';
  var visibleBoxes =  window.jQuery('.info-box:visible');

  if(visibleBoxes.length > 0){
    visibleBoxes.fadeOut('slow', function(){
      window.jQuery(infoBoxID).fadeIn();
    });
  }
  else{
      jQuery('html,body').animate({scrollTop: jQuery("#campus_list").offset().top});
      jQuery('#' + campusInfo.id).expose({ color: "#000" });
    //window.jQuery(infoBoxID).fadeIn();
  }
}

function searchCue(){
    var input = window.jQuery('#zip');
    var val = input.val();
    input.val('Searching near ' + val + '...');
    
    return val;
}

function nearestCampus(data, status){
  var minDistance = Number.MAX_VALUE;
  var campus = null;

  // Loop through elements and find the shortest distance
  for(i=0; i < data.rows[0].elements.length; i=i+1){
    if(data.rows[0].elements[i].distance){
      var distance = data.rows[0].elements[i].distance.value;

      if(distance < minDistance){
        minDistance = distance;
        campus = CAMPUSES[i];
      }
    }
  }

  if(campus != null){
    showCampusInfo(campus);
  }
  else{
    window.jQuery('#zip').val('');
    window.jQuery('#zip').prop('placeholder', "Ooops...Please try again");
  }
}


function findNearestCampusByZip(zip){
  var destinations = [];

  for(i=0; i < CAMPUSES.length; i=i+1){
    destinations.push(new google.maps.LatLng(CAMPUSES[i].coordinates[0], CAMPUSES[i].coordinates[1]));
  }

  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix({
      origins: [zip],
      destinations: destinations,
      travelMode: google.maps.TravelMode.DRIVING
    },
    nearestCampus);
}

