var CREATOR = function() {

	this.init = function() {
		this.baseUrl = "http://localhost/onopix/index.php/gallery/create";
		
		this.updatePhotoInputs();
		
		//$('#searchButton').click( this.delegate(this, this.onClickSearch) );
		//$('#searchInput').change( this.delegate(this, this.onSearchInput) );
	},
	
	this.updatePhotoInputs = function() {
		var items = $('.selectPhoto');
		var i=0, item, length=items.length;
		
		for( ; i<length; i++ ) {
			item = items[i];
			$(item).change( this.delegate(this, this.onSelectPhoto) );
		}
	},
	
	this.onSelectPhoto = function( event ) {
		var target = event.target;
		
		this.evaluateFileSelectors();
		this.updatePhotoInputs();

		//console.log( target.files + ' : ' + target.files.length );
		//for( var x in target ) console.log( x + ' : ' + target[x] );
	},
	
	this.evaluateFileSelectors = function() {
		var items = $('.selectPhoto');
		var i=0, item, length=items.length;
		var filled = true;
		
		for (; i < length; i++) {
			item = items[i];
			if( item.files.length==0 ) filled = false;
		}
		
		if( filled==true ) this.addFileSelector();
	},
	
	this.addFileSelector = function() {
		var items = $('.selectPhoto');
		var id = items.length;
		
		var html = '<input type="file" name="photo_'+id+'" value="" id="photo_'+id+'" class="selectPhoto"  />';
		
		var lastItem = items[items.length-1];
		
		$(html).insertAfter( lastItem );
	},
	
	// General helper.
	this.delegate = function( scope, method ) {
		var fn = function() {
			var target = arguments.callee.target;
			var func = arguments.callee.func;
			
			return func.apply(target, arguments);
		}
		fn.target = scope;
		fn.func = method;
		return fn;
	}
}

var creator = new CREATOR();

$(document).ready( function() {
	creator.init();	
});
