// PORTIONS COPYRIGHT (c) 2007, DON MCCONNELL, DAY LATE & DOLLAR SHORT SOFTWARE
//
// All persons are free to use this file for the purposes of learning
// iPhone application operation. However, wholesale duplication of code
// should be acknowledged with the above copyright notice, as well as
// a visible link to the Day Late & Dollar Short web site:
//
//            http://www.daylateanddollarshort.com


var appState  = "loading";
var appOrient = "portrait";

var currPanel = 0;


var domGlobals;
var tarotType;
var textState;
var infoState;

/************************
WINDOW SIZE / ORIENTATION
************************/
var currWinW = 0;
var currWinH = 0;


function hideAddressBar() { setTimeout( "window.scrollTo(0,1)", 0 ); }


function changeOrientation() // called by <body "onorientationchange">
{ handleResize(); }

function handleResize()
{
	if ( true ) //window.innerWidth != currWinW )
	{
		if (( window.orientation == undefined ) || ( window.orientation % 180 == 0 ))
			setOrientation("portrait");
		else
			setOrientation("landscape");
		
		currWinW = window.innerWidth;
		currWinH = window.innerHeight;
		
		if ( tarotArray )
			updateTarotContents();
	}
}

function clickOrienter( aId ) { setOrientation( aId.split("-")[1] ); }
function setOrientation( aOrient )
{
	appOrient = aOrient;
	document.body.setAttribute( "orient", appOrient );
	
	hideAddressBar();
}

function  widthForOrientation( aOrient ) { return ( aOrient == "portrait" ? 320 : 480 ); }
function heightForOrientation( aOrient ) { return ( aOrient == "portrait" ? 416 : 268 ); }

function adjustSize()
{
	if ( window.innerWidth > 320 )
		resizeInnerTo( 320, 416 );
}

function resizeInnerTo( w, h )
{
	var inW = window.innerWidth;
	var inH = window.innerHeight;
	
	window.resizeBy( w - inW, h - inH );
}



/******************
MISCELLANEOUS SETUP
******************/

function setCopyrightYear()
{
	var theCopySpan = document.getElementById("copy-year");
	
	if ( theCopySpan )
		theCopySpan.innerHTML = ( new Date() ).getFullYear();
}
function setVersion()
{
	document.getElementById("version").innerHTML = ITAROT_VERSION;
}

function startSpinAnim() { } //document.getElementById("splash-loading").style.display = "block"; }
function stopSpinAnim()  { } //document.getElementById("splash-loading").style.display = "none";  }

function setupDOMGlobals()
{
	var aIdx, rIdx, crIdx;
	
	domGlobals = new Object();
	
	domGlobals.clipper = document.getElementById("clipper");
	domGlobals.slipper = document.getElementById("slipper");
	
	domGlobals.slipperStyle = domGlobals.slipper.style;
	
	domGlobals.panes = new Object();
		domGlobals.panes["splash"] = document.getElementById("pane-splash");
		domGlobals.panes["tarot" ] = document.getElementById("pane-tarot" );
	
	domGlobals.tbControls = new Object();
		domGlobals.tbControls["dailyTab"] = document.getElementById("tbtab-daily");
		domGlobals.tbControls[ "loveTab"] = document.getElementById("tbtab-love" );
		
		domGlobals.tbControls["infoBtn" ] = document.getElementById("tbbtn-info");
		domGlobals.tbControls["doneBtn" ] = document.getElementById("tbbtn-done");
		
		domGlobals.tbControls["readBtn" ] = document.getElementById("tbbtn-read");
		domGlobals.tbControls["hideBtn" ] = document.getElementById("tbbtn-hide");
	
	domGlobals.popBoxes = new Object();
		domGlobals.popBoxes["text"] = document.getElementById("pop-text");
		domGlobals.popBoxes["info"] = document.getElementById("pop-info");
	
	domGlobals.contents = new Object();
		domGlobals.contents["card"] = document.getElementById("content-card");
		domGlobals.contents["head"] = document.getElementById("content-head");
		domGlobals.contents["text"] = document.getElementById("content-text");
		domGlobals.contents["date"] = document.getElementById("content-date");
		
		domGlobals.contents["card-0"] = document.getElementById("content-card-0");
		domGlobals.contents["card-1"] = document.getElementById("content-card-1");
		domGlobals.contents["head-0"] = document.getElementById("content-head-0");
		domGlobals.contents["head-1"] = document.getElementById("content-head-1");
		domGlobals.contents["text-0"] = document.getElementById("content-text-0");
		domGlobals.contents["text-1"] = document.getElementById("content-text-1");
		
		domGlobals.contents["scrollNotice"] = document.getElementById("scrollNotice");
}

