/////////////////////////////////////////////////////////////////// DO NOT CHANGE /////////////////////////////////////////////////////////////////////////////////////

var activeVideo = new videoListObject()


function playVideo(videoId, clickedRow) {

	var rowContainer
	var listRows
	var videoIndex

	if (clickedRow != null && clickedRow.parentNode.id == 'videoList_Playlist') {

		rowContainer = clickedRow.parentNode
		listRows = document.getElementsByClassName('listRow', clickedRow.parentNode)

		for (i = 0; i < listRows.length; i++) {
			if (listRows[i] == clickedRow) {
				videoIndex = i
			}
		}

		playChannelFromIndex(loadedChannel, videoIndex)
		return;
	}
	else {

		if (clickedRow != null && clickedRow.parentNode.id != 'videoList_Playlist') {
			activeChannel = new videoListObject()//null
		}

		if (String(videoId).indexOf('W') != -1) {
			$('viewFrame').src = "help/help_" + extractHelpId(videoId)[0] + ".htm?id=" + extractHelpId(videoId)[1]
			$('viewFrameInfo').innerHTML = loadedChannel.title
		}
		else if (String(videoId).indexOf('Y') != -1) {

//alert('Message: ' + extractMailId(videoId)[0] + ', SenderId: ' + extractMailId(videoId)[1])
			$('viewFrame').src = "showMail.asp?id=" + extractMailId(videoId)[0]
			$('viewFrameInfo').innerHTML = "You are checking your inbox"
			clearTimeout(checkMailTimer)
			checkMailTimer = setTimeout("checkMail()", 1000)
		}
		else if (String(videoId).indexOf('Z') != -1) {
			if (activeChannel != null && activeChannel.id != null) {
				$('viewFrame').src = "asp/playAd.asp?id=" + videoId + "&channel=" + activeChannel.id
				$('viewFrameInfo').innerHTML = 'You are watching an Ad Space on "' + activeChannel.title + '"'
			}
			else {
				$('viewFrame').src = "asp/playAd.asp?id=" + videoId
				$('viewFrameInfo').innerHTML = "You are watching an Ad Space"
			}
		}
		else {
			$('viewFrame').src = "asp/playVideo.asp?id=" + videoId
			getVideoInfo(videoId)
		}


		$('focusBox').focus()
	}
}


function changeVideo(direction) {

	var shiftIndex = 0
	var newIndex

	if (direction == 'left') {
		shiftIndex = -1
	}
	else if (direction == 'right') {
		shiftIndex = 1
	}

	if (activeChannel != null && activeChannel.id != null) {
		newIndex = activeChannel.videoListIndex + shiftIndex

		if (newIndex < activeChannel.videoListArray.length && newIndex >= 0) {
			playChannelFromIndex(activeChannel, newIndex)
		}
	}
}



function getVideoInfo(videoId) {

	var url = 'asp/getVideo.asp';
	var pars = 'id=' + escape(videoId) +"&r=" + Math.random();

	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get', 
			parameters: pars, 
			onComplete: function(response) {
				var r = response.responseText
				var xmlDoc

				if (r.substr(0,5) == '<?xml') {
					xmlDoc = loadXml(r)
					activeVideo = new videoListObject(xmlDoc.getElementsByTagName("video")[0].getAttribute("id"), xmlDoc.getElementsByTagName("title")[0].firstChild.nodeValue, xmlDoc.getElementsByTagName("source")[0].firstChild.nodeValue)
					showActiveVideoInfo()
				}
				else {
					$('viewFrameInfo').innnerHTML = 'Information about this video could not be found'
				}
			},
			onFailure: function(response) {
				$('viewFrameInfo').innerHTML = 'There was a problem loading the information about this video'
			}
		});
}


function showActiveVideoInfo() {

	var videoInfoHTML = ''

	if (activeVideo.title != null) {
		videoInfoHTML += 'You are watching '

		videoInfoHTML += '"' + activeVideo.title + '"'
	
		if (activeChannel != null && activeChannel.title != null) {
			videoInfoHTML += ' on "' + activeChannel.title + '"'
		}
	}

	$('viewFrameInfo').innerHTML = videoInfoHTML
}



