/**
 * Freefolder javascript library
 * Project page - http://freefolder.com
 * Copyright (c) 2009 Filinberg Dmitriy, Michael Mikhulya, http://agileminds.ru
 * Version 0.1 (10.10.2009)
 */
/*
 *
 *	jQuery Timer plugin v0.1
 *		Matt Schmidt [http://www.mattptr.net]
 *
 *	Licensed under the BSD License:
 *		http://mattptr.net/license/license.txt
 *
 */
jQuery.timer = function (interval, callback) {
	var interval = interval || 100;

    if (!callback)
		return false;

	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};

		this.internalCallback = function () {
			callback(self);
		};

		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);

			var val = val*1000 || 100;
			this.id = setInterval(this.internalCallback, val);
		};

		this.interval = interval*1000;
		this.id = setInterval(this.internalCallback, this.interval);

		var self = this;
	};
	return new _timer(interval, callback);
 };

FreeFolder = function() {
	this.progressListeners = [];
	this.progressExecuters = new Array();
}

FreeFolder.prototype = {
    unionURL: '',
    unionStarted: false,
    unionProgress: function() {
        req = '';
        for (i in freefolder.progressExecuters) {
            if (freefolder.progressExecuters[i]!=null) {
                if (req!='') {
                    req += ',';
                }
                req += freefolder.progressExecuters[i].uploadId;
            }
        }
        if (req == '') {
            freefolder.unionExecuter.stop();
            freefolder.unionStarted = false;
        } else {
            rtime = new Date();
            $.ajax({
                    url: freefolder.unionURL+'&rnd='+rtime.getTime(),
                    type: 'POST',
                    data: 'ids='+req,
                    async: true,
                    success: function(transport) {
                        var json = eval("(" + transport + ")");
                        if(json) {
                            for (uuid in json) {
                                if(json[uuid].progress) {
                                    freefolder.notifyProgress(uuid, json[uuid].current, json[uuid].total, json[uuid].elapsed, json[uuid].percent);
                                } else if(json[uuid].success) {
                                    freefolder.notifySuccess(uuid);
                                    if(json[uuid].refreshJS != undefined && json[uuid].refreshJS != null && json[uuid].refreshJS != "") {
                                        eval(json[uuid].refreshJS);
                                    }
                                } else if (json[uuid].fail) {
                                    freefolder.notifyFail(uuid);
                                    if(json[uuid].refreshJS != undefined && json[uuid].refreshJS != null && json[uuid].refreshJS != "") {
                                        eval(json[uuid].refreshJS);
                                    }
                                } else {
                                    freefolder.notifyFail(uuid);
                                }
                            }
                        } else {
                            eval(transport);
                        }
                    },
                    error: function(transport) {
                        pe.freefolder.notifyFail(self.uploadId);
                    }});
        }
    },
    clearUploads: function() {
        $('#uploadProgressPanel > div:has(.upload_done)').remove();
    },
	uploadFile: function(uploadId, url, input) {
		var inputFile = document.getElementById(input);
		if(!inputFile.value) {
			return;
		}
		new AjaxUpload(input, inputFile, {
			action: url,
			name: 'fileInput',
			autoSubmit: false
		}).submit();
	},
	downloadFile: function(url) {
		var iframe = document.createElement("iframe");
		iframe.width="0";
		iframe.height="0";
		iframe.src=url;
		iframe.onload=function() {
			if(this.src=="about:blank") {
				document.body.removeChild(this);
				return;
			}
			this.src="about:blank";
		};
		document.body.appendChild(iframe);
	},
	getFile: function(inputId) {
		var input = document.getElementById(inputId);
		var file = new Object();
		file.name = "";
		file.size = 0;
		try {
			file.name = input.value;
			if (jQuery.browser.msie) {
				var fso = new ActiveXObject("Scripting.FileSystemObject"); 
				fileObj = fso.GetFile(input.value);
				file.name = fileObj.Name;
				file.size = fileObj.Size;
			} else if (jQuery.browser.Opera) {
				// how detect size for opera ?
			} else {
				var innerFile = input.files != undefined ? input.files[0] : null ;
				if(innerFile != null) {
					file.name = innerFile.fileName; 
					file.size = innerFile.fileSize;
				}
			}
			if(file.size == 0) {
				try {
					// detect size via Java
					file.size = new java.io.File(input.value).length();
				} catch (ignore) { }
			}
		} catch (ignore) { } 
		finally {
			try {
				var lastPathDelimiter = file.name.lastIndexOf("\\");
				if(lastPathDelimiter != -1) {
					file.name = file.name.substring(lastPathDelimiter + 1)
				}
				// encode
				file.name = encodeURIComponent(file.name);
			} catch (ignore) {}
		}
		return file;
	},
	getMultiUploadLocalFiles: function(containerId) {
		var localFiles = new Object();
		localFiles.ids = "";
		localFiles.files = "";
		localFiles.sizes = "";
		var separator = "|,|";
		try {
			var container = document.getElementById(containerId);
			var inputs = container.getElementsByTagName("input");
			for (var inputCount = 0; inputCount < inputs.length; inputCount++) {
				var input = inputs.item(inputCount);
				if(input.type != "file" || input.value == null || input.value == "") {
					continue;
				}
				var inputFile = this.getFile(input.id);
				if(inputCount > 0) {
					localFiles.ids += separator;
					localFiles.files += separator;
					localFiles.sizes += separator;
				}
				localFiles.ids += input.id;
				localFiles.files += inputFile.name;
				localFiles.sizes += inputFile.size;
			}			
		} catch(ignore) { }
		return localFiles;
	},
	getMultiUploadExternalFiles: function(containerId) {
		var externalFiles = new Object();
		externalFiles.urls = "";
		var separator = "|,|";
		try {
			var container = document.getElementById(containerId);
			var inputs = container.getElementsByTagName("input");
			for (var inputCount = 0; inputCount < inputs.length; inputCount++) {
				var input = inputs.item(inputCount);
				if(input.type != "text" || input.value == null || input.value == "") {
					continue;
				}
				if(inputCount > 0) {
					externalFiles.urls += separator;
				}
				externalFiles.urls += input.value;
			}			
		} catch(ignore) { }
		return externalFiles;
	},
	notifyStart: function(uploadId, fileSize) {
		if(!this.isProgress(uploadId)) {
            for (i in this.progressListeners) {
			//this.progressListeners.each(function(listener) {
				try {
					this.progressListeners[i].onStart.call(this.progressListeners[i], uploadId, fileSize);
				} catch (ignore) { /* TODO handling error */ }
			}
		}
	},
	notifyProgress: function(uploadId, current, total, elapsed, percent) {
		if(this.isProgress(uploadId)) {
			for (i in this.progressListeners) {
				try {
					this.progressListeners[i].onProgress.call(this.progressListeners[i], uploadId, current, total, elapsed, percent);
				} catch (err) { 	
					// TODO handling error
				}
			};
		}
	},
	notifySuccess: function(uploadId) {
		if(this.stopProgress(uploadId)) {
			for (i in this.progressListeners) {
				try {
					this.progressListeners[i].onSuccess.call(this.progressListeners[i], uploadId);
				} catch (err) {
					// TODO handling error
				}
			};
		}
	},
	notifyFail: function(uploadId) {
		if(this.stopProgress(uploadId)) {
			for (i in this.progressListeners) {
				try {
					this.progressListeners[i].onFail.call(this.progressListeners[i], uploadId);
				} catch (err) {
					// TODO handling error
				}
			};
		}
	},
	addProgressListener: function(listener) {
		this.progressListeners.push(listener);
	},
	removeProgressListener: function(listener) {
		this.progressListeners = this.progressListeners.without(listener);
	},
	randomizeParameters: function() {
		return "&r" + Math.floor(Math.random()*10001).toString() + "=" + Math.floor(Math.random()*10001).toString();
	},
	//startProgress: function(uploadId, callbackUrl, duration, fileSize) {
    startProgress: function(uploadId, duration, fileSize) {
		this.notifyStart(uploadId, fileSize);
		//lagutin
        var progressExecuter = new Object();
        ///lagutin
		//progressExecuter.callbackUrl = callbackUrl;
		progressExecuter.freefolder = this;
		progressExecuter.uploadId = uploadId;
		this.progressExecuters[uploadId] = progressExecuter;
        $('.downloads').show();

        //lagutin
        if (!this.unionStarted) {
            this.unionExecuter = $.timer(duration, this.unionProgress);
            this.unionStarted = true;
        }
        ///lagutin
	},
	stopProgress: function(uploadId) {
        if (typeof(this.progressExecuters[uploadId])!='undefined') {
            var progressExecuter = this.progressExecuters[uploadId];
            try {
                //lagutin
                //progressExecuter.stop();
                this.progressExecuters[uploadId] = null;
                return true;
            } catch (err) {
                return false;
            }
        }
		return false;
	},
	isProgress: function(uploadId) {
		return this.progressExecuters[uploadId] != null;
	}
}