var imagesToLoad, imagesLoadCount, imageLoadTimeStamp;
function startLoadImages()
{
	imageLoadTimeStamp = ( new Date() ).getTime();
	imageLoadCount     = 0;
	
	document.getElementById("prog-splash"    ).style.display = "block";
	document.getElementById("prog-splash-ind").style.width   =    "0%";

	var srcArray = new Array
	(
		"images/progbox.png",
		"images/progind.png",
		
		"images/buttons/btn-bg-0.png",
		"images/buttons/btn-bg-1.png",
		"images/buttons/inset-btn-bg-0.png",
		"images/buttons/inset-btn-bg-1.png",
		"images/buttons/sml-inset-btn-bg-0.png",
		"images/buttons/sml-inset-btn-bg-1.png",
		"images/buttons/inset-rtab-bg-0.png",
		"images/buttons/inset-rtab-bg-1.png",
		"images/buttons/inset-ltab-bg-0.png",
		"images/buttons/inset-ltab-bg-1.png",
		"images/buttons/phone.png",
		
		"images/logos/astrologo-139x42.png",
		"images/logos/ivillogo-80x27.png"
	);
	
	imagesToLoad = new Array();
	for ( var aIdx = 0; aIdx < srcArray.length; aIdx++ )
	{
		imagesToLoad[aIdx]        = new Image();
		imagesToLoad[aIdx].src    = srcArray[aIdx];
	}
}

function imagesLoaded()
{
	var imagesLoaded = true;
	var imageCount = 0;
	
	for ( var aIdx = 0; aIdx < imagesToLoad.length; aIdx++ )
		imageCount += ( imagesToLoad[aIdx].complete ? 1 : 0 );
	
	if ( imageCount > imageLoadCount )
	{
		imageLoadCount = imageCount;
		imageLoadTimeStamp = ( new Date() ).getTime();
	}
	
	updateProgressIndicator( "prog-splash-ind", 100*imageCount / imagesToLoad.length );
	
	return ( imageCount == imagesToLoad.length );
}

function updateTarotContents()
{
	var theIdx = ( tarotType == "daily" ? 0 : 1 );
	var nonIdx = ( 1 - theIdx );
	var aIdx;
	
	for ( aIdx = 0; aIdx < 2; aIdx++ )
	{
		domGlobals.contents["card-"+aIdx].style.backgroundImage = "url("+tarotArray[aIdx].image.src+")";
		domGlobals.contents["head-"+aIdx].innerHTML             = tarotArray[aIdx].cardTitle;
		domGlobals.contents["text-"+aIdx].innerHTML             = tarotArray[aIdx].text;
		
		domGlobals.contents["head-"+aIdx].style.display = "block";
		domGlobals.contents["text-"+aIdx].style.display = "block";
	}
	
	domGlobals.contents["date"].innerHTML    = dateFromYYYYMMDD( tarotArray[theIdx].date );
	domGlobals.contents["head"].style.height = 
		Math.max( 
			domGlobals.contents["head-0"].offsetHeight,
			domGlobals.contents["head-1"].offsetHeight
			) + "px";
	
	
	
	var maxTextHeight =
		( appOrient == "portrait" ? 315 : 167 ) 
		- domGlobals.contents["head"].offsetHeight
		+ 24;
	domGlobals.contents["text"].style.maxHeight = maxTextHeight + "px";
	
	var textEndHeight = "0";
	if ( textState )
		textEndHeight = domGlobals.contents["text-"+theIdx].offsetHeight;
	var willNeedToScroll = ( textEndHeight > maxTextHeight );
	textEndHeight = Math.min( textEndHeight, maxTextHeight );
	domGlobals.contents["text"].style.height = textEndHeight + "px";
	
	domGlobals.contents["scrollNotice"].style.opacity = ( willNeedToScroll ? 1.0 : 0.0 );

	domGlobals.contents["card-"+theIdx].style.opacity = 1.0;
	domGlobals.contents["card-"+nonIdx].style.opacity = 0.0;
	domGlobals.contents["head-"+theIdx].style.opacity = 1.0;
	domGlobals.contents["head-"+nonIdx].style.opacity = 0.0;
	domGlobals.contents["text-"+theIdx].style.opacity = 1.0;
	domGlobals.contents["text-"+nonIdx].style.opacity = 0.0;
	
	domGlobals.contents["text-"+nonIdx].style.display = "none";
	
	domGlobals.tbControls["readBtn"].style.opacity = ( textState ? 0.0 : 1.0 );
	domGlobals.tbControls["hideBtn"].style.opacity = ( textState ? 1.0 : 0.0 );
	
	//hideAddressBar();
}

