//
// TransmitEffects.js - (C) 2010 Panic, Inc.
//
// Not for redistribution.

// Initialize important variables when page loads.

var isTouchDevice = false;
var isMacOS = true;
var browser = '';

function initializePageEffects() {
	
	if (navigator.appVersion.indexOf('Mac') < 0)
	{
		isMacOS = false;
	}
	
	if (navigator.appVersion.indexOf('iPhone') > -1 ||
		navigator.appVersion.indexOf('iPod') > -1 ||
		navigator.appVersion.indexOf('iPad') > -1)
	{
		isTouchDevice = true;
		document.body.className += ' touch';
		document.getElementById('downloadButton').onmouseover = download;
	}
	
	if (navigator.appVersion.indexOf('WebKit') > -1)
	{
	
		// Look for backface-visibility compatibility. Requires newest WebKit.
	
		if ((window.media && window.media.matchMedium('(-webkit-transform-3d)')) || (window.styleMedia && window.styleMedia.matchMedium('-webkit-transform-3d')))
		{
			document.body.className += ' browserWebKit';
			browser = 'webkit';
		}
		else
		{
			document.body.className += ' browserOldWebkit';
			browser = 'oldWebkit';		
		}
		
	}
	else
	{
		document.body.className += ' browserOther';
		browser = 'other';
	}

}

//
// LARGE POPUP: Full-Screen Pop-up Functions
//

function download(elem)
{
	// Display Dialog
	showLargePopup(elem);
	
	// Begin Download (if appropriate)	
	if (isMacOS)
	{
		if (! isTouchDevice) {
			// Trigger download in 1.5 seconds (so pop-up graphics finish loading)
			refreshTimer = setTimeout("setLocation('"+elem.getAttribute("href")+"')", 1500);
			
			// Track download with Google Analytics
			_gaq.push(['_trackEvent', 'Downloads', 'Transmit']);

		}
	}
}

function showLargePopup(elem)
{

    var popFullscreen = document.getElementById('fullscreen');
    var popLarge = document.getElementById('largepopup');
    
    // Show correct popup depending on the user's device
    if (isMacOS)
    {
    	// iPad, iPhone, or iPod touch
		if (isTouchDevice)
		{
		    document.getElementById('download-link').style.display = 'block';
		}
		else
		// A non-iPhone Mac
		{
		    document.getElementById('start-download').style.display = 'block';
		}
    }
    else
    {
    	// Not a Mac :(
	    document.getElementById('download-nonmac').style.display = 'block';
    }
 
    // Make fullscreen thing really full screen, and show it
    getSize();
    popFullscreen.style.height = myScrollHeight + 'px';
    popFullscreen.style.display = 'block';
	
    // Position pop-up
    popLarge.style.left = ((myWidth - popLarge.offsetWidth) / 2) + 'px';
    popLarge.style.top = (((myHeight - popLarge.offsetHeight) / 2) + myScroll) + 'px';
    popLarge.style.visibility = 'visible';
    
}

function setLocation(loc) {
	window.location = loc;
}

function hideLargePopup() {
    var popFullscreen = document.getElementById('fullscreen');
    var popLarge = document.getElementById('largepopup');
    
    popLarge.style.visibility = 'hidden';
    popFullscreen.style.display = 'none';
    
    // Reset popup kind
    document.getElementById('start-download').style.display = 'none';
    document.getElementById('download-link').style.display = 'none';
    document.getElementById('download-nonmac').style.display = 'none';
}

//
// DOWNLOAD SMALL POPUP: Download Hint Pop-up Functions
//
// An advantage of using a timer to do a hide is that we can ignore
// any spurious mouseOut events that have bubbled up, into <td>'s, etc.

var dpopTimer = "";