function sortVideoList(videoList, indexValue) {

	var listArray = convertHTMLToList(videoList)
	var sortedListArray = new Array()

	var sortClassName = 'sortedUp' + indexValue
	
	for (i = 0; i < listArray.length; i++) {
		if (indexValue == 'title') {
			listArray[i].indexValue = listArray[i].title
		}
		else if (indexValue == 'source') {
			listArray[i].indexValue = listArray[i].source
		}
	}

	if (Element.hasClassName(videoList, sortClassName)) {
		sortedListArray = bubbleSortObjectArray(listArray, true)
		Element.removeClassName(videoList, sortClassName)
	}
	else {
		sortedListArray = bubbleSortObjectArray(listArray, false)
		Element.addClassName(videoList, sortClassName)
	}

	insertVideoList(sortedListArray, videoList)

}

var currentSearchQuery = ""

function keyListenerForVidistaSearch(e) {

	var keynum

	if(window.event) {keynum = e.keyCode}
	else if(e.which) {keynum = e.which}


	switch (keynum) {
		case Event.KEY_ESC:
			togglePanels()
			break;
		case Event.KEY_RETURN:
			searchVidista();
			break;
		default:
	}

	cancelBubbling(e)
}

function searchVidista() {

	var query = String($('searchVidista').value).strip()

	if ($('errorMessage')) {
		Element.remove($('errorMessage'))
	}

	if (query == "") {
		errorText = "Please enter a search query"
		showErrorMessage($('searchVidista'), errorText)
	}
	else {
		$('videoList_Search').innerHTML = ''
		currentSearchQuery = query
		getVideoList('videoList_Search')
	}
}


function getVideoList(videoList, startingPoint) {

	videoList = $(videoList)

	var xmlUrl = "asp/getPopularList.asp"
	var pars

	var limitNumber = 25
	if (startingPoint == null) {startingPoint = 0}

	if (videoList.id == "videoList_Global") {
		xmlUrl = "asp/getPopularList.asp"
		pars = "start=" + startingPoint + "&limit=" + limitNumber + "&r=" + Math.random()
	}

	if (videoList.id == "videoList_Library") {
		xmlUrl = "asp/getMyLibrary.asp"
		pars = "r=" + Math.random()
	}

	if (videoList.id == "videoList_Search") {
		xmlUrl = "asp/getVideoSearch.asp"
		pars = "q=" + escape(currentSearchQuery) + "&start=" + startingPoint + "&limit=" + limitNumber + "&r=" + Math.random()
	}

	if (videoList.id == "videoList_Ads") {
		xmlUrl = "asp/getMyAds.asp"
		pars = "r=" + Math.random()
	}

	var myAjax = new Ajax.Request(
		xmlUrl, 
		{
			method: 'get', 
			parameters: pars,
			onLoading: function() {
				/*if ($('viewMoreVideosButton') && videoList.id == "videoList_Global") {
					$('viewMoreVideosButton').innerHTML = '<img src="img/magnify_plus.gif" /> Loading...'
				}*/
			},
			onComplete: function(response) {
				var currentListArray
				var startingPoint
				var viewMoreHTML

				if (String(response.responseText) == 'No videos found') {
					if ($('viewMoreVideosButton')) {
						Element.remove('viewMoreVideosButton')
					}
				}
				else if (String(response.responseText) == 'No results found' && videoList.id == 'videoList_Search') {
					if (Element.empty(videoList) && currentSearchQuery == "") {
						videoList.innerHTML = printListHeader(false) + '<div class="emptyListMessage"><div class="emptyListMessageText">Enter search terms in the form below to find videos that have already been added to Vidista</div></div>'
					}
					else if (Element.empty(videoList) && currentSearchQuery != "") {
						videoList.innerHTML = printListHeader(false) + '<div class="emptyListMessage"><div class="emptyListMessageText">No results found<br /><br />Search Vidista again, or try searching for new videos online</div></div>'
					}
					else {
						new Insertion.Bottom(videoList, '<div class="emptyListMessage"><div class="emptyListMessageText">No additional results found<br /><br />Search Vidista again, or try searching for new videos online</div></div>');	
					}
				}
				else if (String(response.responseText) == 'Login error') {
					logout()
				}
				else {
					if (startingPoint = 0) {
						updateVideoList(videoList, response.responseText)
					}
					else {
						appendVideosToTop(videoList, response.responseText, true	)
					}
					if (videoList.id == 'videoList_Global' && ($('viewMoreVideosButton'))) {
						currentListArray = convertHTMLToList(videoList)
						startingPoint = currentListArray.length// + videoListObjectArray.length
						viewMoreHTML = '<div class="miniButton" id="viewMoreVideosButton" onclick="getVideoList(\''+videoList.id+'\','+startingPoint+')"><img src="img/magnify_plus.gif" /> Show more videos</div>'
						$('viewMoreVideosButton').parentNode.innerHTML = viewMoreHTML
					}
					else if (videoList.id == 'videoList_Search' && ($('searchMoreVideosButton'))) {
						currentListArray = convertHTMLToList(videoList)
						startingPoint = currentListArray.length// + videoListObjectArray.length
						viewMoreHTML = '<div class="miniButton" id="searchMoreVideosButton" onclick="getVideoList(\''+videoList.id+'\','+startingPoint+')"><img src="img/magnify_plus.gif" /> Show more results</div>'
						$('searchMoreVideosButton').parentNode.innerHTML = viewMoreHTML
					}
				}

			}
		}
	);
}