function clickToolbar( aBtn )
{
	var theId = aBtn.id.split("-")[1];
	
	switch ( theId ) 
	{
		case "daily":
		case "love":  clickTarotType( theId ); break;
		
		case "info":
		case "done": toggleInfo(); break;
		
		case "read":
		case "hide":
		case "card": toggleText(); break;
	}
}

function clickTarotType( aType )
{
	if ( tarotType == aType )
		return;
	
	setTarotType( aType );
	
	setStateForElement( tarotType == "daily", domGlobals.tbControls["dailyTab"] );
	setStateForElement( tarotType ==  "love", domGlobals.tbControls[ "loveTab"] );
	
	domGlobals.contents["text-0"].style.display = "block";
	domGlobals.contents["text-1"].style.display = "block";
	
	var maxTextHeight =
		( appOrient == "portrait" ? 315 : 167 ) 
		- domGlobals.contents["head"].offsetHeight
		+ 24;
	domGlobals.contents["text"].style.maxHeight = maxTextHeight + "px";
	
	var textStartHeight = domGlobals.contents["text"].offsetHeight;
	var textEndHeight   = "0";
	
	if ( textState )
	{
		textEndHeight = ( tarotType == "daily"
			? domGlobals.contents["text-0"].offsetHeight
			: domGlobals.contents["text-1"].offsetHeight );
	}
	var willNeedToScroll = ( textEndHeight > maxTextHeight );
	textEndHeight = Math.min( textEndHeight, maxTextHeight );
	
	startMultiAnim(
		5,
		new Array(
			domGlobals.contents["card-0"],
			domGlobals.contents["card-1"],
			domGlobals.contents["head-0"],
			domGlobals.contents["head-1"],
			domGlobals.contents["text-0"],
			domGlobals.contents["text-1"],
			domGlobals.contents["text"],
			domGlobals.contents["text"],
			domGlobals.contents["scrollNotice"] ),
		new Array(
			"opacity",
			"opacity",
			"opacity",
			"opacity",
			"opacity",
			"opacity",
			"height",
			"scrollTop",
			"opacity" ),
		new Array(
			( tarotType == "daily" ? "0" : "1" ),
			( tarotType == "daily" ? "1" : "0" ),
			( tarotType == "daily" ? "0" : "1" ),
			( tarotType == "daily" ? "1" : "0" ),
			( tarotType == "daily" ? "0" : "1" ),
			( tarotType == "daily" ? "1" : "0" ),
			textStartHeight,
			domGlobals.contents["text"].scrollTop,
			domGlobals.contents["scrollNotice"].style.opacity
			),
		new Array(
			( tarotType == "daily" ? "1" : "0" ),
			( tarotType == "daily" ? "0" : "1" ),
			( tarotType == "daily" ? "1" : "0" ),
			( tarotType == "daily" ? "0" : "1" ),
			( tarotType == "daily" ? "1" : "0" ),
			( tarotType == "daily" ? "0" : "1" ),
			textEndHeight,
			0,
			( willNeedToScroll ? 1.0 : 0.0 )
			),
		new Array( "", "", "", "", "", "", "px", "", "" ),
		"updateTarotContents()" );
}

function setTarotType( aType  ) { tarotType = aType;  }
function setTextState( aState ) { textState = aState; }
function setInfoState( aState ) { infoState = aState; }

function toggleInfo()
{
	setInfoState( !infoState );
	prepInfoAnim(  infoState );
	
	startMultiAnim(
		10,
		new Array( domGlobals.popBoxes["info"] ),
		new Array( "top" ),
		new Array( ""+( infoState ? 100 : 0 ) ),
		new Array( ""+( infoState ? 0 : 100 ) ),
		new Array( "%" ),
		"postInfoAnim()" );
}

function postInfoAnim() {}

