var previewCode;

$(function () {
	$('#fileupload_lg').fileupload({
		url: "index.php?ads&upload&video",
		dataType: 'json',
		autoUpload: true,
		acceptFileTypes: /(\.|\/)(flv|swf|mp4|webm)$/i,
		maxFileSize: 20971520, // 20 MB
		previewMaxWidth: 100,
		previewMaxHeight: 100,
		previewCrop: true
	}).on('fileuploadadd', function (e, data) {
		data.context = $('<div/>').appendTo('#files_lg');
		$('#progress_lg').find('.progress-bar').css(
				'width',
				0 + '%'
		);
	}).on('fileuploadprocessalways', function (e, data) {
		var index = data.index,
				file = data.files[index],
				node = $(data.context.children()[index]);
		if (file.preview) {
			node
					.prepend('<br>')
					.prepend(file.preview);
		}
		if (file.error) {
			node
					.append('<br>')
					.append($('<span class="text-danger"/>').text(file.error));
		}
		if (index + 1 === data.files.length) {
			data.context.find('button')
					.text('Upload')
					.prop('disabled', !!data.files.error);
		}
	}).on('fileuploadprogressall', function (e, data) {
		var progress = parseInt(data.loaded / data.total * 100, 10);
		$('#progress_lg').find('.progress-bar').css(
				'width',
				progress + '%'
		);
	}).on('fileuploaddone', function (e, data) {
		$.each(data.result, function (index, file) {
			if (file.url) {
				$('#src').val(file.url);
				var height = ($('#height').val() == "0") ? "380" : $('#height').val();
				var width = ($('#width').val() == "0") ? "640" : $('#width').val();
				var url = ($('#url').val() == "") ? '#' : $('#url').val();
				var fallback_image_url = ($('#fallback_image_url').val() == "") ? '' : $('#fallback_image_url').val();
				if (endsWith(file.url.toLowerCase(), 'swf')){
					previewCode = getFlashAdCode(file.url, height, width, url);
				} else if ((endsWith(file.url.toLowerCase(), 'mp4')) || (endsWith(file.url.toLowerCase(), 'webm'))){
					previewCode = getHtml5VideoAdCode(file.url, height, width, url, fallback_image_url);
				}
				$('#files_lg').html('<button data-src="src" type="button" data-content="" data-toggle="popover" class="btn btn-metis-2 preview">' + preview + '</button><div data-src="src" class="modal text-center" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
			} else if (file.error) {
				$('#src').val("");
				var error = $('<span class="text-danger"/>').text(file.error);
				$(data.context.children()[index])
						.append('<br>')
						.append(error);
			}
		});
	}).on('fileuploadfail', function (e, data) {
		$('#src').val("");
		$.each(data.files, function (index, file) {
			var error = $('<span class="text-danger"/>').text('File upload failed.');
			$(data.context.children()[index])
					.append('<br>')
					.append(error);
		});
	}).prop('disabled', !$.support.fileInput)
			.parent().addClass($.support.fileInput ? undefined : 'disabled');
});

$(function () {
	$('#fileupload_sm').fileupload({
		url: "index.php?ads&upload&banner",
		dataType: 'json',
		autoUpload: true,
		acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
		maxFileSize: 2097152, // 2 MB
		previewMaxWidth: 100,
		previewMaxHeight: 100,
		previewCrop: true
	}).on('fileuploadadd', function (e, data) {
		data.context = $('<div/>').appendTo('#files_sm');
		$('#progress_sm').find('.progress-bar').css(
				'width',
				0 + '%'
		);
	}).on('fileuploadprocessalways', function (e, data) {
		var index = data.index,
				file = data.files[index],
				node = $(data.context.children()[index]);
		if (file.preview) {
			node
					.prepend('<br>')
					.prepend(file.preview);
		}
		if (file.error) {
			node
					.append('<br>')
					.append($('<span class="text-danger"/>').text(file.error));
		}
		if (index + 1 === data.files.length) {
			data.context.find('button')
					.text('Upload')
					.prop('disabled', !!data.files.error);
		}
	}).on('fileuploadprogressall', function (e, data) {
		var progress = parseInt(data.loaded / data.total * 100, 10);
		$('#progress_sm').find('.progress-bar').css(
				'width',
				progress + '%'
		);
	}).on('fileuploaddone', function (e, data) {
		$.each(data.result, function (index, file) {
			if (file.url) {
				$('#fallback_image_url').val(file.url);
				previewCode = '<img src="' + file.url + '"/>';
				$('#files_sm').html('<button data-src="fallback_image_url" type="button" data-content="" data-toggle="popover" class="btn btn-metis-2 preview">' + preview + '</button><div data-src="fallback_image_url" class="modal fade text-center" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
			} else if (file.error) {
				$('#fallback_image_url').val("");
				var error = $('<span class="text-danger"/>').text(file.error);
				$(data.context.children()[index])
						.append('<br>')
						.append(error);
			}
		});
	}).on('fileuploadfail', function (e, data) {
		$('#fallback_image_url').val("");
		$.each(data.files, function (index, file) {
			var error = $('<span class="text-danger"/>').text('File upload failed.');
			$(data.context.children()[index])
					.append('<br>')
					.append(error);
		});
	}).prop('disabled', !$.support.fileInput)
			.parent().addClass($.support.fileInput ? undefined : 'disabled');
});

$(function () {

	$('.files').on('click', '.preview', function(){

		var src = $(this).data('src');
		$('.modal[data-src=' + src + ']').html(previewCode).modal().click(function(){
			//$(this).modal('hide');
		});
	});


	// Gallery select
	$(document.body).on('click', '.gallery_modal_select' ,function(){
		$('#modal_select').val($( this ).data('file'));
		$('#galleryModal').modal('hide')
	});

	$('#galleryModal').on('hidden.bs.modal', function () {
		var modalSelect = $('#modal_select').val();
		if (modalSelect == '') return;
		$('#' + $('#modal_size').val()).val(modalSelect);
	});

	$('.btn-gallery').click(function() {
		$('#modal_size').val($(this).data('size'));
		var url = "index.php?ads&getimages&";
		if ($(this).data('size') == 'fallback_image_url'){
			url += "banner";
		} else {
			url += "video";
		}
		$.getJSON( url, function( data ) {
			$('#galleryModalBody').html(data);
			$('#galleryModal').modal();
		});
	});

});

function getFlashAdCode(src, height, width, url){
	var code;
	code += "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" height=\"" + height + "\" width=\"" + width + "\">";
	code += "<param name=\"movie\" value=\"" + src + "\"> ";
	code += "<param name=\"quality\" value=\"high\">";
	code += "<param name=\"menu\" value=\"false\">";
	code += "<param name=\"flashvars\" value=\"clickTAG=" + url + "\">";
	code += "<param name=\"allowScriptAccess\" value=\"always\" />";
	code += "<param name=\"wmode\" value=\"transparent\">";
	code += " <!--[if !IE]>-->";
	code += "  <object data=\"" + src + "\" height=\"" + height + "\" width=\"" + width + "\" type=\"application/x-shockwave-flash\">";
	code += "   <param name=\"quality\" value=\"high\">";
	code += "   <param name=\"menu\" value=\"false\">";
	code += "   <param name=\"pluginurl\" value=\"http://www.macromedia.com/go/getflashplayer\">";
	code += "   <param name=\"flashvars\" value=\"clickTAG=" + url + "\">";
	code += "   <param name=\"allowScriptAccess\" value=\"always\" />";
	code += "  </object>";
	code += " <!--<![endif]-->";
	code += "</object>";
	return code;
}

function getHtml5VideoAdCode(src, height, width, url, fallback_image_url){
	var code;
	var type;
	if (endsWith(src, 'mp4')){
		type = 'video/mp4';
	}else if (endsWith(src, 'webm')){
		type = 'video/webm';
	}
	var div_height = parseInt(height) - 20;
	code = "<a href=\"" + url + "\"><div style=\"position:absolute; width:" + width + "px; height:" + div_height + "px; z-index:10000;\"></div></a>";
	code += "<video width=\"" + width + "\" height=\"" + height + "\" poster=\"" + fallback_image_url + "\" controls autoplay muted>" +
			"<source src=\"" + src+ "\" type=\"" + type + "\"></video>";
	return code;
}

function endsWith(str, suffix) {
	return str.indexOf(suffix, str.length - suffix.length) !== -1;
}