onSelectFired = false;
var singleMode = false;
var privateFlag = false;


/**
 * Swiff.Uploader - Flash FileReference Control
 *
 * @version		1.2
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

Swiff.Uploader = new Class({

	Extends: Swiff,

	Implements: Events,

	options: {
		path: 'Swiff.Uploader.swf',
		multiple: true,
		queued: true,
		typeFilter: null,
		url: null,
		method: 'post',
		data: null,
		fieldName: 'Filedata',
		target: null,
		height: '100%',
		width: '100%',
		callBacks: null
	},

	initialize: function(options){
		if (Browser.Plugins.Flash.version < 9) return false;
		this.setOptions(options);

		var callBacks = this.options.callBacks || this;
		if (callBacks.onLoad) this.addEvent('onLoad', callBacks.onLoad);
		if (!callBacks.onBrowse) {
			callBacks.onBrowse = function() {
				return this.options.typeFilter;
			}
		}

		var prepare = {}, self = this;
		['onBrowse', 'onSelect', 'onAllSelect', 'onCancel', 'onBeforeOpen', 'onOpen', 'onProgress', 'onComplete', 'onError', 'onAllComplete'].each(function(index) {
			var fn = callBacks[index] || $empty;
			prepare[index] = function() {
				self.fireEvent(index, arguments, 10);
				return fn.apply(self, arguments);
			};
		});

		prepare.onLoad = this.load.create({delay: 10, bind: this});
		this.options.callBacks = prepare;

		var path = this.options.path;
		if (!path.contains('?')) path += '?noCache=' + $time(); // quick fix

		this.parent(path);

		var scroll = window.getScroll();
		this.box = new Element('div', {
			styles: {
				position: 'absolute',
				visibility: 'visible',
				zIndex: 999,
				overflow: 'hidden',
				height: 15, width: 15,
				top: scroll.y, left: scroll.x
			}
		});
		this.inject(this.box);
		this.box.inject($(this.options.container) || document.body);

		return this;
	},

	load: function(){
		this.remote('register', this.instance, this.options.multiple, this.options.queued);
		this.fireEvent('onLoad');

		this.target = $(this.options.target);
		if (Browser.Plugins.Flash.version >= 10 && this.target) {
			this.reposition();
			window.addEvent('resize', this.reposition.bind(this));
		}
	},

	reposition: function() {
		var pos = this.target.getCoordinates(this.box.getOffsetParent());
		this.box.setStyles(pos);
	},

	/*
	Method: browse
		Open the file browser.
	*/

	browse: function(typeFilter){
		this.options.typeFilter = $pick(typeFilter, this.options.typeFilter);
		return this.remote('browse');
	},

	/*
	Method: upload
		Starts the upload of all selected files.
	*/

	upload: function(options){
		var current = this.options;
		current.url = current.url + '&batchID=' + uploadBatchID + '&isPrivate=' + privateFlag;
		options = $extend({data: current.data, url: current.url, method: current.method, fieldName: current.fieldName}, options);
		if ($type(options.data) == 'element') options.data = $(options.data).toQueryString();
		return this.remote('upload', options);
	},

	/*
	Method: removeFile
		For multiple uploads cancels and removes the given file from queue.

	Arguments:
		name - (string) Filename
		name - (string) Filesize in byte
	*/

	removeFile: function(file){
		if (file) file = {name: file.name, size: file.size};
		return this.remote('removeFile', file);
	},

	/*
	Method: getFileList
		Returns one Array with with arrays containing name and size of the file.

	Returns:
		(array) An array with files
	*/

	getFileList: function(){
		return this.remote('getFileList');
	}

});


