/**
 * Polaris
 */

 var map,marker,myCenter;

var Design = {
	bindKeys : function() {
		Cargo.Core.KeyboardShortcut.Add("Left", 37, function() {
			Action.Project.Prev();
			return false;
		});

		Cargo.Core.KeyboardShortcut.Add("Right", 39, function() {
			Action.Project.Next();
			return false;
		});
	},
	
	hoverProject: function() {
		// Thumbnail hover
		$(".thumbnails")
			.on("mouseenter", ".project_thumb", function(e) {
				$(".project_link[data-id='" + $(this).attr("data-id") +"'] a").addClass("hover");
			})
			.on("mouseleave", ".project_thumb", function(e) {
				$(".project_link[data-id='" + $(this).attr("data-id") +"'] a").removeClass("hover");
			});

		// Navigation
		$(".navigation")
			.on("mouseenter", ".project_link a", function(e) {
				$(".project_thumb[data-id='" + $(this).closest('.project_link').attr("data-id") +"']").addClass("hover");
			})
			.on("mouseleave", ".project_link a", function(e) {
				$(".project_thumb[data-id='" + $(this).closest('.project_link').attr("data-id") +"']").removeClass("hover");
			});
	},

	checkNavigationHeight: function() {
		var navigation = $(".navigation");
		// if (navigation.length > 0) {
		// 	if (navigation.height() + navigation.position().top > $(window).height()) {
		// 		if (!navigation.hasClass("scroll")) {
		// 			navigation.add(".site_header").removeClass("fixed").addClass("scroll");
		// 		}
		// 	} else {
		// 		if (!navigation.hasClass("fixed")) {
		// 			navigation.add(".site_header").removeClass("scroll").addClass("fixed");
		// 		}
		// 	}
		// }
	},

	checkSetVisibility: function() {
		// Find the active set based on the project ID
		var parentSet = $("[data-setid='" + Cargo.Model.Project.GetSetId() + "']"),
			otherSets = $("[data-setid]").not(parentSet);

		// If the set exists, set active/inactive
		if (parentSet.length > 0) {
			otherSets.removeClass("active").addClass("inactive");
			parentSet.removeClass("inactive").addClass("active");

			// Show the footer link
			$(".set_footer").show();
		} else {
			$(".set_footer").hide();
		}



    // activate navigation menu items
    $(".navigation li").removeClass('active');
    var currentMenuItem = $(".navigation [data-id='" + Cargo.Model.Project.GetId() + "']");
    // console.log(currentMenuItem);
    currentMenuItem.addClass('active');
	},

	checkSetSpacing: function() {
		$(".set_link").removeClass("first-set last-set spacer");

		var first_set = $(".set_link:first"),
			last_set = $(".set_link:last");

		first_set.addClass("first-set");
		last_set.addClass("last-set");

		if (Cargo.Model.DisplayOptions.attributes.use_set_links) {
			var setLinksPosition = Cargo.Model.DisplayOptions.GetSetLinksPosition();

			if (first_set.attr("id") == last_set.attr("id")) {
				// Only one set
				if (setLinksPosition == "top") {
					last_set.addClass("spacer").removeClass("first-set");
				} else if (setLinksPosition == "bottom") {
					first_set.addClass("spacer");
				}
			} else {
				if (setLinksPosition == "top") {
					last_set.addClass("spacer");
				} else if (setLinksPosition == "bottom") {
					first_set.add(last_set).addClass("spacer");
				}
			}
		}
	}
};

var thumbEls = '#info, .tag-info, .thumb_image, .thumb_title, .thumb_excerpt';