function showDownloadPopup(e) {
	var popDownload = document.getElementById('dpop');
	var btnDownload = document.getElementById('navbar');  // 11/2009 Changed this from "download" to "navbar" to make it work with the new image-free buttons. -Tim

	if (moveanim.timer != null) {
		clearInterval(moveanim.timer);
		moveanim.timer = null;
	}

	// Determine where we should pop up in relation to the download button
	// 11/2009 - Changed this section to work with the new buttons. -Tim
	position = findElementPos(btnDownload);
	if (position[0] < 40)
		{
		popDownload.style.left = "15" +"px";
		popDownload.style.top = "-" + "83" +"px";
		}
	else {
		popDownload.style.left = "-" + "52" +"px";
		popDownload.style.top = "-" + "86" +"px";		
		}

	// If already trigger a rollover, cancel it because we're back in

	if (dpopTimer != "")
	{
		clearTimeout(dpopTimer);
		dpopTimer = "";
	} else {
		setOpacity(0, 'dpop');
		popDownload.style.visibility = 'visible';
		moveStart(popDownload, parseInt(popDownload.style.left), parseInt(popDownload.style.left), parseInt(popDownload.style.top) + 10, parseInt(popDownload.style.top), 15);
		fadeElementSetup('dpop', 0, 100, 13);
	}
}

function hideDownloadPopup() {
	// Start timer to hide the pop-up and the overlay
	dpopTimer = setTimeout("actuallyHide()", 500);
}

function actuallyHide() {
	var popDownload = document.getElementById('dpop');
	if (dpopTimer != "")
	{
		dpopTimer = "";
		moveStart(popDownload, parseInt(popDownload.style.left), parseInt(popDownload.style.left), parseInt(popDownload.style.top), parseInt(popDownload.style.top) - 10, 15);		
		fadeElementSetup('dpop', 100, 0, 13, 1);
	}
}

//
// MOVE: Animate the move of an element.
//
// Move is also synchronous. One at a time, please.
//

var moveanim = {time:0, beginX:0, changeX:0.0, beginY:0, changeY:0, duration:0.0, element:null, timer:null};

function moveStart(elem, startX, endX, startY, endY, duration)
{
	if (moveanim.timer != null) {
		clearInterval(moveanim.timer);
		moveanim.timer = null;
	}
	moveanim.time = 0;
	moveanim.beginX = startX;
	moveanim.changeX = endX - startX;
	moveanim.beginY = startY;
	moveanim.changeY = endY - startY;
	moveanim.duration = duration;
	moveanim.element = elem;

	moveanim.timer = setInterval("moveAnimDo();", 15);
}

function moveAnimDo()
{
	if (moveanim.time > moveanim.duration) {
		clearInterval(moveanim.timer);
		moveanim.timer = null;
	}
	else {
		moveX = cubicOut(moveanim.time, moveanim.beginX, moveanim.changeX, moveanim.duration);
		moveY = cubicOut(moveanim.time, moveanim.beginY, moveanim.changeY, moveanim.duration);
		moveanim.element.style.left = moveX + "px";
		moveanim.element.style.top = moveY + "px";
		moveanim.time++;
	}
}



/* Popups and other effects */

var swappedView = 'Default'; // remember which of the 3 screenshots we're showing
var activePopup = null;
var activeTimer = null;
var leavingTimer = null;
var specialTimer = null;
var popupTimer = null;
var flipMidpoint = null;

var marks = [ 'Places', 'DualToggle', 'PathBar', 'NewViews', 'NewUI', 'Protocols', 'LocalToggle', 'Disclosable', 'Labels', 'Before', 'CustomIcons', 'TwinProgress', 'SyncUI', 'SyncRules', 'SyncFileSize', 'SyncFriendly', 'TransferDisclosable', 'TransferPerFolder', 'TransferLimit', 'TransferCount' ];

function flipFeaturesCard(evt)
{
	dismissActivePopup(); 
	
	var element = document.getElementById('featuresCard');
	var button = document.getElementById('featuresFlipButton');
	
	if (testShift(evt)) {
		document.getElementById('featuresCard').style.webkitTransitionDuration = '3s';
		flipMidpoint = 900;
	} else {
		document.getElementById('featuresCard').style.webkitTransitionDuration = '1s';
		flipMidpoint = 300;
	}
	
	if (element.className == '') // Screenshot is showing. Hide it, show list
	{
		hideAllEffects();
		
		if (browser == 'oldWebkit') // WebKit 4.0.5 Snow Leopard supports backface, Leopard doesn't, sigh. Let's change views on a timer and not reply on backface-visibility
		{
			setTimeout("document.getElementById('featuresList').style.display = 'block'", flipMidpoint);
			setTimeout("document.getElementById('featuresScreenshots').style.display = 'none'", flipMidpoint);
		}
		else if (browser == 'other') // Other browsers don't transition at all, so we just show/hide.
		{
			document.getElementById('featuresList').style.display = 'block';
			document.getElementById('featuresScreenshots').style.display = 'none';
		}
	}
	else // List is showing. Hide it, show screenshot
	{	                                           // show the right screenshot when we flip //
		setTimeout("document.getElementById('featuresEffects" + swappedView + "').style.display = 'block'", (flipMidpoint * 2));
		if (browser == 'oldWebkit')
		{
			setTimeout("document.getElementById('featuresList').style.display = 'none'", flipMidpoint);
			setTimeout("document.getElementById('featuresScreenshots').style.display = 'block'", flipMidpoint);
		}
		else if (browser == 'other')
		{
			document.getElementById('featuresList').style.display = 'none';
			document.getElementById('featuresScreenshots').style.display = 'block';
		}
	}
	
	// As "newest" WebKit supports backface visibility, this is all that will be executed on there.
		
	element.className = (element.className == '') ? 'card flipped' : '';
	button.className = (button.className == '') ? 'pressed' : '';
}

