// Created By: Stewart Smith - WGBH Interactive
// for use with mootools v1.11

// include other js files
document.write('<script type="text/javascript" src="../../j/users-v1.1.js"></script>');
document.write('<script type="text/javascript" src="../../j/social.js"></script>');

// include the comments functionality
// uncommented by mitch_smith 80080508
 document.write('<script type="text/javascript" src="../j/_comments.js"></script>');

// commented out by mitch_smith 80080508
/*var amexComments = {
	addComment:function(){
		return;
	},
	loadComments:function(){
		return;
	}
}; */
var curQuestionID;

var presidents = {
	// nmaing conventions
	ncVidFormats: ['_qt', '_wm', '_flv', '_rm'],
	main_clip_info: {},
	now_playing_list: {},
	now_playing_order: {},
	now_playing_vid_group: '',
	now_playing_vid_name: '',
	now_playing_vid_id: '',
	accordian: {},	//handle to the accordian obj
	accordian_open: '',			//handle to the toggler of the open section

	// add an Fx.Scroll	obj for the window
	scroll_fx: new Fx.Scroll(window, {
		wait: 500,
		duration: 500,
		transition: Fx.Transitions.Quad.easeIn
	}),

	init: function(){
	
		if( $E('.main_clip_info') )
			presidents.init_main_clip_info();

		if( $('chapter_nav') )
			presidents.init_now_playing();

		if( $('prez_watch_nav') )
			presidents.init_prez_watch_nav();
			
		if( $('cnt_accordian') )
			presidents.init_accordian();

		if( $('social_bookmarking') ){
			amex.addCSS('../../c/social.css');
			SocialBookmarking.replaceDIV('social_bookmarking');
		}

		if( $('rate_it') )
			presidents.init_ratings();

		// Define and setup comments
//		if( 1 == 2 ){
			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:"/wgbh/amex/presidents/2008/pages/" , 
				formAdd : 'comments_add' ,
				submitButton : 'comments_submit' ,
				onComplete : this.onCommentAdded
			});
			disQuestion();
			checkLogin();
//		}

	},
// STEW start 03.20.2008



	init_ratings: function(){
		
	},