/**
 * Fx.ProgressBar
 *
 * @version		1.0
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

Fx.ProgressBar = new Class({

	Extends: Fx,

	options: {
		text: null,
		transition: Fx.Transitions.Circ.easeOut,
		link: 'cancel'
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.parent(options);
		this.text = $(this.options.text);
		this.set(0);
	},

	start: function(to, total) {
		return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
	},

	set: function(to) {
	    this.now = to;
	    this.element.setStyle('width', Math.round(to) + '%');
	    if (this.text) this.text.set('text', Math.round(to) + '%');
		return this;
	}

});


/**
 * FancyUpload - Flash meets Ajax for powerful and elegant uploads.
 *
 * @version		2.1
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

var FancyUpload2 = new Class({

	Extends: Swiff.Uploader,

	options: {
		limitSize: false,
		limitFiles: 5,
		instantStart: false,
		allowDuplicates: false,
		validateFile: $lambda(true), // provide a function that returns true for valid and false for invalid files.
		debug: false,

		fileInvalid: null, // called for invalid files with error stack as 2nd argument
		fileCreate: null, // creates file element after select
		fileUpload: null, // called when file is opened for upload, allows to modify the upload options (2nd argument) for every upload
		fileComplete: null, // updates the file element to completed state and gets the response (2nd argument)
		fileRemove: null // removes the element
		/**
		* Events:
		* onBrowse, onSelect, onAllSelect, onCancel, onBeforeOpen, onOpen, onProgress, onComplete, onError, onAllComplete
		*/
	},

	initialize: function(status, list, options) {
		this.status = $(status);
		this.list = $(list);

		this.files = [];

		if (options.callBacks) {
			this.addEvents(options.callBacks);
			options.callBacks = null;
		}

		this.parent(options);
		this.render();
	},

	render: function() {

	},

	onLoad: function() {
		this.log('Uploader ready!');
	},

	onBeforeOpen: function(file, options) {
		this.log('Initialize upload for "{name}".', file);
		var fn = this.options.fileUpload;
		var obj = (fn) ? fn.call(this, this.getFile(file), options) : options;
		return obj;
	},

	onOpen: function(file, overall) {
		this.log('Starting upload "{name}".', file);
		file = this.getFile(file);
		file.element.addClass('file-uploading');
		file.progress.cancel().set(0);
	},

	onProgress: function(file, current, overall) {
		file = this.getFile(file);
		file.progress.start(current.bytesLoaded, current.bytesTotal);
	},

	onSelect: function(file, index, length) {
		var errors = [];
		if (this.options.limitSize && (file.size > this.options.limitSize)) { ; errors.push('size') };
		if (this.options.limitFiles && (this.countFiles() >= this.options.limitFiles)) errors.push('length');
		if (!this.options.allowDuplicates && this.getFile(file)) errors.push('duplicate');
		if (!this.options.validateFile.call(this, file, errors)) errors.push('custom');
		if (errors.length) {
			file.isValid = false;
			var fn = this.options.fileInvalid;
			if (fn) fn.call(this, file, errors);
			return false;
		}
		file.isValid = true;
		(this.options.fileCreate || this.fileCreate).call(this, file);
		this.files.push(file);
		return true;
	},

	onAllSelect: function(files, current, overall) {
		if (this.files.length == 0) return;
		privateFlag = this.options.uploadPrivate;

		if (!checkedHandler) CheckUploadHandler();

		$('upbox').style.display = 'block';
		if (!privateFlag) {
			$('maskPrivate').style.display = 'block';
			disableBrowse('fileUploaderPublic');
		} else {
			$('maskPublic').style.display = 'block';
			disableBrowse('fileUploaderPrivate');
		}

		this.log('Added ' + files.length + ' files, now we have (' + current.bytesTotal + ' bytes).', arguments);
		this.updateOverall(current.bytesTotal);
		this.status.removeClass('status-browsing');
		if (this.files.length && this.options.instantStart) this.upload.delay(10, this);
	},

	onComplete: function(file, response) {
		file = this.getFile(file);
		this.log('Completed upload "' + file.name + '".', arguments);
		file.progress.start(100);
		(this.options.fileComplete || this.fileComplete).call(this, this.finishFile(file), response);
		file.element.getElement('input').style.visibility = 'hidden';
		file.element.getElement('a').style.visibility = 'hidden';
		if (!multiple) {
			goToNextStep();
		}
	},

	onError: function(file, error, info) {
		this.log('Upload "' + file.name + '" failed. "{1}": "{2}".', arguments);
		(this.options.fileError || this.fileError).call(this, this.finishFile(file), error, info);
	},

	onCancel: function() {
		this.log('Filebrowser cancelled.', arguments);
		this.status.removeClass('file-browsing');
	},

	onAllComplete: function(current) {
		this.log('Completed all files, ' + current.bytesTotal + ' bytes.', arguments);
		this.updateOverall(current.bytesTotal);
		this.status.removeClass('file-uploading');
		$('bar1').style.display = 'none';
		$('bar2').style.display = 'none';
		goToNextStep();
	},

	browse: function(fileList) {
		var ret = this.parent(fileList);
		if (ret !== true) {
			if (ret) this.log('An error occured: ' + ret);
			else this.log('Browse in progress.');
		} else {
			this.log('Browse started.');
			this.status.addClass('file-browsing');
		}
	},

	upload: function(options) {
		var ret = this.parent(options);
		if (ret !== true) {
			this.log('Upload in progress or nothing to upload.');
			if (ret) alert(ret);
		} else {
			this.log('Upload started.');
			this.status.addClass('file-uploading');
		}
	},

	removeFile: function(file) {
		var remove = this.options.fileRemove || this.fileRemove;
		if (!file) {
			this.files.each(remove, this);
			this.files.empty();
			this.updateOverall(0);
		} else {
			if (!file.element) file = this.getFile(file);
			this.files.erase(file);
			remove.call(this, file);
			this.updateOverall(this.bytesTotal - file.size);
		}
		this.parent(file);
	},

	getFile: function(file) {
		var ret = null;
		this.files.some(function(value) {
			if ((value.name != file.name) || (value.size != file.size)) return false;
			ret = value;
			return true;
		});
		return ret;
	},

	countFiles: function() {
		var ret = 0;
		for (var i = 0, j = this.files.length; i < j; i++) {
			if (!this.files[i].finished) ret++;
		}
		return ret;
	},

	updateOverall: function(bytesTotal) {
		this.bytesTotal = bytesTotal;
	},

	finishFile: function(file) {
		file = this.getFile(file);
		file.element.removeClass('file-uploading');
		file.finished = true;
		return file;
	},

	fileCreate: function(file) {
		file.info = new Element('span', { 'class': 'file-info' });
		file.toDelete = false;
		file.element = new Element('li', { 'class': 'file' }).adopt(
			new Element('input', {
				type: 'checkbox',
				'class': 'chkDelete',
				'events': {
					'click': function() {
						if (!file.toDelete) { file.toDelete = true } else { file.toDelete = false }
					} .bind(this)
				}
			}),
			new Element('a', {
				'class': 'input-delete',
				'href': '#',
				'events': {
					'click': function() {
						this.removeFile(file);
						return false;
					} .bind(this)
				}
			}),
			new Element('span', { 'class': 'queue-file', 'html': file.name }),
			new Element('div', { 'class': 'queue-loader' }).adopt(new Element('div', { 'class': 'queue-subloader' })),
			file.info
		).inject(this.list);
		progressBar = file.element.getElement('.queue-subloader');
		file.progress = new Fx.ProgressBar(progressBar, {
			text: new Element('span', { 'class': 'progress-text' }).injectInside(progressBar)
		});
		progressBar.style.width = '0%';
	},

	fileComplete: function(file, response) {
		this.options.processResponse || this
		var json = $H(JSON.decode(response, true));
		if (json.get('result') == 'success') {
			file.element.addClass('file-success');
			file.info.set('html', json.get('size'));
		} else {
			file.element.addClass('file-failed');
			file.info.set('html', json.get('error') || response);
		}
	},

	fileError: function(file, error, info) {
		file.element.addClass('file-failed');
		file.info.set('html', '<strong>' + error + '</strong><br />' + info);
	},

	fileRemove: function(file) {
		file.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, file.element));
	},

	sizeToKB: function(size) {
		var unit = 'B';
		if ((size / 1048576) > 1) {
			unit = 'MB';
			size /= 1048576;
		} else if ((size / 1024) > 1) {
			unit = 'kB';
			size /= 1024;
		}
		return size.round(1) + ' ' + unit;
	},

	log: function(text, args) {
		if (this.options.debug && window.console) console.log(text.substitute(args || {}));
	},

	clearDeleted: function() {
		var i = -1;
		while (++i < this.files.length) if (this.files[i].toDelete && this.files[i].status != 2) this.fileRemove(this.files[i]);
	},

	setAllDeletedFalse: function() {
		var i = -1;
		while (++i < this.files.length) this.files[i].toDelete = false;
	},

	setAllDeletedTrue: function() {
		var i = -1;
		while (++i < this.files.length) this.files[i].toDelete = true;
	}

});

