jQuery(document).ready(function(){
	
	// GET variables
	$.extend({
		getUrlVars: function(url){
			if (! url ) url = window.location.href;
			var vars = [], hash;
			var hashes = url.slice(url.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++) {
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
			}
			return vars;
		},
		getUrlVar: function(name){
			return $.getUrlVars()[name];
		}
	});
	
	// ADD titlecase
	function toTitleCase(str) {
		return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}
	
	var $mbcms = false;
	if ( window.location.href.indexOf("mbcms") != -1 ) $mbcms = true;
	
	var base_path = ( $mbcms ) ? '../' : 'mbcms/';
	
// UPLOADIFY / JCROP
	var fileDataName;
	var lib_path			= base_path +'libs/';
	var inc_path			= base_path +'inc/';
	var crop_script			= lib_path +'uploader_jcrop.php';
	var upload_script		= lib_path +'uploader_uploadify.php';
	var delete_script		= lib_path +'uploader_delete.php';
	var upload_cancelImg	= inc_path +'uploadify/cancel.png';
	var upload_folder		= 'uploads';
	var upload_path			= ( $mbcms ) ? '../../'+ upload_folder +'/' : upload_folder +'/';
	
	ImgInfo = new Object();
	var date = new Date();
	ImgInfo.date			= date.getTime();
	ImgInfo.refreshLink	= "?reload=true&time=";
	ImgInfo.uploadFolder	= 'uploads';
	ImgInfo.loading		= '<img class="show-loading" src="../images/loader_01.gif" alt="loading..." />';
	
	updateEditLinks();
	function updateEditLinks() {
		/* Add manual crop to the size links */
		$('.croplink a')
			.each(function(){
				$(this)
					.data('size', 		$(this).attr('id'))
					.data('id', 		$(this).attr('class'))
					.data('category', 	$(this).parent().parent().parent().siblings('input').attr('id'))
					.data('table', 		$(this).parent().parent().parent().siblings('input').attr('class'))
					.data('folder', 	upload_path + $(this).parent().parent().parent().siblings('input').attr('class'));
			})
			.click(function(e){
				e.preventDefault();
				$('img.show-loading').remove();
				$(this).parent().append('<img class="show-loading" src="../images/loader_01.gif" alt="loading..." />');
				// Get custom data from php
				//$(this).text('size = '+$(this).data('size')+', id = '+$(this).data('id')+', category= '+$(this).data('category')+', table= '+$(this).data('table')+', folder= '+$(this).data('folder'));
				var customData = loadCustomData($(this).data('id'), $(this).data('category'), $(this).data('table'), $(this).data('folder'));
				addManualCrop(customData, $(this).data('size'));
			});
		/**/
	}
	
	// Convert view links and thumbnail to use lightbox
	updateViewLinks();
	function updateViewLinks(date) {
		if (! date ) date = ImgInfo.date;
		$('.viewlink a, td.thumb a')
			.each(function(){
				var link = $(this).attr('href').replace("javascript:popImage('", '').replace("', '');", '');
				$(this)
					.data('link', link)
					.data('cache', ImgInfo.refreshLink + date);
			})
			.click(function(e){
				e.preventDefault();
				$.colorbox({href:$(this).data('link') + ImgInfo.refreshLink + ImgInfo.date});
			});
	};
	
	// Load the custom image data only
	function loadCustomData(id, category, table, folder) {
		/**/
		var output = $.ajax({
			type 		: 'POST',
			url 		: upload_script,
			dataType 	: 'json',
			data: {
				getCustomData	: '1',
				id				: id,
				category		: category,
				table			: table,
				folder			: folder
			},
			async:false,
			success : function(data) {
				//return $.parseJSON(data);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				//$(ImgInfo.container).after('<p class="form message email-status">'+XMLHttpRequest+'</p><p class="message email-status">'+textStatus+'</p><p class="message email-status">'+errorThrown+'</p><br />');
			}
		}).responseText;
		return $.parseJSON(output);
	};
	
	// Add manual cropping
	function addManualCrop(data, size) {
		ImgInfo.container 	= '#'+data.column+'-meta';
		ImgInfo.width  		= data.width;//data.customData.width;
		ImgInfo.height 		= data.height;//data.customData.height;
		ImgInfo.thumbWidth 	= data.customData.sizes[size].width;
		ImgInfo.thumbHeight = data.customData.sizes[size].height;
		ImgInfo.uploadTable	= data.table;
		ImgInfo.uploadPath	= ( $mbcms ) ? '../../'+ ImgInfo.uploadFolder +'/' + ImgInfo.uploadTable +'/' : '../'+ ImgInfo.uploadFolder +'/' + ImgInfo.uploadTable +'/';
		ImgInfo.data		= data;
		
		$("#cropper").remove();
		
		// $(".size a").colorbox({width:"75%", inline:true, href:"#aboutsizes"});
		// Build all of the new items for thumbnail cropping
		$(ImgInfo.container)
			.append( $(document.createElement('div')).attr('id', 'cropper').hide()
				.append( $(document.createElement('div')).attr('id', 'croparea')
					.prepend( '<h4>Select the Crop Area:</h4>' )
					.append( '<span class="button button-crop"><a class="crop" href="#" title="Crop the image">CROP</a></span>' )
					.append( $(document.createElement('div')).addClass('previewarea').css({'float':'right'})
						.append( $(document.createElement('div')).addClass('preview_container').css({'margin':0, 'padding':0, 'overflow':'hidden', 'width':ImgInfo.thumbWidth+'px', 'height':ImgInfo.thumbHeight+'px'}) )
						.append('<span class="preview-label" style="float:right; clear:right;">Preview</span>')
					)
					.append( $(document.createElement('div')).addClass('image_container').css({'float':'left', 'margin':0, 'padding':0}) )
					.append( $(document.createElement('input')).attr('name','x').attr('id','x').attr('type','hidden') )
					.append( $(document.createElement('input')).attr('name','y').attr('id','y').attr('type','hidden') )
					.append( $(document.createElement('input')).attr('name','w').attr('id','w').attr('type','hidden') )
					.append( $(document.createElement('input')).attr('name','h').attr('id','h').attr('type','hidden') )
				)
			);
		//$('#'+data.column+'-meta .deletelink a').text('../'+ upload_path + data.table +'/'+ data.filename );
		
		//var cropFilename = (data.manualCropBaseSize) ? ImgInfo.data.filename.replace('.jpg', '_'+data.manualCropBaseSize+'.jpg') : ImgInfo.data.filename;
		var cropFilename = ImgInfo.data.filename;
		
		var date = new Date();
		ImgInfo.date = date.getTime();
		
		// Create images to power the cropping
		var img = new Image();
		// Setup the new image for cropping
		$(img)
			.attr('id','cropbox')
			.attr('src', ImgInfo.uploadPath + cropFilename + ImgInfo.refreshLink + ImgInfo.date)
			.load(function(){
				if (! ImgInfo.height ) ImgInfo.height = $(this).attr('height');
				var height = $(this).attr('height');
				if (! ImgInfo.width ) ImgInfo.width = $(this).attr('width');
				$(ImgInfo.container +' .image_container').append( $(this) );
				
				$(ImgInfo.container +' .image_container').css({'width':ImgInfo.width+'px', 'height':ImgInfo.height+'px'});
				$(this).css({'width':ImgInfo.width+'px', 'height':ImgInfo.height+'px'});
				
				// Create the crop preview area
				var imgPrev = new Image();
				$(imgPrev)
					.attr('id','preview')
					.attr('src', ImgInfo.uploadPath + cropFilename + ImgInfo.refreshLink + ImgInfo.date);
				$(ImgInfo.container +' .preview_container').append( $(imgPrev) );
					
				// Open popup lightbox using colorbox
				//$.colorbox.close();
				var activeWidth = (ImgInfo.data.customData.manualCropWidth) ? ImgInfo.data.customData.manualCropWidth : "700";
				$.colorbox({width:activeWidth+"px", inline:true, href:"#croparea", scrolling:false, onClosed:function(){ $("#cropper").remove(); }}, function(){
					ImgInfo.container_active = '#cboxContent';
					$('img.show-loading').remove();
					// Activate Jcrop
					$(ImgInfo.container_active +' .image_container img').Jcrop({
						onChange	: showPreview,
						aspectRatio	: ImgInfo.thumbWidth / ImgInfo.thumbHeight,
						onSelect	: updateCoords,
						setSelect	: [ 0, 0, ImgInfo.thumbWidth, ImgInfo.thumbHeight ],
						minSize		: [ ImgInfo.thumbWidth, ImgInfo.thumbHeight ]
					});
					
					// Crop the image and save when crop button is clicked
					$(ImgInfo.container_active +' a.crop').click(function(e){
						e.preventDefault();
						$('img.show-loading').remove();
						$(this).before( ImgInfo.loading );
						//$(ImgInfo.container_active +' a.crop').text('test: '+ImgInfo.uploadFolder +'/'+ ImgInfo.uploadTable +'/'+ImgInfo.data.filename);
						var crop_returnData = $.ajax({
							type 		: 'POST',
							url 		: crop_script,
							dataType 	: 'json',
							data : {
								src_x 		: $(ImgInfo.container_active+' #x').val(),
								src_y 		: $(ImgInfo.container_active+' #y').val(),
								src_w 		: $(ImgInfo.container_active+' #w').val(),
								src_h 		: $(ImgInfo.container_active+' #h').val(),
								id 			: $.getUrlVar('id'),
								col 		: ImgInfo.data.column,
								size		: size,
								customData	: ImgInfo.data.customData,
								filepath	: ImgInfo.uploadFolder +'/'+ ImgInfo.uploadTable +'/',
								filename	: ImgInfo.data.filename,
								table		: ImgInfo.data.table
							},
							success : function(data){
								//$(ImgInfo.container_active +' a.crop').text('success');
								var date = new Date();
								ImgInfo.date = date.getTime();
								
								$(ImgInfo.container +' .viewlink a[rel='+data.request.size+']')
									.data('cache', ImgInfo.refreshLink + ImgInfo.date);
									//.text(ImgInfo.refreshLink + ImgInfo.date);
								
								// Create success message
								var $msg_success = $(document.createElement('span'))
									.addClass('updated')
									.attr('id','updated')
									.css({'background-color':'#ffc', 'color':'#f60', 'display':'block', 'font-weight':'bold', 'padding':'4px 8px', 'margin':'4px 0 0', 'text-align':'center', 'width':'auto'})
									.text('Image Sizes Updated');
								
								// Remove active crop area
								$(ImgInfo.container_active +' #croparea').fadeOut(1000, function(){ 
									// Add success message
									$(this)
										.after( $msg_success.fadeIn(500, function(){ $(this).animate({backgroundColor:'#ffffff'}, 3000); }) );
									$.colorbox.close();
								});
									
								// Update thumbnails and links (old)
								//$(ImgInfo.container +' .thumb2').html("<a href=\"javascript:popImage('"+ ImgInfo.uploadPath + ImgInfo.filethumbname + ImgInfo.refreshLink +"', '');\"><img src=\""+ ImgInfo.uploadPath + ImgInfo.filethumbname + ImgInfo.refreshLink +"\" width=\"70\" />");
								//if ( $(ImgInfo.container +' .thumb2 img').length != 0 ) {
								//	$(ImgInfo.container +' .thumb2 img').attr('src', $(ImgInfo.container +' .thumb2 img').attr('src') + ImgInfo.refreshLink);
								//}
							},
							error : function(XMLHttpRequest, textStatus, errorThrown) {
								//$(ImgInfo.container_active +' a.crop').text('error');
							}
						});
					});
				});
			});
		
	};
	
	addDeletePop();
	function addDeletePop() {
		$('body')
			.append( $(document.createElement('div')).attr('id', 'deleter').hide()
				.append( $(document.createElement('div')).attr('id', 'deletearea')
					.html('<h2>Are you sure you want to delete this?</h2> <p>This action is irreversible.</p>')
					.append( $(document.createElement('p'))
						.addClass('button button-cancel')
						.append( '<a href="#" title="Do not delete file">Cancel</a>' )
					)
					.append( $(document.createElement('p'))
						.addClass('button button-delete')
						.append( '<a href="#" title="Delete file">Delete</a>' )
					)
				)
			);
	};
	
	updateDeleteLinks();
	function updateDeleteLinks() {
		// Override Delete Image to add popup dialog and AJAX delete
		$('.deletelink a').click(function(e){
			e.preventDefault();
			var delete_variables, table;
			
			ImgInfo.deleter = $(this);
			
			// Process link variables
			delete_variables = $.getUrlVars($(this).attr('href'));
			table = $(this).parent().parent().siblings('input').attr('class');
			
			$('.button-delete')
				.data('table', table)
				.data('file_name', delete_variables['file_name'])
				.data('id', delete_variables['id'])
				.data('field_name', delete_variables['field_name'])
				.data('script', delete_script);
			
			$.colorbox({width:"400px", inline:true, href:"#deletearea", scrolling:false}, function() {
				$('.button-cancel').click(function(e){
					e.preventDefault();
					$.colorbox.close();
				});
				$('.button-delete').click(function(e){
					e.preventDefault();
					var test = $.ajax({
						type 		: 'POST',
						url 		: $(this).data('script'),
						dataType 	: 'json',
						data : {
							table		: $(this).data('table'),
							file_name	: $(this).data('file_name'),
							id			: $(this).data('id'),
							field_name	: $(this).data('field_name')
						},
						success : function(data){
							//ImgInfo.deleter.text('success');
							ImgInfo.deleter.parent().parent().empty();
						},
						error : function(XMLHttpRequest, textStatus, errorThrown) {
							ImgInfo.deleter.text('error');
						}
					});
					$.colorbox.close();
				});
			});
		});
	};
	
	function updateCoords(c) {
		$(ImgInfo.container_active+' #x').val(c.x);
		$(ImgInfo.container_active+' #y').val(c.y);
		$(ImgInfo.container_active+' #w').val(c.w);
		$(ImgInfo.container_active+' #h').val(c.h);
	};
	function checkCoords() {
		if (parseInt($('#w').val()) ) return true;
		alert('Please select a crop region then press submit.');
		/*$('#x').val(0);
		$('#y').val(0);
		$('#w').val(150);
		$('#h').val(150);*/
		return false;
	};
	function showPreview(coords) {
		if ( parseInt(coords.w) > 0 ) {
			var rx = ImgInfo.thumbWidth / coords.w;
			var ry = ImgInfo.thumbHeight / coords.h;
			$(ImgInfo.container_active +' #preview').css({
				width		: Math.round(rx * ImgInfo.width) + 'px',
				height		: Math.round(ry * ImgInfo.height) + 'px',
				marginLeft	: '-' + Math.round(rx * coords.x) + 'px',
				marginTop	: '-' + Math.round(ry * coords.y) + 'px'
			});
		}
	};
	
	addUploadify();
	function addUploadify() {
		$('input[rel=uploadify]').each(function(){
			fileDataName = $(this).attr('name');
			var table = $(this).attr('class');
			var categoryId = ( $mbcms ) ? $.getUrlVar('categoryId') : $(this).parent().siblings('#categoryId').attr('value');
			var scriptData = {'col': $(this).attr('name'), 'id': $.getUrlVar('id'), 'categoryId': categoryId, 'table': table, 'userId': $('input[name=userId]').val()};
			$(this).uploadify({
				'uploader'		: base_path +'inc/uploadify/uploadify.swf',
				'script'		: upload_script,
				'scriptData'	: {'col': $(this).attr('name'), 'id': $.getUrlVar('id'), 'categoryId': categoryId, 'table': table, 'userId': $('input[name=userId]').val(), 'active': ($mbcms ? '1' : '0')},
				'method'		: 'GET',
				'cancelImg'		: base_path +'inc/uploadify/cancel.png',
				'auto'			: true,
				'folder'		: upload_path + table,
				'buttonText'	: 'Choose File',
				'multi'			: false,
				'fileDataName'	: fileDataName,
				'sizeLimit'		: 1024*1024*100, //100M = 1024*1024*100
				'fileExt'		: '*.jpg;*.gif;*.png;*.avi;*.mjp;*.mpg;*.mpeg;*.mp4;*.m4v;*.3pg;*.mov;*.wmv;*.divx;*.flv',
				'fileDesc'		: 'File types (jpg,gif,png,avi,mjp,mpg,mpeg,mp4,m4v,3pg,mov,wmv,divx,flv)',
				/** /'onSelect'		: function (event, queueID, fileObj) {
					var file_array = fileObj.name.split('.');
					var extension = file_array.pop();
					var ext = extension.toLowerCase();
					console.log('ext = '+ext);
					console.log(1024*1024*7);
					console.log(event);
					console.log(queueID);
					console.log(fileObj);
					switch (ext) {
						case 'jpg':
						case 'jpeg':
						case 'gif':
						case 'png':
							if ( fileObj.size > (1024*1024*7) ) {
								$('input[rel=uploadify]').each(function(){
									$('#fileUploader').uploadifyCancel(queueID);
								});
								return false;
							}
							break;
						default:
							break;
					}
				},/**/
				'onComplete'	: function(event,queueID,fileObj,response,data){ 
					//alert(response);
					if ( $mbcms ) {
						updatePostUploadifyMbcms(response);
					} else {
						updatePostUploadify(response);
					}
				},
				'onError'		: function(event,ID,fileObj,errorObj){
					//alert(errorObj.info);
					//var json = eval('(' + errorObj + ')');
					
					//$('form p.message').html(json.msg);
				}
			});
		});
	};
	
	function updatePostUploadifyMbcms( response ) {
		var json = eval('(' + response + ')');
		if ( json.status ) {
			//$('.uploadifyQueue').hide();
			
			var date = new Date();
			ImgInfo.date = json.date; //date.getTime();
			ImgInfo.container = '#'+json.column+'-meta';
			
			$(ImgInfo.container).siblings('input#file').remove();
			
			if ( $(ImgInfo.container +' input[name=id]').length == 0 ) {
				$(ImgInfo.container)
					.append( $(document.createElement('input')).attr('type',"hidden").attr('name',"id") );
			}
			$('input[name=id]').attr('value', json.id);
			
			// Build the basics if this is a new image upload
			if ( $(ImgInfo.container +' .deletelink').length == 0 ) {
				$(ImgInfo.container)
					.append( $(document.createElement('span')).addClass("deletelink") )
					.append( "<br />Click on the image to see it full-size.<br />" )
					.append( "<table><tr><td><img src=\"../images/image_arrow.gif\"></td><td class=\"thumb\"></td><td class=\"thumb2\"></td></tr><tr><td></td><td class=\"filename\"></td></tr></table>" );
			}
			
			// Make sure there is a deletelink to delete file
			$(ImgInfo.container +' .deletelink').html("<a href=\"?action=delete_file&file_name="+json.filename+"&id="+json.id+"&field_name="+json.column+"\">DELETE</a> "+json.filename);
			
			// Update filename (incase filename is set to use uploaded name)
			$(ImgInfo.container +' .filename').html(json.filename);
			// Remove updated, since it will be added again below
			$(ImgInfo.container +' .updated').remove();
			
			// Update the main area and add "Updated" banner
			$('#'+json.column+'-meta')
				.fadeIn('slow')
				.prepend("<span class=\"updated\" style=\"background-color:#ffc; color:#f60; display:block; font-weight:bold; padding:4px 8px; margin:4px 0 0; text-align:center; \">Updated</span><br />")
				.stop()
				.animate({ backgroundColor: '#ffffcc' }, 500, function() { $(this).animate({ backgroundColor: '#ffffff' }, 3000); });
			
			// Test for manual crop
			var setupManualCrop = json.customData.manualCrop;
			if ( $.isArray(json.customData.sizes) && json.customData.sizes.length != 0 ) {
				$.each( json.customData.sizes, function(key, value) {
					if ( value.manualCrop === true ) {
						setupManualCrop = true;
						
						// Add crop and view links if needed
						if ( $(ImgInfo.container +' .croplinks').length == 0 ) {
							$(ImgInfo.container +' .deletelink')
								.after( $(document.createElement('br'))
									.after( $(document.createElement('div')).addClass('croplinks') )
								);
						}
						if ( $(ImgInfo.container +' .croplinks a#'+ key).length == 0 ) {
							$(ImgInfo.container +' .croplinks')
								.append( $(document.createElement('span')).addClass('croplink')
									.append( '<a href="#" id="'+key+'" class="'+json.id+'" rel="jcrop['+key+']">Crop '+toTitleCase(key)+' Size</a>' )
								)
								.append( $(document.createElement('span')).addClass('viewlink')
									.append( " (<a href=\"javascript:popImage('"+json.filepath+'/'+ json.filename.replace('.jpg', '_'+key+'.jpg') + ImgInfo.refreshLink + ImgInfo.date+"', '');\">View</a>)" )
								)
								.append( $(document.createElement('br')) );
						} else {
							$(ImgInfo.container +' .croplinks a#'+ key).parent().siblings('.viewlink').children('a')
								.data('link', json.filepath+'/'+json.filename.replace('.jpg', '_'+key+'.jpg'))
								.data('cache', ImgInfo.refreshLink + ImgInfo.date);
						}
					}
				});
			}
			
			$(ImgInfo.container +' .thumb a')
				.data('link', json.filepath+'/'+json.filename)
				.data('cache', ImgInfo.refreshLink + ImgInfo.date);
			
			if ( $(ImgInfo.container +' .thumb img').length == 0 ) {
				$(ImgInfo.container +' .thumb')
					.append( $(document.createElement('a')).attr('href',"javascript:popImage('"+ json.filepath +'/'+ json.filename + ImgInfo.refreshLink + ImgInfo.date +"', '');")
						.append( $(document.createElement('img')).attr('width','70') )
					)
			}
			$(ImgInfo.container +' .thumb img').attr('src', json.filepath +'/'+ json.filename + ImgInfo.refreshLink + ImgInfo.date);
			
			updateDeleteLinks();
			updateEditLinks();
			updateViewLinks(json.date);
			
		} else {
			alert('error');
		}
	}
	
	function updatePostUploadify( response ) {
		/**
		 * Using alert(response) is VERY important! you will see any php errors returned, without it your are blind.
		 * Use it to troubleshoot EVER TIME something goes wrong.
		 */
		// alert(response);
		var json = eval('(' + response + ')');
		
		$('form p.message').html(json.msg);
		
		if ( json.status ) {
			$('input[name=id]').attr('value', json.id);
			$('input#file').remove();
			//alert('complete id='+json.id+' id='+json.id+' column='+json.column);
			
			// Setup whether is image and the parent upload containers
			var file_array = json.filename.split('.');
			var extension = file_array.pop();
			var file_thumbnail = file_array.join('') +'_thumbnail.jpg';
			/**/
			var ext_lower = extension.toLowerCase();
			
			// Only concerned with web-ready images
			var is_image = ( ext_lower == 'jpeg' || ext_lower == 'jpg' || ext_lower == 'png' || ext_lower == 'gif' ) ? true : false;
			
			var $photo_link = $('div.upload h4.photo a');
			var $video_link = $('div.upload h4.video a');
			
			/**/
			var date = new Date();
			ImgInfo.date = json.date; //date.getTime();
			ImgInfo.container = '#'+json.column+'-meta';
			/**/
			if ( $(ImgInfo.container +' .thumb img').length == 0 ) {
				if ( $(ImgInfo.container +' .thumb').length == 0 ) {
					$(ImgInfo.container)
						.append( $(document.createElement('p')).addClass('thumb') );
				}
				
				$thumb_container = $(ImgInfo.container +' .thumb');
				if ( is_image ) {
					$thumb_container.append( $(document.createElement('a')).addClass('colorbox').attr('href', json.filepath +'/'+ json.filename + ImgInfo.refreshLink + ImgInfo.date) );
					$thumb_container = $(ImgInfo.container +' .thumb a');
					$('a.colorbox').colorbox();
				}
				$thumb_container.append( $(document.createElement('img')).attr('width','70') );
			}
			
			$(ImgInfo.container +' .thumb img').attr('src', json.filepath +'/'+ file_thumbnail + ImgInfo.refreshLink + ImgInfo.date);
			
			/**/
			if ( is_image == true ) {
				disablePhotoVideoUploader($video_link);
				switchPhotoVideoUploader($photo_link);
			} else {
				disablePhotoVideoUploader($photo_link);
				switchPhotoVideoUploader($video_link);
			}
			$('div.upload form .submit').show();
			//$video_link.text(is_image);
			/**/
		} else {
			
		}
	}

});