ProgressListener = function(onStart, onProgress, onSuccess, onFail) {
	this._onStart = onStart;
	this._onProgress = onProgress;
	this._onSuccess = onSuccess;
	this._onFail = onFail;
}

ProgressListener.prototype = {
	onStart: function(uploadId, fileSize) {
		this._onStart.call(this, uploadId, fileSize);
	},
	onProgress: function(uploadId, current, total, elapsed, percent) {
		this._onProgress.call(this, uploadId, current, total, elapsed, percent);
	},
	onSuccess: function(uploadId) {
		this._onSuccess.call(this, uploadId);
	},
	onFail: function(uploadId) {
		this._onFail.call(this, uploadId);
	}
}

var freefolder = new FreeFolder();
uploadProgressListener = new ProgressListener(
	/* onStart */
	function(uploadId, fileSize) {  
		var item = this.getItem(uploadId);

		var count = parseInt(document.getElementById('amountUploads').innerHTML);
		count++;
		document.getElementById('downloadSearch').className = "download-search";
		document.getElementById('amountUploads').innerHTML = count.toString();
	},
	/* onProgress */
	function(uploadId, current, total, elapsed, percent) {  
		var item = this.getItem(uploadId);
		if(item != null && item != undefined) {
			item.uploadLength.html(current);
            if (total=='0 б') {
                $('.hidden-is').hide();
                item.totalLength.hide();
            } else {
                item.totalLength.html(total);
            }
			item.progressBar.css('width',percent);
		}
	},
	/* onSuccess */
	function(uploadId) {
		try {
			// TODO
			var count = parseInt(document.getElementById('amountUploads').innerHTML);
			count = (count == 1) ? 0 : (count - 1);
			if(count == 0) {
				document.getElementById('downloadSearch').className = "download-search no-download";
			}
			document.getElementById('amountUploads').innerHTML = count.toString();
			
			var item = this.getItem(uploadId);
			if(item != null && item != undefined) {
				if (item.fileSize!='0 б') {
                    item.uploadLength.html(item.fileSize);
                } else {
                    item.uploadLength.hide();
                }
				item.progressBar.css('width',"100%");
			}
		} catch(e) {}
		finally {
			this.unregisterItem(uploadId);
		}
	},
	/* onFail */	
	function(uploadId) {
		try {
			// TODO
			var count = parseInt(document.getElementById('amountUploads').innerHTML);
			count = (count == 1) ? 0 : (count - 1);
			if(count == 0) {
				document.getElementById('downloadSearch').className = "download-search no-download";
			}
			document.getElementById('amountUploads').innerHTML = count.toString();
		} catch(e) {}
		finally {
			this.unregisterItem(uploadId);
		}
	}
);
uploadProgressListener.getItem = function(uploadId) {
	return this._uploadItems[uploadId];
}