function deleteSelected() {
    if (!privateFlag)
    {
        objUploadPublic.clearDeleted();
    } else
    {
        objUploadPrivate.clearDeleted();
    }
}

/**
 * @todo Clean-up, into Date.js
 */
Date.parseDuration = function(sec) {
	var units = {}, conv = Date.durations;
	for (var unit in conv) {
		var value = Math.floor(sec / conv[unit]);
		if (value) {
			units[unit] = value;
			if (!(sec -= value * conv[unit])) break;
		}
	}
	return units;
};

Date.fancyDuration = function(sec) {
	var ret = [], units = Date.parseDuration(sec);
	for (var unit in units) ret.push(units[unit] + Date.durationsAbbr[unit]);
	return ret.join(', ');
};

Date.durations = {years: 31556926, months: 2629743.83, days: 86400, hours: 3600, minutes: 60, seconds: 1, milliseconds: 0.001};
Date.durationsAbbr = {
	years: 'j',
	months: 'm',
	days: 'd',
	hours: 'h',
	minutes: 'min',
	seconds: 'sec',
	milliseconds: 'ms'
};







var _errorCount = 0;
var _errorFileList = "";
var objUpload = null;
var uploadInitTries = 0;
var fInt;

function showSingleUp() {
    if (!fancyLoaded)
    {
        $$('.opaqueFile').each(function(el) {
            el.style.display = 'block';
        });
    }
    $('fileUploaderPublic').src = '/i/upload/btn_browse.gif';
	$('fileUploaderPrivate').src = '/i/upload/btn_browse.gif';
    $('fileUploaderPublic').style.display = 'block';
	$('fileUploaderPrivate').style.display = 'block';
}

