/**
 * @project talenthouse
 * @package th.upload
 * @since   11.06.2009
 *
 * Controller for upload events
 * 
 */

// th_upload_Load( '#TH_Uploader' );
th_upload_uploadItems = [];
th_upload_processingItems = [];
th_upload_completeItems = [];
th_upload_failedItems = [];
th_upload_cancelledItems = [];

th_upload_projectId = '';
th_upload_activeTab = '';

function th_upload_Load( targetId , script, folder, activeTab, projectId ) {
	
	th_upload_activeTab = activeTab; 
	th_upload_projectId = projectId; 
	
	$(targetId).fileUpload ({

		'script':			script,
		'folder':			folder,
		
		'uploader':			th.params.bucketPath + '/flash/uploader.swf',
		'cancelImg':		th.params.bucketPath + '/images/blank.png',
		'scriptAccess':		'always',
		'multi':			true,
		'auto':				true,
		'buttonImg':		th.params.bucketPath + '/images/browse.png',
		'width':			72,
		'height':			24,
		'simUploadLimit':	1,
		'fileDesc':			'Files',

		//'wmode':			'Window',
		
		// to enable video:
		// 'fileExt':			'*.mp3:10;*.jpg:5;*.gif:5;*.png:5;*.tiff:5;*.wmv:150;*.avi:150;*.mp4:150;*.mov:150',
		'fileExt':			'*.mp3:15;*.jpg:5;*.gif:5;*.png:5;*.tiff:5;',
		
		'onInit':			th_upload_onInit,
		'onSelect':			th_upload_onSelect,							
		'onProgress':		th_upload_onProgress,
		'onComplete':		th_upload_onComplete,
		// 'onCancel':			
		'onError':			th_upload_onError
		,'onAllComplete':	function(event, data) {
								if ( $.browser.safari != true ) {
									th_upload_onAllComplete();
								} else {
									setTimeout( function() { th_upload_onAllComplete(); }, 1000 );									
								}
							}
		
	});

};

function th_upload_onInit() {

	try {
		$('#uploadingMsg').css('display', 'none');
		
		// th.log('UPLOAD: Init');
		th_upload_uploadItems= [];
		th_upload_processingItems= [];
		th_upload_completeItems= [];
		th_upload_failedItems= [];
		th_upload_cancelledItems = [];

	$('div#upload_selectfiles').css('display', 'block');

	} catch(e) {
		// th.log('ERROR: th_upload_onInit: ' + e);
	}
	
	return true;

};

		
function th_upload_onSelect(event, queueID, fileObj) 
{
	try {

		// Item selected
		th_upload_uploadItems.push({ 
			'queueId': queueID,
			'projectId': th_upload_projectId
		});
		$('#uploadingMsg').css('border', '2px solid rgb(128, 194, 66)');

	} catch(e) {
		// th.log('ERROR: th_upload_onSelect: ' + e);
	}

	// th.log('UPLOAD: Select [' + queueID + ']');
	return queueID;
};

function th_upload_onProgress(event, queueID, fileObj, data) 
{
	// th.log('UPLOAD: Progress [' + queueID + ']');

	try 
	{
		if (typeof data == 'object') {
			if ( data.percentage == 100 ) {
				// th.log('UPLOAD: Progress 100% [' + queueID + ']');
				
				for (var i=0; i<th_upload_uploadItems.length; i++) {
					if ( th_upload_uploadItems[i]['queueId'] == queueID ) {
						th_upload_processingItems.push(th_upload_uploadItems[i]);
						th_upload_uploadItems.splice(i,1);
						break;
					}
				}
				
			}
		}

		th_upload_updateLoadingMsg();
	} catch(e) {
		// th.log('ERROR: th_upload_onProgress: ' + e);
	}
	
	return true;
};

function th_upload_onComplete(event, queueID, fileObj, response, data)
{
	try {
		
		var item = { 
			'queueId': '',
			'projectId': ''
		};
		
		for (var i=0; i<th_upload_uploadItems.length; i++) {
			if ( th_upload_uploadItems[i]['queueId'] == queueID ) {
				th_upload_completeItems.push(th_upload_uploadItems[i]);
				item = th_upload_uploadItems[i]; 
				th_upload_uploadItems.splice(i,1);
				break;
			}
		}
		
		for (var i=0; i<th_upload_processingItems.length; i++) {
			if ( th_upload_processingItems[i]['queueId'] == queueID ) {
				th_upload_completeItems.push(th_upload_uploadItems[i]);
				item = th_upload_processingItems[i];
				th_upload_processingItems.splice(i,1);
				break;
			}
		}

		th_upload_updateLoadingMsg();
		
		try {
			var obj_Response = eval('(' + response + ')');
		} 
		catch (e) { return true; }


		if ( typeof obj_Response != 'object') {
			return true;
		}

		if ( typeof obj_Response.success == 'undefined' || obj_Response.success == false )
		{
			return true;
		}

		th.myprofile.medialist.append(obj_Response.id, obj_Response.path, obj_Response.type, fileObj.name, '#pnl_' + th_upload_activeTab, obj_Response.projectId);
		th.myprofile.medialist.mark('#' + obj_Response.id + '');
		th.flash.addMedia(obj_Response.mediaJsonObject, obj_Response.projectId, obj_Response.mediaCategory, 1);


		th.myprofile.medialist.updateMediaCounts();
		th.myprofile.medialist.checkTopPic();
		
	} catch(e) {
		// th.log('ERROR: th_upload_onComplete: ' + e);
	}
	
	return true;
};


