/* Set up logging: Log through the integration controller
 * if it exists; otherwise, log through the console
 */

var log;
if (typeof gettingStartedController == "undefined") {
	gettingStartedController = null;
	log = function(i) { console.log(i) };
} else {
	log = function(i) { gettingStartedController.logMessage_(i) };
}

var KSExampleDocumentImage = 0;
var KSExampleDocumentText = 1;
var KSExampleDocumentFolder = 2;
var KSExampleDocumentIntegration = 3;

// Scope Switching

function switchScope(event) {
	var element = event.currentTarget;
	
	var identifier = $(element).attr('id');
	switchToScopeWithIdentifier(identifier);
		
	return false;
	
}

function switchToScopeWithIdentifier(identifier)
{
	log("switch to scope with identifiier: " + identifier);
	var elementToSelectSelector = "#" + identifier;
	var bodySelector = elementToSelectSelector + '-screenshot';

	var isSelected = $(elementToSelectSelector).hasClass("selected");
	
	if (isSelected == false) {
		// hide all the content on the right.
		$("*[data-content]").addClass("hidden");
		
		//  unselect all items on the left
		$("li").removeClass("selected");
		// select the new selection on the left
		$(elementToSelectSelector).addClass("selected");
		var arrowTop = $(elementToSelectSelector).position().top + "px";
		$("#arrow").css("top",arrowTop);

		// show the appropriate content on the right
		$(bodySelector).removeClass("hidden");
	}

	// Configure callouts
	$(bodySelector).find("[data-callout-width]").each(function(index, calloutElement) {
		initializeCallout(calloutElement);
	});

	
	// Make sure the popover is hidden to start.
	hidePopOver();
}

function reportErrorForMoreFrame(errorString)
{
	var errorIdentifier = "more-frame-error";
	if ($("#"+errorIdentifier).length == 0) {
		$("#more-container").append("<div id='"+errorIdentifier+"' class='more-error'></div>");
	}
	$("#"+errorIdentifier).html(errorString);
}

// Callout Management

var calloutHoverPopoverDelay = 0.1; //seconds

function initializeCallout(calloutElement) {
	// Position it (without transition)
	setCalloutTransitionsEnabled(calloutElement, false);
	showCalloutUnselected(calloutElement);
	
		
	// On mouse enter, show popover.
	$(calloutElement).mouseenter( function() {
		setCalloutTransitionsEnabled(calloutElement, true);
		
		showCalloutSelected(calloutElement);
		
		// Create a timer to show the popover, if one exists clear it.
		var calloutHoverPopoverTimer = $(calloutElement).attr("hover-popover-timer");
		if (calloutHoverPopoverTimer != null) {
			clearTimeout(calloutHoverPopoverTimer);
		}
		calloutHoverPopoverTimer = setTimeout(function() {
			populatePopoverFromCalloutElement(calloutElement);
			showPopOverPositionedFromElement(calloutElement);
		}, 1000 * calloutHoverPopoverDelay);
		$(calloutElement).attr("hover-popover-timer", calloutHoverPopoverTimer);
	});
	
	// On mouse leave, hide it.
	$(calloutElement).mouseleave( function() {
		hidePopOver();
		showCalloutUnselected(calloutElement);
		
		// Clear the timer
		var calloutHoverPopoverTimer = $(calloutElement).attr("hover-popover-timer");
		clearTimeout(calloutHoverPopoverTimer);
		calloutHoverPopoverTimer = null;
		$(calloutElement).attr("hover-popover-timer", calloutHoverPopoverTimer);
	});
}

function setCalloutTransitionsEnabled(calloutElement, isEnabled)
{
	if (isEnabled == true) {
		$(calloutElement).css("-webkit-transition-property", "");
		$(calloutElement).css("-webkit-transition-duration", "0.1s")
		$(calloutElement).css("-webkit-transition-timing-function", "linear")
	}
	else {
		$(calloutElement).css("-webkit-transition-property", "");
		$(calloutElement).css("-webkit-transition-duration", "0.0s")
	}
}

function showCalloutUnselected(calloutElement) 
{
	$( ".screenshot" ).button( "enable" );
	
	var left = $(calloutElement).attr("data-callout-position-left");
	var top = $(calloutElement).attr("data-callout-position-top");
	var width = $(calloutElement).attr("data-callout-width");
	var height = $(calloutElement).attr("data-callout-height");
	
	$(calloutElement).css("left", left + "px");
	$(calloutElement).css("top", top + "px");
	$(calloutElement).css("width", width + "px");
	$(calloutElement).css("height", height + "px");
	$(calloutElement).css("background-image", "");
	$(calloutElement).css("-webkit-animation-play-state", "running");
}