uploadProgressListener.removeItem = function(itemId) {
	var ui=document.getElementById(itemId); 
	ui.parentNode.removeChild(ui);
	return false;
}

uploadProgressListener.removeFile = function(removeUrl, itemId) {
	wicketShow('ajax-indicator');
	uploadProgressListener.removeItem(itemId);
	$.ajax({
        url: removeUrl,
        type: 'POST',
        async: true,
        success: function(transport) {
            wicketHide('ajax-indicator');
        },
        error: function(transport) {
            wicketHide('ajax-indicator');
        }});
	return false;
}

uploadProgressListener.refreshItemSuccess = function(itemId, fileName, fileSize, fileId) {
	var item = document.getElementById(itemId);
    if (item!=null) {
        item.innerHTML = '';
        var left=document.createElement('p');
        left.className='left';
        left.id = itemId+'_done';
        if (fileSize=='0 б') {
            left.innerHTML = "&nbsp;<span class=\"upload_done\"></span><a href=\"/?t=1#FileInfo&id=" + fileId + "\">" + fileName + "</a>";
        } else {
            left.innerHTML = "&nbsp;<span class=\"upload_done\"></span><a href=\"/?t=1#FileInfo&id=" + fileId + "\">" + fileName + "</a>&nbsp;" + fileSize;
        }
        item.appendChild(left);
        var right=document.createElement('p');
        item.appendChild(right);
        right.className='right';
        right.innerHTML="<a href=\"/?t=1#FileInfo&id=" + fileId + "\">Редактировать файл</a>&nbsp;" +
            "<a onclick=\"return uploadProgressListener.removeFile('/fileRemove?id=" + fileId + "', '" + itemId + "');\">Удалить файл</a>&nbsp;" +
            "Готово! &nbsp; <a onClick=\"return uploadProgressListener.removeItem('" + itemId + "');\" ><img src='images/close1.png' alt='' width='11' height='11'/></a>";
        var download = document.createElement('div');
        download.className='download';
        item.appendChild(download);
        download.innerHTML="<b>Скачать:</b>&nbsp;<a href=\"/?t=1#FileInfo&id=" + fileId + "\">http://freefolder.com/?t=1#FileInfo&id=" + fileId + "</a>&nbsp;&nbsp;<b>Удалить:</b>&nbsp;<a onclick=\"return uploadProgressListener.removeFile('/fileRemove?id=" + fileId + "', '" + itemId + "');\">http://freefolder.com/fileRemove?id=" + fileId + "</a>";
    }
}

