/**
 * Initialize Red Swoosh Manager
 *
**/
function mediamanager_rs_init() {			
	// the download manager is only for registered members
	if (!gMemberId) {
		message = 'Want to watch these videos in full-screen, DVD-quality with no stuttering or buffering?<br><br>This feature is only available to members. <br><br><a href="/login/"><img style="margin-left:8px" src="'+gPlayList_loginButtonSrc+'" width="132" height="67" alt=""  border="0"></a><a href="/register/"><img style="margin-left:30px" src="'+gPlayList_registerButtonSrc+'" width="132" height="67" alt="" border="0"></a>';
		
		mediamanager_playlist2_showMessage(message);				
	}
	else if (!gHasAccessToDeliveries) {
		mediamanager_playlist2_showMessage('',2);
	}
	else {		
		// intialize Red Swoosh. Unfortunately if the visitor allready has Red Swoosh he will be subscribed for the content
		redswooshInitialize(mediamanager_rs_onInit, '', gCID);
	}
}

/**
 * on Red Swoosh Init call back
 *
*/

function mediamanager_rs_onInit(success,handle) {
	if (success) {		
		// this should be here instead of mediamanager_rs_onUpdateAttributes, otherwise we will have many async calls
		mediamanager_rs_repeatinglyUpdateAttributes();		
	}
	else {
		message = 'Want to watch these videos in full-screen, DVD-quality with no stuttering or buffering?<br><br><a href="/register/installdownloadmanager.php">Click here</a> to install our download manager to begin receiving these videos delivered right to your computer.';
		
		mediamanager_playlist2_showMessage(message);
	}	
}

/**
 * Update attributes on 15 second intervals
 *
*/
function mediamanager_rs_repeatinglyUpdateAttributes() {
	if (gRedSwooshAllowAttributesLoop) {
		redswooshUpdateAttributes(mediamanager_rs_onUpdateAttributes,'');
	
		setTimeout("mediamanager_rs_repeatinglyUpdateAttributes()",1000*15);	
	}
}

function mediamanager_rs_onUpdateAttributes(success,handle) {
	if (success) {
		// loop files
	  for(fileUrl in rs_fileAttributes) {      	  	
    	// file name
			fileName 			= rs_fileAttributes[fileUrl]['rs_name'];
			mediaLocalUrl = rs_fileAttributes[fileUrl]['rs_localURL'];
			mediaUrl 			= rs_fileAttributes[fileUrl]['rs_originURL'];		
			rsStatus			= rs_fileAttributes[fileUrl]['rs_status'];			
						
			// if the extension is flv delete the ads for backward stupidity
			if (fileUrl.match(".flv") || fileUrl.match(".swf")) { // do nothing
				redswooshDeleteFile(mediamanager_rs_onDeleteAdCallback, '', rs_fileAttributes[fileUrl]['rs_originURL']);
				continue;			
			}						
		

  		mediaId = gMediaURLtoID[mediaUrl];			
			
  		// if we have media id this means we have the file listed
  		if (mediaId) {  
  			// update global media array
  			gMediaInfo[mediaId]['rs_localURL'] 	= mediaLocalUrl; 
  			gMediaInfo[mediaId]['rs_originURL'] = mediaUrl; 
  			
				// if the media campaign is cancled  			 			
  			if (gMediaInfo[mediaId]['cmp_status'] == 100)	{
  				mediamanager_rs_deleteFile(mediaId);
  			}
  			else {  				  			
	  			delDisplay = 'none';
	  			
	  			// check media status
	  			if (rsStatus == 'COMPLETE') {
	  				// if media is downloaded show the play button
	  				mediamanager_showItemButton(mediaId,'play');
	  				
	  				// change status to complete
						document.getElementById('mediamanager_item_status_' + mediaId).innerHTML = 'Downloaded ' + mediamanager_rs_genProgressString(rs_fileAttributes[fileUrl]['rs_progress'],rs_fileAttributes[fileUrl]['rs_size']);   				
						
						delDisplay = '';
	  			}
	  			else if (rsStatus == 'DOWNLOADING') {
	  				// change status to downloading
						document.getElementById('mediamanager_item_status_' + mediaId).innerHTML = 'Downloading ' + mediamanager_rs_genProgressString(rs_fileAttributes[fileUrl]['rs_progress'],rs_fileAttributes[fileUrl]['rs_size']);  				
	
						// show the pause button
	  				mediamanager_showItemButton(mediaId,'pause');
	  				
	  				delDisplay = '';
	  			}
	  			else if (rsStatus == 'PAUSED') {
	  				// change status to paused
	  				document.getElementById('mediamanager_item_status_' + mediaId).innerHTML = 'Paused ' + mediamanager_rs_genProgressString(rs_fileAttributes[fileUrl]['rs_progress'],rs_fileAttributes[fileUrl]['rs_size']);
	  				
	  				// show the resume button
	  				mediamanager_showItemButton(mediaId,'resume');  				
	  				
	  				delDisplay = '';
	  			}  			
	  			else if (rsStatus == 'WAITING') {
	  				// change status to Ready to Dwnld
	  				document.getElementById('mediamanager_item_status_' + mediaId).innerHTML = 'Ready to Download';
	  				
	  				// show the resume button
	  				mediamanager_showItemButton(mediaId,'dwnld');  				
	  				
	  				delDisplay = '';
	  			}  			  			
	  			document.getElementById('mediamanager_item_del_' + mediaId).style.display = delDisplay;
	  			
	  			
	  				
					//alert(rs_fileAttributes[fileUrl]['rs_originURL']);
		  		//alert(rs_fileAttributes[fileUrl]['rs_localURL']);
		  		//alert(rs_fileAttributes[fileUrl]['rs_name']);
		  		//alert(rs_fileAttributes[fileUrl]['rs_path']);
		  		//alert(rs_fileAttributes[fileUrl]['rs_expiration']);
		  		// alert(rs_fileAttributes[fileUrl]['rs_campaignid']);
  			}	  		
  		}
	  }
	  // download instants
		mediamanager_rs_downloadInstants();  		
	}
	// i should display a message on unsuccesfull update of attributes	
}