function updateVideoList(videoList, responseText) {

	var listArray = convertXMLToList(videoList, responseText, 0)
	insertVideoList(listArray, videoList)
}


function updatePlaylist(videoList, responseText) {

	var listArray = convertXMLToList(videoList, responseText, 0)

	insertPlaylist(listArray, videoList)

}


function appendVideosToTop(videoList, responseText, bottom) {

	var newListArray
	var currentListArray = convertHTMLToList(videoList)
	var startCount = currentListArray.length

	newListArray = convertXMLToList(videoList, responseText, startCount)

	if (bottom) {
		insertVideoList(currentListArray.concat(newListArray), videoList)
	}
	else {
		insertVideoList(newListArray.concat(currentListArray), videoList)
	}


}

function printListHeader(sortable) {

	var listHeaderHTML

	if (!sortable) {
		listHeaderHTML = '<div class="listHeader"><div class="listColumn width60"><div class="listItem">Title</div></div><div class="listColumn width40"><div class="listItem">Source</div></div></div>'
	}
	else {
		listHeaderHTML = '<div class="listHeader"><div class="listColumn width60" onclick="sortVideoList(this.parentNode.parentNode, \'title\')"><div class="listItem">Title</div></div><div class="listColumn width40" onclick="sortVideoList(this.parentNode.parentNode, \'source\')"><div class="listItem">Source</div></div></div>'
	}
	
	return listHeaderHTML;
}


function insertVideoList(videoListObjectArray, videoList) {



	var listHeaderHTML = printListHeader(true)
	var listHTML = convertListToHTML(videoListObjectArray)

	videoList.innerHTML = listHeaderHTML
	new Insertion.Bottom(videoList, listHTML);




	if (userHasPermission() || userCanEdit()) {
		refreshSortablePlaylist()
	}

	refreshSortableVideoList(videoList)

}

function insertPlaylist(videoListObjectArray, videoList) {

	var listHeaderHTML = printListHeader(false)
	var listHTML = convertListToHTML(videoListObjectArray)

	videoList.innerHTML = listHeaderHTML
	new Insertion.Bottom(videoList, listHTML);

	refreshSortablePlaylist()
	loadedChannel.videoList = getPlaylistIds(true)

}

function convertListToHTML(videoListObjectArray) {

	var listHTML = ''

	for (i=0; i < videoListObjectArray.length; i++) {
		
		listHTML += '<div class="listRow" onmousedown="selectRow(this)" ondblclick="playVideo(extractVideoId(this),this)" id="' + videoListObjectArray[i].id + '" title="' + videoListObjectArray[i].title + '">'
		listHTML += '<div class="listColumn width60"><div class="listItem">'

		listHTML += videoListObjectArray[i].title
	
		listHTML += '</div></div>'
		listHTML += '<div class="listColumn width40"><div class="listItem">'

		listHTML += videoListObjectArray[i].source
	
		listHTML += '</div></div>'
		listHTML += '</div>'
	
	}

	return listHTML;
}


function convertHTMLToList(videoList) {

	var listRows = document.getElementsByClassName('listRow', videoList)

	var listArray = new Array()
	
	for (i = 0; i < listRows.length; i++) {
		var listItems = document.getElementsByClassName('listItem', listRows[i])
		listArray[i] = new videoListObject(listRows[i].id, listItems[0].innerHTML, listItems[1].innerHTML)
	}

	return listArray;
}


function convertXMLToList(videoList, responseText, startCount) {

	var xmlDoc = loadXml(responseText)
	var listArray = new Array()

	var listLength = xmlDoc.getElementsByTagName("video").length

	for (i = 0; i < listLength; i++) {
		listArray[i] = new videoListObject(videoList.id + '_' + xmlDoc.getElementsByTagName("video")[i].getAttribute("id") + 'X' + (i + startCount), xmlDoc.getElementsByTagName("title")[i].firstChild.nodeValue, xmlDoc.getElementsByTagName("source")[i].firstChild.nodeValue)
	}

	return listArray;
}