function clearFPoll() {
    clearInterval(fInt);
}

fancyLoaded = false;

function isFancy() {
    if (fancyLoaded)
    {
        clearInterval(fInt);
        $$('.opaqueFile').each(function(el) { 
	        el.style.display = 'none';
	    });
	    
	    $('fileUploaderPublic').src = '/i/upload/btn_browse.gif';
	    $('fileUploaderPrivate').src = '/i/upload/btn_browse.gif';
	    $('instruction').style.display = 'block';
    }
}

window.addEvent('domready', function()
{
	var fver = swfobject.getFlashPlayerVersion().major;
	
    if (fver == 0) 
    {
        showSingleUp();
    } 
    else
    {
	    setTimeout(function(){
		    loadUploader();
		    var d = new Date();
	    },1);
	    fInt = setInterval('isFancy()',100);
	    setTimeout('clearFPoll()',5000);
	    setTimeout('showSingleUp()',1500);
	}
});
		
function UploadError(name, size)
{
	try
	{
		if (_errorFileList.length > 0) _errorFileList = _errorFileList + ", ";
		_errorFileList = _errorFileList + name;
		_errorCount++;
	}
	catch(e)
	{
		alert(e.message);
	}
}

function AllUploadsComplete()
{

    document.getElementById('bar1').style.display = 'none';
    document.getElementById('bar2').style.display = 'none';
    
	try
	{
		if (_errorCount == 0)
		{
			// ShowGenWin('Thank you for uploading your documents, they are in the process of being converted and will be available shortly.');
			// if (objUpload) {objUpload.clearList(false); }
			goToNextStep()
		}
		else
		{
			ShowGenWin('The files ' + _errorFileList + ' could not be uploaded.  Please check individual file lines for error messages.');
		}
	}
	catch(e)
	{
		alert(e.message);
	}
}
function fireSelectAll(el) {n
   if ($(el).checked) 
   { 
        $('chkSelectAll1').checked = true;
        $('chkSelectAll2').checked = true;
        $$('.chkDelete').each(function(el) { el.checked = true; });
        if (!privateFlag)
            {
                objUploadPublic.setAllDeletedTrue();
            } else
            {
                objUploadPrivate.setAllDeletedTrue();
            }
   } else
   {
        $('chkSelectAll1').checked = false;
        $('chkSelectAll2').checked = false;
        $$('.chkDelete').each(function(el) { el.checked = false; });
        if (privateFlag)
            {
                objUploadPublic.setAllDeletedFalse();
            } else
            {
                objUploadPrivate.setAllDeletedFalse();
            }
   }
}