// STEW end 03.20.2008
	init_main_clip_info: function(){
		element = $E('.main_clip_info');
		presidents.now_playing_vid_id = element.getProperty('video_id');


//alert('hi: ' + element.getProperty('video_id'));


		presidents.main_clip_info['default'] = {
			h1_html: ( element.getFirst().getNext().getTag == 'h1' ) ? element.getFirst().getNext().getProperty('innerHTML') : $E('.main_clip_info h1 span.normal').getParent().getProperty('innerHTML'),
			clip_title: ( $E('span.clip_title', element) ) ? $E('span.clip_title', element).getText() : '',
			clip_duration: ( $E('span.clip_duration', element) ) ? $E('span.clip_duration', element).getText() : '',
			clip_blurb: ( $E('span.clip_blurb', element) ) ? $E('span.clip_blurb', element).getText() : ''
		};
		
		presidents.main_clip_info[0] = {
			h1_html: ( element.getFirst().getNext().getTag == 'h1' ) ? element.getFirst().getNext() : $E('.main_clip_info h1 span.normal').getParent(),
			clip_title: ( $E('span.clip_title', element) ) ? $E('span.clip_title', element) : element.appendChild( new Element('span').addClass('clip_title') ),
			clip_duration: ( $E('span.clip_duration', element) ) ? $E('span.clip_duration', element) : element.appendChild( new Element('span').addClass('clip_duration') ),
			clip_blurb: ( $E('span.clip_blurb', element) ) ? $E('span.clip_blurb', element) : element.appendChild( new Element('span').addClass('clip_blurb') )
		};
	},
	set_main_clip_info: function(vid_name){
		if(vid_name && presidents.now_playing_list[vid_name]){
			presidents.main_clip_info[0].h1_html.setHTML( presidents.now_playing_list[vid_name].h1_html );
			presidents.main_clip_info[0].clip_title.setHTML( presidents.now_playing_list[vid_name].clip_title );
			presidents.main_clip_info[0].clip_duration.setHTML( presidents.now_playing_list[vid_name].clip_duration );
			presidents.main_clip_info[0].clip_blurb.setHTML( presidents.now_playing_list[vid_name].clip_blurb );			
		}else{
			if( presidents.now_playing_vid_name != '' && presidents.now_playing_list[presidents.now_playing_vid_name]){
				// if an active video
				presidents.main_clip_info[0].h1_html.setHTML( presidents.now_playing_list[presidents.now_playing_vid_name].h1_html );
				presidents.main_clip_info[0].clip_title.setHTML( presidents.now_playing_list[presidents.now_playing_vid_name].clip_title );
				presidents.main_clip_info[0].clip_duration.setHTML( presidents.now_playing_list[presidents.now_playing_vid_name].clip_duration );
				presidents.main_clip_info[0].clip_blurb.setHTML( presidents.now_playing_list[presidents.now_playing_vid_name].clip_blurb );
			}else{
				// use the original page default
				presidents.main_clip_info[0].h1_html.setHTML( presidents.main_clip_info['default'].h1_html );
				presidents.main_clip_info[0].clip_title.setHTML( presidents.main_clip_info['default'].clip_title );
				presidents.main_clip_info[0].clip_duration.setHTML( presidents.main_clip_info['default'].clip_duration );
				presidents.main_clip_info[0].clip_blurb.setHTML( presidents.main_clip_info['default'].clip_blurb );
			}
		}
	},
	init_now_playing: function() {
		// ******************************************************
		// CHAPTER BLURBS: read and store the Now Playing list
		// ******************************************************
		var chapter_blurbs = $ES('.cnt_now_playing div');
		if ( chapter_blurbs.legth == 0 ) return;
		
		// get vid_group from id like current_reagan_01
		presidents.now_playing_vid_group = chapter_blurbs[0].id.slice(8, chapter_blurbs[0].id.length-3);
		//alert('presidents.now_playing_vid_group: ' + presidents.now_playing_vid_group + ' (' + presidents.now_playing_vid_group.length + ')');
		
		chapter_blurbs.each(function(element) {
			// get vid_name and play order from id like current_reagan_01
			var vid_name = element.id.slice(8, element.id.length);
			var play_order = presidents.get_play_order_from_href( element.id.slice(element.id.length-2, element.id.length) + '.html' );
			if( play_order.slice(0,1) == '0' ){
				play_order = play_order.slice(1,play_order.length);
			}
			//alert(presidents.now_playing_vid_group + ', <span class="normal"> Chapter ' + play_order + '</span>');
			presidents.now_playing_order[play_order] = vid_name;
			presidents.now_playing_list[vid_name] = {
				list_id: element.id,
				vid_name: vid_name,
				play_order: play_order,
				film_chapter: ( $E('p', element) ) ? $E('p', element).getText() : '',
/* 			2008-04-30 - mitch_smith@wgbh.org :
				h1_html: presidents.now_playing_vid_group + ', <span class="normal"> Chapter ' + play_order + '</span>', */
				h1_html: '<span class="normal"> Chapter: </span>',
				clip_title: ( $E('span.clip_title', element) ) ? $E('span.clip_title', element).getText() : '',
				clip_duration: ( $E('span.clip_duration', element) ) ? $E('span.clip_duration', element).getText() : '',
				clip_blurb: ( $E('span.clip_blurb', element) ) ? $E('span.clip_blurb', element).getText() : ''
			};
			
			// SAVE TO PLAYLIST link
			// id with 'np' for Now Playing
			var save_lnk = new Element('a').setProperty('id','np_' + vid_name).setText('Save').setProperty('href','#').addEvent('click', presidents.save_np_lnk_click);
			element.appendChild(save_lnk);
		});
		
		//alert('vid_name: ' + presidents.now_playing_list['reagan_03'].clip_title);

		// ********************************
		// CHAPTER NAV SQUARES
		// ********************************
		var chapter_nav = $$('#chapter_nav a');
		chapter_nav.each(function(element) {
			// replace box imgs with a span
//			var chapter_nav_lnk = new Element('span').setHTML('&nbsp;');
			// set data vars on each link
			var aryH1 = element.getFirst().alt.split(': ');
			element.h1_html = aryH1[0] + ', <span class="normal">' + aryH1[1] + '</span>';
			element.play_order = presidents.get_play_order_from_href(element.href);
			element.vid_name = aryH1[0].toLowerCase() + '_' + element.play_order; // with leading zero
			
			// add h1_html to now_playing_list for main_clip_info obj
			// presidents.now_playing_list[element.vid_name].h1_html = element.h1_html;

			// the active chapter image has no class
			if( !element.getFirst().hasClass('roll') ){
				//alert('NOW PLAYING: ' + element.getFirst().alt);
//				chapter_nav_lnk.addClass('active');
				element.addClass('active');
				presidents.now_playing_vid_name = element.vid_name;
			}
			// strip leading zero
			if( element.play_order.slice(0,1) == '0' ){
				element.play_order = element.play_order.slice(1,1);
			}

//			element.empty(); // remove img
//			element.appendChild(chapter_nav_lnk); // add span
			

			element.addEvent('mouseenter', function(e){
				presidents.set_main_clip_info(this.vid_name);
			});
			element.addEvent('mouseleave', function(e){
				presidents.set_main_clip_info();
			});
			/*
			element.addEvent('click', function(e){
				event = new Event(e);
				event.stop();
				try{ window.location = this.linkto; }catch(e){}
			});
			*/
		});
	},
	get_play_order_from_href: function(thisHREF){
		if( !thisHREF ) return '';
		// strip any vid format info from link
		presidents.ncVidFormats.each(function(element) {
			thisHREF = thisHREF.replace( new RegExp(element+'\.'), '.' );
		});
		return thisHREF.slice(thisHREF.length-7, thisHREF.length-5);
	},
	save_np_lnk_click: function(e) {
		e = new Event(e).stop();
		alert(this.id);
	},
	init_prez_watch_nav: function() {
		$ES('.righty img', 'prez_watch_nav').each( function(element){
			var isActive = false;
			element.title = '';
			if( element.getParent().getTag() == 'a' ){
				// the vids ARE online
				if( element.getParent().getPrevious() ){
					if( element.getParent().getPrevious().getTag() != 'h2' ){
						// if the link doesn't already have an h2 in front - add it
						new Element('h2').setHTML( element.alt ).addClass('hide').addClass('oneline').injectBefore( element );
					}else{
						// if the link already has an h2 in front - add active class and don't add events
						isActive = true;
						element.getParent().getPrevious().addClass('active');
					}
				}else{
					// if there is a link but no previous elem then vid is first in the list and not the active group
					new Element('h2').setHTML( element.alt ).addClass('hide').addClass('oneline').injectBefore( element );
				}

			}else{
				// the vids are NOT online
				var aryAlt = element.alt.split(/\s+/);
				var tmpHTML = aryAlt[0] + '<br /><span>';
				for( var i=1; i < aryAlt.length; i++){
					tmpHTML += aryAlt[i] + ' ';
				}
				tmpHTML = tmpHTML.trim() + '</span>';
				new Element('h2').setHTML( tmpHTML ).addClass('hide').injectBefore( element );
			}

			// hide and show the h2 on mouseover and mouseout for not active
			if ( !isActive ){
				element.addEvent('mouseover', function(e){
					new Element(this).getPrevious().toggleClass('hide');
				});
				element.addEvent('mouseout', function(e){
					new Element(this).getPrevious().toggleClass('hide');
				});
			}

		});
	},
	init_accordian: function(){
		// create the accordian
		presidents.accordian = new Accordion('h3.toggler', 'div.toggle_section', {
			display: false,
			alwaysHide: true,
			onComplete: function(e){
				// if all sections closed scroll to top
				var allClosed = true;
				$ES('div.toggle_section', 'cnt_accordian').each( function(element){
					if( element.getStyle('visibility') != 'hidden' ){
						allClosed = false;
					}
				});
				if( allClosed ){
					presidents.scroll_fx.toTop();
					presidents.accordian_open = '';
				}else{
					presidents.scroll_fx.scrollTo( 0, presidents.accordian_open.getTop() );
				}
			},
			onActive: function(toggler, element){
				toggler.addClass('active');
				presidents.accordian_open = toggler;
			},
			onBackground: function(toggler, element){
				toggler.removeClass('active');
			}
		}, $('cnt_accordian'));

	}

};// end presidents obj