function mouseOver(name)
{	
	clearTimeout(activeTimer);
	activeTimer = setTimeout("showPopup('" + name + "')", 100);
	
	// Marks have a z-index of 100 to ensure consistent mouseOver/mouseOut
	// behavior when a popup appears.  Once a popup is up, set the z-indexes
	// of the other marks to 0 so they don't appear in front of the popup.
	
	clearTimeout(popupTimer);
	for ( var i in marks )
	{
		var markName = marks[i];
		
		if ( markName != name )
		{
			var mark = document.getElementById('mark' + markName);
			mark.style.zIndex = 0;
		}	
	}
	
	clearTimeout(leavingTimer);
}

function mouseOut(name)
{
	clearTimeout(activeTimer);
	activeTimer = setTimeout("dismissActivePopup()", 100);
	
	// Restore marks to z-index of 100
	clearTimeout(popupTimer);	
	popupTimer = setTimeout("restoreMarks(activePopup)", 500);
	
	clearTimeout(leavingTimer);
}

function restoreMarks(activePopup)
{
	for ( var i in marks )
	{
		var markName = marks[i];
		
		if ( markName != name )
		{
			var mark = document.getElementById('mark' + markName);
			mark.style.zIndex = 100;
		}	
	}
}


function showPopup(name)
{
	if ( activePopup == name )
		return;
		
	dismissActivePopup(); 
	setTimeout("showPopupDeferred('" + name + "')", 1);
}

function showPopupDeferred(name)
{
	var mark = document.getElementById('mark' + name);
	var left = mark.style.left.replace(/[^0-9\-]/g, '');
	var top = mark.style.top.replace(/[^0-9\-]/g, '');

	var element = document.getElementById('featuresPopup' + name);
	left -= (element.clientWidth / 2) - 21;
	top -= element.clientHeight + 8; 
				
	element.style.visibility = 'visible';
	element.style.left = left + 'px';
	element.style.top = top + 'px';
	element.className = 'featuresPopup popped';
	
	if (document.all)
	{
		// IE doesn't handle classNames well, so we should literally show the element
		element.style.visibility = 'visible';
	}
	
	activePopup = name;	
	
	// Special cases where the mouseover action also shows other elements
	if (name == 'Places')
	{
		clearTimeout(specialTimer);
		specialTimer = setTimeout("showPlacesPopup()", 100);		
	}
	else if (name == 'TwinProgress')
	{
		clearTimeout(specialTimer);
		specialTimer = setTimeout("showProgressAnimation()", 100);		
	}
}

function dismissActivePopup()
{
	if ( activePopup != null )
	{
		var mark = document.getElementById('mark' + activePopup);
		mark.className += ' visited';
		mark.onmousemove = null;

		setTimeout("document.getElementById('featuresPopup" + activePopup + "').className = 'featuresPopup leaving'", 1);
		
		if (document.all)
		{
			// IE doesn't handle classNames well, so let's just literally hide the element
			setTimeout("document.getElementById('featuresPopup" + activePopup + "').style.visibility = 'hidden'", 501);
		}
		else
		{
			// not IE, so do the sane thing
			leavingTimer = setTimeout("document.getElementById('featuresPopup" + activePopup + "').className = 'featuresPopup'", 501);
		}
		
		// Special cases where the mouseover action also showed other elements
		if (activePopup == 'Places')
		{
			setTimeout("hidePlacesPopup()", 100);		
		}
		else if (activePopup == 'TwinProgress')
		{
			setTimeout("hideProgressAnimation()", 100);		
		}
		
		activePopup = null;
	}
}