checkedHandler = false;

function CheckUploadHandler()
{
	checkedHandler = true;
	if (documentID>0){
		OnCheckUpComplete("{ 'success':1, 'message':'', 'batchID':1 }");
	}else{
		var oAjax = new AjaxObject101();
		oAjax.returnXml = false;
		oAjax.funcDone = OnCheckUpComplete;
		var data = "";
		oAjax.sndReq("POST", "/upload/AddUploadBatch.ashx", data);

	}
}

function OnCheckUpComplete(result)
{
    var result = eval("(" + result + ")");
    
    if (result.success==1){
        uploadBatchID = result.batchID;
        if (singleMode){
			postSingleFile();
        }else{
            if (!privateFlag) {
			objUploadPublic.upload.delay(10, objUploadPublic);
            } else {
			objUploadPrivate.upload.delay(10, objUploadPrivate);
			}
        }
    }else{
        alert(result.message);
    }
    
}

var objUploadPublic;
var objUploadPrivate;

function loadUploader(){
    try{		
	    var inputPublic = $('fileUploaderPublic');
	    var inputPrivate = $('fileUploaderPrivate');
	    var d = new Date();
	    
    	objUploadPublic = new FancyUpload2($('demo-status'), $('filesQueue'), {
	        url: urlBase,
	        limitSize: limitSize,
	        limitFiles: limitFiles,
	        fieldName: 'photoupload',
	        typeFilter: doctypes,
	        multiple: multiple,
	        path: 'Swiff.Uploader.swf',
	        onLoad: function() {
                fancyLoaded = true;
	        },
	        debug: false,
	        uploadPrivate: false,
	        target: 'fileUploaderPublic'
        });
        
        var cUpload = getCookie('cUpload');
        
        if(cUpload == undefined)
        {
			objUploadPrivate = new FancyUpload2($('demo-status'), $('filesQueue'), {
				url: urlBase,
				limitSize: limitSize,
				limitFiles: limitFiles,
				fieldName: 'photoupload',
				typeFilter: doctypes,
				multiple: multiple,
				path: 'Swiff.Uploader.swf',
				onLoad: function() {
					fancyLoaded = true;
				},
				debug: false,
				uploadPrivate: true,
				target: 'fileUploaderPrivate' 
			});
	        
    		$('fileUploaderPrivate').addEvent('click', function() {
				privateFlag = true;
				objUploadPrivate.browse();
				return false;
			});
        }
        
		$('fileUploaderPublic').addEvent('click', function() {
            privateFlag = false;
	        objUploadPublic.browse();
	        return false;
        });
			
    }catch(e){
	    //setTimeout(loadUploader,500);
    }
}



function submitSingle(fType) {
	singleMode =true;
	$('body').focus();
	if (fType == 'public')
	{
		urlBase+="&isPrivate=false";	
		disableBrowse('fileUploaderPublic');
		$('maskPrivate').style.display = 'block';
		$('sPrivate').destroy();
	}
	else
	{
		urlBase+="&isPrivate=true";
		disableBrowse('fileUploaderPrivate');
		$('maskPublic').style.display = 'block';
		$('sPublic').destroy();
	}
   $('singleUploadAnim').style.display = 'block';
	CheckUploadHandler();
}
function postSingleFile()
{
	setStoreCookies();
	
	var p="";if (documentID>0){p="&docID=" + documentID;}
	document.forms['aspnetForm'].action = urlBase + p + '&batchID=' + uploadBatchID + '&returnURL=/upload/edit/';
	document.forms['aspnetForm'].submit();
}

function disableBrowse(obj) {
        $(obj).style.display = 'none';
        $(obj + '_disabled').style.display = 'block';
}

