// JavaScript Document
var ensembleAPIUrl = 'http://ensemble.syr.edu/app/simpleapi/';
var loaderHTML = '<div id="loader"><img src="/Newsroom/images/ajax-loader.gif" alt="Loading..." style="border: none; margin-top: 3px;" align="absmiddle" /> Loading...</div>';
var websiteID = 'jTSRq3tf2kmiN0vjg-MjZw';
var siteURL = 'http://ensemble.syr.edu';

function initVideo() {
	getVideos(ensembleAPIUrl + 'video/list.json/' + websiteID + '?orderBy=videoDate&orderByDirection=desc&searchString=salzberg&resultsCount=4');
}

function AjaxRequest(url,successCallBack, loaderCallBack) {
	
	new Ajax.Request(url + '&ran=' + Math.floor(Math.random() * 100001),
	  {
		method:'get',
		crossSite: true,
		onUninitialized: loaderCallBack,
		onLoading: loaderCallBack,
		onLoaded: loaderCallBack,
		onSuccess: successCallBack,
		onFailure: throwFailure,
		onException: throwExp
	  });	
}

function getVideos(url) {
	AjaxRequest(url,writeVideos,videoLoader);	
}

function videoLoader() {
	$("videoShowcase").innerHTML = loaderHTML;	
}

function writeVideos() {
	
	if ( typeof(data) != "undefined" && typeof(data.videos) != "undefined" && data.videos.errors) {
		
		var myTemplate = new Template(
		'<div id="errors">#{errorMessage}</div>');
		
		$("videoShowcase").innerHTML = "";
		
		if ($A(data.videos.errors).length > 1) {
			data.videos.errors.each((function(e) {
				var show = {errorMessage: e.message};
				Element.insert($("errorBox"),myTemplate.evaluate(show));
			}).bind(this));
		}
		else {
			
			var show = {errorMessage: data.videos.errors.message};
			Element.insert($("errorBox"),myTemplate.evaluate(show));
		}
		
	}
	else {
		
		$("videoShowcase").innerHTML = "";
		writeVideoList(data);
		
	}
}

function writeVideoListing() {

    if ( false && (typeof(data) == "undefined" || typeof(data.videos) == "undefined" ) || (typeof(data) != "undefined" && typeof(data.videos) != "undefined" && data.videos.errors)) {
        
		var myTemplate = new Template(
            '<div id="errors">#{errorMessage}</div>'
        );

        data.videos.errors.each((function(e) {
            var show = {errorMessage: e.message};
            Element.insert($("errorBox"), {'bottom': myTemplate.evaluate(show)});
        }).bind(this));
		
    }
    else {
    
        var videoListTemplate = new Template(
	    '<div id="list_#{videoID}" style="width: 100%">' +
		    '<div class="listThumb">' +
			    '<a href="/videoarchive/video.asp?vid=#{videoID}" target="_blank"><img src="#{videoThumbnail}" alt="#{videoTitle}" class="listThumbImage" /></a>' +
		    '</div>' +
		    '<div style="float: left" class="listNewsVideoInfo">' +
			    '<a href="/videoarchive/video.asp?vid=#{videoID}" target="_blank" class="listLink">#{videoTitle}</a><br />' +
		    '</div>' +
	    '</div><br class="clearboth" /><br class="clearboth" />');
	    
	    var imageURL = "";
	    
	    data.videos.videoImages.each((function(i) {
            if (i.imageType == "thumb" || i.imageType == "Thumb") {
                imageURL = i.imageUrl;
            }
        }).bind(this));
	     
         var show = {videoID: data.videos.videoInformation.videoID,  
                     videoTitle: data.videos.videoInformation.primaryTitle,
                     videoThumbnail: imageURL};
                     
	     Element.insert($("videoList"),videoListTemplate.evaluate(show));                          
       
    }	
}


function writeVideoList(data) {

	var videoListTemplate = new Template(
	'<div id="list_#{videoID}" class="listEntry">' +
		'<div class="listThumb">' +
			'<a href="/videoarchive/video.asp?vid=#{videoID}" target="_blank"><img src="#{videoThumbnail}" alt="#{videoTitle}" class="listThumbImage" /></a>' +
		'</div>' +
		'<div style="float: left" class="listVideoInfo">' +
			'<a href="/videoarchive/video.asp?vid=#{videoID}" target="_blank" class="listLink">#{videoTitle}</a><br />' +
		'</div>' +
	'</div>');
	
	if ($A(data.videos.video).length > 1) {
		
		data.videos.video.each((function(v) {
										
			var show = {videoThumbnail: v.thumbnailUrl, 
						videoTitle: v.videoTitle, 
						videoID: v.videoID, 
						videoDuration: v.videoDuration, 
						departmentName: v.departmentName, 
						videoDate: formatDate(v.videoDate),
						videoDescription: formatDescription(v.videoDescription)};
						
			Element.insert($("videoShowcase"),videoListTemplate.evaluate(show));
			
	   }).bind(this));  
		
	}
	else {
		
		var show = {videoThumbnail: data.videos.video.thumbnailUrl, 
					videoTitle: data.videos.video.videoTitle,
					videoID: data.videos.video.videoID, 
					videoDuration: data.videos.video.videoDuration,
					departmentName: data.videos.video.departmentName,
					videoDate: formatDate(data.videos.video.videoDate),
					videoDescription: formatDescription(data.videos.video.videoDescription)};
					
		Element.insert($("videoShowcase"),videoListTemplate.evaluate(show));

	}
}

function formatDescription(description) {
	
	if (description.length > 200) {
		return description.substr(0,200) + "...";
	}
	else {
		return description;
	}
}

function formatDate(theDateTime) {
	
	// split the time out
	var parts = theDateTime.split("T");
	var datepart = parts[0];
	
	// split the date parts and concatenate them according to display preference
	var dateparts = datepart.split("-");
	return (dateparts[1] + "/" + dateparts[2] + "/" + dateparts[0]);
	
}

function throwExp(req,exception) {
	alert('The request had a fatal exception thrown.\n' + exception);
	return true;
}

function throwFailure(req){
	alert('Error: ' + req.status + "\n" + req.statusText); 
	return true;
}