function swapSync()
{
	if (document.getElementById('screenshotSync').className != 'swapped')
	{
		hideAllEffects();
		setTimeout("document.getElementById('featuresEffectsSync').style.display = 'block';", 300);
		document.getElementById('screenshotSync').className = 'swapped';
		setTimeout("document.getElementById('featureScreenshotBase').src = 'img/card-screenshot2.png';", 300);
		swappedView = 'Sync';
	}
	else
	{
		swapDefault();
		document.getElementById('screenshotSync').className = '';
	}
}

function swapTransfers()
{
	if (document.getElementById('screenshotTransfers').className != 'swapped')
	{
		hideAllEffects();
		setTimeout("document.getElementById('featuresEffectsTransfers').style.display = 'block';", 300);
		document.getElementById('screenshotTransfers').className = 'swapped';
		setTimeout("document.getElementById('featureScreenshotBase').src = 'img/card-screenshot3.png';", 300);
		swappedView = 'Transfers';
	}
	else
	{
		swapDefault();
		document.getElementById('screenshotTransfers').className = '';
	}
}

function hideAllEffects()
{
	document.getElementById('featuresEffectsDefault').style.display = 'none';
	document.getElementById('featuresEffectsSync').style.display = 'none';
	document.getElementById('featuresEffectsTransfers').style.display = 'none';
}

function swapDefault()
{
	hideAllEffects();
	document.getElementById('featuresEffectsDefault').style.display = 'block';
	document.getElementById('featureScreenshotBase').src = 'img/card-screenshot1.png';
}


function featuresListScrollBottom()
{
	document.getElementById('featuresListScrollUp').style.opacity = 1;
	document.getElementById('featuresListScrollDown').style.opacity = 0;
	document.getElementById('featuresListScrollArea').scrollTop = 500;
}

function featuresListScrollTop()
{
	document.getElementById('featuresListScrollUp').style.opacity = 0;
	document.getElementById('featuresListScrollDown').style.opacity = 1;
	document.getElementById('featuresListScrollArea').scrollTop = 0;
}

function showProgressAnimation()
{
	document.getElementById('featuresTwinProgressAnimation').innerHTML = '';
	var animation = document.createElement('img');
	animation.src = 'img/progress-bar-animation.gif';
	animation.width = '189';
	animation.height = '8';
	document.getElementById('featuresTwinProgressAnimation').appendChild(animation);
}
function hideProgressAnimation()
{
	document.getElementById('featuresTwinProgressAnimation').innerHTML = '';
}

function showPlacesPopup()
{
	document.getElementById('featuresPlacesPopup').style.display = 'block';
	setTimeout("document.getElementById('featuresPlacesPopup').className = 'popped'", 100);	
}
function hidePlacesPopup()
{
	document.getElementById('featuresPlacesPopup').className = '';
	setTimeout("document.getElementById('featuresPlacesPopup').style.display = 'none';", 100);
}

// Utility: Get Shift Key Status
// IE events don't seem to get passed through the function, so grab it from the window.

function testShift(evt) {
	var shift = false;
	if (! evt && window.event) {
		shift = window.event.shiftKey;
	} else if (evt) {
		shift = evt.shiftKey;
		if (shift) evt.stopPropagation(); // Prevents Firefox from doing shifty things
	}
	return shift;
}


function sendDownloadLink(subj, body)
{
	var email = document.getElementById('downloadLinkEmail').value;
	var dleFlag = document.getElementById('dleFlag').value;
	var urlEncodedEmail = encodeURI(email);	
	var subj = encodeURI(subj); 
	var body = encodeURI(body); 
		
	var xhr = new XMLHttpRequest();
	xhr.open('GET', '/bin/ajax-email-dl-link.php?app=transmit4&dleFlag=' + dleFlag + '&email=' + urlEncodedEmail + '&subj=' + subj + '&body=' + body, true);
	xhr.onreadystatechange = function () 
	{
		if ( xhr.readyState == 4 )
		{
			if ( xhr.status == 200 )
				console.log(xhr.responseText);
			else
				console.log("Error in xhr");
		}
	};
	xhr.send(null);
}

//console.log("Initialized");