function toggleText()
{
	setTextState( !textState );
	prepTextAnim( textState );
	
	var textType = ( tarotType == "daily" ? "text-0" : "text-1" );
	
	
	var maxTextHeight =
		( appOrient == "portrait" ? 315 : 167 ) 
		- domGlobals.contents["head"].offsetHeight
		+ 24;
	domGlobals.contents["text"].style.maxHeight = maxTextHeight + "px";
	
	var textStartHeight = domGlobals.contents["text"].offsetHeight;
	var textEndHeight   = "0";
	
	if ( textState )
		textEndHeight = domGlobals.contents[textType].offsetHeight;
	var willNeedToScroll = ( textEndHeight > maxTextHeight );
	textEndHeight = Math.min( textEndHeight, maxTextHeight );
	
	startMultiAnim(
		10,
		new Array(
			domGlobals.contents["text"],
			domGlobals.tbControls["readBtn"],
			domGlobals.tbControls["hideBtn"],
			domGlobals.contents["text"],
			domGlobals.contents["scrollNotice"] ),
		new Array(
			"height",
			"opacity",
			"opacity",
			"scrollTop",
			"opacity" ),
		new Array(
			""+textStartHeight,
			""+( textState ? 1 : 0 ),
			""+( textState ? 0 : 1 ),
			""+domGlobals.contents["text"].scrollTop,
			""+domGlobals.contents["scrollNotice"].style.opacity ),
		new Array(
			""+textEndHeight,
			""+( textState ? 0 : 1 ),
			""+( textState ? 1 : 0 ),
			""+0,
			""+( willNeedToScroll ? 1.0 : 0.0 ) ),
		new Array( "px", "", "", "", "" ),
		"postTextAnim()" );
}

function prepInfoAnim( aInfoState ) {
	setStateForElement(  aInfoState, domGlobals.tbControls["infoBtn"] );
	setStateForElement( !aInfoState, domGlobals.tbControls["doneBtn"] );
}

function prepTextAnim( aTextState ) {
	setStateForElement(  aTextState, domGlobals.tbControls["readBtn"] );
	setStateForElement( !aTextState, domGlobals.tbControls["hideBtn"] );
}
function postTextAnim()
{
	setStateForElement( false, domGlobals.tbControls["readBtn"] );
	setStateForElement( false, domGlobals.tbControls["hideBtn"] );
}


function startSlide( aDir )
{
	if ( appState != "normal" )
		return;
	
	startMultiAnim( 
		10,
		new Array ( domGlobals.slipper ),
		new Array ( "left" ),
		new Array ( ""+(-100*  currPanel          ) ),
		new Array ( ""+(-100*( currPanel + aDir ) ) ),
		new Array ( "%" ),
		"" );
}




var multiAnim = { timeout:null, counter:0, maxCounter:0, elements:null, props:null, startVals:null, endVals:null, valUnits:null, callback:null };

function startMultiAnim( aCount, aElems, aProps, aStartVals, aEndVals, aValUnits, aCallBack )
{
	multiAnim.counter    = -1;
	multiAnim.maxCounter = aCount;
	
	multiAnim.elems     = aElems;
	multiAnim.props     = aProps;
	multiAnim.startVals = aStartVals;
	multiAnim.endVals   = aEndVals;
	multiAnim.valUnits  = aValUnits;
	
	multiAnim.callback  = aCallBack;
	
	
	multiAnim.timout = setTimeout( "stepMultiAnim()", 0 );
}

function stepMultiAnim()
{
	multiAnim.counter += 1;
	
	var theC = ( 1 - Math.cos( Math.PI * multiAnim.counter / multiAnim.maxCounter ) )/2.0;
	
	for ( var aIdx = 0; aIdx < multiAnim.elems.length; aIdx++ )
	{
		if ( multiAnim.props[aIdx] == "scrollTop" )
			multiAnim.elems[aIdx].scrollTop =
				( 1*multiAnim.startVals[aIdx] + ( 1*multiAnim.endVals[aIdx] - 1*multiAnim.startVals[aIdx] )*theC ) + multiAnim.valUnits[aIdx];
		else
			multiAnim.elems[aIdx].style[multiAnim.props[aIdx]] = 
				( 1*multiAnim.startVals[aIdx] + ( 1*multiAnim.endVals[aIdx] - 1*multiAnim.startVals[aIdx] )*theC ) + multiAnim.valUnits[aIdx];
	}
	if ( multiAnim.counter < multiAnim.maxCounter )
		multiAnim.timeout = setTimeout( "stepMultiAnim()", 0 );
	else
		multiAnim.timeout = setTimeout( multiAnim.callback, 0 );
}