function loadTransition() {

  $('[data-loading="page"]').hide();
  var homeURL = Cargo.Helper.GetHomeUrl();
  // console.log(homeURL.indexOf("filter/"));

  // if(homeURL.indexOf("filter/") > -1 ){
    // console.log('has filter');
  // }

  if (Cargo.Helper.IsDirectLink() || homeURL.indexOf("filter/") > -1) {
    // if (Cargo.Helper.IsDirectLink() ) {
    // console.log('IsDirectLink');
    $('#header').fitText(0.37);
    $('#header').css('visibility', 'visible');
    $('#header span, .project_thumb').css('opacity', 1);
    return false;
  }
  // console.log('animation');


  $(thumbEls).css('opacity', 0);
  $('html').addClass('wf-active');

  var old_translateY = ($(window).height() - ( $('#header').height() * 1.5) ) / 2
  var translateY = $("#header").height() * 1.4;

  $("#header")
    .fitText(0.37)
    .velocity({
      'translateY' : translateY,
      complete : function() {
        setTimeout(function() {
          $('#header').css('visibility', 'visible');
        }, 50);
      }
    }, 0);

    // Continue transition
    setTimeout(function() { contentTransition() }, 1000);
}

function contentTransition() {
  $('#header')
    .velocity({
      'translateY' : 0,
    }, {
      'duration' : 500,
      'easing'   : 'easeInExpo',
      complete: function() {
        setTimeout(thumbTransition, 200);
      }
    });
}

function thumbTransition() {
  $('.project_thumb').css('opacity', 1);
  $(thumbEls).each(function(i) {
    $(this)
      .velocity({
        'opacity' : 1
      }, {
        'easing'   : 'easeInOutCubic',
        'duration' : 250,
        'delay'    : 50 * i
      });
  });
}



function resizer() {
  


  // alert('resizer');

  var width = $(window).width();
  var containerWidth = $('.container').width();

  // Min
  // if ( width < 800 ) width = 800;

  var font_size = Math.floor(width * 0.022);
  var title_font_size = Math.floor(width * 0.022);
  if(font_size > 24){
    font_size = 24;
  }else if(font_size < 14){
    font_size = 14;
  }

  // console.log(font_size);

  $('body').css({
    'font-size'   : font_size + 'px',
    'width'       : width
  });

  $('#header').css({
    'line-height' : Math.floor(width * 0.21) + 'px',
    'left' : Math.floor(width * 0.012) * -1 + 'px',
  });

  $('#header span').css({
    'letter-spacing' : (width * 0.0038) * -1 + 'px',
    'display' : 'inline-block',
  });

  // set client logo height
  if($('.client-logo').length > 1){
    var logoWidth = $('.client-logo').width();
    // console.log(logoWidth);
    var logoHeight =  logoWidth * .35;
    // console.log(logoHeight);
    $('.client-logo').css({'height':logoHeight});
  }
  




  // Contact list resize and recenter elements
  if($('.contact-list').length > 0){
    $('.contact-list:first-child').addClass('first');
    var cl_height =  $('.contact-list:not(.first)').height();
    console.log(cl_height);
    $('#map').css({
      'height':(cl_height-18)+'px',
      'min-height': '220px'
    });
    $('.contact-list h1').fitText(0.3875);
    $('.contact').fitText(1.2);
  }
  


  $('.main-menu-list li ').css({
    'padding-right' : 0 + 'px',
  });

  // NAVIGATION Font Size
  var nav_font_size = (containerWidth * 0.055);
  var a_totalWidth = 0;
  var menuCount = ($('.navigation .main-menu-list a').length) - 1;

  $('.main-menu-list a').css({
    'font-size' : nav_font_size + 'px',
  });

  
  if ( width >= 1200 ){
    $('.thumb_meta').css({
      // 'width' : Math.floor(width - 690) + 'px'
    });

    title_font_size = Math.floor(width * 0.030);

    // $('.thumb_title').css({
    //   'font-size' : title_font_size + 'px',
    // });

  }else{
    // $('.thumb_title').css({
    //   'font-size' : 'normal',
    // });
  }

  if ( width <= 768 ){
    font_size = Math.floor(width * 0.06);
    $('body').css({
      'font-size'   : 16 + 'px',
    });
    $('.thumb_meta').css({
      // 'width' : Math.floor(width - 375) + 'px'
    });
  }

  if ( width <= 767 ){
    $('.thumb_meta').css({
      'width' : '100%'
    });

    nav_font_size = (containerWidth * 0.06);
    $('.main-menu-list a').css({
      'font-size' : nav_font_size + 'px',
    });

     if($('.client-logo').length > 1){
      var logoWidth = $('.client-logo').width();
      // console.log(logoWidth);
      var logoHeight =  logoWidth * .40;
      // console.log(logoHeight);
      $('.client-logo').css({'height':logoHeight});
    }

  }

  // NAVIGATION Spacer
  $('.navigation .main-menu-list li').each(function(){
    // console.log($(this).width());
    a_totalWidth =a_totalWidth + $(this).width() + 0;
  });
  
  navOffset = containerWidth - a_totalWidth ;

  $('.main-menu-list li:not(:last-child) ').css({
    'padding-right' : Math.floor(navOffset / menuCount) + 'px',
  });

  if(map){
    map.setCenter(myCenter);
  }
   



}


