function encrypt(str) {
	if ( !str ) {
		return('');
	} else {
		var pt, key;
		blockSizeInBits=128;
		keySizeInBits = 128;
		key = hex2s(key);
		enc=byteArrayToHex(rijndaelEncrypt(str, key, "ECB"));
		return(enc);
	}
}


function page(dir) {
	var newpage=currpage+dir;
	if ( newpage >= 1 & newpage <= totalPages ) {
		currpage=newpage;
		submitSearch();
	}
}

function setStatus(status,uid) {
	//icon in browser?
	
	
//	if ( uid == curruid ) {
//		movie['status']=
//	}
	

	//console.log(status,uid);
}

function deleteCurrentMovie() {
 	var agree=confirm("Are you sure you wish to delete this?");
	if (agree) {
		deleteMovie(curruid);
		//var nextuid=$('div_'+curruid).next('.movieThumbnail',0);//, 1);
		
		if ( $('div_'+curruid) ) $('div_'+curruid).remove();	 
		
		curruid='';
		movie={};
		showMovie();
		
		//console.log(nextuid['id']);
		
		
	}
 }
 

function destroyToolTips() {
	for (var key in renderPopups) {
		//console.log('desrtoy '+key);
		renderPopups[key].destroy();
	}
	renderPopups={};
}

function destroyStatusPopupOnMovie(id) {
	renderPopups[id].destroyOnMove();
	delete renderPopups[id];
}

function addStatusPopup(id) {
	if ( !renderPopups[id] ) {
		 
		renderPopups[id]=new Tooltip(id, 'renderStatusPopup',updateStatus);
	}
	
	
}

function clearPopupStatus() {
	var currentClasses=$w($('renderStatusPopup').className);
	for (var c = 0; c < currentClasses.length; c++) {
		$('renderStatusPopup').removeClassName(currentClasses[c]);
	}
}


function setPopupStatus(status) {
	 
	
	$('renderStatusPopup').addClassName(status);
			
}



function initStatusPopups() {
	destroyToolTips();

	var arePopups=$$('.error','.needsrender','.needsrenderupdate','.queued','.rendering','.stopped');
	for (var i = 0; i < arePopups.length; i++) {
 		addStatusPopup(arePopups[i]['id']);
		
	}
	 
	
	
}

function refreshRenderStatus() {
	updateStatus(curruid);
}
function updateStatus(uid) {
	clearPopupStatus(); 
	$('renderingStatus').hide();
//	new Ajax.Request('/php/api/Render.getStatus.php', {method:'get',parameters:'uid='+uid,asynchronous:true,onSuccess:statusComplete});
	new Ajax.Request('/php/api/Movie.getDetails.php', {method:'get',parameters:'uid='+uid+'&auth='+auth,asynchronous:true,onSuccess:statusComplete});
	 
}

function setRendering(uid) {
	//console.log('setRendering');
	$('status_'+uid).removeClassName("needsrender");
	$('status_'+uid).addClassName("rendering");
 		
	initStatusPopups();
}

function setNeedsRendering(uid) {
	$('status_'+uid).removeClassName("rendering");
	$('status_'+uid).addClassName("needsrender");
 		 
	initStatusPopups();
}

 

function showStatus(statusmovie) {
	  
 	 
	
	if ( $('status_'+statusmovie['uid']) ) {
		
		setPopupStatus(statusmovie['status']);
		
		
		if ( !$('status_'+statusmovie['uid']).hasClassName(statusmovie['status']) ) {
			//no status
			 
			var currentClasses=$w($('status_'+statusmovie['uid']).className);
			 
			for (var c = 0; c < currentClasses.length; c++) {
				$('status_'+statusmovie['uid']).removeClassName(currentClasses[c]);
			}
			 
			$('status_'+statusmovie['uid']).addClassName(statusmovie['status']);
			
			 
			addStatusPopup('status_'+statusmovie['uid']);
		}
		
		
		 
		if ( statusmovie['status'] == "rendering" ) {
			$('renderingStatus').update(statusmovie['status']+"..."+statusmovie['render']['progress']+" ("+statusmovie['render']['elapsed']+")");
		} else if ( statusmovie['status'] == "rendered" ) {
			$('renderingStatus').update("done! ("+statusmovie['render']['totaltime']+")");
		 	
		 	destroyStatusPopupOnMovie('status_'+statusmovie['uid']);
		
		} else if ( statusmovie['status'] == "needsrender" || statusmovie['status'] == "needsrenderupdate" ) {
			$('renderingStatus').update("this movie needs to be rendered.");
		
		} else if ( statusmovie['status'] == "stopped" ) {
			$('renderingStatus').update("render stopped.");
		
		
		} else { 
			$('renderingStatus').update("no render data.");
		}
		
		
		 
	
	}
	 
	if ( statusmovie['uid']==curruid ) {
	 
		showRenderStatusPane(statusmovie['render']);		
	}
	$('renderingStatus').show();
	
	
}


