/**
 * CompanyVideos functions (upload, edit, delete video mainly)
 */
var CompanyVideos = {};

/**
 * Ajax header for video upload
 */
CompanyVideos.X_AJAX_INFO_UPLOAD = 'videos_validate_upload_form';
CompanyVideos.X_AJAX_INFO_EDIT = 'users_edit_video';
CompanyVideos.X_AJAX_INFO_DELETE = 'users_delete_video';
CompanyVideos.X_AJAX_INFO_OFFICIAL = 'users_company_official_items';

CompanyVideos.ONLEAVE_MESSAGE = 'THE UPLOAD IN PROGRESS WILL BE AFFECTED IF YOU LEAVE THE PAGE !';
CompanyVideos.RELOAD_MESSAGE = 'The new uploaded video will appear in the page after its processing has finished !\nPress OK to reload the page.';

/**
 * Upload in progress
 */
CompanyVideos.isProcessing = false;

/**
 * Title mandatory or not
 */
CompanyVideos.titleOptional = true;

/**
 * related to Compatible formats dialog box
 */
CompanyVideos.formats_dialog_created = false;

/**
 * Default video ID value
 */
CompanyVideos.videoID = 0;

/**
 * default ID of the video file input
 */
CompanyVideos.file_input_id = 'file_to_upload';

/**
 * URL to the edit form
 */
CompanyVideos.edit_url = 'edit-company-video.html';

/**
 * URL to load after the video was deleted
 */
CompanyVideos.reload_after_delete;

/**
 * Upload form
 */
CompanyVideos.postForm = $('#videoFrm');

/**
 * Video uploader
 */
CompanyVideos.fileUploader = {};

/**
 * Initialize triggers and stuff
 */
CompanyVideos.initialize = function() {
    // show login form if user not logged in
	if( $('#logged_in').val() != 1 ) {
		$('.add_company_video').click(function(){$('a#login').trigger('click');return false;});
		$('a.edit_video_box').click( function(){$('a#login').trigger('click');return false;});
		return;
	}

	$('#upload_video_box').jqm({trigger: '.add_company_video',  overlay: 0, onShow: CompanyVideos.openUpoadForm});
	$('#edit_video_box').jqm({trigger: 'a.edit_video_box', overlay: 0, onShow: CompanyVideos.openEditForm});

	if (typeof main_video_id != 'undefined') {
		CompanyVideos.videoID = main_video_id;
	}
}

/**
 * Show the video upload dialog
 */
CompanyVideos.openUpoadForm = function(hash) {
	hash.w.show();
	
	$('#upload_video_progress').hide();
	$('#upload_video_form').show();
	$('#upload_video_box').jqmAddClose($('#videoCloseButton', $('#upload_video_box')));
	$('#upload_video_box').center();
}

/**
 * Show the edit video dialog
 */
CompanyVideos.openEditForm = function(hash) {
    var ajax_url = 'http://' + location.hostname + '/' + CompanyVideos.edit_url;

	$.get(
	    ajax_url + '?media_id=' + CompanyVideos.videoID,
	    function(response_data) {
			$('.content', $('#edit_video_box')).html(response_data);

			hash.w.show();

            $('#edit_video_box').show();
			$('#edit_video_box').jqmAddClose($('#editVideoCloseButton', $('#edit_video_box')));
			$('#edit_video_box').center();
		}
	);
}

/**
 * Upload the video
 */
CompanyVideos.upload = function() {
	if (!CompanyVideos.isProcessing) {
		$.ajax({
			url:	CompanyVideos.postForm.action,
			type:	'post',
			data:	{
				X_AJAX_INFO     : CompanyVideos.X_AJAX_INFO_UPLOAD,
				ts              : (new Date()).getTime(),
				'action'        : 'add',
				'title'         : encodeURIComponent($('#video_title', CompanyVideos.postForm).val()),
                'description'	: encodeURIComponent($('#video_description', CompanyVideos.postForm).val()),
                'file_to_upload': encodeURIComponent($('#' + CompanyVideos.file_input_id, CompanyVideos.postForm).val()),
                'terms'			: $('#terms', CompanyVideos.postForm).get(0).checked ? 1 : 0,
                'title_optional': CompanyVideos.titleOptional ? 1 : 0
			},
			success: CompanyVideos.handleValidation,
			error: CompanyVideos.handleError,
			dataType: 'json'
		});

		CompanyVideos.isProcessing = true;
	} else {
		//alert('Please wait until the submitted data is processed!')
	}

	return false;
}

/**
 * Submit the edit form
 */
CompanyVideos.edit = function() {
    $('#videoEditFrm', $('#edit_video_box')).ajaxSubmit({
        url: location.href,
		data: {
		    X_AJAX_INFO : CompanyVideos.X_AJAX_INFO_EDIT,
		    ts			: (new Date()).getTime(),
		    'action'    : 'action_submit'
		},
		success: function(data) {
		    if(data.status == 'success') {
                alert('Video successfully updated.');

                if (data['reload_page'] == '') {
                    window.location.reload();
                } else {
                    window.location.href = 'http://' + window.location.hostname + '/' + data['reload_page'];
                }
            } else {
                // show error message
                var error_msg = data.errors.join("\n- ");
                alert("Please correct the following errors:\n " + error_msg);
            }
            return false;
		},
		dataType: 'json'
    });

    return false;
}

/**
 * Mark a video as official
 */