uploadProgressListener.refreshItemFail = function(itemId, fileName, fileSize, fileId) {
    var item = document.getElementById(itemId);
    if (item!=null) {
        item.innerHTML = '';
        var left=document.createElement('p');
        left.className='left';
        left.id = itemId+'_done';
        if (fileSize=='0 б') {
            left.innerHTML = "&nbsp;<span class=\"upload_done\"></span>" + fileName;
        } else {
            left.innerHTML = "&nbsp;<span class=\"upload_done\"></span>" + fileName + "&nbsp;" + fileSize;
        }
        item.appendChild(left);
        var right=document.createElement('p');
        item.appendChild(right);
        right.className='right';
        right.innerHTML="<a onclick=\"return uploadProgressListener.removeFile('/fileRemove?id=" + fileId + "', '" + itemId + "');\">Удалить</a>&nbsp;<img src='images/close1.png' alt='' width='11' height='11'/></a>";
        var download = document.createElement('div');
        download.className='download';
        item.appendChild(download);
        download.innerHTML="<b>Ошибка закачки</b>";
    }
}

uploadProgressListener.setAmountUploads = function(amountUploads) {
	this._amountUploads = amountUploads;
}

uploadProgressListener.registerItem = function(uploadId, uploadLength, totalLength, progressBar) {
	if(this._uploadItems == null || this._uploadItems == undefined) {
		this._uploadItems = new Array();
	}
	var item = new Object();
	item.uploadLength = uploadLength;
	item.progressBar = progressBar;
	item.totalLength = totalLength;
	this._uploadItems[uploadId] = item;
};

