document.observe('dom:loaded', function() {
	
	//alternate row colors
var rows = $$('.profile-info-row');
var color1 = '#f9f9f9';
var color2 = '#fcfcfc';
if (rows.length > 0) {
	bgColor = color1;
	for (i = 0; i < rows.length; i++) {
		rows[i].style.backgroundColor = bgColor;
		bgColor = (bgColor == color1) ? color2 : color1;
	}
}

//buttons on left side
if ( $('manage-files') ) {
	$('manage-files').observe('click', function () {
		openCenteredWindow('/dyn/mng/' + $('profile-id').value);
	});
}
if ( $('edit-profile') )
{
	$('edit-profile').observe('click', function() {
		window.location = '/dyn/actions/manageProfile';
	});
}


/*	
	function activatePages(dataStyle, dataParent, maxPages, itemsPerPage, pagePrefixName) {
		
		//attach event handlers to each child
		$$(dataStyle).each(function(page) {
			page.childElements().each(function(el) {
				el.observe('click', function paginate(event) {
					var element = event.element();

					var oldCurrent = 0;
					var hashloc = parent.location.hash;
					if (hashloc != '') {
						oldCurrent = parseInt(hashloc.substring(1));
					}
					var current = 0;
					if (element.innerHTML == String.fromCharCode(171)) {
						current = 0;
					} else if (element.innerHTML == String.fromCharCode(187)) {
						current = maxPages;
					} else if (element.innerHTML == '&lt; Previous') {
						current = Math.max(0, oldCurrent - 1);
					} else if (element.innerHTML == 'Next &gt;'){
						current = Math.min(maxPages, oldCurrent + 1);
					} else {
						current = parseInt(element.innerHTML)-1;
					}
					
					$$(dataStyle).each(function(p) {
						p.childElements().each(function(act) {
							act.removeClassName("active");
							act.removeClassName("disabled");
						});
					});
					
					$(pagePrefixName+current).addClassName("active");
					
					parent.location.hash=current;
					var start = current*itemsPerPage;
					var end = current*itemsPerPage+itemsPerPage;
					
					children = $(dataParent).childElements();
					children.each(function(el, index) {
						if ((index >= start && index < end)) {
							el.show();
						} else {
							el.hide();
						}
					})
					
					return false;
				});
			});
		});
	};
*/	
	
	
// help icon next to search folders input
if (getInternetExplorerVersion() != 6) //only show if not ie6
{
	$('search-shares-help-icon').style.display = 'inline';
	$('search-shares-help-icon').observe('mouseover', function() {
		$('search-shares-help').style.display = 'inline';
	});
	
	$('search-shares-help-icon').observe('mouseout', function() {
		$('search-shares-help').style.display = 'none';
	});
}


var Shares = Class.create({
	initialize: function( sharesData, parentElement, owner )
	{
	
		this.parentElement = parentElement;
		this.sharesData = sharesData;
		this.owner = owner;
		this.foldersPerPage = getPageSize(20);
		
		$('search-shares-info-details').hide();
		
		this.buildHeader();
		
		if ( this.sharesData.length == 0 )
		{
			$('search-shares-info').hide();
			$('search-shares-container').hide();
			
			if (owner)
			{
				parentElement.insert({bottom: new Element('div', {'class': 'profile-notice'}).update('You are not sharing any folders.')});
			}
			else
			{
				parentElement.insert({bottom: new Element('div', {'class': 'profile-notice'}).update('This user is not sharing any folders.')});
			}
		}
		else
		{			
			this.buildShares(this.sharesData, getCurrentPage(), this.foldersPerPage);
			this.activateRows('share', 'share-cell-hover');
		}
		
	},
	
	buildHeader: function()
	{
		headerContainer = new Element( 'div', { id: 'shares-header-container' } );
		firstChild = new Element('div', { id: 'shares-header-icon', 'class': 'shares-list-icon shares-header'}).update('&nbsp');
		secondChild = new Element( 'div', { id: 'shares-header-folder', 'class' : 'shares-list-folder shares-header' } ).update('<span class="shares-column-title">Folder Path</span><span class="shares-sort-element"></span>');
		thirdChild = new Element( 'div', { id: 'shares-header-files', 'class' : 'shares-list-files shares-header' } ).update('<span class="shares-column-title">Total Files</span><span class="shares-sort-element"></span>');
		fourthChild = new Element( 'div', { 'class' : 'shares-list-tools shares-header' } ).update('&nbsp;');
		
		this.parentElement.insert({top: headerContainer });
		headerContainer.insert({ bottom: firstChild } );
		headerContainer.insert({ bottom: secondChild } );
		headerContainer.insert({ bottom: thirdChild } );
		headerContainer.insert({ bottom: fourthChild } );
		
		this.headerColumns = [ secondChild, thirdChild ];	
	},
	
	attachEventHandlers: function()
	{
		globalScope = this;
		hoverClass = "shares-header-hover";
		activeClass = "shares-header-active";
		
		this.headerColumns.each( function( el, i )
		{
			el.observe('mouseover', function() {
				el.addClassName(hoverClass);
			});
			el.observe('mouseout', function() {
				el.removeClassName(hoverClass);
			});
			el.observe('click', function() {
				globalScope.sortByColumn( el );
			});
		});
	},
	
	buildShares: function(shares, currPage, pageSize) {

		start = currPage*pageSize;
		end = currPage*pageSize+pageSize;
		globalScope = this;
		
		//create parent container for all folders
		sharesList = new Element('div', {'id': 'shares-list'});

		for (j = 0; j < shares.length; j++) {		
			folderRoot = shares[j][0];
			folderName = this.cleanFolderPath(shares[j][1]);
			folderPathVal = shares[j][2];
			groupPerm = parseInt(shares[j][3]);
			publicPerm = parseInt(shares[j][4]);			
			totalFilesVal = shares[j][6];
			folderIconImg = this.getFolderIcon(publicPerm, groupPerm, shares[j][5]);
									
			//build new row
			rowId = (shares[j][1] == '/') ? 'Root' : shares[j][1];
			row = new Element('div', {'class' : 'share', id: rowId});
			//hide rows not on current page
			//if (j < start || j > end - 1) row.hide();
			
			//build icon
			folderIcon = new Element('div', {'class' : 'shares-list-icon share-cell-first'}).update(folderIconImg);
			
			//build folder path container
			pathClass = (row.hasClassName('child')) ? 'shares-list-folder-child' : 'shares-list-folder';		
			folderPath = new Element('div', {'class' : pathClass + ' share-cell'});
			folderHref = '/dyn/ls/' + folderRoot + '/' + folderPathVal;
			pathAnchor = new Element('a', {href : folderHref, 'rel' : 'nofollow'}).update('<span class="share-cell-text share-folder-name">' + folderName + '</span>');
			folderPath.insert({bottom: pathAnchor });
			
			//build total files container
			totalFiles = new Element('div', {'class' : 'shares-list-files share-cell'}).update('<span class="share-cell-text">' + totalFilesVal + '</span>');
			
			//if owner, build folder tools cell; else build empty cell in row
			folderTools = new Element('div', {'class' : 'shares-list-tools share-cell'});
			if (this.owner)
			{
				folderTools.update('&nbsp;');
			}
			else
			{
				folderTools.update('&nbsp;');
			}
							
			//put row together
			row.insert({bottom: folderIcon });
			row.insert({bottom: folderPath });
			row.insert({bottom: totalFiles });
			row.insert({bottom: folderTools });
			//send row out
			sharesList.insert({bottom: row });
			sharesList.insert({bottom: new Element('div', {'class': 'clear'})});
			$('total-shares').update(j+1);
		}
		//send all rows to parent
		this.parentElement.insert({bottom: sharesList });
			
		//insert a clearing row
		this.parentElement.insert({bottom: new Element('div', {'class': 'clear'})});
	},
	
	activateRows: function(rowClass, rowHoverClass)
	{
		globalScope = this;
		shares = $$('.'+rowClass);
		shares.each( function(el, index) {
			el.observe('mouseover', function() {
				rowColumns = el.childElements();
				rowColumns.each(function(el, index) {
					if (index == 0)
					{ el.addClassName(rowHoverClass+'-first'); }
					else
					{ el.addClassName(rowHoverClass); }
				});
			});
			el.observe('mouseout', function() {
				rowColumns = el.childElements();
				rowColumns.each( function(el, index) {
					if (index == 0)
					{ el.removeClassName(rowHoverClass+'-first'); }
					else
					{ el.removeClassName(rowHoverClass); }
				});
			});
		});
		
		$('search-shares').observe('keyup', function(e, i) {
			if ( $('search-shares').value.length > 3 )
			{
				globalScope.filterShares( $('search-shares').value );
			}
		});
		
		$('search-shares').observe('keyup', function() {
				if (this.value != 'Search folders...') {
					globalScope.filterShares($('search-shares').value);
				}
			});
			
		$('search-shares').observe('focus', function() {
			if (this.value == 'Search folders...') {
				this.value = '';
				this.style.color = '#000';
			}
		});
			
		$('search-shares').observe('blur', function() {
			if (this.value == '') {
				this.value = 'Search folders...';
				this.style.color = '#999';
			}
		});	
	},
	
	getFolderIcon: function(publicPerm, groupPerm, folderEncrypted)
	{	
		icon = new Element('img');
		if (publicPerm == 0) {
			if (groupPerm == 0) {
				if (folderEncrypted) {
					icon.setAttribute('src', '/images/folder_encrypted.gif');
					icon.setAttribute('alt', 'Encrypted Folder');
				} else {
					icon.setAttribute('src', '/images/folder_closed.gif');
					icon.setAttribute('alt', 'Closed Folder');
				}	
			} else if (groupPerm & 0x10 == 0x10) {
				if (folderEncrypted) {
					icon.setAttribute('src', '/images/folder_friend_encrypted.gif');
					icon.setAttribute('alt', 'Encrypted Folder');
				} else {
					icon.setAttribute('src', '/images/folder_friend.gif');
					icon.setAttribute('alt', 'Shared Folder');
				}
			} 
		} else if (publicPerm & 0x10 == 0x10) {
			icon.setAttribute('src', '/images/folder_public_download.gif');
			icon.setAttribute('alt', 'Public Folder Downloadable');
		} else if (publicPerm & 0x01 == 0x01) {
			icon.setAttribute('src', '/images/folder_shared_closed.gif');
			icon.setAttribute('alt', 'Shared Folder');
		}
		return icon;
	},
	
	cleanFolderPath: function(folderPath)
	{
		if (folderPath == "/") //folder path is root
		{
			return "<strong>Root</strong>";
		}
		else
		{
			newPath = ""
			pathArr = folderPath.split("/");
			for (i = 1; i < pathArr.length - 1; i++)
				newPath += (i < pathArr.length - 2) ? pathArr[i] + "/" : "<strong>" + pathArr[i] + "</strong>";
				
			return newPath;	
		}	
	},
	
	filterShares: function(searchStr)
	{
		globalScope = this;		
		$('default-shares-info').hide();
		$('search-shares-info-details').show();
		j = 0;
		shareRows = $$('.share');
		shareRows.each( function(el, index) {
			if (searchStr.length == 0) {
				$('search-shares-info-details').hide();
				$('default-shares-info').show();
				el.show();
			} else {
				if (typeof document.body.style.maxHeight == "undefined") //ie6
				{
					filterExp = searchStr.replace(' ', '.');
					filterExp = new RegExp(filterExp,"gi");
				}
				else
				{
					filterExp = searchStr.replace(' ', '.');
					filterExp = globalScope.wildcardToRegexString(filterExp);
					filterExp = new RegExp(filterExp,"gi");
				}
				currentFolder = (folderPath == "/") ? "Root" : el.id;
				if (currentFolder.search(filterExp) != -1) {
					el.show();
					j++;
				} else {
					el.hide();
				}
				$('search-shares-info-details').update('Found <span>' + j + '</span> results.');
			}
		});
	},
	
	wildcardToRegexString: function(wildcard)
	{
		s = "";
		is = wildcard.length;
		for (i = 0; i < is; i++)
		{
			c = wildcard[i];
			
			switch(c)
			{
			case '*':
				s += ".*";
				break;
		
			case '?':
				s += ".";
				break;
		
			// escape special regexp-characters
			case '(': case ')': case '[': case ']': case '$':
			case '^': case '.': case '{': case '}': case '|':
			case '\\':
				s += "\\";
				s += c;
				break;
		
			default:
				s += c;
				break;
			}
		}
		return s;
	}
	
		
});
	sharesList = new Shares( myShares, $('shares-container'), false );

});