function showCalloutSelected(calloutElement) 
{
	$( ".screenshot" ).button( "disable" );
	
	var frame = frameOfSelectedCalloutElement(calloutElement);
	var zoomImage = $(calloutElement).attr("data-zoom-image");
	
	if (isScreenRetina()) {
		zoomImage = zoomImage.replace(".png", "@2x.png");
	}
	
	$(calloutElement).css("left", frame.left + "px");
	$(calloutElement).css("top", frame.top + "px");
	$(calloutElement).css("width", frame.width + "px");
	$(calloutElement).css("height", frame.height + "px");	
	$(calloutElement).css("background-image", 'url("images/'+zoomImage+'")');
	$(calloutElement).css("background-size", frame.width + "px " + frame.height + "px");
	$(calloutElement).css("-webkit-animation-play-state", "paused");
	//$(calloutElement).css("background-position", "center, center");
}

function frameOfSelectedCalloutElement(calloutElement)
{
	var unselectedLeft = parseInt($(calloutElement).attr("data-callout-position-left"));
	var unselectedTop = parseInt($(calloutElement).attr("data-callout-position-top"));
	var unselectedWidth = parseInt($(calloutElement).attr("data-callout-width"));
	var unselectedHeight = parseInt($(calloutElement).attr("data-callout-height"));
	var selectedWidth = parseInt($(calloutElement).attr("data-zoom-width"));
	var selectedHeight = parseInt($(calloutElement).attr("data-zoom-height"));
	var selectedLeftOffset = parseInt($(calloutElement).attr("data-zoom-position-offset-left"));
	var selectedTopOffset = parseInt($(calloutElement).attr("data-zoom-position-offset-top"));
	
	var positionLeft = unselectedLeft - ((selectedWidth-unselectedWidth)/2.0) + selectedLeftOffset;
	var positionTop = unselectedTop - ((selectedHeight-unselectedHeight)/2.0) + selectedTopOffset;
	var sizeWidth = selectedWidth;
	var sizeHeight = selectedHeight;
	
	return {left: positionLeft, top: positionTop, width: sizeWidth, height: sizeHeight };
}

// Popover

function populatePopoverFromCalloutElement(calloutElement)
{
	var title = $(calloutElement).attr("data-popover-text-title");
	var contentText = $(calloutElement).attr("data-popover-text-content");
	var popoverWidth = parseInt($(calloutElement).attr("data-popover-width"));
	var popoverPointPosition = parseInt($(calloutElement).attr("data-popover-point-position-x"));
	
	if (popoverWidth == 0)
		popoverWidth = 320;
	
	if (popoverPointPosition <= 8)
		popoverPointPosition = 8;
	else if (popoverPointPosition > 92)
		popoverPointPosition = 92;
		
	$("#popover-text-title").html(title);
	$("#popover-text-content").html(contentText);
	$("#popover").css("width", popoverWidth + "px");
	// Avoid jQuery, using .css("left", "value") seems to be weird when getting it later.
	document.getElementById("popover-point").style.left = popoverPointPosition + "%";
}

function showPopOverPositionedFromElement(positioningElement)
{
	var position = popOverPositionForElement(positioningElement);
	$("#popover").css("top",position.top + "px");
	$("#popover").css("left",position.left + "px");
	$("#popover").fadeIn(200);
}

function hidePopOver()
{
	$("#popover").fadeOut(200);
}

function popOverPositionForElement(calloutElement)
{
	var elementFrame = frameOfSelectedCalloutElement(calloutElement);
	var elementHeight = elementFrame.height;
	var elementWidth = elementFrame.width;
	
	// parent is span for ui-button
	// grandparent is actual screenshot
	var screenshotElementHeight = $(calloutElement).parent().parent().height();
		
	var popoverWidth = $("#popover").width();
	var popoverHeight = $("#popover").height();
	
	var popoverPointWidth = $("#popover-point").width();
	// This is actually a square that's rotated 45deg, so we need the hypotenus of it for actual width
	popoverPointWidth = Math.sqrt( Math.pow(popoverPointWidth, 2) + Math.pow(popoverPointWidth, 2) );
	popoverPointWidth = Math.floor( popoverPointWidth );

	var popoverPointLeftPercentage = document.getElementById("popover-point").style.left;// Avoid jQuery to get the value, since it wasn't set via jQuery.
	popoverPointLeftPercentage = popoverPointLeftPercentage.replace("%", "");
	if (popoverPointLeftPercentage <= 8)
		popoverPointLeftPercentage = 8;
	else if (popoverPointLeftPercentage > 92)
		popoverPointLeftPercentage = 92;
	var popoverPointLeftPixels = popoverWidth * (popoverPointLeftPercentage/100.0);
	var popoverPointCenter = popoverPointLeftPixels + (popoverPointWidth); // you'd think popoverPointWidth/2.0, but I think the 45deg rotation screws with us here.
	
	// Now we want to make popoverPointCenter == the center of calloutElement
	// Which means positionLeft == center of calloutElement - popoverPointCenter
	var calloutElementCenterX = elementFrame.left + (elementWidth/2.0);
	var positionLeft = calloutElementCenterX - popoverPointCenter;
	
	var positionTop = 0;
		
	if (elementFrame.top < screenshotElementHeight/2.0)
	{
		// top half, popover will be under.
		positionTop = elementFrame.top + elementHeight;
		$("#popover-point").css("bottom", "auto");
		$("#popover-point").css("top", "-10px");
		$("#popover-point").css("-webkit-mask-image", "-webkit-linear-gradient(315deg, black, black 50%, transparent  50%)");
	}
	else {
		// bottom half, popover will be above.
		positionTop = elementFrame.top - 2*elementHeight - popoverHeight;
		$("#popover-point").css("top", "auto");
		$("#popover-point").css("bottom", "-10px");
		$("#popover-point").css("-webkit-mask-image", "-webkit-linear-gradient(135deg, black, black 50%, transparent  50%)");
	}
	
	
	var popoverPosition = {left: positionLeft, top:positionTop};
	
	return popoverPosition;
}

