function fileUploaderView(container, params)
{
    return new fileUploaderView.prototype.init(container, params)
}

function isAnyFilesExist(container, errMess)
{
	var c = fileUploaderView(container);
	if(c && !c.files.count())
	{
		alert(errMess);
		return false;
	}
	return true;
}

//$(window).bind('beforeunload', function() {alert('before unload');})

fileUploaderView.prototype = fileUploaderView.fn =
{
    controls: [],
    files: [],
    names:[],
    init: function (container, params)
    {
        this.$container = container instanceof jQuery? container: $(container);
        this.id = this.$container.data("fileUploaderView");
        if(!this.id)
        {
            this.$container.empty();
            params = params || {};
            this.id = "fileUploaderView"+fileUploaderView.fn.getUniqId();
            this.$container.data("fileUploaderView", this.id);
            fileUploaderView.fn.names[this.id] = params.name || "file";
            fileUploaderView.fn.controls[this.id] = {};            
            fileUploaderView.fn.controls[this.id].$hiddenControls = $('<div></div>').css({'position':'absolute', 'display':'none'}).addClass('hidden')
                .appendTo(this.$container);
            fileUploaderView.fn.controls[this.id].$filesOutput = $('<div></div>').addClass('filesOutput')
            	.appendTo(this.$container);
            if(params.button)
                fileUploaderView.fn.controls[this.id].$button = params.button instanceof jQuery? params.button: $(params.button);
            fileUploaderView.fn.files[this.id] = {farray:[]};
        }
                
        this.$button = fileUploaderView.fn.controls[this.id].$button;
        this.$button.val("");
        this.$hiddenControls = fileUploaderView.fn.controls[this.id].$hiddenControls;
        this.$filesOutput = fileUploaderView.fn.controls[this.id].$filesOutput;
        this.fileServerName = fileUploaderView.fn.names[this.id];
        this.timeInteval = null;
        this.files = fileUploaderView.fn.files[this.id];
        $.extend(this.files,
        {
            getFile: function(id, name)
            {
                for(var i in this.farray)
                {
                	if(!this.farray[i]) continue;
                    if((id && this.farray[i].id == id) || (name && this.farray[i].name == name))
                        return this.farray[i];
                }
                return null;
            },
            
            addFile: function(id, name, ndnCtrl, view)
            {
            	if(name!=null && view!=null)
            		this.farray[this.farray.length] = {id:id, name:name, ctrl:ndnCtrl, view:view};            	
            },
            
            removeFile: function(id, name)
            {
            	for(var i in this.farray)
                {
            		if(!this.farray[i]) continue;
	                if((id && this.farray[i].id == id) || (name && this.farray[i].name == name))
	                {
	                	this.farray[i] = null;
	                	return;
	                }
                }
            },
            
            count: function()
            {
            	var j = 0;
            	for(var i in this.farray)
                {
            		if(this.farray[i]!=null) j++;
                }
            	return j;
            }
        });
        
        fileUploaderView.fn.bindButtonEvent(this);
    },
    
    bindButtonEvent: function(obj)
    {
    	(function(obj){
            obj.$button.bind('mousedown', function() {fileUploaderView.fn.addFileClick(obj);});
        })(obj);
    },
    
    addFileClick: function(obj)
    {
    	obj.$button.trigger('click');
        fileUploaderView.fn.traceStart(obj);
    },
    
    traceStart: function(obj)
    {
    	if(!obj) return;
    	(function(obj)
		{
    		obj.timeInteval = setInterval(
    				function(){ fileUploaderView.fn.traceEnd(obj);},
    				2000);
		})(obj);        
    },
    
    traceEnd: function(obj)
    {    	
    	if(!obj.timeInteval) return;    	
    	if(obj.$button.val().length)
    	{
    		if(fileUploaderView.fn.isValid(obj))
    		{
	    		var hdn = obj.$button.clone();
	    		fileUploaderView.fn.cancelTrace(obj);
	    		if($.browser.msie)
	    		{	    		    
	    		    var tmp = obj.$button;
	    		    obj.$button.parent().append(hdn);
	    		    obj.$button = hdn;
	    		    hdn = tmp;
	    		    fileUploaderView.fn.bindButtonEvent(obj);
	    		    hdn.unbind('mousedown');	    		    
	    		}
	    		var dfFile = obj.fileServerName + obj.files.farray.length;
	    		hdn.attr({'id':dfFile, 'name':dfFile});
	    		obj.$hiddenControls.append(hdn);
	    		fileUploaderView.fn.addClientFile(obj, hdn);
    		}
    		else
				fileUploaderView.fn.cancelTrace(obj);			
    	}
    },
    
    cancelTrace: function(obj)
    {
    	obj.$button.val("");
		clearInterval(obj.timeInteval);
		obj.timeInteval = null;
    },
    
    isValid: function(obj)
    {
    	//debugger
    	var accept = obj.$button.attr('accept').toLowerCase();
    	var filePath = obj.$button.val();
    	var file = fileUploaderView.fn.getFileName(filePath);
    	if(accept && accept.length)
    	{
    		/*accept = accept.split('.');
    		accept = accept.length == 2 ? accept[1]: accept[0];*/
    		accept = accept.split('|');
    		var bAccepted = false;
    		//if(typeof(accept) == 'string')
    		for(var i in accept)
    		{
    			if(accept[i]==file.fileName.substring(file.fileName.lastIndexOf(".")+1).toLowerCase())
	    		{
    				bAccepted = true;
    				break;
	    		}
    		}
    		
    		if(!bAccepted)
    		{
    			alert('Разрешено загружать фотографии только форматов: ' + accept.join(', ') + '!');
    			return false;
    		}
    	}
    	if(obj.files.getFile(null, file.fileName))
    	{
    		alert('Файл' + file.fileName + ' уже загружен!');
			return false;
    	}
    	var reg=/[а-яА-Я]/; 
        var arr=reg.exec(file.fileName);  
        //alert(arr);
         if(arr!=null)
        {
            alert('Имена файлов должны содержать только латинские буквы');
            return false;
        }

    	var maxFilesCount = obj.$button.attr('maxFilesCount');
    	if(maxFilesCount && parseInt(maxFilesCount) <= obj.files.count())
		{
    		alert('Вы можете загрузить только ' + maxFilesCount + ' изображений!');
			return false;
    	}	
    	return true;
    },
    
    getFileName: function(filepath)
    {
    	var strs = filepath.split('\\');
    	var file = strs[strs.length-1];
    	var extFile = file.split('.');
    	return {fileName: file, name: extFile[0], ext: (extFile.length==2?extFile[1]:'')};
    },
    
    addClientFile: function(obj, newHdnCtrl)
    {
    	//debugger;
    	var filePath = newHdnCtrl.val();
    	var file = fileUploaderView.fn.getFileName(filePath).fileName;
    	var isCheckFirst = obj.$filesOutput.find('[checked=true]').length == 0;
    	fileUploaderView.fn.addFile(obj, filePath, file, null, newHdnCtrl, isCheckFirst);
    },
    
    addFile: function(obj, filePath, file, id, ctrl, isTop)
    {
    	var view = fileUploaderView.fn.getFileView(obj, filePath, file, id, isTop);
    	var ul = null;
    	ul = obj.$filesOutput.find('ul');
    	if(!ul.length)
    		ul = $('<ul></ul>').appendTo(obj.$filesOutput);
    	ul.append(view);
    	if(typeof(CustomControls) == 'function')
    		CustomControls();
    	obj.files.addFile(id, file, ctrl, view);
    },
    
    initFiles: function(obj, data)
    {
    	for(var i in data)
    	{
    		var item = data[i];
    		fileUploaderView.fn.addFile(obj, item.filePath, item.fileName, item.id, null, item.isTop);
    	}
    },
    
    getFileView: function(obj, filePath, fileName, id, isTop)
    {
    	var fileCounter = obj.files.farray.length;
    	var dblKey = (!id ? "null" : id) + "~" + fileName;
    	var key = 'general'+fileCounter;
    	var deleteLink = $('<a></a>').append($('<img src="'+jsOpt.base_url+'/images/add-new/delete.png" alt="основная"/>'));
    	(function(obj, id, fileName, deleteLink)
		{
    		deleteLink.bind('click', function() {fileUploaderView.fn.removeFile(obj, id, fileName);});
		})(obj, id, fileName, deleteLink)
    	
		var imgPic = $('<img class="foto" alt=""/>');
    	// if image not saved
		if(!id)
		{
			imgPic.addClass('noSizing');
			filePath = "./images/photo.gif";
		}
		imgPic.attr('src', filePath);
		var checker = $('<input type="radio" name="general" id="'+key+'" class="styled" value="'+dblKey+'"/>');
		if(!!isTop)
		{
			//checker.attr({'selected':'selected', 'checked':true});
			checker[0].checked = !!isTop;			
		}
		
    	var view = $('<li></li>').append(imgPic)
    		.append($('<p class="name"></p>').append($('<span></span>').text(fileName))
			.append(deleteLink)).append(checker)
			.append($('<label for="'+key+'">основная</label>'));
    	
    	return view.attr({fileName: fileName, fileId: id});
    },
    
    removeFile: function(obj, id, file)
    {
    	//debugger;
    	var fileInfo = obj.files.getFile(id, file);
    	if(fileInfo)
    	{
    		// file saved to db
    		if(fileInfo.id)
    		{
    			(function(obj, fileInfo)
				{
	    			$.getJSON(jsOpt.base_url+'/php.inc/catalog.handler.php',
    					{mode:"deleteImage", id: fileInfo.id},
	    				function(data)
	    				{
	    					debugger;
	    					if(data)
	    						fileUploaderView.fn.fileRemoved(obj, fileInfo);
	    				});
				})(obj, fileInfo);
				// �������� ����� �� ���� � � �������... ajax, 
    			// � ������� jsOpt����������� fileUploaderView.fn.fileRemoved(obj, fileInfo);
    		}
    		else
    			fileUploaderView.fn.fileRemoved(obj, fileInfo);
    	}
    },
    
    fileRemoved: function(obj, fileInfo)
    {
    	if(fileInfo.ctrl)
    		fileInfo.ctrl.remove();
    	if(fileInfo.view)
    		fileInfo.view.remove();
    	obj.files.removeFile(fileInfo.id, fileInfo.name);
    },
    
    getUniqId: function()
    {
        if (typeof this.lastId != "undefined")
            return ++this.lastId;
        this.lastId = 0;
        return 0;
    }
}