function statusComplete(response) {
	 
 	var status=eval('(' + response.responseText + ')');
	
	//console.log(status);
	showStatus(status);
	
	 
  
	
	
}


 

function editCurrentMovie() {
	makeMovie(curruid);
}







//ick="togglePane('settingsLink');" id="settingsArrow">


 


function cancelMovieRender() {
	$('cancelRenderWait').update('<img style="float:left;" src="/img/busyddd.gif" />');
	new Ajax.Request('/php/api/Render.cancel.php', {method:'get',parameters:'auth='+auth+'&uid='+curruid,asynchronous:true,onSuccess:cancelRenderComplete,onFailure:cancelRenderComplete});
	
}

function cancelRenderComplete(response) {
	 
	var status=eval('(' + response.responseText + ')');
	//console.log('CANCEL');
	//console.log(status);
	$('cancelRenderWait').update('');
	
	//showRenderStatusPane(status);	
	showStatus(status);
	
	/*if ( !newmovie['error'] && newmovie['uid']) {
		if (movie['uid']==curruid) {
			movie=newmovie;
		}
		refresh(movie['uid']);

	//} else {
	
	}
	
	*/
	
}
 

function submitMovieUpdate() {
	var public=($('public').checked)?1:0;
	var feature=($('defaultMovieCheck').checked)?1:0;
	new Ajax.Request('/php/api/Movie.update.php', {method:'get',parameters:'auth='+auth+'&uid='+curruid+'&name='+$('movieNameInput').value+'&desc='+$('movieDescriptionInput').value+'&public='+public+'&feature='+feature,asynchronous:true,onSuccess:updateComplete});
	$('updateWait').update('<img style="float:left;" src="/img/busyddd.gif" />');
	$('updateSettingsWait').update('<img style="float:left;" src="/img/busyddd.gif" />');
	
	 
}

function updateComplete(response) {
	submitSearch();
	$('updateWait').update('');
	$('updateSettingsWait').update('');
	
	//console.log(response.responseText);
}





function submitMovieUpload() {
	var replace=($('ytReplace').checked)?1:0;
	
	new Ajax.Request('/php/api/YouTube.upload.php', {method:'get',parameters:'auth='+auth+'&replace='+replace+'&uid='+curruid+'&username='+encrypt($('ytUsername').value)+'&password='+encrypt($('ytPassword').value),asynchronous:true,onSuccess:uploadComplete});
	$('uploadResponse').update('<img style="float:left;" src="/img/busyddd.gif" />');
	
}
function uploadComplete(response) {
	$('uploadResponse').update('');
	
	 
	var response=eval('(' + response.responseText + ')');
	
	if ( response['success'] == 0 ) {
		$('uploadResponse').update("<span class='error'>"+response['reason']+"<\/span>");		
	} else {
		$movie['youtube_id']=response['youtube_id'];
	}
	
	showYouTubeVersion();
	
	
	 
}
 


function submitSearch() {
	var sortDir=(sortStates[currsort]==1)?"ASC":"DESC";
	new Ajax.Request('/php/api/Movies.search.php', {method:'get',parameters:'auth='+auth+'&keyword='+$('searchKeyword').value+'&sort='+currsort+'&show='+perpage+'&page='+currpage+'&dir='+sortDir+'&user='+user,asynchronous:true,onSuccess:searchComplete});
	
}
function searchMovieUpdate() {
	submitSearch({});
}
function searchFavesUpdate() {
	submitFaveSearch({});
}
function toggleSort(href,sortBy) {
	if ( currsort == sortBy ) {
		sortStates[sortBy]=-1*sortStates[sortBy];	
	}
	 
	currsort=sortBy;
	
	var toggleLinks=$$('.sort');

	for (var i = 0; i < toggleLinks.length; i++) {
 		toggleLinks[i].removeClassName("currentSort");
	}
 	href.addClassName("currentSort");
	currpage=1;
	submitSearch();
}

