/**
 * TODO:
 *  _ Test and optimize for all required browsers
 *	_ Compress/optimize for delivery?
 */
 
var pbsPoll;
var amexComments;
var curQuestionID;

/**
 * domready event handler. Initializes everything.
 */
function onPageReady ( )
{
	// Define and setup poll
	pbsPoll = new PBSPoll({
		url : '/cgi-registry/poll/poll.pl' ,
		form : 'poll_form' ,
		update : 'poll_content' ,
		submitButton : 'poll_submit' ,
		onComplete : this.onPollSubmitted
	});
	
	// Define and setup comments
	amexComments = new AMEXComments({
		urlFlag:"/wgbh/amex/presidents/comments/flag.php",
		urlAdd:"/wgbh/amex/presidents/comments/add.php",
		updateAdd:"comments_add_result",
		updateFlag:"comments_flag_result",
		xmlPath:"pages/" , 
		formAdd : 'comments_add' ,
		submitButton : 'comments_submit' ,
		onComplete : this.onCommentAdded
	});
	
	checkLogin();
}

// Listen for domready event.
window.addEvent( 'domready' , onPageReady );

/**
 * Poll submitted event handler.
 */
function onPollSubmitted ( )
{
} 

function onCommentSubmitted ( )
{
	// Check if comment is too long
	if ( $( 'comments_form_commenttxt' ).getValue().length > 5000 )
	{
		alert( 'Your comment is too long. Please condense it and try again.' );
		return false;
	}
	// Check if comment is blank
	else if ( $( 'comments_form_commenttxt' ).getValue().length == 0 )
	{
		alert( 'You forgot to write something for your comment. Please try again.' );
		return false;
	}
	
	amexComments.addComment( curQuestionID );
}

/**
 * Displays the specified question's content below the Flash content
 * @param {String} pQuestionID      ID of selected question.
 * @param {String} pQuestionString  Question text to display in comment title.
 */
function displayQuestion ( pQuestionID , pQuestionString )
{
	if ( pQuestionID != undefined && pQuestionID != null && pQuestionID != '' )
	{
		curQuestionID = pQuestionID;
		
		// Display question's comments
		amexComments.loadComments( pQuestionID );
		
		// Set comment title
		$( 'comments_questionTitle' ).setHTML( pQuestionString );
		
		// update url w/ hash and pQuestionID so we can use that in Share elements
		window.location.hash = pQuestionID;
		
		checkLogin();
		
		doFix();
	}
}


// generic page update function for GA.  this way if the base url changes we can change it here rather than updating and recompiling flash
// flash passed in the action, podcast, bio, 
function updateAnalytics( action, arg1, arg2 )
{
	var ptUpdate;
	var baseRef = "/presidents/2008/questions/";
	switch( action )
	{
		// update w/ arg1 is link for these
		case "podcast":
		case "bio":
		case "postroll":
			ptUpdate = arg1;
			break;
		case "question":
			// update w/ arg1 is question ID 
			// create virtual folder reference
			ptUpdate = baseRef + arg1;
			break;
		case "clip":
			// update w/ arg1 is question ID, arg2 is clip title 
			// create virtual folder reference
			ptUpdate = baseRef + arg1 + "/" + arg2;
			break;
		case "clip_end":
			// update w/ arg1 is question ID, arg2 is clip title 
			ptUpdate = baseRef + arg1 + "/" + arg2 + "-complete";
			break;
		default:
			break;
	}
	pageTracker._trackPageview( ptUpdate );
}