var popAnim = { timeout:null, counter:0, direction:0, popper:null, animProp:null, startVal:-1, endVal:-1, valUnit:null, callback:null };

function startPopAnim( aDir, aPop, aAnimProp, aMinVal, aMaxVal, aValUnit, aCallBack )
{
	popAnim.counter   = 0;
	
	popAnim.direction = aDir;
	popAnim.popper    = aPop;
	popAnim.animProp  = aAnimProp;
	popAnim.startVal  = ( aDir == 1 ? aMinVal : aMaxVal );
	popAnim.endVal    = ( aDir == 1 ? aMaxVal : aMinVal );
	popAnim.valUnit   = aValUnit;
	popAnim.callback  = aCallBack;
	
	popAnim.popper.style[popAnim.animProp] = ( popAnim.startVal + popAnim.valUnit );
	
	popAnim.timeout = setTimeout( "stepPopAnim()", 0 );
}

function stepPopAnim()
{
	popAnim.counter += 1;
	
	var theC = ( 1 - Math.cos( Math.PI * popAnim.counter / 10.0 ) )/2.0;
	
	popAnim.popper.style[popAnim.animProp] = ( popAnim.startVal + ( popAnim.endVal - popAnim.startVal )*theC ) + popAnim.valUnit;
	
	if ( popAnim.counter < 10 )
		popAnim.timeout = setTimeout( "stepPopAnim()", 0 );
	else
		popAnim.timeout = setTimeout( popAnim.callback, 0 );
}

function stepInfoAnim()
{
	infoAnim.counter += 1;
	
	var theC = ( 1 - Math.cos( Math.PI*infoAnim.counter / 10.0 ) )/2.0;
	
	infoAnim.popper.style.top = ( 100*( infoAnim.direction == 1 ? 1-theC : theC ) ) + "%"
	
	if ( infoAnim.counter < 10 )
		infoAnim.timeout = setTimeout( "stepInfoAnim()", 0 );
	
	else
	{
		appState = "normal";
		
		if ( infoAnim.direction == -1 )
			infoAnim.popper.style.top = "100%";
		else
			infoAnim.popper.style.top = "0";
	}
}



/***********
UI UTILITIES
***********/

function setSlipperForPanel( aPanel ) { domGlobals.slipperStyle.left = -100*currPanel + "%"; } //( -1*currPanel*currentPanelWidth() ) +"px"; }

function setStateForElement( aState, aElement )
{
	var bState = ( aState ? "-off" : "-onn" );
	aState = ( aState ? "-onn" : "-off" );
	
	aElement.className = replaceAll( aElement.className, bState, aState );
}

function updateProgressIndicator( aId, aPercent )
{
	aPercent += 100 * Math.min( 3000, ( new Date() ).getTime() - imageLoadTimeStamp ) / 3000.0 / imagesToLoad.length;
	aPercent = Math.min( aPercent, 100 );
	
	document.getElementById(aId).style.width = ( aPercent + "%" );
}


/****************
GENERIC UTILITIES
****************/

function replaceAll( aSrcStr, aFindStr, aReplaceStr ) { return aSrcStr.replace( new RegExp( aFindStr, "g" ), aReplaceStr ); }

function dateFromYYYYMMDD( aYYYYMMDD )
{
	var theY = 1*aYYYYMMDD.substring( 0, 4 );
	var theM = 1*aYYYYMMDD.substring( 4, 6 );
	var theD = 1*aYYYYMMDD.substring( 6, 8 );
	
	var theMonths = new Array( "Zer", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
	
	return theD + " " + theMonths[theM];
}

function goToForm( aURL ) { window.open( aURL ); }
function goToSite( aSiteDotCom ) {
	
	switch ( aSiteDotCom )
	{
		case "www.astrology.com": aSiteDotCom += ASTROLOGY_OMNITURE_CODE; break;
		case "www.ivillage.com":  aSiteDotCom += IVILLAGE_OMNITURE_CODE;  break;
		
		case "www.daylateanddollarshort.com":
		case "www.iconicon.net":
			aSiteDotCom += DLDS_SENDER_CODE;
			break;
	}
	
	aSiteDotCom  = "http://"+aSiteDotCom;
	
	window.open( aSiteDotCom );
}