function refreshSortablePlaylist() {

	var selectedRow

	Sortable.create("videoList_Playlist",
		{tag: 'div',only:'listRow',dropOnEmpty:true,containment:["videoList_Playlist","videoList_Library","videoList_Global","videoList_Search","videoList_Ads"],constraint:false,ghosting:true,scrollOverride:false,
		onChange: function(movedRow) {
			selectedRow = movedRow
		},
		onUpdate:function(){

			if ($('emptyPlaylistMessage')) {
				Element.remove($('emptyPlaylistMessage'))
			}
			unsavedChannelChanges = true
			autoSave()
			loadedChannel.videoList = getPlaylistIds(true)
			if (loadedChannel.id == activeChannel.id) {
				activeChannel.videoList = loadedChannel.videoList
				activeChannel.videoListArray = String(activeChannel.videoList).split(',')
				activeChannel.videoListArray.pop()
			}
			selectRow(selectedRow)
		}
	});

}


function getPlaylistIds(updateThis) {

// Error when no items:

	var unparsedIdList = String(Sortable.serialize("videoList_Playlist"))
	var idListArray = unparsedIdList.split("&")
	var listRows = document.getElementsByClassName('listRow', 'videoList_Playlist')
	var videoListString, extractedId

	if (idListArray.toString() != '') {
		for (i=0; i<idListArray.length; i++) {
			extractedId = idListArray[i].slice((idListArray[i].indexOf("=")+1), idListArray[i].indexOf("X"))
			idListArray[i] = extractedId

			if (updateThis) {
				listRows[i].id = 'videoList_Playlist_' + extractedId + 'X' + i
				//Event.observe(listRows[i], 'mouseover', function(event){ showDeleteIcon(event);})
				//Event.observe(listRows[i], 'mouseout', function(event){ hideDeleteIcon(event);})
			}
		}

		
		videoListString = idListArray.toString() + ','
	}
	else {
		videoListString = ''
	}

	return videoListString;

}


function deleteThisRow(listRowId) {

	if (userHasPermission() || userCanEdit()) {

		if ($(listRowId).parentNode.id == "videoList_Playlist") {
			loadedChannel.selectedRow = null
		}

		Element.remove(listRowId)
		loadedChannel.videoList = getPlaylistIds(false)
		unsavedChannelChanges = true
	}
}


function deleteSelectedRow() {

	listRowId = loadedChannel.selectedRow

	if ((userHasPermission() || userCanEdit()) && listRowId != null) {

		Element.remove(listRowId)
		loadedChannel.selectedRow = null

		loadedChannel.videoList = getPlaylistIds(false)
		unsavedChannelChanges = true
	}

}


var globalListSelectedRow
var searchListSelectedRow
var adsListSelectedRow

function selectRow(selectedRow, playOnSelect) {

	var rowContainer = selectedRow.parentNode
	var listRows = document.getElementsByClassName('listRow', selectedRow.parentNode)

	listRows.each( function(listRow){
		resetRow(listRow)
	});

	highlightRow(selectedRow)

	if (playOnSelect == null) {playOnSelect = true}

	if (selectedRow.parentNode.id == "videoList_Playlist") {
		loadedChannel.selectedRow = selectedRow.id
//alert((loadedChannel == null) + ' ' + playOnSelect + ' ' + String(selectedRow.id).indexOf('W') + ' ' + String(selectedRow.id).indexOf('Y'))
		if (loadedChannel != null && playOnSelect && (String(selectedRow.id).indexOf('W') != -1 || String(selectedRow.id).indexOf('Y') != -1)) {
			playVideo(extractVideoId(selectedRow), selectedRow)

		}
	}
	else if (selectedRow.parentNode.id == "videoList_Library") {
		libraryChannel.selectedRow = selectedRow.id
		if (Element.visible('editVideoContainer')) {
			editVideoInfo()
		}
	}
	else if (selectedRow.parentNode.id == "videoList_Global") {
		globalListSelectedRow = selectedRow.id
	}
	else if (selectedRow.parentNode.id == "videoList_Search") {
		searchListSelectedRow = selectedRow.id
	}
	else if (selectedRow.parentNode.id == "videoList_Ads") {
		adsListSelectedRow = selectedRow.id
	}
}