uploadProgressListener.unregisterItem = function(uploadId) {
	if (typeof(this._uploadItems[uploadId])!='undefined' && this._uploadItems[uploadId]!=null) {
		this._uploadItems[uploadId] = null;
	}
};

freefolder.addProgressListener(uploadProgressListener);

// File list
freefolder.fileList = new Object();
freefolder.fileList.lastFileId = null;
freefolder.fileList.lastActionId = null;
freefolder.fileList.refreshFiles = function() {
	if(this.lastFileId != null) {
		var fileId = document.getElementById(this.lastFileId);
		if(fileId != null) {
			fileId.style.display="";
		}
	}
	if(this.lastActionId != null) {
		var actionId = document.getElementById(this.lastActionId);
		if(actionId != null) {
			actionId.style.display="none";
		}
	}
}
freefolder.fileList.resetFiles = function(files, event, force) {
	if(force || this._isOut(files, event)) {
		this.refreshFiles();
		this.lastFileId = null;
		this.lastActionId = null;
	}
}
freefolder.fileList._isOut = function(files, event) {
	var bound = document.getElementById(files).getBoundingClientRect();
	return bound.top > event.clientY || bound.bottom < event.clientY || bound.left > event.clientX || bound.right < event.clientX; 
}
freefolder.fileList.showAction = function(fileId, actionId) {
	if(fileId != this.lastFileId) {
		this.refreshFiles();
		document.getElementById(fileId).style.display="none";
		document.getElementById(actionId).style.display="";
		this.lastFileId = fileId;
		this.lastActionId = actionId;
	}
	return true;
}
// files progress bar for uploading
freefolder.fileList.uploadProgressListener = new ProgressListener(
	/* onStart */
	function(uploadId, fileSize) {  
		// ignore
	},
	/* onProgress */
	function(uploadId, current, total, elapsed, percent) {
		if(this._progressItems == null) {
			return;
		}
        if (typeof(this._progressItems[uploadId])!='undefined' && this._progressItems[uploadId]!=null) {
            var item = this._progressItems[uploadId];
			var progressBar = document.getElementById(item.progressBarId);
			if(progressBar != null) {
				progressBar.style.width = percent;
			}
		}
	},
	/* onSuccess */
	function(uploadId) {
		try {
			if(this._progressItems == null) {
				return;
			}
			if (typeof(this._progressItems[uploadId])!='undefined' && this._progressItems[uploadId]!=null) {
                var item = this._progressItems[uploadId];
				wicketAjaxGet(item.callbackUrl, null, null, null, null);
			}
		} catch(e) {}
		finally {
			this.unregisterItem(uploadId);
		}
	},
	/* onFail */	
	function(uploadId) {
		try {
			if(this._progressItems == null) {
				return;
			}
            if (typeof(this._progressItems[uploadId])!='undefined' && this._progressItems[uploadId]!=null) {
                var item = this._progressItems[uploadId];
				wicketAjaxGet(item.callbackUrl, null, null, null, null);
			}
		} catch(e) {}
		finally {
			this.unregisterItem(uploadId);
		}
	}
);
freefolder.addProgressListener(freefolder.fileList.uploadProgressListener);
freefolder.fileList.uploadProgressListener.registerItem = function(uploadId, progressBarId, callbackUrl) {
	if(this._progressItems == null) {
		this._progressItems = new Array();
	}
    if (typeof(this._progressItems[uploadId])=='undefined' || this._progressItems[uploadId]==null) {
		item = new Object();
		this._progressItems[uploadId] = item;
	}
	item.progressBarId = progressBarId;
	item.callbackUrl = callbackUrl;
}
freefolder.fileList.uploadProgressListener.unregisterItem = function(uploadId) {
	if(this._progressItems == null) {
		return;
	}
	this._progressItems[uploadId] = null;
}
freefolder.fileList.uploadProgressListener.resetItems = function() {
	if(this._progressItems == null) {
		return;
	}
	this._progressItems = null;
}
// link generator
freefolder.linkGenerator = new Object();
freefolder.linkGenerator.labelFilterTimer = function(labelFilterId, callbackUrl) {
	if(this._timer != null) {
		clearTimeout(this._timer);
	}
	this._timer = setTimeout("wicketAjaxGet('" + callbackUrl + "&labelFilter=' + document.getElementById('" + labelFilterId + "').value, null, null, null, null);", 1200);
};
freefolder.onInputEnter = function(script, event) {
	var keycode; 
	if (window.event) { 
		keycode = window.event.keyCode; 
	} else if (event) { 
		keycode = event.which;
	} else { 
		return true;
	}
	if (keycode == 13) {
		eval(script); 
		return false; 
	} else {
		return true; 
	}
}