/**
 * Events
 */

$(function() {




  $('[data-loading="page"]').show();

  $(window).on('resize', resizer);

  $(window).on('resize', function(){
    setTimeout(function(){ resizer(); }, 50);
  }).trigger('resize');

  // Type fallback
  setTimeout(function() {
    if ( ! $('html').hasClass('wf-active') ) loadTransition();
  }, 5000);

  $('#header').on('click', function() {
    Action.Project.Index();
  });

  $('.navigation a').on('click', function(e, target ){
    // Cargo.Helper.GetHomeUrl();
    if(Cargo.Helper.GetHomeUrl()){
      console.log(Cargo.Helper.GetHomeUrl());
      var homeURL = Cargo.Helper.GetHomeUrl();
    }
   

    if(Cargo.Helper.GetHomeUrl() && homeURL.includes("filter/")){

    }else{
      if( e ) {
            e.preventDefault();
            target = e.currentTarget;
      }
      /* Get the absolute anchor href */
          var href = ( $(target).attr("href") ) ? $(target).attr("href") : $(target).data("href");
          var id   = ( $(target).attr("data-id") ) ? $(target).attr("data-id") : $(target).data("id");
          // console.log(href);
          /* Navigate to the new URL */
          // console.log('using history');
          Cargo.Event.trigger("add_history", href);
          return false;
    }
    
    
  });


	Cargo.Core.ReplaceLoadingAnims.init();

	Design.bindKeys();
	Design.hoverProject();
	Design.checkSetSpacing();
	Design.checkNavigationHeight();

});

// Window Resize
$(window).resize(function() {
  setTimeout(function(){ resizer(); }, 500);
	Design.checkNavigationHeight();
});

// Project Load Complete
Cargo.Event.on("project_load_complete", function(pid) {
	Design.checkSetVisibility();
  $('#info').hide();


  var cl_parent = $( ".contact-list" ).parent();

  $( ".contact-list" ).clone().prependTo( cl_parent );

  $('.contact-list h1').fitText(0.3875);
  $('.contact').fitText(1.2);


  // iframe resize
  $('.project_content iframe').resizeMedia();

	/*
	 *   Move the project navigation if the default image width is > 670px.
	 */
	
	var defaultImageWidth = parseInt(Cargo.Model.DisplayOptions.GetImageWidth());

	if (defaultImageWidth < 670) {
		defaultImageWidth = 670;
	}

	defaultImageWidth += 305;

	$(".project_navigation").css("left", defaultImageWidth + "px");

  // inject page title into the body class
  var classInject = Cargo.Helper.GetCurrentProjectUrl().toLowerCase();
  $('body').removeClass();
  $('body').addClass(classInject+'-page');

  var projectURL = Cargo.Helper.GetCurrentProjectUrl();
  var type = Cargo.Helper.GetCurrentPageType();
  // if(type != "page" && Cargo.Helper.GetCurrentProjectUrl() != "COMMERCIAL-REEL-2015"){
  //   // scroll animate page 
  //   var body = $("html, body");
  //   setTimeout(function(){
  //     body.stop().animate({
  //         scrollTop: $(".container").offset().top - 60
  //     }, 800);
  //   }, 500);

  // }


  if(projectURL == 'Contact-2'){
    console.log('MAP');
    setTimeout(function(){
      $.ajax({
        dataType: 'jsonp',
        url: "https://maps.googleapis.com/maps/api/js?key=AIzaSyATHXR-FRpcy3ndiE1tbyuZbPJRJomHx7k&callback=myMap",
        context: document.body
      }).done(function() {
        // $( this ).addClass( "done" );
        myMap();
        setTimeout(function(){ resizer(); }, 100);

      });

    }, 100);

    
    
  }else{
    // console.log('otherpage');
    setTimeout(function(){ resizer(); }, 0);
  }


  // FB SHARE PROJECT BUTTON
  $('#shareBtn').on('click', function (e){
    e.preventDefault();
    // console.log('#shareBtn');
    // console.log(Cargo.Helper.GetBaseDomain());
    FB.ui({
      method: 'share',
      display: 'popup',
      href: Cargo.Helper.GetBaseDomain()+'/'+Cargo.Helper.GetCurrentProjectUrl(),

    }, function(response){
      console.log(response);
    });
  });

  

});