function th_upload_onError(event, queueID, fileObj, errorObj) 
{
	try {
		$('#uploadingMsg').css('border', '2px solid #f00');
		$('#uploadingMsg').css('border-top', '2px solid #f00');

		// th.log('UPLOAD: Error [' + JSON.stringify(queueID) + '][' + JSON.stringify(errorObj) + ']');

		for (var i=0; i<th_upload_uploadItems.length; i++) {
			if ( th_upload_uploadItems[i]['queueId'] == queueID ) {
				th_upload_failedItems.push(th_upload_uploadItems[i]);
				th_upload_uploadItems.splice(i,1);
				break;
			}
		}
		for (var i=0; i<th_upload_processingItems.length; i++) {
			if ( th_upload_processingItems[i]['queueId'] == queueID ) {
				th_upload_failedItems.push(th_upload_uploadItems[i]);
				th_upload_processingItems.splice(i,1);
				break;
			}
		}

		th_upload_updateLoadingMsg();
		
		// Cancel upload
		// $('#TH_Uploader').fileUploadCancel(queueID); 
		// $('#TH_Uploader' + queueID).remove();
		
		
	} catch(e) {
		// th.log('ERROR: th_upload_onError: ' + e);
	}
	
	// Flash Update and Redirect Code inserted in Project_IndexController / uploadAction
	
	return true;
};

function th_upload_onCancel(event, queueID, fileObj, data) 
{
	try {
		$('#TH_Uploader' + queueID).remove();
		
		for (var i=0; i<th_upload_uploadItems.length; i++) {
			if ( th_upload_uploadItems[i]['queueId'] == queueID ) {
				th_upload_cancelledItems.push(th_upload_uploadItems[i]);
				th_upload_uploadItems.splice(i,1);
				break;
			}
		}
		for (var i=0; i<th_upload_processingItems.length; i++) {
			if ( th_upload_processingItems[i]['queueId'] == queueID ) {
				th_upload_cancelledItems.push(th_upload_uploadItems[i]);
				th_upload_processingItems.splice(i,1);
				break;
			}
		}
		
		th_upload_updateLoadingMsg();
		
	} catch(e) {
		// th.log('ERROR: th_upload_onCancel: ' + e);
	}
	// Cancel upload
	return true;
};

function th_upload_onAllComplete(event, data) 
{
	// th.log('UPLOAD: Init');
	th_upload_uploadItems= [];
	th_upload_processingItems= [];
	th_upload_completeItems= [];
	th_upload_failedItems= [];
	th_upload_cancelledItems = [];
	
	try {
		if ( th_upload_cancelledItems.length > 0 ) {
			th_upload_updateLoadingMsg();
			$('#uploadingMsg').css('border', '2px solid #f00');
		} else {
			$('#uploadingMsg').css('display', 'none');
			$('#import_result').css('display', 'none');
			$('#import_action_panel').css('display', 'block');
			
			th.ui.panels.load('/project/'+th_upload_activeTab+'/'+th_upload_projectId, '#pnl_'+th_upload_activeTab, false, function() { 
				th.ui.loadingAnimation.stop(); 
				th.ui.panels.markTabActive('#'+th_upload_projectId +' a.projectitem');  
				th.myprofile.medialist.updateMediaOrder(''+th_upload_activeTab+'', th_upload_projectId); 
				th.myprofile.medialist.checkTopPic( true ); 
				th.myprofile.medialist.updateMediaCounts();
			}); 
		}
	} catch(e) {
		//th.log('ERROR: th_upload_onAllComplete: ' + e);
	}
	// Flash Update and Redirect Code inserted in Project_IndexController / uploadAction
	return true;
};

function th_upload_updateLoadingMsg() 
{
	try {

		// th.log('UPLOAD: Update Message');
		
		// cover: 
		// edit_submenue
		
		if ( $('#exposeMask').size() < 1 ) {
			//th.ui.loadingAnimation.start('#pnl_upload');
		}
		
		var msg = th.params.tr_Uploading + ': ' + th_upload_uploadItems.length
					+ ' / '
					+ th.params.tr_Processing + ': ' + th_upload_processingItems.length
					+ ' / '
					+ th.params.tr_Complete + ': ' + th_upload_completeItems.length
					+ '';

		if (th_upload_uploadItems.length == 0 && th_upload_processingItems.length == 0 ) {
			msg = th.params.tr_Complete + '!';
		}
		// th.log('UPLOAD: Message: ' + msg);
		
		$('#uploadingMsg').html( msg );
		$('#uploadingMsg').css('display', 'block');

	} catch(e) {
		// th.log('ERROR: th_upload_updateLoadingMsg: ' + e);
	}
};

