/*
* uploads -- multiple files uploader jQuery plugin  
* https://github.com/Johntaa/upload-multiple-files
* Copyright 2015, Johntaa
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/



(function ($) {

	$.fn.uploads = function (e) {
		 
		var elem = document.getElementById('images');
		elem.style.display =  "none";
		var l = document.createElement("div");
		l.setAttribute('id', 'imgWrap');
		l.setAttribute('counter',0);
		var parentDiv = elem.parentNode; 
		parentDiv.insertBefore(l, elem);
		 
		$('#clickImage').click(function () {
			 $("input#images").trigger('click');
		});

		
		$(document).on('click', "button[id^='img-']", (function (event) {
			var $id = $(this).attr('id')
			 $(this).parent('div').remove();
			  $(document).find("input[id='"+$id+"']").remove();
			  return false;
		}));
		
		
		$(document).on('change', "input#images", (function (event) {
			 
			var counter = document.getElementById('imgWrap').getAttribute('counter');
				counter = parseInt(counter) + 1;
				document.getElementById('imgWrap').setAttribute('counter',counter);
				
				var imgsrc = URL.createObjectURL(event.target.files[0]);
				var wrap = document.createElement("div");
				wrap.setAttribute('id', "img-"+counter);
				
				var img = document.createElement("img");
				img.src = imgsrc;				
				img.setAttribute('id', "img-"+counter);
				
				var span = document.createElement("button");
				span.setAttribute('id', "img-"+counter);
				span.innerHTML = "X";
				
				document.getElementById("imgWrap").appendChild(wrap).appendChild(img);
				document.querySelectorAll("div#img-"+counter)[0].appendChild(span);
				
				var l = document.createElement("input");
				l.type = 'file';
				l.name = "images[]";
				l.setAttribute('id', "images");
				l.style.display = "none";
				
				 
				var parentD  = this.parentNode; 
				parentD.insertBefore(l, this);
				
				
				$(this).attr('id', 'img-'+counter);
				$(this).attr('name', 'img-'+counter);
				
				 

			}));

		return this;
	};

}
	(jQuery));