function checkLogin ( ) 
{
	// If user is logged in..
	if ( Cookie.get( "amex.user_id" ) != undefined && 
	     Cookie.get( "amex.user_id" ) != false && 
	     curQuestionID != undefined && 
	     curQuestionID != '' )
	{
		// Show comment form
		$( 'loginRegister' ).set( { 'styles':{ 'display':'none' } } );
		$( 'submitComment' ).set( { 'styles':{ 'display':'block' } } );
		$( 'comments_login' ).set( { 'styles':{ 'display':'none' } } );
		$( 'comments_form' ).set( { 'styles':{ 'display':'block' } } );
		
		// Update form fields
		$( 'comments_add' ).user_id.value = Cookie.get( 'amex.user_id' );
		$( 'comments_add' ).video_id.value = curQuestionID; 
		$( 'comments_form_name' ).innerHTML = Cookie.get( "amex.user_name" );
		$( 'comments_form_initials' ).innerHTML = Cookie.get( "amex.user_initials" );
	}
	// If user isn't logged in...
	else if ( curQuestionID != undefined && curQuestionID != '' )
	{
		// Show login prompts
		$( 'loginRegister' ).set( { 'styles':{ 'display':'block' } } );
		$( 'submitComment' ).set( { 'styles':{ 'display':'none' } } );
		$( 'comments_login' ).set( { 'styles':{ 'display':'block' } } );
		$( 'comments_form' ).set( { 'styles':{ 'display':'none' } } );
		
		// Update login links with latest question id from hash
		updateLoginLinks();
	}
}

/**
 * Temporary method to fake a login.
 */
function login ( )
{
	Cookie.set( 'amex.user_id' , 'marcelray' );
	Cookie.set( 'amex.user_name' , 'Marcel Ray' );
	Cookie.set( 'amex.user_initials' , 'M.R.' );
	
	// Hide login prompts, show comment form
	$( 'loginRegister' ).set( { 'styles':{ 'display':'none' } } );
	$( 'submitComment' ).set( { 'styles':{ 'display':'none' } } );
	$( 'comments_login' ).set( { 'styles':{ 'display':'none' } } );
	$( 'comments_form' ).set( { 'styles':{ 'display':'block' } } );
	
	$( 'comments_form_name' ).innerHTML = Cookie.get( "amex.user_name" );
	$( 'comments_form_initials' ).innerHTML = Cookie.get( "amex.user_initials" );
}

/**
 * Updates all login links with latest question ID in the hash.
 */
function updateLoginLinks ( )
{
	var arrLoginLinks = getElementsByClassName( document , "a" , "loginRegisterLink" );
	
	// Loop through and update links
	var iLink = arrLoginLinks.length;
	var bareHref;
	while ( iLink-- )
	{
		bareHref = arrLoginLinks[ iLink ].href;
		hashIndex = bareHref.indexOf( '#' );
		if ( hashIndex >= 0)
		{
			bareHref = bareHref.substring( 0 , hashIndex );
		}
		arrLoginLinks[ iLink ].href = bareHref + window.location.hash;
	}
}

/**
 * Expands the specified comment to display it in its entirety.
 * @param {Object} pID   Comment ID.
 */
function expandComment( pID )
{
	// Hide preview block
	var previewBlock = document.getElementById( "copy_preview_c" + pID );
	previewBlock.style.display = "none";
	// Hide expand link
	var expandLink = document.getElementById( "expand_c" + pID );
	expandLink.style.display = "none";
	// Display full text block
	var fulltextBlock = document.getElementById( "copy_full_c" + pID );
	fulltextBlock.style.display = "block";
	// Display collapse link
	var expandLink = document.getElementById( "collapse_c" + pID );
	expandLink.style.display = "block";
}

/**
 * Collapses the specified comment back to preview mode.
 * @param {Number} pID   Comment ID.
 */
function collapseComment( pID )
{
	// Display preview block
	var previewBlock = document.getElementById( "copy_preview_c" + pID );
	previewBlock.style.display = "block";
	// Display expand link
	var expandLink = document.getElementById( "expand_c" + pID );
	expandLink.style.display = "inline";
	// Hide full text block
	var fulltextBlock = document.getElementById( "copy_full_c" + pID );
	fulltextBlock.style.display = "none";
	// Hide collapse link
	var expandLink = document.getElementById( "collapse_c" + pID );
	expandLink.style.display = "none";
}