function resetRow(listRow) {
	listRow.style.backgroundColor = 'transparent'
	listRow.style.color = '#000'
}


function highlightRow(listRow) {
	listRow.style.backgroundColor = '#316AC5'
	listRow.style.color = '#fff'
}


function extractVideoId(listRow) {

	if (listRow != null && listRow.id != null) {
		listRowId = String(listRow.id)
		return listRowId.slice((listRowId.lastIndexOf("_")+1),listRowId.indexOf("X"))
	}
	else {
		return null;
	}
}


function downloadSelectedVideo() {

	var videoId = extractVideoId($(loadedChannel.selectedRow))

	if (videoId != null && String(videoId).indexOf('W') == -1 && String(videoId).indexOf('Y') == -1 && String(videoId).indexOf('Z') == -1) {
		$('downloadVideoButton').href = 'download.asp?id=' + videoId
	}
	else {
		$('downloadVideoButton').href = 'download.asp'
	}
}

function refreshSortableVideoList(videoList) {


	Sortable.create(videoList,
		{tag: 'div',only:'listRow',dropOnEmpty:true,containment:[],constraint:false,ghosting:true,scrollOverride:true,
		onChange:function(movedRow){

			var movedRowHTML = ''
			movedRowHTML += '<div class="listRow listRowUsed" id="' + movedRow.id + '">'
			movedRowHTML += movedRow.innerHTML
			movedRowHTML += '</div>'

			new Insertion.Bottom(videoList, movedRowHTML);

			libraryChannel = new channelObject()
			$('focusBox').focus()
		}
	});


	if (videoList.id == "videoList_Library" && libraryChannel.selectedRow != null) {
		selectRow($(libraryChannel.selectedRow))
	}

}


function assignSerialIds(listContainer) {

	var listRows = document.getElementsByClassName('listRow', listContainer)

	for (i=0; i<listRows.length; i++) {
		listRows[i].id = listContainer + "_" + "0002" + "X" + i
	}


}


function displayTabbedList(contentId, tab) {

	var container = Element.classNames($(contentId))
	var panelContents = document.getElementsByClassName(container, $(contentId).parentNode)
	var listBody = document.getElementsByClassName('listBody', $(contentId))[0]

	var tabsInRow = document.getElementsByClassName('tab', tab.parentNode)

	panelContents.each( function(panelContent){
		Element.hide(panelContent)
	});



	Element.show($(contentId))

	tabsInRow.each( function(tabInRow){
		if (tabInRow != tab) {
			tabInRow.style.backgroundImage = 'url(img/mini_tab_faded.gif)'
			tabInRow.style.color = '#666'
			//new Effect.Opacity(tabInRow, {duration:0.0, to:0.5});
		}
		else if (tabInRow == tab) {
//			tabInRow.style.backgroundImage = 'url(img/mini_tab_dark.gif)'
//			tabInRow.style.color = '#fafafa'
			tabInRow.style.backgroundImage = 'url(img/mini_tab_grey.gif)'
			tabInRow.style.color = '#000'
			//new Effect.Opacity(tabInRow, {duration:0.0, to:1.0});
		}

	});

	if (container == "videoListContainer") {
		if (Element.empty(listBody)) {
			getVideoList(listBody)
		}
	}
	else if (container == "channelListContainer") {
	//	if (Element.empty(listBody)) {
			getChannelList($(contentId))
		//}
	}

}

function bubbleSortObjectArray(arrayName, reverseOrder) {
	if (reverseOrder) {
		for (var i=0; i<(arrayName.length-1); i++) {
			for (var j=i+1; j<arrayName.length; j++) {
				if (String(arrayName[j].indexValue).toLowerCase() > String(arrayName[i].indexValue).toLowerCase()) {
					var dummy = arrayName[i];
					arrayName[i] = arrayName[j];
					arrayName[j] = dummy;
				}
			}
		}
	}
	else {
		for (var i=0; i<(arrayName.length-1); i++) {
			for (var j=i+1; j<arrayName.length; j++) {
				if (String(arrayName[j].indexValue).toLowerCase() < String(arrayName[i].indexValue).toLowerCase()) {
					var dummy = arrayName[i];
					arrayName[i] = arrayName[j];
					arrayName[j] = dummy;
				}
			}
		}
	}

	return arrayName;
}


function videoListObject(id, title, source) {

	this.id = id
	this.title = title
	this.source = source

	this.indexValue
}