var isRegistered = false;
function showLoginWindow()
{
	
    window.scrollTo(0, 0);
	loginWin = new DocstocWindow();

	loginWin.title = '';
	loginWin.draggable = false;  
	loginWin.height = '420px';  
	loginWin.width = '970px';
	loginWin.instanceName = 'loginWin';
	loginWin.init("loginWin");
	loginWin.closeOnEsc = true;
	loginWin.setUrl("/login/mini.aspx");
	loginWin.onClose = function()
	    {
	        if (!isRegistered)
	        {
	            showNotRegistered();
	        } else
	        {
	            if ($('blackbg')) $('blackbg').setStyle('display','none');
	        }
	    }
	loginWin.show()
	$('loginWin').style.top = "56px";
	DisableScreen('blackbg','#000000','.7');
    $('blackbg').setStyle('display','block');
}
function showDocCashWindow()
{
    window.scrollTo(0, 0);
	docCashWin = new DocstocWindow();

	docCashWin.title = '';
	docCashWin.draggable = false;  
	docCashWin.height = '600px';  
	docCashWin.width = '970px';
	docCashWin.instanceName = 'docCashWin';
	docCashWin.init("docCashWin");
	docCashWin.closeOnEsc = true;
	docCashWin.setUrl("/doccash/mini.aspx?m=1");
	docCashWin.onClose = function()
	    {
			if ($('blackbg')) $('blackbg').setStyle('display','none');
				var p="";if (documentID>0){p="?docID=" + documentID;}
				top.location.href = 'http://' + top.location.host + '/upload/edit/' + p;
	    }
	docCashWin.center();
	docCashWin.show();
	//$('loginWin').style.top = "56px";
	DisableScreen('blackbg','#000000','.7');
    $('blackbg').setStyle('display','block');
}

function hideDocCashWindow()
{
	if(docCashWin){
		docCashWin.hide();
	}
	return true;
}
function showNotRegistered()
{
	noReg = new DocstocWindow();

	noReg.title = '';
	noReg.draggable = false;  
	noReg.height = '90px';  
	noReg.width = '488px';
	noReg.instanceName = 'noReg';
	noReg.init("noReg");
	noReg.setContent("<div class='noReg'>The documents you selected are saved on Docstoc and will be published as soon as you register/login. Remember that you can always return back to the upload page and complete this process at a later time.</div>");
	noReg.closeOnEsc = true;
	noReg.clearContentOnHide = false;
	noReg.show();
	noReg.onClose = function()
    {
        if ($('blackbg')) $('blackbg').setStyle('display','none');
    }
   }
function showDocProcessing() {
	rc = new DocstocWindow();
	DisableScreen('blackbg', '#000000', '.7');
	rc.title = '';
	rc.draggable = false;
	rc.height = '90px';
	rc.width = '488px';
	rc.instanceName = 'rc';
	rc.init("rc");
	rc.setContent("<div class='noReg' style='padding-top:20px;'>Your document was successfuly uploaded and is being processed now. Please allow 2-3 minutes for the new version to appear on the site.</div>");
	rc.closeOnEsc = true;
	rc.clearContentOnHide = false;
	rc.show();
	rc.onClose = function() {
		if ($('blackbg')) $('blackbg').setStyle('display', 'none');
		top.location.href = '/docs/' + documentID + '/';
	}
}

var newRegister = false;
function loginComplete(email, memId, justRegistered)
{
	newRegister = justRegistered;
	isRegistered = true;
	currentUserID = 1;
	loginWin.hide();
	goToNextStep();
}
function goToNextStep()
{
	if (currentUserID==-10){
		showLoginWindow();
	}else{
		setTimeout('sendNextPage()',1);
	};	
}

function sendNextPage()
{
	setStoreCookies();
	
	//newRegister = true;
	if(newRegister)
	{
		showDocCashWindow();
	}
	else
	{

		if (documentID > 0) {
			showDocProcessing();
		} else {
			top.location.href = '/upload/edit/';
		}
		
	}
	
}
function setStoreCookies()
{
	if (($('chkPublicStore') !=null || $('chkPrivateStore') !=null) && ($('chkPublicStore').checked || $('chkPublicStore').checked)){
		setCookie("store_upload", "1");
	}
}