function share( link ) 
{
	// get ref
    pageUrl = location.href;
	pageTitle = document.title;
	var info = null;
	// which link to add to?
	switch( link ) 
	{
		case "reddit":
			// todo
			info = redditInfo( pageUrl, pageTitle );
			break;		
		case "digg":
			info = diggInfo( pageUrl, pageTitle );
			break;
		case "slashdot":
			info = slashdotInfo( pageUrl );
			break;
		case "delicious":
			info = deliciousInto( pageUrl, pageTitle );
			break;
		case "stumbleupon":
			info = stumbleInto( pageUrl, pageTitle );
			break;
		case "technorati":
			info = technoratiInfo( pageUrl );
			break;
		case "facebook":
			info = facebookInfo( pageUrl, pageTitle );
			break;
	}
	// something is missed
	if( info != null ) 
	{
	   if( info.onclick == '') 
	   {
	       window.open( info.href );
	   }
	   else 
	   {
	       window.open( info.href,info.handle,'toolbar=no,width=700,height=400' );
	   }
	}
}

// FACEBOOK share
function facebookInfo( url, title )
{
	var info = new Object();
	info.handle = "facebook";
	info.href = 'http://www.facebook.com/sharer.php?u='+encodeURIComponent( url )+'&t='+encodeURIComponent( title ); 
	info.alt = "Facebook";
	info.onclick = "";
	return info;
}

// SLASHDOT share
function slashdotInfo( url ) 
{
	var info = new Object();
	info.text = "reddit"
	info.handle = "reddit";
	info.onclick = "";
	info.href = "http://slashdot.org/slashdot-it.pl?op=basic&url="+encodeURIComponent( url );
	return info;
}

// REDDIT share
function redditInfo( url, title ) 
{
	var info = new Object();
	info.text = "reddit"
	info.handle = "reddit";
	info.onclick = "";
	info.href = "http://reddit.com/submit?url="+encodeURIComponent( url )+"&title="+encodeURIComponent( title );
	return info;
}
// DIGG share
function diggInfo( url, title ) 
{
	var info = new Object();
	info.handle = "digg";
	info.text = "Digg";
	info.href = "http://digg.com/submit?phase=2&url="+encodeURIComponent( url )+"&title="+encodeURIComponent( title )+"&topic=2008_us_elections";
	info.onclick = "";
	info.alt = "Digg!";
	return info;
}
// DELICIOUS share
function deliciousInto( url, title )
{
	var info = new Object();
	info.handle = "del.icio.us";
	info.text = "del.icio.us";
	info.href = 'http://del.icio.us/post?v=4&noui&jump=close&url='+encodeURIComponent( url )+'&title='+encodeURIComponent( title );
	info.onclick = "";
	info.alt = "del.icio.us!";
	return info;
}
// STUMBLEUPON share
function stumbleInto( url, title )
{
	var info = new Object();
	info.handle = "stumbleupon";
	info.text = "Stumble It!";
	info.href = 'http://www.stumbleupon.com/submit?url='+encodeURIComponent( url )+'&title='+encodeURIComponent( title );
	info.onclick = "";
	info.alt = "Stumble It!";
	return info;
}
// TECHNORATI share	
function technoratiInfo( url ) 
{
	var info = new Object();
	info.handle = "technorati";
	info.text = "Technorati";
	info.href = "http://technorati.com/faves/?add="+encodeURIComponent( url );
	info.onclick = "";
	info.alt = "Technorati";
	return info;
}
// EMAIL to friend
function email() 
{
  	// using AMEX sendtofriend.  has a hidden SSI REFERER value in it
	url = "../../sendtofriend.html";
	window.open(url,'tell_friend','toolbar=no,width=605,height=380');
}