/**
 * Gen progress string
 *
*/

function mediamanager_rs_genProgressString(downloadedBytes,totalFileSize) {
	if (!downloadedBytes || !totalFileSize) {
		return '';
	}
	
	progressString = '';
	
	downlaodedPercent = downloadedBytes / totalFileSize * 100;	
	downlaodedPercent = Math.round(downlaodedPercent);
	
	totalFileSizeMegabytes = Math.round(totalFileSize/1024/1024);
	
	if (downlaodedPercent == 100) {
		progressString = "(" + totalFileSizeMegabytes + " MB)";
	}
	else {
		progressString = "(" + downlaodedPercent + "% of " + totalFileSizeMegabytes + " MB)";
	}
	
	return progressString;
}

/**
 * Start a new downlaod or resume an existing one
 *
*/
function mediamanager_rs_downloadFile(mediaId) {
	redswooshDownloadFile(mediamanager_rs_onDownloadFileCallback, mediaId, gMediaInfo[mediaId]['rs_originURL']);
}

/**
 * On resume download callback
 *
*/
function mediamanager_rs_onDownloadFileCallback(success,mediaId) {
	if (success) {
		fileUrl = gMediaInfo[mediaId]['rs_originURL'];
		
		//  show pause button
		mediamanager_showItemButton(mediaId,'pause');		
		
		document.getElementById('mediamanager_item_status_' + mediaId).innerHTML = 'Downloading '  + mediamanager_rs_genProgressString(rs_fileAttributes[fileUrl]['rs_progress'],rs_fileAttributes[fileUrl]['rs_size']);
	}
	// else display some error message
}

/**
 * Pause a downlaod
 *
*/
function mediamanager_rs_pauseFile(mediaId) {
	redswooshPauseFile(mediamanager_rs_onPauseFileCallback, mediaId, gMediaInfo[mediaId]['rs_originURL']);
}

/**
 * On pause a download callback
 *
*/
function mediamanager_rs_onPauseFileCallback(success,mediaId) {
	if (success) {
		fileUrl = gMediaInfo[mediaId]['rs_originURL'];
		
		//  show resume button
		mediamanager_showItemButton(mediaId,'resume');		
		
		// change status
		document.getElementById('mediamanager_item_status_' + mediaId).innerHTML = 'Paused ' + mediamanager_rs_genProgressString(rs_fileAttributes[fileUrl]['rs_progress'],rs_fileAttributes[fileUrl]['rs_size']);
	}
	// else display some error message
}

/**
 * Delete a downlaod
 *
*/
function mediamanager_rs_deleteFile(mediaId) {		
	redswooshDeleteFile(mediamanager_rs_onDeleteFileCallback, mediaId, gMediaInfo[mediaId]['rs_originURL']);
}

/**
 * On delete a download callback
 *
*/
function mediamanager_rs_onDeleteFileCallback(success,mediaId) {
	if (success) {
		// check if the element is there, because canceled campaigns files are not displayed in the list
		if (document.getElementById('mediamanager_playlist2_itemcontainertr_' + mediaId)) {
			document.getElementById('mediamanager_playlist2_itemcontainertr_' + mediaId).style.display = "none";
		}
		
		campaignId = gMediaInfo[mediaId]['cmp_id'];
		
		xajax_campaignMemberDel(campaignId,gMemberId);
		
		gMediaInfo[i]['camp_mdel_isdel'] = 1;
	}
	// else display some error message
}

/**
 * On delete a download callback
 *
*/
function mediamanager_rs_onDeleteAdCallback(success,handler) {
	// do nothing
}

/**
 * Check and download instant campaigns	
 *
**/
function mediamanager_rs_downloadInstants() {
	for (i in gMediaInfo) {
		if ((gMediaInfo[i]['cmp_isinstant'] == 1) && (gMediaInfo[i]['cmp_status'] != 100) && (gMediaInfo[i]['camp_mdel_isdel'] != 1)) {			
			// check if we have the file in the red swoosh invenory
			fileUrl = gMediaInfo[i]['cmp_mediaurl'];
			if (!rs_fileAttributes[fileUrl]) {				
				 redswooshDownloadFile(mediamanager_rs_onInstantDownloadFileCallback, i, gMediaInfo[i]['cmp_mediaurl']);
			}					
		}
	}
}

function mediamanager_rs_onInstantDownloadFileCallback(success,mediaId) {
	// do nothing
}
