
var bgImages = [];
var currentBGIndex = 0;
var stayDuration = 10000;
var fadeDuration = 4000;
var isBGAspectRtoSet = false;
var isDocReady = false;
var googleMapMade = false;
var isMobile = false;

var vimeoLink = 'http://player.vimeo.com/video/'+ vimeoId +'?api=1&amp;title=0&amp;byline=0&amp;portrait=0&amp;color=ec4f24';

$(document).ready(function () {
	isDocReady = true;
	
	checkMobile();
	
	if (isUAMobile || isUATablet){
		convertToMobile();
	}
	
	$(window).resize(scaleSite);
	scaleSite();
	
	initTabs();
	
	//Froogaloop.init();
	//initializeGoogleMap();
	
	if (!isMobile && bgImages.length > 1){
		queBGChange();
	}
});


// ----- //
var isUAMobile = false;
var isUATablet = false;
function checkMobile(){
	var agent = navigator.userAgent.toLowerCase();
	isUAMobile =!!(agent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i));
	isUATablet =!!(agent.match(/(iPad|SCH-I800|xoom|kindle)/i));
}

function convertToMobile(){
	isMobile = true;
	$("#footer_section").css("margin-top", "-42px");
	$("#footer_section").css("position", "relative");
	
}


function makeBGImageObject(src, aspectRatio){
	var bgImageObject = new Object();
	bgImageObject['src'] = src;
	bgImageObject['aspectRatio'] = aspectRatio;
	return bgImageObject;
}


function scaleSite(){
	var wW = $(window).width();
	var wH;
	if (isMobile){
		wH = document.documentElement.offsetHeight;
	}else{
		wH = $(window).height();
	}
	
	// - video player - 
	$("#video_player_container").css("height", wH - 114);
	
	// - client page - 
	var clientPgMaxW = $("#clients_page").css("max-width");
	var clientPgMidW = 590;
	var widthPlusMargin = wW - (parseFloat($("#clients_page").css("margin-left")) + 25);// 25 is for scrollbar
	
	if (widthPlusMargin < clientPgMidW){
		$("#clients_page").css("width", $("#clients_page").css("min-width") );
	}else if(widthPlusMargin >= parseFloat(clientPgMaxW) ){
		$("#clients_page").css("width", clientPgMaxW);
	}else{
		$("#clients_page").css("width", clientPgMidW + "px");
	}
	
	// - bg image - 
	wH = $(window).height();
	var windowAspectRto = wW / wH;
	var backgroundImages = $(".backgroundImage");
	var bgIndex;
	var i;
	for (i = 0; i < backgroundImages.length; i++){
		bgIndex = (currentBGIndex + i) % backgroundImages.length;
		
		if (bgImages[bgIndex]['aspectRatio'] > windowAspectRto){
			$(backgroundImages[i]).css("height", "100%");
			$(backgroundImages[i]).css("width", "auto");
			//trace(bgImages[bgIndex]['aspectRatio'] +"  >  "+ windowAspectRto);
		}else{
			$(backgroundImages[i]).css("width", "100%");
			$(backgroundImages[i]).css("height", "auto");
			//trace(bgImages[bgIndex]['aspectRatio'] +"  <=  "+ windowAspectRto);
		}
	}
}