freefolder.noSubmit = function(buttonId, event) {
	var keycode; 
	if (window.event) { 
		keycode = window.event.keyCode; 
	} else if (event) { 
		keycode = event.which;
	} else { 
		return true;
	}
	if (keycode == 13) { 
		return false; 
	} else {
		return true; 
	}
}

// delay before download
freefolder.delayBeforeDownload = function(timerId, url, time) {
	if(!this.delayBeforeDownloadState) {
		this.delayBeforeDownloadState = new Object();
	}
	this.delayBeforeDownloadState.time = time;
	this.delayBeforeDownloadState.timerId = timerId;
	this.delayBeforeDownloadState.url = url;
	if(this.delayBeforeDownloadExecuter) {
		this.delayBeforeDownloadExecuter.stop();
	}
	this.delayBeforeDownloadExecuter = $.timer(1, this.onDelayBeforeDownloadCallback);
}

freefolder.onDelayBeforeDownloadCallback = function() {
	if(freefolder.delayBeforeDownloadState.time==0) {
		freefolder.delayBeforeDownloadExecuter.stop();
		wicketShow('ajax-indicator');
		var wcall=wicketAjaxGet(freefolder.delayBeforeDownloadState.url, 
			function() { 
				wicketHide('ajax-indicator');
			}.bind(this), 
			function() { 
				wicketHide('ajax-indicator');
			}.bind(this)); 
		return;
	}
	var timer = $('#' + freefolder.delayBeforeDownloadState.timerId)
	timer.html(freefolder.Utils.splitTime(--freefolder.delayBeforeDownloadState.time));
	timer.attr('title', 'Осталось ' + freefolder.delayBeforeDownloadState.time + ' секунд');
}

freefolder.Utils = new Object();
freefolder.Utils.splitTime = function(second) {
	var h=Math.floor(second/3600);
	var m=Math.floor(second/60)-(h*60);
	if(h > 0 || m > 0) {
		var s=second-(h*3600)-(m*60);
		return (h < 10 ? "0" : "") + h + (s % 2 ? " " : ":") + (m < 10 ? "0" : "") + m + (s % 2 ? " " : ":") + (s < 10 ? "0" : "") + s;
	} else {
		return (second < 10 ? "0" : "") + second;
	}
}
freefolder.Utils.isValidNumber = function(inputId) {
    input = document.getElementById(inputId);
    if (input != null) {
        value = input.value.replace(',', '.');
        value_float = parseFloat(value);
        return (value_float.toString() == value && value_float >= 0.01);
    }
    return false;
}