// update More about the presidents section
function updateMoreInfoSection( pQuestionID )
{
	//console.log( "updating MORE sectin for " + pQuestionID );
	var items = array();
	// Q0//		When is it OK to lie?  
		items[ 0 ] = [ "<li><a href=\"http://www.pbs.org/wgbh/amex/presidents/32_f_roosevelt/filmmore/ra_lendlease.html\"><em>FDR</em>: Lend-Lease</a></li>",
					"<li><a href=\"http://www.pbs.org/wgbh/amex/reagan/peopleevents/pande08.html\"><em>Reagan</em>: The Iran-Contra Affair</a></li>"
				  ];
		 //Q1 //	Who is the enemy?   
		items[ 1 ] = [ "<li><a href=\"http://www.pbs.org/wgbh/amex/carter/sfeature/sf_hostage.html\">Carter and the Iranian hostage crisis</a></li>",
				"<li><a href=\"http://www.pbs.org/wgbh/amex/reagan/filmmore/reference/primary/evil.html\">Reagan's \"evil empire\" speech</a></li>"
				];  
		// Q2 //	How influential is the first lady?		
		items[ 2 ] = ["<li><a href=\"http://www.pbs.org/wgbh/amex/eleanor/\">More about Eleanor Roosevelt</a></li>",
				"<li><a href=\"http://www.pbs.org/wgbh/amex/reagan/peopleevents/pande03.html\">More about Nancy Reagan</a></li>"
				];
		// Q3 // 	How to end a war?  		
		items[ 3 ] = [ "<li><a href=\"http://www.pbs.org/wgbh/amex/nuremberg/sfeature/sf_ww2.html\">More on World War II</a></li>",
				"<li><a href=\"http://www.pbs.org/wgbh/amex/vietnam/\"><em>Vietnam Online</em></a></li>"
				];
		// Q4 // Can the president abuse his power?
		items[ 4 ] = ["<li><a href=\"http://www.pbs.org/wgbh/amex/presidents/32_f_roosevelt/f_roosevelt_politics.html\">FDR and the Supreme Court</a></li>",
				"<li><a href=\"http://www.pbs.org/wgbh/amex/presidents/37_nixon/psources/ps_subpoena.html\">Nixon defends executive privilege</a></li>"
				];
			
	// strip the "p" off our question id to get a number		
	var pQID = parseInt( pQuestionID.substring( 1 ) );
	//console.log( "array of items " + items[ pQID ] );
	//console.log( " question id " + pQID );		
	var moreInfoHTML = "<ul>";
	moreInfoHTML += items[ pQID ][ 0 ];
	moreInfoHTML += items[ pQID ][ 1 ];
	moreInfoHTML += "</ul>";
	//udpate div
	$( "dyn_questions" ).innerHTML = moreInfoHTML;	
	//console.log( "more data " + moreInfHTML );
	//console.log ("for div  "+ $( "dyn_questions" ) );
		
}

/**
 * Written by Jonathan Snook, http://www.snook.ca/jonathan
 * Add-ons by Robert Nyman, http://www.robertnyman.com
 */

function getElementsByClassName(oElm, strTagName, strClassName)
{
	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.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements);
}

function parseXML(xml /* req.responseXML */) {
	var obj = { _text : "" };
	var child = xml.firstChild;
	while (child) {
		if (child.nodeName == "#text") {
			obj._text += child.nodeValue;
		} else if (child.nodeType == 1) {
			if (typeof obj[child.nodeName] == "undefined") {
				obj[child.nodeName] = [];
			}
			obj[child.nodeName][obj[child.nodeName].length] = parseXML(child);
		}
		child = child.nextSibling;
	}
	var att = xml.attributes;
	var i = 0;
	if (att) { // there are attributes
		for (var i = 0; i < att.length; i++) {
			obj[att[i].name] = att[i].value;
		}
	}
	if (obj._text.match(/^\s*$/)) {
		delete obj._text;
	}
	return obj;
}