function initializeGoogleMap() {
	googleMapMade = true;
	var latlng = new google.maps.LatLng(40.702785, -73.986861);
	var myOptions = {
			zoom: 15,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var googleMap = new google.maps.Map(document.getElementById("map_canvas"),
	    myOptions);
	
	var googleMarker = new google.maps.Marker({
		  position: latlng,
		  map: googleMap
		});
}

// --- page interactions --- //

// - settings - //
var tabOpenDuration = 1000;// - remember: milliseconds 
var tabCloseDuration = 400;

// - vars - //
var capabilitiesTab;
var clientsTab;
var contactTab;
var tabs = [];

var videoOpen = false;

function initTabs(){
	capabilitiesTab = makeTab("#capabilities_page", "#capabilities_btn", "#capabilities_btn", "assets/capabilitiesBtn_over.png", "assets/capabilitiesBtn_selected.png");
	clientsTab = makeTab("#clients_page", "#clients_btn", "#clients_btn", "assets/clientsBtn_over.png", "assets/clientsBtn_selected.png");
	contactTab = makeTab("#contact_page", "#contact_btn", "#contact_btn", "assets/contactBtn_over.png", "assets/contactBtn_selected.png");
	tabs = [capabilitiesTab, clientsTab, contactTab];
	
	makeButton("#close_btn_capabilities", "#close_btn_capabilities", "assets/closeBtn_over.png", closeTab, capabilitiesTab);
	makeButton("#close_btn_clients", "#close_btn_clients", "assets/closeBtn_over.png", closeTab, clientsTab);
	makeButton("#close_btn_contact", "#close_btn_contact", "assets/closeBtn_over.png", closeTab, contactTab);
	
	
	if (vimeoId != ""){
		if (isMobile){
			makeButton("#reel_btn", "#reel_btn_img", "assets/tabBtn_over.png", vimeoLink, "", true);
		}else{
			var videoHTML = '<iframe class="vim" id="vimeo_frame0" src="'+ vimeoLink +'" width="100%" height="100%" frameborder="0" webkitAllowFullScreen allowFullScreen>' + 
							'</iframe>' + 
							'<img src="assets/closeBtn.png" class="close_btn" id="close_btn_video" />';
			$("#video_player_container").html(videoHTML);
			
			makeButton("#reel_btn", "#reel_btn_img", "assets/tabBtn_over.png", openVideoPlayer);
			makeButton("#close_btn_video", "#close_btn_video", "assets/closeBtn_over.png", closeVideoPlayer);
		}
	}
	
	if ( $("#next_btn").length ){
		makeButton("#next_btn", "#next_btn_img", "assets/tabBtn_over.png", "ourwork.php?pid="+nextProjectID, "", true);
	}
	
	
	if (pgID != 0){
		makeButton("#logo_home_btn", "#logo_home_btn", "", "index.php", "", true);
	}
	
	if (pgID != 1){
		makeButton("#aboutus_btn", "#aboutus_btn", "assets/aboutUs_over.png", "aboutus.php", "", true);
	}else{
		$("#aboutus_btn").prop("src", "assets/aboutUs_over.png");
	}
	
	if (pgID != 2){
		makeButton("#ourwork_btn", "#ourwork_btn", "assets/ourWork_over.png", "ourwork.php", "", true);
	}else{
		$("#ourwork_btn").prop("src", "assets/ourWork_over.png");
	}
	
	// - social buttons - 
	makeButton("#facebook_btn", "#facebook_btn", "assets/facebookIcon_over.png", "http://www.facebook.com/pages/Underdog-Films-Inc/284517318239786");
	makeButton("#linkedin_btn", "#linkedin_btn", "assets/linkedinIcon_over.png", "http://www.linkedin.com/company/2345668?trk=tyah");
	makeButton("#twitter_btn", "#twitter_btn", "assets/twitterIcon_over.png", "http://twitter.com/#!/UnderdogFIlms");
	makeButton("#vimeo_btn", "#vimeo_btn", "assets/vimeoIcon_over.png", "http://vimeo.com/channels/255161");
	
	initClientLogoBtns();
}


function closeAllTabs(){
	var i = 0;
	for (i = 0; i < tabs.length; i++){
		if(tabs[i].isOpen){
			closeTab(tabs[i]);
		}
	}
}

function toggleTab(tab){
	if(tab.isOpen){
		closeTab(tab);
	}else{
		openTab(tab);
	}
}

function openTab(tab){
	closeAllTabs();
	tab.isOpen = true;
	$(tab.id).stop(true, false);
	
	tab.figureOutPos();
	var currentPos = parseFloat( $(tab.id).css("bottom") );
	var scaleMult = Math.abs( (tab.inPos - currentPos) / (tab.inPos - tab.outPos) );
	
	var adjustedDuration = tabOpenDuration * scaleMult;
	$(tab.id).css("z-index", "101");
	$(tab.id).css("display", "block");
	$(tab.id).animate({ "bottom": tab.inPos+"px" }, adjustedDuration);
	
	$(tab.imageId).prop("src", tab.btnImgOpen.src);
	
	// - damn special cases
	if (!googleMapMade && tab.id == "#contact_page"){
		initializeGoogleMap();
	}
}

function closeTab(tab){
	tab.isOpen = false;
	$(tab.id).stop(true, false);
	tab.figureOutPos();
	var currentPos = parseFloat( $(tab.id).css("bottom") );
	var scaleMult = Math.abs( (tab.outPos - currentPos) / (tab.outPos - tab.inPos) );
	
	var adjustedDuration = tabCloseDuration * scaleMult;
	$(tab.id).css("z-index", "auto");
	$(tab.id).animate({ "bottom": tab.outPos+"px" }, adjustedDuration, function() {
	    // - animation complete -
		$(tab.id).css("display", "none");
	  });
	
	$(tab.imageId).prop("src", tab.btnImg.src);
}


function closeVideoPlayer(){
	videoOpen = false;
	$f( $('.vim')[0] ).api('pause');

	$("#content_layer_video").animate({ "left": "-100%" }, tabCloseDuration);
	onVideoClose();
}

function openVideoPlayer(){
	videoOpen = true;
	closeAllTabs();
	$("#content_layer_video").animate({ "left": "0%" }, tabOpenDuration);
	$f( $('.vim')[0] ).api('play');
}


function makeTab(tabId, buttonId, imageId, overSrc, openSrc){
	var tab = new Object();
	tab.id = tabId;
	tab.buttonId = buttonId;
	tab.imageId = imageId;
	tab.isOpen = false;
	
	tab.btnImg = new Image();
	tab.btnImgOver = new Image();
	tab.btnImgOpen = new Image();
	// these also function as preloaders
	tab.btnImg.src = $(imageId).prop("src");
	tab.btnImgOver.src = overSrc;
	tab.btnImgOpen.src = openSrc;
	tab.inPos = parseFloat( $(tab.id).css("bottom") );
	tab.outPos = 0;
	
	tab.figureOutPos = function(){
		tab.outPos = tab.inPos - $(tab.id).height();
	}
	
	tab.figureOutPos();
	$(tab.id).css("bottom", tab.outPos+"px");
	
	$(tab.buttonId).mouseenter(function(){
		$(tab.imageId).prop("src", tab.btnImgOver.src);
		if (!isMobile){
			openTab(tab);
		}
	}).mouseleave(function (){
		if (tab.isOpen){
			$(tab.imageId).prop("src", tab.btnImgOpen.src);
			if (!isMobile){
				closeTab(tab);
			}
		}else{
			$(tab.imageId).prop("src", tab.btnImg.src);
		}
	});
	
	if (!isMobile){
		$(tab.id).mouseleave(function (){
			if (tab.isOpen){
				closeTab(tab);
			}
		}).mouseenter(function(){
			openTab(tab);
		});
	}
	
	$(tab.buttonId).click(function(){
		toggleTab(tab);
	});
	
	return tab;
}


// --- utilities --- //

function makeButton(buttonId, imageId, overSrc, href, parameters, sameWindow){
	
	// - these also function as preloaders
	var linkImg = new Image();
	linkImg.src = $(imageId).prop("src");
	
	var linkImgRO = new Image();
	
	if (typeof overSrc != undefined && overSrc != ""){
		linkImgRO.src = overSrc;
	}else{
		linkImgRO = linkImg;
	}
	
	$(buttonId).mouseenter(function(){
		$(imageId).prop("src", linkImgRO.src);
	}).mouseleave(function (){
		$(imageId).prop("src", linkImg.src);
	});
	
	if (typeof href != 'undefined'){
		if (typeof href == 'function'){
			if (typeof parameters != 'undefined'){
				$(buttonId).click(function(){
					href(parameters);
				});
			}else{
				$(buttonId).click(function(){
					href();
				});
			}
		}else{
			
			var target = "";
			if (typeof sameWindow == 'undefined' || sameWindow == false){
				target = ' target="_blank"';
			}
			$(buttonId).wrap('<a href="'+href+'"' + target + ' />');
		}
	}
}

// --- //
var onVideoClose = function(){};// - for use ONLY by changeBG()

function queBGChange(){
	setTimeout(changeBG, stayDuration);
}

function changeBG(){
	if (videoOpen){
		onVideoClose = function(){
			setTimeout(changeBG, tabCloseDuration * 2);
		}
	}else{
		onVideoClose = function(){};
		var nextBGIndex = (currentBGIndex + 1) % bgImages.length;
		var nextBGID = "backgroundImage" + nextBGIndex;
		var currentBGID = "backgroundImage" + currentBGIndex;
		
		var nextImage = new Image();
		nextImage.className = "backgroundImage";
		nextImage.id = nextBGID;
		nextImage.onload = function(){
			$('#background').insertBefore($('#'+nextBGIndex), $('#'+currentBGID) );
			document.getElementById('background').insertBefore(nextImage, document.getElementById('background').childNodes[0]);
			scaleSite();
			$('#'+currentBGID).fadeOut(fadeDuration, function(){
				$('#'+currentBGID).remove();
				currentBGIndex = nextBGIndex;
				queBGChange();
			});
		}
		
		nextImage.src = bgImages[nextBGIndex]['src'];// - kick it all off
	}
}

function trace(msg){
	if (typeof(console) != 'undefined') console.log(msg);
}