// **********************************
// **********************************
function disQuestion(){
//	element = $E('.main_clip_info');
//	presidents.now_playing_vid_id = element.getProperty('video_id');


//	alert(presidents.now_playing_vid_id);


	if( presidents.now_playing_vid_id )
		displayQuestion( presidents.now_playing_vid_id, users.display_name );
}


window.addEvent('domready', presidents.init);
window.addEvent('load', disQuestion);
// **********************************
// **********************************

// functions from the RoguePDX dase.js file

function onCommentSubmitted ( ){
	var err = false;
	var strOut = ''; 
	// Check if comment is too long
	if ( $( 'comments_form_commenttxt' ).getValue().length > 5000 ){
		strOut = 'Your comment is too long. Please condense it and try again.';
		err = true;
	}else if ( !err && $( 'comments_form_commenttxt' ).getValue().length == 0 ){
	// Check if comment is blank
		strOut = 'You forgot to write something for your comment. Please try again.';
		err = true;
	}
	if( err ){
		alert( strOut );
	}else{
		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 form fields
		$( 'comments_add' ).user_id.value = '';
		$( 'comments_add' ).video_id.value = ''; 
		$( 'comments_form_name' ).setHTML = '';
		$( 'comments_form_initials' ).setHTML = '';
		$( 'comments_questionTitle' ).setHTML('');
		
		// Update login links with latest question id from hash
		updateLoginLinks();
	}
}

/**
 * Updates all login links with latest question ID in the hash.
 */
function updateLoginLinks ( )
{
//	var arrLoginLinks = getElementsByClassName( document , "a" , "loginRegisterLink" );
	var arrLoginLinks = $$( '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";
}


// 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');
}

// Written by Jonathan Snook, http://www.snook.ca/jonathan
// Add-ons by Robert Nyman, http://www.robertnyman.com
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;
}
