/**
 * CollegePublisher article transforming javascript
 * Written by Michael Schultz (mjschultz{at}gmail{dot}com)
 *            Paul Hinze (paul{dot}t{dot}hinze{at}gmail{dot}com)
 * 
 * Licensed under Creative Commons Attribution-ShareAlike 3.0
 * http://creativecommons.org/licenses/by-sa/3.0/
 *
 * You are free to share or adapt this work givin you attribute the
 * author(s) and release your alterations under the same license.
 */

/* helper functions from various other sources */
function getElementsByClassName (root, name) {
	var results = new Array();
	var elems = root.getElementsByTagName("*");
	for (var i=0; i<elems.length; i++) {
		if (elems[i].className.indexOf(name) != -1) {
			results[results.length] = elems[i];
		}
	}
	return results;
};

function validCssName(string) {
	return string.toLowerCase().replace(/[^a-zA-Z 0-9]+/g,').replace(/\s*/g,');
}

/* Image Hackery */
/* set the story_convert variable to on, allows conversion to be disabled   *
 * on a story by story basis. (Just set story_convert = 'off'; in the story */
story_convert = 'on';

/**
 * Main function to transform CP article images which are in <table> tags
 * into more semantic <div> tags with descriptive classes for credit
 * and captions.
 * Call fixArticleImages() after the story is on the page (so sometime after
 * [[data.Article.StoryTextWebPage]], code as below should suffice:
 * <script type="text/javascript">
 *   if (story_convert != 'off') {
 *     fixArticleImages();
 *   }
 * </script>
 */
function fixArticleImages() {
	
	if ( document.all || document.getElementById ) {
		// we only care about the contents of the story
		storyElt    = document.getElementById('cp_story_text');
		// now we only care about the table in the story
		tableArray  = storyElt.getElementsByTagName('table');
		img_count   = tableArray.length-1;
		img_showing = 0;

		if ( img_count < 1 ) return;
		
		// initialize all the arrays to the correct size.
		imgArray     = new Array(img_count);
		creditArray  = new Array(img_count);
		creditLinks  = new Array(img_count);
		captionArray = new Array(img_count);
		captionArray = new Array(img_count);
		linkArray    = new Array(img_count);

		// skip the first wrapper table, but get all the info for images
		for ( var i = 1; i < tableArray.length; i++ ) {
			myTable = tableArray[i];
			// first two are inherent to a media instance
			linkArray[i-1]    = myTable.getElementsByTagName('a')[0].href;
			imgArray[i-1]     = myTable.getElementsByTagName('img')[0].src;
			// grab the credit if it exists
			if ( getElementsByClassName(myTable, 'mediacredit').length > 0 ) {
				// ok, grab the mediaCredit element
				var mediaCredit = getElementsByClassName(myTable, 'mediacredit')[0];
				var mediaCreditLinks = mediaCredit.getElementsByTagName('a');
				if ( mediaCreditLinks.length > 0 ) {
					// credited name
					creditArray[i-1] = mediaCreditLinks[0].innerHTML;
					// link to profile
					creditLinks[i-1] = mediaCreditLinks[0].href;
				}
				else {
					// just credited name
					creditArray[i-1] = mediaCredit.innerHTML;
					creditLinks[i-1] = "";
				}
			}
			else {
				// no credit info
				creditArray[i-1] = "";
				creditLinks[i-1] = "";
			}

			// similar (but simpler) logic for captions
			var mediaCaptions = getElementsByClassName(myTable, 'caption');
			if ( mediaCaptions.length > 0 ) {
				captionArray[i-1] = mediaCaptions[0].innerHTML;
			}
			else {
				captionArray[i-1] = "";
			}
		}

		/* at this point we should have all the data to rebuild the page *
		 * so, Phase I is complete, now we will remove the table and     *
		 * build more semantic code, thus allowing thickbox to live!     */

		// tableArray[0].innerHTML = "";
		/*
		 * The above code produces a runtime error in IE 6 & 7
		 * (thanks  Microsoft), so we will hide old images with css.
		 * [Done here because we know user has JS enabled otherwise we
		 * run the risk of hiding imgs from CSS capable people with JS
		 * turned off.
		 */
		tableArray[0].style.display = 'none'; 
		
		// we are prefixing the html, so loop backwards
		for ( var j = linkArray.length - 1; j >= 0; j-- ) {
			var credit        = ""; /* plaintext to be appended to caption */
			var caption       = ""; /* full caption */
			var thumb_credit  = ""; /* photo credit (can have html) */
			var thumb_caption = ""; /* preview of full caption for thumb */

			var rel_attrib    = ' rel="battalion"';
			var class_attrib  = '" class="thickbox"';
                        var link_attrib   = ' rel="thebatt"';
			// if we have a caption set it up
			if ( captionArray[j].length > 0) {
				caption = captionArray[j];
				/*max_length = 50;
				// get at least max_length characters of caption for thumb 
				if (captionArray[j].length > max_length && captionArray[j].lastIndexOf(' ', max_length) > -1) {
					// last index of prevents word truncation
					thumb_caption = captionArray[j].substr(0, captionArray[j].lastIndexOf(' ', max_length)) + '...';
				}
				else {
					// its short, just add it :)
					thumb_caption = captionArray[j];
				}*/
			} 

			/* build up the credit information */
			// grab the names
			if ( creditArray[j].length > 0 ) {
				credit = creditArray[j];
				thumb_credit = credit;
			}

			// link the names if applicable
			if ( creditLinks[j].length > 0 ) {
				thumb_credit = 'Credit: <a href="' + creditLinks[j] + '" class="media_credit">'
				+ creditArray[j] + '</a>';
				credit = 'Credit: ' + credit;
			}

			// now append the credit to the caption
			if ( credit.length > 0 ) {
				caption += ' (' + credit + ')';
				thumb_caption += ' (' + thumb_credit + ')';
			}

			// disable thickbox on pdfs
			if ( linkArray.indexOf( 'pdf' ) != -1 ) {
				class_attrib = "";
			}

			// do not display media with caption 'hide'
			if( captionArray[j] != 'hide' ) {
				// actually insert the tag
				storyElt.innerHTML =
					'<div class="article_media">'
						+ '<a href="' + linkArray[j] + class_attrib + '" '
							+ 'title="' + caption + '"' + rel_attrib + '>'
							+ '<img sr' + 'c="' + linkArray[j] + '" '
								+ 'alt="' + credit + '" />'
						+ '</a>'
						+ thumb_caption+"&nbsp;&nbsp;&nbsp;&nbsp;"
                                                + '<a href="' + linkArray[j]  + class_attrib+ '" '
							+ 'title="' + caption + '"' + link_attrib + '>[zoom]'
						+ '</a>' 
					+ '</div>'
					+ storyElt.innerHTML;
			}
		}
	}
}

/* End Image Hackery */