// Project Close Complete
Cargo.Event.on("show_index_complete", function(pid) {
  Design.checkSetVisibility();
  // $('body[data-bodyview="index"] #info').show();
	setTimeout(function() {
		// Reset sets
		$("[data-setid]").removeClass("active inactive");
		$(".set_footer").hide();
	}, 20);
});

Cargo.Event.on("navigation_reset", function(new_page) {
	Design.checkSetSpacing();
});

Cargo.Event.on("navigation_set_toggle", function() {
	Design.checkNavigationHeight();
});

// Pagination
Cargo.Event.on("pagination_complete", function(new_page) {
	Design.checkSetVisibility();
	Design.checkSetSpacing();
	window.setTimeout(function() {
		Design.checkNavigationHeight();
	}, 10);
});

Cargo.Event.on("project_collection_reset", function(new_page) {
	Design.checkSetVisibility();
	Design.checkSetSpacing();
	window.setTimeout(function() {
		Design.checkNavigationHeight();
	}, 10);
});

Cargo.Event.on("fullscreen_destroy_hotkeys", function() {
    Design.bindKeys();
});

/**
 * Typography
 */
// $(function() {
WebFontConfig = {
	monotype: { projectId: '4ab2bdcc-4e41-46ce-9dc7-d8e54abe3c85' },
  timeout: 5000,
  active: function() {

    
    setTimeout(function(){ 
      loadTransition();
      resizer(); 
    }, 1000);

  }
};
// });