$.extend(fileUploaderView.fn.init.prototype,{
    getFiles: function()
    {
        return this.files;
    },
    
    initFiles: function(data)
    {
    	if(!data) return;
    	fileUploaderView.fn.initFiles(this, data);
    },
    
    prepare: function(fileSendName)
    {
        /*var hdn = this.$container.find('.hidden');
        if(!hdn.length)
        {
            hdn = $('<div></div>').css({'position':'absolute', 'display':'none'};
            this.$container.append(hdn);
        }
        for(var i in this.files)
        {
            var file = this.files[i];
            var inp = $('<input/>').attr('type', 'file').attr('name', fileSendName);
            inp.val(file);
        }*/
    }
});

function catalogViewImages(id, view)
{
	var container = $('#'+id);
	var view = $('#'+view);	
	if(!container.length || !view.length)
		return;
	var lis = container.find('ul li');
	(function(lis, view)
	{
		lis.bind('click', 
				function(){
                    view[0].src = String($(this).find('img').attr('src')).replace("thumb_","main_"); // Заменим файл эскиза на главный файл.
					view[0].alt = String($(this).find('img').attr('alt')); // Заменим файл эскиза на главный файл.
					lis.removeClass('active');
					$(this).addClass('active');
				});
	})(lis, view);
}