CompanyVideos.makeOfficial = function() {
    $.ajax({
        url: location.href,
		type: 'POST',
		data: {
			X_AJAX_INFO	:	CompanyVideos.X_AJAX_INFO_OFFICIAL,
			'action'	:	'mark_official',
			'section'	:	'videos',
			'id_item'	:	CompanyVideos.videoID
		},
		dataType: 'json',
		success: function(response) {
		    if (response.status == 'failure') {
                var error_msg = response.errors.join("\n- ");
                alert("An error has occurred: \n " + error_msg);
		    } else {
                window.location.reload();
		    }
		}
    });

    return false;
}

/**
 * Delete a video
 */
CompanyVideos.remove = function() {
    if (confirm('Are you sure you want to delete this video?')) {
		$('#main_video_container').blockElement({'html_content': $('#delete_video_loader').html()});

		var video_over_div = $('#main_video_container').get(0).over_div;
		$.fn.blockElement.start(video_over_div);

		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: 'http://' + location.hostname,
			data: {
					'video_id': CompanyVideos.videoID,
					'X_AJAX_INFO': CompanyVideos.X_AJAX_INFO_DELETE,
					ts: (new Date()).getTime()
				  },
			success: function(response) {
				$.fn.blockElement.stop(video_over_div);
				alert(response.message);

				if (response.status == 'success') {
					if (CompanyVideos.reload_after_delete.length > 0) {
						window.location = 'http://' + location.hostname + '/' + CompanyVideos.reload_after_delete;
					} else {
						window.location.reload();
					}
				}
			},
			error: function(xhr, status, err_thrown) {
				$.fn.blockElement.stop(video_over_div);
				if (status=='error' || status=='parseerror') {
					alert('An error occured, please try again.')
				}
			}
		})
	}
	
	return false;
}

/**
 * Error handler
 */
CompanyVideos.handleError = function() {
	CompanyVideos.isProcessing = false;
	alert('An error has occurred, please retry.');
}

/*
 * Upload video
 */
CompanyVideos.handleValidation = function(response) {
    // validation has finished
    CompanyVideos.isProcessing = false;

	var ajax_url = 'http://' + location.hostname;
	var show_progress_bar = parseInt($('#show_progress_bar', CompanyVideos.postForm).val(), 10);

	// no errors
	if (response.type == 1) {
        // upload the video
        if ($.trim($('input#' + CompanyVideos.file_input_id, CompanyVideos.postForm).val()) != '') {
            // set status to processing
            CompanyVideos.isProcessing = true;

            CompanyVideos.fileUploader = new ProgressAjaxFileUploader.init(
                CompanyVideos.file_input_id,
                ajax_url,
                show_progress_bar,
                {
					progressContainerID	: 'upload_video_progress',
					track_upload_data  	: {'X_AJAX_INFO': 'videos_track_upload_progress'},
					extra_data			: {
                        'reload_on_success': true,
                        'success_msg': 'File successfully uploaded',
                        'while_uploading_msg': 'Uploading video ... please wait!',
                        'callback_on_success': function(data) {
                            CompanyVideos.isProcessing = false;
                            return CompanyVideos.facebookSubmit(data);
                        },
                        'on_unload_alert': CompanyVideos.ONLEAVE_MESSAGE,
                        'reload_alert_message': CompanyVideos.RELOAD_MESSAGE
                   }
				}
            );
        } else {
            // no file selected for upload
            alert('Please provide a file to upload.');
        }
	} else {
	    // errors
	    var error_msg = response.messages.join("\n- ");
		alert("Please correct the following errors:\n- " + error_msg);
	}
}

/*
 * Post to Facebook
 */
CompanyVideos.facebookSubmit = function(data) {
	if (data && (typeof data.status != 'undefined') && (data.status == 'publish_facebook')) {
        var facebookPublish = function(id, error) {
            alert(window.reload_message);
            window.location.reload(true);
        }

        FB.Connect.streamPublish(
            '',
            data.facebook_event.attachment,
            data.facebook_event.action_links,
            null,
            null,
            facebookPublish
        );

        return false;
    }

    return true;
}

/**
 * Set if the title is mandatory or not
 */
CompanyVideos.setTitleOptional = function(required) {
	if (typeof required == 'undefined') {
		required = true;
	}

	CompanyVideos.titleOptional = required;
}

/**
 * set custom ID
 */
CompanyVideos.setFileInput = function(file_input_id) {
	CompanyVideos.file_input_id = file_input_id;
}

/**
 * Caches the image having the specified source and retursn the created image object
 */
CompanyVideos.cacheImage = function(img_src, img_onload_handler, img_onerror_handler) {
	var img = new Image();

	if (img_onload_handler) {
		img.onload = img_onload_handler;
	}
	img.onerror = img_onerror_handler || function() {};
	img.src = img_src;

	return img;
}

/**
 * Show available video formats
 */
CompanyVideos.showCompatibleFormats = function(e) {
	if (!CompanyVideos.formats_dialog_created) {
		$('#compatible_formats').dialog({ width: 575 });
		CompanyVideos.formats_dialog_created = true;
	} else {
		$('#compatible_formats').dialog('open');
	}
	var evt = e || window.event;
	if (evt) {
		// prevent event propagation
		if(evt.stopPropagation) {
			evt.stopPropagation();
		} else if(typeof evt.cancelBubble != 'undefined') {
			evt.cancelBubble = true;
		}
	}
}

/**
 * Set the current video ID
 */
CompanyVideos.setVideoID = function(_video_id) {
	CompanyVideos.videoID = _video_id;
}