function myMap() {
  var width = $(window).width();
  var zoom = (width < 767)? 15 : 16;
  var myposition = {lat: 40.744623, lng: -73.989236};
  var mapCanvas = document.getElementById("map");
  myCenter = {lat: 40.746623, lng: -73.989236}; 
  var mapOptions = {center: myCenter, zoom: zoom, disableDefaultUI: true};
  map = new google.maps.Map(mapCanvas,mapOptions);
  marker = new google.maps.Marker({
    position: myposition
    // icon: "pinkball.png"
  });
  
  
  marker.setMap(map);
  var mapAddress="<b>Fireshot Productions LLC</b> <br>12 W. 27th street 8th floor <br>New York, New York 10001"
  mapAddress += "<br><a href='https://www.google.com/maps/place/Fireshot+Productions/@40.74452,-73.98931,20z/data=!4m5!3m4!1s0x0:0x9c8aaef748beafd2!8m2!3d40.7445201!4d-73.9893102?hl=en-US' target='_blank'>view larger map</a>"
  var mapImg = '<img src="http://payload496.cargocollective.com/1/12/409063/12224558/map-image.jpg" border="0" >';
  var contentString = "<div class='map-info-image'>"+mapImg+"</div><div class='map-info-text'>"+mapAddress+"</div>";

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  infowindow.open(map, marker);

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

  var styledMapType = new google.maps.StyledMapType(
            [
              {elementType: 'geometry', stylers: [{color: '#cccccc'}]},
              {elementType: 'labels.text.fill', stylers: [{color: '#666666'}]},
              {elementType: 'labels.text.stroke', stylers: [{color: '#dddddd'}]},
              {
                featureType: 'administrative',
                elementType: 'geometry.stroke',
                stylers: [{color: '#d38d8d'}]
              },
              {
                featureType: 'administrative.land_parcel',
                elementType: 'geometry.stroke',
                stylers: [{color: '#FF0000'}]
              },
              {
                featureType: 'administrative.land_parcel',
                elementType: 'labels.text.fill',
                stylers: [{color: '#ae9e90'}]
              },
              {
                featureType: 'landscape.natural',
                elementType: 'geometry',
                stylers: [{color: '#cccccc'}]
              },
              {
                featureType: 'poi',
                elementType: 'geometry',
                stylers: [{color: '#c6c6c6'}]
              },
              {
                featureType: 'poi',
                elementType: 'labels.text.fill',
                stylers: [{color: '#93817c'}]
              },
              {
                featureType: 'poi',
                stylers: [{visibility: 'off'}]
              },
              {
                featureType: 'poi.park',
                stylers: [{visibility: 'on'}]
              },
              {
                featureType: 'poi.park',
                elementType: 'geometry.fill',
                stylers: [{color: '#b4beb4'}]
              },
              {
                featureType: 'poi.park',
                elementType: 'labels.text.fill',
                stylers: [{color: '#447530'}]
              },
              {
                featureType: 'road',
                elementType: 'geometry',
                stylers: [{color: '#eeeeee'}]
              },
              {
                featureType: 'road.arterial',
                elementType: 'geometry',
                stylers: [{color: '#ececec'}]
              },
              {
                featureType: 'road.highway',
                elementType: 'geometry',
                stylers: [{color: '#eaeaea'}]
              },
              {
                featureType: 'road.highway',
                elementType: 'geometry.stroke',
                stylers: [{color: '#e0e0e0e0'}]
              },
              {
                featureType: 'road.highway.controlled_access',
                elementType: 'geometry',
                stylers: [{color: '#eaeaea'}]
              },
              {
                featureType: 'road.highway.controlled_access',
                elementType: 'geometry.stroke',
                stylers: [{color: '#e0e0e0e0'}]
              },
              {
                featureType: 'road.local',
                elementType: 'labels.text.fill',
                stylers: [{color: '#999999'}]
              },
              {
                featureType: 'transit.station',
                elementType: 'geometry',
                // stylers: [{color: '#dfd2ae'}]
                stylers: [{visibility: 'off'}]
              },
              {
                featureType: 'transit.line',
                elementType: 'geometry',
                // stylers: [{color: '#dfd2ae'}]
                stylers: [{visibility: 'off'}]
              },
              {
                featureType: 'transit.line',
                elementType: 'labels.text.fill',
                stylers: [{color: '#8f7d77'}]
              },
              {
                featureType: 'transit.line',
                elementType: 'labels.text.stroke',
                stylers: [{color: '#ebe3cd'}]

              },
              {
                featureType: 'transit.station',
                elementType: 'geometry',
                stylers: [{color: '#bbbbbb'}]
              },
              {
                featureType: 'water',
                elementType: 'geometry.fill',
                stylers: [{color: '#b2b9c0'}]
              },
              {
                featureType: 'water',
                elementType: 'labels.text.fill',
                stylers: [{color: '#92998d'}]
              }
            ],
            {name: 'Styled Map'});

    map.mapTypes.set('styled_map', styledMapType);
    map.setMapTypeId('styled_map');


}

(function() {
	var wf = document.createElement("script");
	wf.src = ("https:" == document.location.protocol ? "https" : "http") + "://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js";
	wf.type = "text/javascript";
	wf.async = "true";
	var s = document.getElementsByTagName("script")[0];
	s.parentNode.insertBefore(wf, s);
})();

