var tarotArray;

var URL_SERVERDATE      = "http://astrology.com/wdg/server_date.txt";
var URL_ASTROFEED       = "http://www.astrology.com/wdg/TAROTLOVE_TAROT/XX.xml";
var URL_ASTROFEED_TEST  = "http://www.daylateanddollarshort.com/misc/itarota/curler.php";

var URL_CALL_PREFIX = "tel://"; // or "callto://"

//
// RETRIEVING TAROT XML DATA
//

var feedXMLRequest;


function getAstroFeed( aPhase, aCards )
{
	startSpinAnim();
	
	var feedDirForPhase = ( aPhase == 0 ? "tarot" : "love_tarot" );
	var cardForPhase = 1*aCards.split("xxx")[aPhase];
	
	var theURL = URL_ASTROFEED;
	theURL = theURL.split("TAROTLOVE_TAROT").join( feedDirForPhase );
	theURL = theURL.split("XX").join( cardForPhase );
	
	if (( document.domain != "" ) && ( document.domain.indexOf("astrology.com") == -1 ))
		//theURL = URL_ASTROFEED_TEST + "?card=" + (1000*aPhase + cardForPhase );
		theURL = "curler.php?card=" + (1000*aPhase + cardForPhase );
	zapFeedXMLRequest( feedXMLRequest );
	
	feedXMLRequest = null;
	feedXMLRequest = new XMLHttpRequest();
	feedXMLRequest.onreadystatechange = receiveAstroFeed;
	
	feedXMLRequest.phase = aPhase;
	feedXMLRequest.cards = aCards;
	
	feedXMLRequest.open( "GET", theURL, true );
	feedXMLRequest.send( null );
}

function zapFeedXMLRequest( aRequest )
{
	if ( aRequest )
	{
		aRequest.onreadystatechange = null;
		aRequest.responseXML        = null;
		aRequest.responseText       = null;
		aRequest.readyState         = null;
		aRequest.status             = null;
		
		aRequest = null;
	}
}

function receiveAstroFeed()
{
	if ( feedXMLRequest.readyState == 4 ) // data request shows "loaded"
	{	
		stopSpinAnim();
		
		if (( feedXMLRequest.status == 200 ) && ( feedXMLRequest.responseXML ))
		// data request status is "OK"
		{
			appState = "normal";
			
			var theXML    = feedXMLRequest.responseXML;
			var theText   = feedXMLRequest.responseText;
			zapFeedXMLRequest( feedXMLRequest );
			
			processAstroFeed( feedXMLRequest.responseXML, "", feedXMLRequest.phase );
			if ( feedXMLRequest.phase == 0 )
				getAstroFeed( 1, feedXMLRequest.cards );
		}
		else
		{
			appState = "error:loading";
			
			zapFeedXMLRequest( feedXMLRequest );
			processNoAstroFeed();
			
			document.getElementById("splash-error").style.display = "block";
		}
	}
}

function gotAstroFeed()
{
	var theResult = false;
	
	if ( tarotArray && ( tarotArray.length > 1 ) && ( tarotArray[0].image ) && ( tarotArray[1].image ))
	{
		theResult = ( tarotArray[0].image.complete && tarotArray[1].image.complete );
	}
	
	return theResult;
}

function xcompleteSetup()
{
	if ( !( tarotArray[0].image.complete ) || !( tarotArray[1].image.complete ) )
	{
		var theProgress = ( 100*( ( new Date() ).getTime() - progTimeStamp )/10000 );
	
		document.getElementById("prog-ind").style.width = ( Math.min( 100, theProgress ) + "%" );
	
		if ( theProgress > 100 )
			document.getElementById("prog-ind").style.opacity = ( 0.75 + 0.25*Math.cos( ( theProgress - 100 ) * Math.PI / 30.0 ) );
	
		setTimeout( "completeSetup()", 0 );
	}
	else
	{
		updateTarotContents();
		
		if ( currPanel == 0 )
			startSlide(1);
	}
}

