/*
	NOTICE: Plugin uses class attribute for storing key. DO NOT dynamically clear class attribute!
*/

//
var fileUploading = false;	//	When file is uploaded this is set to true.

var counter = 0;

(function($){
	
	$.jimgupSettings = [];
	
	$.fn.jImageUploader = function(options) {
		/**
		 * Default options
		 */
		var messages = {
			wrongType: 'Netinkamo formato failas.',
			deleteImageConfirm:  'Ar tikrai norite ištrinti?',
			maxImages: 'Jūs įkėlėte maksimalų nuotraukų skaičių.',
			deleteImage: 'Trinti',
			moveUp: 'Aukštyn',
			moveDown: 'Žemyn'
		}
		
		var defaults = {
			dellink: '',
			groupName: 'Image',
			required: '',
			admin: '',
			image: [],
			type: 'multiple',
			maxImages: 5,
			sizeS: '',
			sizeM: '',
			resizeType: 'default'
		};
		
		var settings = {
			imageCounter : 0,
			imageCounterAbs : 0
		};
		
		/**
		 * Default model patterns
		 */
		var models = {
			singleModel: '<div><div style="float: left"><img class="thumb" src="" alt="" style="display:none" /></div><div style="margin-left: -25px; margin-top: 3px; float:left; background: transparent url(/img/bg-navlist.png) repeat scroll 0 0"><img src="/img/cross.png" class="delimg" alt="'+messages.deleteImage+'" style="display: none"/></div><input type="hidden" id="%did%" name="%hname%"'+((options.required == 'required') ? ' class="required"' : '')+'/><input type="hidden" name="dellink" value="%dellink%"/><div class="clear"></div><div><input type="file" name="%fname%" id="%fid%"><img src="/img/uploading.gif" class="imgUploading" alt="" style="display: none"/></div>',
			multipleModel: '<ul></ul><table><tr><td class="p0"><div><input type="file" name="%fname%" id="%fid%"/><img src="/img/uploading.gif" class="imgUploading" alt="" style="display: none"/></div></td><td class="vt p0">'+((options.required == 'required') ? '<span style="display:none" class="error">Privalote įkelti bent vieną nuotrauką.</span>' : '')+'</td></tr></table>',
			multipleSubmodel: '<li><div style="float: left"><img class="thumb" src="%src%" alt="%alt"/></div><div style="margin-left: -65px; margin-top: 3px; float:left; background: transparent url(/img/bg-navlist.png) repeat scroll 0 0"><img src="/img/cross.png" class="delimg" alt="'+messages.deleteImage+'"/><img src="/img/up.png" class="moveup" alt="'+messages.moveUp+'" /><img src="/img/down.png" class="movedown" alt="'+messages.moveDown+'" /></div><input type="hidden" name="%hname%" value="%hvalue%"/><input type="hidden" name="dellink" value="%dellink%"/><div class="clear"></div></li>'
		}
		
		/**
		 * Reference to selected object
		 */
		var selObjId;
		
		/**
		 * Returns object id by element class attribute
		 * @param string className Element class attribute
		 * @return mixed Id of the object or false if id is not found
		 */
		getObjIdByClass = function(className){
			if (strpos(className, 'jImgUp-') !== false) {
				objId = className.substr(strpos(className, 'jImgUp-')+7);
				objId = parseInt(objId.substr(0, strpos(objId, ' ')));
				return objId;
			}
			else return false;
		}
		
		/**
		 * Find object in parameters list and returns params
		 * @param mixed element Mixed type of element (ex. div, span, input)
		 * @return Object Upload object
		 */
		getObjectParams = function(element){
			//	Checking whether passed element is not top element
			if (!$(element).hasClass('imageUploader')){
				element = $(element).parents('div.imageUploader', 0);
			}
			
			//	Retrieving Upload object Id
			objId = getObjIdByClass($(element).attr('class'));
			
			if (objId !== false){
				if (!empty($.jimgupSettings[objId])) {
					//	Saving selected Upload object id
					selObjId = objId;
					return $.jimgupSettings[objId];
				}
				else
					return false;
			}
			else return false;
		}

		// Refreshes file input field. This is needed due to impossibility to set value="" for file input.
		refreshInput = function(_this){
			_this = $(_this).parent('div, span');
			$(_this).html($(_this).html());
		}
		
		//	Checks whether messages[msg] exists ad if so then calls alertMessage(msg). Otherwise alerts error 01;
		alertMessage = function(msg){
			if (!empty(messages[msg])) {
				_alertMessage(messages[msg]);
			}
			else
				alert('Plugin error 01.');
		}
		//	Later could be used to develop friendly alers.
		_alertMessage = function(msg){
			alert(msg);
		}
		
		//	Gets file extension.
		getExt = function(_this){
			str = $(_this).val();
		//	alert(str);
			dot = str.lastIndexOf(".");
			if(dot == -1) return false; 
			return str.substr(dot + 1,str.length).toLowerCase(); 
		}
		
		//	Checks whether chosen file is image. 
		isImage = function(_this, displayAlert){
			ext = getExt(_this);
			if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'png' || ext == 'gif')
				return true;
			else {
				if (displayAlert != false)
					alertMessage('wrongType');
				return false;
			}
		}
		
		//	Uploads image
		upload = function(_this){
			//	Retrieving upload object params
			params = getObjectParams(_this);

			input = $(_this).find('input[type=file]');
			elmId = $(input).attr('id');
		//	$(input).attr('disabled', 'disabled');
	
			$(_this).find('img.imgUploading')
			.ajaxStart(function(){
				fileUploading = true;
				$(this).show();
			});

			if (params.imageCounter >= params.maxImages) {
				alertMessage('maxImages');
				refreshInput(input);
				return false;
			}
			
			elmName = groupName = $(input).attr('name');
			elmName = elmName.substr(strpos(elmName, '][')+2);
			elmName = elmName.substr(0, elmName.length - 1);
			
			$.ajaxFileUpload({
				url: urlPath+params.admin+'/images/upload/'+elmName+'/'+params.groupName+'/s:'+params.sizeS+'/m:'+params.sizeM+'/t:'+params.resizeType, 
				secureuri:false,
				fileElementId: elmId,
				dataType: 'json',
				success: function (data, status){
					if(typeof(data.error) != 'undefined'){
						if(data.error != ''){
							alert(data.error);
							$(input).removeAttr('disabled');
						//	refreshInput($(_this).find('input[type=file]'));
						//	afterUpload(_this);
						//	onChange(_this);
						} 
						else {
							src = urlPath + 'files/uploads/temp_images/s' + data.msg;
							if (params.type == 'single') {
								$.jimgupSettings[selObjId].imageCounter = 1;
								$.jimgupSettings[selObjId].imageCounterAbs = 1;
								thumb = $(_this).find("img.thumb");
								del = $(_this).find("img.delimg");
								$(thumb).attr('src', src);
								$(thumb).attr('alt', data.msg);
								$(thumb).attr('title', data.msg);
								$(thumb).show();
								$(del).show();
								$(_this).find('input[type=hidden][name!=dellink]').val(data.id);
								$(input).removeAttr('disabled');
							}
							else if (params.type == 'multiple') {
								$.jimgupSettings[selObjId].imageCounter++;
								$.jimgupSettings[selObjId].imageCounterAbs++;
								ul = $(_this).find('ul');
								ins = models.multipleSubmodel
								.replace(/%src%/g, src)
								.replace(/%alt%/g, data.msg)
								.replace(/%hname%/g, 'data['+params.groupName+'][img'+$.jimgupSettings[selObjId].imageCounterAbs+']')
								.replace(/%hvalue%/g, data.id);
								$(ul).append(ins);
							}
						}
					}
				},
				error: function (data, status, e){
					alert(e);
					$(input).removeAttr('disabled');
					refreshInput($(_this).find('input[type=file]'));
					afterUpload(_this);
					onChange(_this);
				}
			})
		}

		//	Binds event onChange.
		onChange = function(_this){
			$(_this).find('input[type=file]').change(function(){
				if (!empty($(this).val())){
					if (!isImage(this)) {
						refreshInput(this);
					}
					else {
						upload(_this);
					}
					refreshInput($(_this).find('input[type=file]'));
					afterUpload(_this);
					onChange(_this);
				}
			});
		}
		
		//	Removes all binded events.
		afterUpload = function(_this){
			$(_this).find('input[type=file]').unbind('change');
			$(_this).find('img.imgUploading').ajaxComplete(function(){
				fileUploading = false;
				$(this).hide();
			});
		}
		
		/*
		// Generates multiple upload file list.
		generateList = function(_this){
			list = $(_this).find('ul li');
			
			/*
			newlist = [];
			$.each(list, function(i, item){
				newlist[i] = item;
			});
			/
			
			return list;
		}
		*/
		
		/**
		 * Extracts images for single Upload object
		 * @param object _this Upload object main element
		 * @param int objId Object id
		 */
		extractSingle = function(_this, objId){
			//	Retrieving object
			if (!empty($.jimgupSettings[objId])) {
			
				//	If object has some images
				if (!empty($.jimgupSettings[objId].image)){
					$.each($.jimgupSettings[objId].image, function(i,item){
						$.jimgupSettings[objId].imageCounter++;
						$.jimgupSettings[objId].imageCounterAbs++;
						thumb = $(_this).find("img.thumb");
						del = $(_this).find("img.delimg");
						$(thumb).attr('src', item.link+'s'+item.name);
						$(thumb).attr('alt', item.name);
						$(thumb).attr('title', item.name);
						$(thumb).show();
						$(del).show();
						$(_this).find('input[type=hidden][name!=dellink]').val(item.name);
					});
				}
			}
			//	Otherwise object does not exist
			else{
				alert('Plugin error 02s.');
			}	
		}
		
		/**
		 * Extracts images for multiple Upload object
		 * @param object _this Upload object main element
		 * @param int objId Object id
		 */
		extractMultiple = function(_this, objId){
			//	Retrieving object
			if (!empty($.jimgupSettings[objId])) {
				//	If object has some images
				if (!empty($.jimgupSettings[objId].image)){
					//	Retrieving list
					ul = $(_this).find('ul');
					
					//	Looping through all images in param
					$.each($.jimgupSettings[objId].image, function(i,item){
						$.jimgupSettings[objId].imageCounter++;
						$.jimgupSettings[objId].imageCounterAbs++;
						ins = models.multipleSubmodel
						.replace(/%src%/g, item.link+'s'+item.name)
						.replace(/%alt%/g, item.name)
						.replace(/%hname%/g, 'data['+$.jimgupSettings[objId].groupName+'][img'+$.jimgupSettings[objId].imageCounter+']')
						.replace(/%hvalue%/g, item.id);
						$(ul).append(ins);
					});
				}
			}
			//	Otherwise object does not exist
			else{
				alert('Plugin error 02m.');
			}
		}
		
		/**
		 * Initializes single upload object
		 * @param object _this Upload object main element
		 * @param object params Supplied parameters of Upload object
		 */
		single = function(_this, params){
			did = params.groupName+'Img'+counter;
			hname = 'data['+params.groupName+'][img'+counter+']';
			fid = params.groupName+'image'+counter;
			fname = 'data['+params.groupName+'][image'+counter+']';
			$(_this).addClass('jImgUp-'+counter).addClass('imageUploader');
			$(_this).html(models.singleModel.replace(/%fname%/g, fname).replace(/%hname%/g, hname).replace(/%fid%/g, fid).replace(/%did%/g, did).replace(/%dellink%/g, ''));
			onChange(_this);
			extractSingle(_this, counter);
		}
		
		/**
		 * Initializes multiple upload object
		 * @param object _this Upload object main element
		 * @param object params Supplied parameters of Upload object
		 */
		multiple = function(_this, params){
			fid = 'image'+counter;
			fname = 'data['+params.groupName+'][image'+counter+']';
			$(_this).addClass('jImgUp-'+counter).addClass('imageUploader');
			$(_this).html(models.multipleModel.replace(/%fname%/g, fname).replace(/%fid%/g, fid));
			onChange(_this);
			extractMultiple(_this, counter);
		}
		
		/**
		 * Main loop
		 */
		this.each(function() {
			//	Incrementing Upload object counter
			counter++;

			//	Merging settings
			$.jimgupSettings[counter] = $.extend({'id' : counter}, defaults, settings, {'messages' : messages}, {'models' : models}, options);
			
			//	If single Upload object
			if ($.jimgupSettings[counter].type == 'single'){
				single(this, $.jimgupSettings[counter]);
			}
			//	Else if multiple
			else if ($.jimgupSettings[counter].type == 'multiple'){
				multiple(this, $.jimgupSettings[counter]);
			}
		});
	};
})(jQuery);