// iFrame Theatre

function showTheatreWithURL(url, backgroundColorValue)
{
	var html = '<iframe src="' + url + '" height="100%" width="100%" seamless></iframe>';
	$("#theatre").css("background-color", backgroundColorValue);
	$("#theatre").fadeIn(500, function() {
		$("#theatre").html(html);
	});
}

function hideTheatre()
{
	$("#theatre").fadeOut(500, function(){
		$("#theatre").html("");
	});
}

// Newsletter Subscription Related

function isSubsciptionEmailAddressValid()
{
	var value = $("#newsletter-email-address").val();
	value = $.trim(value);
	var simpleEmailRegex = /.+@.+/;
	if (value.match(simpleEmailRegex) != null)
		return true;
	return false;
}

function subscribeToNewsletter()
{
	var message = "";
	if (isSubsciptionEmailAddressValid() == false)
	{
		message = $("#string-subscribe-invalid-email").html();
	}
	else
	{
		message = $("#string-subscribe-subscribing").html();
		disableSubscriptionFields();
		if (gettingStartedController != null)
		{
			gettingStartedController.subscribeEmailAddressToNewsletter();
		}
	}
	log("messge = " + message);
	setSubscribeStatusMessage(message)
}

function enableSubcriptionFields()
{
	$("#newsletter-email-address").removeAttr("disabled");
 	$("#newsletter-subscribe-button").removeAttr("disabled");
}

function disableSubscriptionFields()
{
	$("#newsletter-email-address").attr("disabled",true);
 	$("#newsletter-subscribe-button").attr("disabled",true);
}

function setSubscribeStatusMessage(message)
{
	message = $.trim(message);
	$("#subscribe-message").html(message);
	
	document.getElementById("subscribe-message-container").style.display = "none";
	
	setTimeout(function() {
		var aMessage = $("#subscribe-message").html();
		var isContainerVisible = aMessage.length > 0 ? true : false;
		var displayValue = isContainerVisible ? "inline" : "none";
		document.getElementById("subscribe-message-container").style.display = displayValue;
	}, 50);
}

// General

function isScreenRetina(){
    var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
                      (min--moz-device-pixel-ratio: 1.5),\
                      (-o-min-device-pixel-ratio: 3/2),\
                      (min-resolution: 1.5dppx)";
	var root = (typeof exports == 'undefined' ? window : exports);

    if (root.devicePixelRatio > 1)
      return true;

    if (root.matchMedia && root.matchMedia(mediaQuery).matches)
      return true;

    return false;
};

$(document).ready(function() {
	// Make sure the popover is hidden to start.
	hidePopOver();
	
	// Convert buttons to jQuery-UI Buttons so that we get proper active state mouse-tracking
	$( "button" ).button();
	
	// Mark all headers as collapsible
	$("#scopes li").click(switchScope);
		
	// Update the controller when the email address changes
	$('#newsletter-email-address').bind('keyup change', function() {
		var emailAddress = this.value;
		if (gettingStartedController != null)
			gettingStartedController.setEmailAddress_(emailAddress);
	});
	
	// Hook up the subscribe button
	$('#newsletter-subscribe-button').click( function() {
		subscribeToNewsletter();
	});
	
	// Hook up the example such that we can open them
	$("[data-example-document-index]").each(function(index, exampleDocument) {
		var documentIndex = $(exampleDocument).attr("data-example-document-index");
		$(exampleDocument).click( function() {
			openExample(documentIndex);
		});
	});
	
	// Convert screenshots into jquery-ui buttons to get better active support
	$(".screenshot").button();
	
	// Disable click bubbling up for callouts, so that they don't open documents
	$(".callout").click( function(event) {
	  	event.stopPropagation();
	});
	
	// Move us to the first section
	switchToScopeWithIdentifier('images');
});

function openExample(exampleIndex)
{
	if (gettingStartedController != null)
	{
		gettingStartedController.openExample_(exampleIndex);
	}
	else
	{
		log("Opening example " + exampleIndex);
	}
}

// Functions that are called from ObjC

function updateNewsletterEmailAddressValue(emailAddress) {
	$('#newsletter-email-address').val(emailAddress)
    return emailAddress;
}

function newsletterSubscriptionSucceeded() {
	var message = $("#string-subscribe-success").html();
	setSubscribeStatusMessage(message)
}

function newsletterSubscriptionFailed() {
	var message = $("#string-subscribe-error").html();
	setSubscribeStatusMessage(message)
	enableSubcriptionFields();
}