function processAstroFeed( aXML, aText, aPhase )
{
	var aIdx;
	var theTarotArray = aXML.getElementsByTagName("astrofeed");
	
	if ( aPhase == 0 )
		tarotArray = new Array();
	
	var theDate = new Date();
	var theDD   = theDate.getDate();
	theDD       = (( theDD < 10 ) ? '0' + theDD : theDD );
	var theMM   = theDate.getMonth() + 1;
    theMM       = (( theMM < 10 ) ? '0' + theMM : theMM );
	var theYYYY = theDate.getFullYear();
	theDate = theYYYY + "" + theMM + "" + theDD;
	
	for ( var aIdx = 0; aIdx < 2; aIdx++ ) // Hard-coding for two tarots; more would require layout changes.
	{
		tarotArray[aPhase] = new tarotObject
		(
			aIdx, // "id"
			aIdx, // "index"
			theTarotArray[0].getAttribute("name"), // "name"
			theDate, //"20071026", //theTarotArray[aIdx].getAttribute("date").split("/")[0],  // start date
			
			innerHTMLOfXMLObject( theTarotArray[0].getElementsByTagName("index"    )[0] ),
			innerHTMLOfXMLObject( theTarotArray[0].getElementsByTagName("title"    )[0] ),
			innerHTMLOfXMLObject( theTarotArray[0].getElementsByTagName("body"     )[0] ),
			innerHTMLOfXMLObject( theTarotArray[0].getElementsByTagName("promolink")[0] )
		);
	}
	
	tarotArray.sort( compareObjectIds );  // DEBUG: Should sort by sortOrder, but current XML doesn't give sortOrders. 
	                                      // Be sure to adjust "promo" sortOrders to come last.
}

function tarotObject( aId, aIdx, aName, aDate, aCardIdx, aCardTitle, aText, aPromoLink )
{
	this.id    = aId;
	this.index = aIdx;
	this.name  = aName;
	this.date  = aDate;
	
	this.cardIndex = 1*aCardIdx;
	this.cardTitle = aCardTitle;
	this.text      = aText;
	this.promoLink = aPromoLink;
	
	// URL: http://g.astrology.com/trt/xx/xxyyz.jpg (upright) and xxyyzr.jpg (reversed)
	// xx = deck id (see below)
	// yy = card id (00-77) (note the leading zero for single digit numbers)
	// z  = card size (0 = big, 1 = medium, 2 = small, 3 = tiny)
	// These images all have red (#660000) backgrounds.
	
	
	var theReverser = ( aCardIdx > 77 ? "r" : "" );
	if ( theReverser == "r" )
		this.cardTitle = this.cardTitle +",<span class='vis-in-portrait'><br /></span><span class='vis-in-landscape'> </span>Reversed";
	
	aCardIdx = aCardIdx % 78;
	if ( aCardIdx < 10 )
		aCardIdx = "0" + aCardIdx;
	
	this.image     = new Image();
	this.image.src = "http://g.astrology.com/trt/" + DECK_ID + "/" + DECK_ID + "" + aCardIdx + "" + CARD_SIZE_CODE + "" + theReverser + ".jpg";
}

function processNoAstroFeed()
{
}

function getElementsByClassName(oElm, strTagName, strClassName)
{
/*
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
*/
	var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	
	strClassName = strClassName.replace(/\-/g, "\\-");
	
	
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	
	for( var i = 0; i < arrElements.length; i++ )
	{
		oElement = arrElements[i];
		
		if ( oRegExp.test( oElement.getAttribute("class") )
			|| oRegExp.text( oElement.className ) )			 // DLDS Edit: changed 'oElement.className' to 
															 // 'oElement.getAttribute("class")', since original
															 // inexplicably failed for 'div's of class 'promoText'.
			arrReturnElements.push(oElement);
	}
	return (arrReturnElements)
}




//
// MISC UTILITIES
//

function compareObjectIds       ( aObj, bObj ) { return 1*aObj.id        - 1*bObj.id;        }
function compareObjectSortOrders( aObj, bObj ) { return 1*aObj.sortOrder - 1*bObj.sortOrder; }



//
// XML UTILITIES
//

function xmlObjectToString( aXML ) { return (new XMLSerializer()).serializeToString(aXML); }
function stringToXMLObject( aStr )
{
	var theParser = new DOMParser();
	
	return theParser.parseFromString( aStr, "text/xml" );
}
function innerHTMLOfXMLObject( aXML )
{
	aXML = xmlObjectToString( aXML );
	aXML = aXML.split(">");
	aXML.shift();
	aXML = aXML.join(">").split("<");
	aXML.pop();
	aXML = aXML.join("<");
	
	return aXML;
}