(function($){
	$().ready(function(){
		// Livequery for image remove
		$("div.imageUploader img.delimg").livequery('click', function(){
			params = getObjectParams(this);

			if(confirm(params.messages.deleteImageConfirm)){
				if (params.type == 'single'){
					$.jimgupSettings[params.id].imageCounter = 0;
					parent = $(this).parent().parent('div');
					thumb = $(parent).find("img.thumb");
					name = $(thumb).attr('title');
					id = $(parent).find('input[type=hidden][name!=dellink]').val();
					dellink = $(parent).find('input[type=hidden][name=dellink]').val();
					$(thumb).attr('src', '');
					$(thumb).attr('alt', '');
					$(thumb).attr('title', '');
					$(thumb).hide();
					$(this).hide();
					$(parent).find('input[type=hidden][name!=dellink]').val('');
					if (!empty(dellink)) {
					}
					else {
						refreshInput($(this).find('input[type=file]'));
						$("#garbage").load(urlPath+'images/remove/'+id+'/'+name);
					}
				}
				else{
					li = $(this).parent().parent('li');
					thumb = $(li).find("img.thumb");
					name = $(thumb).attr('title');
					id = $(li).find('input[type=hidden][name!=dellink]').val();
					dellink = $(li).find('input[type=hidden][name=dellink]').val();
					$(li).remove();
					$.jimgupSettings[params.id].imageCounter--;
					if (!empty(dellink)) {
					}
					else {
						$("#garbage").load(urlPath+'images/remove/'+id+'/'+name);
					}
				}
			}
		});
		
		//	Livequery for multiple sort
		$('div.imageUploader div img.moveup:not(:first)').livequery('click', function(){
			_this = $(this).parent().parent('li');
			$(_this).insertBefore($(_this).prev());
		});
		$('div.imageUploader div img.movedown:not(:last)').livequery('click', function(){
			_this = $(this).parent().parent('li');
			$(_this).insertAfter($(_this).next());
		});
	});
})(jQuery);