function toggleFaveSort(href,sortBy) {
	if ( currfavesort == sortBy ) {
		faveSortStates[sortBy]=-1*faveSortStates[sortBy];	
	}
	 
	currfavesort=sortBy;
	
	var toggleLinks=$$('.favesort');

	for (var i = 0; i < toggleLinks.length; i++) {
 		toggleLinks[i].removeClassName("currentSort");
	}
 	href.addClassName("currentSort");
	currfavepage=1;
	submitFaveSearch();
}


function pageNav(whichDropdown) {
	totalPages=Math.floor((  Number($('count').value)-1)/perpage)+1;
	
	
	//$('pageDropdown').options.length = 0;
	
	var selectObj = $(whichDropdown);
	var selectParentNode = selectObj.parentNode;
	var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
	selectParentNode.replaceChild(newSelectObj, selectObj);
//	$('pageDropdown')=newSelectObj;
	
	for ( var p=1;p<=totalPages;p++) {
		 
		var opt = document.createElement('option');
		opt.text = p;
		opt.value = p;
		
		if ( p == currpage ) {
			 
			opt.selected="selected";
 		
		} else {
		 
			opt.selected="false";
		
		}
		 
		$(whichDropdown).options.add(opt);
	}
	$(whichDropdown).options[currpage-1].selected=true;
	

	// alert('selected '+p+','+currpage); 
}

function goToPage() {
	currpage=Number($('pageDropdown').value);
	submitSearch();
}
function goToFavePage() {
	currpage=Number($('favePageDropdown').value);
	submitSearch();
}

function searchComplete(response) {
	
	$('moviesList').update(response.responseText);
	 
	 
	pageNav('pageDropdown');

	 
	initStatusPopups();
}
 

function showMyMovies() {
	$('favesDiv').hide();
	$('moviesDiv').show();
	
	$('favesList').update("");
	
	$('favesTab').removeClassName("showing");
	$('moviesTab').addClassName("showing");
	
	submitSearch();
	
}
function showMyFaves() {
	$('favesTab').addClassName("showing");
	$('moviesTab').removeClassName("showing");
	
	$('moviesList').update("");
	
	
	$('favesDiv').show();
	$('moviesDiv').hide();
	 
	submitFaveSearch();
	 
}
function submitFaveSearch() {
	var sortDir=(faveSortStates[currfavesort]==1)?"ASC":"DESC";
	 
	
	new Ajax.Request('/php/api/Movies.search.php', {method:'get',parameters:'faves=1&auth='+auth+'&keyword='+$('searchFaveKeyword').value+'&sort='+currfavesort+'&show='+perpage+'&page='+currfavepage+'&dir='+sortDir+'&user='+user,asnchronous:true,onSuccess:favesComplete});
	
}

function favesComplete(response) {
	$('favesList').update(response.responseText);
	pageNav('favePageDropdown');
	initStatusPopups();
}

function togglePublicFaves() {
	var showfaves=($('showFaves').checked)?1:0;
	new Ajax.Request('/php/api/User.update.php', {method:'get',parameters:'auth='+auth+'&showfaves='+showfaves,asynchronous:true});
}

function togglePrivate() {
	var private=($('privateAccount').checked)?1:0;
	new Ajax.Request('/php/api/User.update.php', {method:'get',parameters:'auth='+auth+'&private='+private,asynchronous:true});
}


function showUpload() {
	if ( $('divupload')) $('divupload').remove();
	$('uploadFeedback').update('');
	uploadPopup = new Popup();
	
	uploadPopup.popupDiv="uploadPopup";
	 
	uploadPopup.center();
	uploadPopup.show();

}
function startHeadshotUpload() {
	$('uploadFeedback').update('<img src="/img/busyfff.gif" />');
	return true;
}

function completeCallback(r) { 
 	var response=eval('(' + r + ')');
	$('uploadFeedback').update('');
	
	uploadPopup.hide();
	
	$('headshotImg').src="/media/headshots/"+response.hash+".jpg?"+Math.floor(Math.random()*99999);
}

function updateStudio() {
	new Ajax.Request('/php/api/User.update.php', {method:'get',parameters:'auth='+auth+'&name='+$('studioName').value,asynchronous:true});
}

AIM = {
	frame : function(c) {
	
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = new Element('div',{id:'divupload'});//document.createElement('div');
		
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
	
		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
	
		return n;
	},
	
	form : function(f, name) {
		f.setAttribute('target', name);
	},
	
	submit : function(f, c) {
		 
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},
	
	loaded : function(id) {
	 
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
	
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}

}


