var xTimer = null;

/************************************************/
/*				Comment Pagination				*/
/************************************************/
function paginationAjax(url) {
	new Ajax.Updater('commentContent',url,{
		method: 'get',
		evalScripts:true,
		onSuccess:function(){
		},
		onComplete:function(){
			var reportComments = $$('.rep');
			reportComments.each(function(reportElement) {
				createControlModal($(reportElement));
			});
		}
	});
}
 
/************************************************/
/*				Add to Favorites				*/
/************************************************/
function addFavorite(obj,sid,oid,uid) {
	var data = $H({ sid: sid, oid: oid, uid: uid });
	obj = $(obj);
	new Ajax.Request('/ajax/favorite/', {
		method: 'post',
		parameters: data.toQueryString(),
		onSuccess: function(result) {
			$('actionFavorite1').addClassName('addedFavorite');
			$('actionFavorite1').innerHTML = '<span><em></em>Favorited</span>';
			$('actionFavorite2').addClassName('addedFavorite');
			$('actionFavorite2').innerHTML = '<span><em></em>Favorited</span>';
		},
		onFailure: function(result) {
			alert(result.responseText);
		}
	});
	return false;
}

/************************************************/
/*					Get Tagger					*/
/************************************************/
function getTaggingForm(id) {
	new Ajax.Updater('tagit_submission',
		 '/modules/tags/form.php?section=submission&id=' + id, {
		 asynchronous:true,
		 evalScripts:true,
		 onSuccess: function() {
			 Effect.toggle('tagit_submission','appear',{duration:0.3});
		 }
	});
	return false;
}

/************************************************/
/*					Tag it						*/
/************************************************/
function tagIt() {
	data = $('tagit').serialize(true);
	new Ajax.Request('/modules/tags/tagit.php', {
		asynchronous:true,
		evalScripts:true,
		method: 'post',
		parameters: data,
		onSuccess: function(transport) {
			if($('tagsLabel')){
				if(!$('tagsLabel').visible()){
					$('tagsLabel').show();
				}
			}
			$('tags').innerHTML = transport.responseText;
			Effect.Fade('tagit_submission',{duration:0.3});
		}
	});
}

/************************************************/
/*					Watch User					*/
/************************************************/
function startWatching(rid) {
	var d = new Hash();
	d.set('rid', rid);
	new Ajax.Request('/ajax/startwatching/', {
		method: 'post',
		parameters: d.toQueryString(),
		onSuccess: function(transport) {
            if(result.responseText == 'Success') {
                alert('You are now watching this user');
                $('watchCon').innerHTML = '<a href="#" id="watchUser" class="watch current" title="Remove this user from your Watchlist" onclick="javascript:stopWatching(&quot;'+rid+'&quot;); return false;"></a>'
            }
            else {
                alert('There was an error. Try again.');
            }
		},
		onFailure: function(result) {
			alert(result.responseText);
		}
	});
	return false;
}

/************************************************/
/*				Stop Watching User				*/
/************************************************/
function stopWatching(rid) {
	if(confirm('Are you sure you want to remove this user from your Watchlist?')) {
		var d = new Hash();
		d.set('rid', rid);
		new Ajax.Request('/ajax/stopwatching/', {
			method: 'post',
			parameters: d.toQueryString(),
			onSuccess: function(transport) {
				$('watchCon').innerHTML = '<a href="#" id="watchUser" class="watch" title="Watch this User" onclick="javascript:startWatching(&quot;'+rid+'&quot;); return false;"></a>'
			},
			onFailure: function(result) {
				alert(result.responseText);
			}
		});
		return false;
	}
}

/************************************************/
/*				Add to Dashboard				*/
/************************************************/
function addDash(id) {
	new Ajax.Request('/ajax/browse/?action=add&eopt='+id, {
		method: 'get',
		onSuccess: function(transport) { 
			$('DashCon').innerHTML = '<a href="#" title="Remove from your Browse Dashboard" class="removeDash" onclick="javascript:removeDash(&quot;'+id+'&quot;);return false;"</a>'
		}
	});	
}

/************************************************/
/*			Remove from Dashboard				*/
/************************************************/
function removeDash(id) {
	new Ajax.Request('/ajax/browse/?action=remove&eopt='+id, {
		method: 'get',
		onSuccess: function(transport) { 
			$('DashCon').innerHTML = '<a href="#" title="Add to your Browse Dashboard" class="addDash" onclick="javascript:addDash(&quot;'+id+'&quot;);return false;"></a>'
		}
	});	
}

/************************************************/
/*				Send Friend Request				*/
/************************************************/
function sendFriendRequest(formName) {
	var formname=formName;
	data = $(formName).serialize(true);
	new Ajax.Request('/ajax/befriend/', {
		method: 'post',
		parameters: data,
		onSuccess: function(result) {
			xTimer = 5;
			//console.log($(formname).select('input[name="id"]'));
			//$('friendCon').innerHTML = '<a href="#" class="addFriend current" title="Remove this Friend" onclick="removeFriend('+$(formname).select('input[name="id"]')[0].value+'); return false"></a>';
			$('modal_container').innerHTML = result.responseText;
			new PeriodicalExecuter(function(pe) {
				xTimer = xTimer-1;
				if(xTimer==0) {
					Control.Modal.close();
					pe.stop();
				}
			}, 1);
		},
		onFailure: function(result) {
			alert(result.responseText);
		}
	});
}

/************************************************/
/*				Remove Friend					*/
/************************************************/
function removeFriend(id) {
	if(confirm('Are you sure you want to remove this Friend?')) {
		var d = new Hash();
		d.set('id', id);
		new Ajax.Request('/ajax/removefriend/', {
			method: 'post',
			parameters: d.toQueryString(),
			onSuccess: function(transport) {
				$('friendCon').innerHTML = '<a href="/ajax/friend_request/?id='+id+'" id="addFriend" class="addFriend" title="Request as Friend"></a>'
			},
			onFailure: function(result) {
				alert(result.responseText);
			}
		});
		return false;
	}
}


/************************************************/
/*			Auto Expand View Preference			*/
/************************************************/
//prefix,preview,largeview
function enlargeView() {
	$('view_panel').toggle();
	imgsrc=$('submissionFull').getElementsBySelector('img')[0].src;
	imgalt=$('submissionFull').getElementsBySelector('img')[0].alt;
	imgid=$('submissionFull').getElementsBySelector('img')[0].id;
	imgclass=$('submissionFull').getElementsBySelector('img')[0].id;
	if ($('view_panel').visible()) {
		$('submissionFull').update('<img src="'+ artwork_data.prefix + artwork_data.preview +'" alt="'+imgalt+'" class="'+imgid+'" id="'+imgclass+'">');
		$('submissionCol').className = 'left_col';
		$('submissionFull').className = 'zoomIn';
	}
	else {
		$('submissionFull').update('<img src="'+ artwork_data.prefix + artwork_data.largeview +'" alt="'+imgalt+'" class="'+imgid+'" id="'+imgclass+'">');
		$('submissionCol').className = 'full_col';
		$('submissionFull').className = 'zoomOut';
	}
	return false;
}


/************************************************/
/*			Auto Expand View for Flash			*/
/************************************************/
function enlargeViewForFlash() {
	$('view_panel').toggle();
	$('flash_view_close').toggle();
	swfHTML = "<OBJECT class=\"jsembed\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\"" +
		"WIDTH=\""+SWFwidth+"\" HEIGHT=\""+SWFheight+"\">" +
		"<PARAM NAME=\"allowScriptAccess\" VALUE=\"never\">" +
		"<PARAM NAME=\"allowNetworking\" VALUE=\"never\">" +
		"<PARAM NAME=\"movie\" VALUE=\"" + $('submissionFull').href + "\" id=\"src2\">" +
		"<PARAM NAME=\"quality\" VALUE=\"high\">" +
		"<EMBED id=\"lightboxImageEmbed\" class=\"jsembed\" src=\"" + $('submissionFull').href + "\" quality=\"high\" WIDTH=\""+SWFwidth+"\" HEIGHT=\""+SWFheight+"\" ALIGN=\"center\" TYPE=\"application/x-shockwave-flash\" PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\">" +
		"</EMBED></OBJECT>";
		if ($('view_panel').visible()) {
		$('submissionFull').show();
		$('submissionCol').className = 'left_col';
		$('submissionFull').className = 'zoomIn';
		$('flash_html').innerHTML = '';
	}
	else {
		$('submissionFull').hide();
		$('submissionCol').className = 'full_col';
		$('flash_view_close').className = 'zoomOut';
		$('flash_html').innerHTML = swfHTML;
	}
	return false;
}

/************************************************/
/*			Open Full View Preference			*/
/************************************************/
Event.domReady.add(function() {
	var fvp = $$('.fullViewPref');
	fvp.each(function(fvpElement) {
		createNotice($(fvpElement));
	});
	if ($('fullViewPrefModal')) { createNotice($('fullViewPrefModal')); }
});


/************************************************/
/*			Set User View Preference			*/
/************************************************/
function setViewType(val) {
	new Ajax.Updater('modal_container','/modules/view/setfv.php?fvset='+val, {
		method: 'get',
		onSuccess: function(result) {
			if(val == 'modal') {
				var timg = $('submissionFull').getElementsBySelector('img')[0];
				
				//Image
                if($('flash_url') != null) {
                    $('submissionFull').href = $('flash_url').value;
                }
                else {
				    $('submissionFull').href = timg.src.replace('.preview.', '.largeview.');
                }
				$('submissionFull').rel = 'lightbox';
				$('submissionFull').title = timg.title;
				
				myLightbox.updateImageList();
				myLightbox.start($('submissionFull'));
			}
			if(val == 'expand') {
				$('submissionFull').onclick = function() {
					enlargeView();
					return false;
				}
				enlargeView();
			}
		}
	});
	xTimer = 2;
	new PeriodicalExecuter(function(pe) {
		xTimer = xTimer-1;
		if(xTimer==0) {
			Control.Modal.close();
			pe.stop();
		}
	}, 1);
	return false;
}

/************************************************/
/*				Initialize Rating				*/
/************************************************/
function initRating() {
	children = $('unit-rating').getElementsBySelector('a');
	$('unit-rating').className = 'rateEnabled';
	for (var i=0; i<children.length; i++){
		child = children[i];
		if(child.className == ('r' + (i+1) + '-unit')) {
			child.value = i+1;
			child.onclick = function() {
				rateSubmission(this.value);
				return false;
			};
		}
	}
}

/************************************************/
/*				Deactivate Rating				*/
/************************************************/
function unlinkRating() {
	children = $('unit-rating').getElementsBySelector('a');
	$('unit-rating').className = 'rateDisabled';
	for (var i=0; i<children.length; i++){
		child = children[i];
		if(child.className == ('r' + (i+1) + '-unit')) {
			child.value = i+1;
			child.onclick = function() {
				return false;
			};
		}
	}	
}

/************************************************/
/*				Rate Submission					*/
/************************************************/
function rateSubmission(val) {
	new Ajax.Updater('modal_container',
		'/modules/view/setrating.php?rating='+val+'&artwork_id=' + artwork_id, {
		method: 'get',
		onSuccess: function(result) {
			$('rateMatte').style.width = (parseFloat(result.responseText)*10).toString() + 'px';
			$('avgRating').innerHTML = (parseFloat(result.responseText)*10).toString();
			unlinkRating();
		},
		onFailure: function(result) {
			alert(result.responseText);
		}
	});
	return false;
}

/************************************************/
/*				Report Submission				*/
/************************************************/
//(This needs to stay in the view page)
Event.domReady.add(function() {
	var reportComments = $$('.rep');
	reportComments.each(function(reportElement) {
		createNotice($(reportElement));
	});
	if ($('reportContent')) { createNotice($('reportContent')); }
});

/************************************************/
/*					Share This					*/
/************************************************/
function shareThis(id,div) {
	if($(div).innerHTML == '') {
		new Ajax.Updater(div, '/modules/view/share.php?id='+id,{
			 asynchronous:true,
			 evalScripts:true,
			 onSuccess: function(result) {
				 Effect.toggle(div,'blind',{duration:0.3});
			 }
		});
	}
	else {
		Effect.toggle(div,'blind',{duration:0.3});
	}
	return false;	
}

/************************************************/
/*				Share Toggler					*/
/************************************************/
function shareToggle(id) {
	buttons = new Array('st_web','st_artician','st_email');
	sharecontent = new Array('shareSocial','shareArtician','shareEmail');
	activeClass = 'current';
	inactiveClass = null;
	for(i=0;i<sharecontent.length;i++) {
		if(i==(id-1)) {
			Effect.Appear(sharecontent[i],{duration:0.4});
			setObjClass(buttons[i],activeClass);
		}
		else {
			hide(sharecontent[i]);
			setObjClass(buttons[i],inactiveClass);
		}
	}
}

/************************************************/
/*			Retreive Similar Content			*/
/************************************************/
function simcon(id,type) {
	new Ajax.Updater('similarSubmissions', '/modules/view/similar.php?id='+id+'&type='+type,{
		asynchronous:true,
		evalScripts:true
	});
}

/************************************************/
/*			Similar Content Tabs				*/
/************************************************/
function simtabs(id) {
	tab = new Array('sim_1','sim_2','sim_3','sim_4','sim_5');
	activeClass = 'current';
	inactiveClass = null;
	for(i=0;i<tab.length;i++) {
		if(i==(id-1)) { if ($(tab[i])) setObjClass(tab[i],activeClass);}
		else { if ($(tab[i])) setObjClass(tab[i],inactiveClass);}
	}
}

/************************************************/
/*				Literature Controls				*/
/************************************************/
var litFontsize = 100;
var litLineHeight = 1.5;
var litIndentAmount = 40;
var litIndent = false;
var litContrast = false;
var litFormat = false;

function litControl(type){
	if(type == 'zoomOut'){
		if (litFontsize<=90) { return; }
		litFontsize -= 15;
		if (litFontsize>100) { litLineHeight -= 0.1; }
		$('submissionLiterature').setStyle({fontSize: litFontsize+'%','lineHeight': litLineHeight+'em'});
		$('submissionLiterature').select('p').each(function(e){ e.setStyle({fontSize: litFontsize+'%','lineHeight': litLineHeight+'em'}); });
		$('submissionLiterature').select('ul').each(function(e){ e.setStyle({fontSize: litFontsize+'%','lineHeight': litLineHeight+'em'}); });

	}
	else if(type == 'zoomIn'){
		if (litFontsize>=120) { return; }
		litFontsize += 15;
		if (litFontsize>120) { litLineHeight += 0.1; }
		$('submissionLiterature').setStyle({fontSize: litFontsize+'%','lineHeight': litLineHeight+'em'});
		$('submissionLiterature').select('p').each(function(e){ e.setStyle({fontSize: litFontsize+'%','lineHeight': litLineHeight+'em'});});
		$('submissionLiterature').select('ul').each(function(e){ e.setStyle({fontSize: litFontsize+'%','lineHeight': litLineHeight+'em'});});
	}
	else if(type == 'format'){
		if($('lit_stripped').innerHTML == ''){
			d = $('submissionLiterature').innerHTML;
			var output = cleanHTML();
			$('lit_stripped').innerHTML = output;
			$('lit_stripped').show();
			$('lit_orig').hide();
			$('vc_format').addClassName('active');
		} 
		else {
			if($('lit_stripped').visible()){
				$('lit_stripped').hide();
				$('lit_orig').show();
				$('vc_format').removeClassName('active');
			}
			else{
				$('lit_stripped').show();
				$('lit_orig').hide();
				$('vc_format').addClassName('active');
			}
		}
	}
	else if(type == 'indent'){
		if(!litIndent){
			$('submissionLiterature').select('p').each(function(e){ e.setStyle({'textIndent': litIndentAmount+'px'});});
			$('vc_indent').addClassName('active');
			litIndent = true;
		}
		else {
			$('submissionLiterature').select('p').each(function(e){ e.setStyle({'textIndent': 0+'px'});});
			$('vc_indent').removeClassName('active');
			litIndent = false;
		}
		
	}
	else if(type == 'contrast'){
		if(!litContrast){
			$('submissionLiterature').addClassName('highContrast');
			$('vc_contrast').addClassName('active');
			litContrast = true;
		}
		else {
			$('submissionLiterature').removeClassName('highContrast');
			$('vc_contrast').removeClassName('active');
			litContrast = false;
		}
	
	}
}

/************************************************/
/*				HTML Word Cleaner				*/
/*	  	Copyright (C) 2005 Connor McKay			*/
/************************************************/

//remplacement characters
var rchars = [["Ã±","Ã³", "Ã«", "Ã­", "Ã¬", "Ã®", 'â€ '], ["-", "-", "'", "'", '"', '"', ' ']];

//html entities translation array
var hents = new Array();
hents['Â°'] = '&iexcl;';
hents['Â¢'] = '&cent;';
hents['Â£'] = '&pound;';
hents['Â§'] = '&curren;';
hents['â€¢'] = '&yen;';
hents['Â¶'] = '&brvbar;';
hents['ÃŸ'] = '&sect;';
hents['Â®'] = '&uml;';
hents['Â©'] = '&copy;';
hents['â„¢'] = '&ordf;';
hents['Â´'] = '&laquo;';
hents['Â¨'] = '&not;';
hents['â‰ '] = '&shy;';
hents['Ã†'] = '&reg;';
hents['Ã˜'] = '&macr;';
hents['âˆž'] = '&deg;';
hents['Â±'] = '&plusmn;';
hents['â‰¤'] = '&sup2;';
hents['â‰¥'] = '&sup3;';
hents['Â¥'] = '&acute;';
hents['Âµ'] = '&micro;';
hents['âˆ‚'] = '&para;';
hents['âˆ‘'] = '&middot;';
hents['âˆ?'] = '&cedil;';
hents['Ï€'] = '&sup1;';
hents['âˆ«'] = '&ordm;';
hents['Âª'] = '&raquo;';
hents['Âº'] = '&frac14;';
hents['Î©'] = '&frac12;';
hents['Ã¦'] = '&frac34;';
hents['Ã¸'] = '&iquest;';
hents['Â¿'] = '&Agrave;';
hents['Â¡'] = '&Aacute;';
hents['Â¬'] = '&Acirc;';
hents['âˆš'] = '&Atilde;';
hents['Æ’'] = '&Auml;';
hents['â‰ˆ'] = '&Aring;';
hents['âˆ†'] = '&AElig;';
hents['Â«'] = '&Ccedil;';
hents['Â»'] = '&Egrave;';
hents['â€¦'] = '&Eacute;';
hents['Â '] = '&Ecirc;';
hents['Ã€'] = '&Euml;';
hents['Ãƒ'] = '&Igrave;';
hents['Ã•'] = '&Iacute;';
hents['Å’'] = '&Icirc;';
hents['Å“'] = '&Iuml;';
hents['â€“'] = '&ETH;';
hents['â€”'] = '&Ntilde;';
hents['â€œ'] = '&Ograve;';
hents['â€?'] = '&Oacute;';
hents['â€˜'] = '&Ocirc;';
hents['â€™'] = '&Otilde;';
hents['Ã·'] = '&Ouml;';
hents['â—Š'] = '&times;';
hents['Ã¿'] = '&Oslash;';
hents['Å¸'] = '&Ugrave;';
hents['â?„'] = '&Uacute;';
hents['â‚¬'] = '&Ucirc;';
hents['â€¹'] = '&Uuml;';
hents['â€º'] = '&Yacute;';
hents['ï¬?'] = '&THORN;';
hents['ï¬‚'] = '&szlig;';
hents['â€¡'] = '&agrave;';
hents['Â·'] = '&aacute;';
hents['â€š'] = '&acirc;';
hents['â€ž'] = '&atilde;';
hents['â€°'] = '&auml;';
hents['Ã‚'] = '&aring;';
hents['ÃŠ'] = '&aelig;';
hents['Ã?'] = '&ccedil;';
hents['Ã‹'] = '&egrave;';
hents['Ãˆ'] = '&eacute;';
hents['Ã?'] = '&ecirc;';
hents['ÃŽ'] = '&euml;';
hents['Ã?'] = '&igrave;';
hents['ÃŒ'] = '&iacute;';
hents['Ã“'] = '&icirc;';
hents['Ã”'] = '&iuml;';
hents['ï£¿'] = '&eth;';
hents['Ã’'] = '&ntilde;';
hents['Ãš'] = '&ograve;';
hents['Ã›'] = '&oacute;';
hents['Ã™'] = '&ocirc;';
hents['Ä±'] = '&otilde;';
hents['Ë†'] = '&ouml;';
hents['Ëœ'] = '&divide;';
hents['Â¯'] = '&oslash;';
hents['Ë˜'] = '&ugrave;';
hents['Ë™'] = '&uacute;';
hents['Ëš'] = '&ucirc;';
hents['Â¸'] = '&uuml;';
hents['Ë?'] = '&yacute;';
hents['Ë›'] = '&thorn;';
hents['Ë‡'] = '&yuml;';
hents['"'] = '&quot;';
hents['<'] = '&lt;';
hents['>'] = '&gt;';

//allowed tags
var tags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'ul', 'ol', 'li', 'table', 'tr', 'th', 'td', 'br'];

//tags which should be removed when empty
var rempty = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'ul', 'ol', 'li', 'u', 'i', 'b', 'a', 'table', 'tr', 'em', 'strong','link','style'];

//allowed atributes for tags
var aattr = new Array();
aattr['a'] = ['href', 'name', 'alt', 'title'];
aattr['table'] = ['border'];
aattr['th'] = ['colspan', 'rowspan'];
aattr['td'] = ['colspan', 'rowspan'];
aattr['img'] = ['src', 'width', 'height', 'alt'];
aattr['p'] = [];

//tags who's content should be deleted
var dctags = ['head','style','link','meta'];

//Quote characters
var quotes = ["'", '"'];

//tags which are displayed as a block
var btags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'ul', 'ol', 'li', 'table', 'tr', 'th', 'td', 'br'];

//d = data, o = out, c = character, n = next character
//in and out variables
var d = '';
var o = '';

function cleanHTML(){
	o = '';
	var i;
	//Replace all whitespace characters with spaces
	d = d.replace(/(\s|&nbsp;)+/g, ' ');
	//replace weird word characters
	for (i = 0; i < rchars[0].length; i++)
		d = d.replace(new RegExp(rchars[0][i], 'g'), rchars[1][i]);
	
	//initialize flags
	//what the next character is expected to be
	var expected = ''; //tag text
	var tag = ''; //tag name
	var tagname = ''; //what type of tag it is, start, end, or single
	var tagtype = 'start'; //attribute text
	var attribute = ''; //attribute name
	var attributen = ''; //if the attribute has had an equals sign
	var attributeequals = false; //if attribute has quotes, and what they are
	var attributequotes = '';
	var c = '';
	var n = '';
	
	/*Parser format:
	The parser is divided into three parts:
	The first section is for when the current type of character is known
	The second is for when it is an unknown character in a tag
	The third is for anything outside of a tag
	*/
	
	//editing pass
	for (i = 0; i < d.length; i++)
	{
		//current character
		c = getc(i);
		//next character
		n = getc(i+1);
		
		//***Section for when the current character is known
		
		//if the tagname is expected
		if (expected == 'tagname')
		{
			tagname += c.toLowerCase();
			//lookahead for end of tag name
			if (n == ' ' || n == '>' || n == '/')
			{
				tag += tagname;
				expected = 'tag';
			}
		}
		//if an attribute name is expected
		else if (expected == 'attributen')
		{
			attributen += c.toLowerCase();
			//lookahead for end of attribute name
			if (n == ' ' || n == '>' || n == '/' || n == '=')
			{
				attribute += attributen;
				//check to see if its an attribute without an assigned value
				//determines whether there is anything but spaces between the attribute name and the next equals sign
				if (endOfAttr(i))
				{
					//if the attribute is allowed, add it to the output
					if (ae(attributen, aattr[tagname]))
						tag += attribute;
					
					attribute = '';
					attributen = '';
					attributeequals = false;
					attributequotes = '';
				}
				expected = 'tag';
			}
		}
		//if an attribute value is expected
		else if (expected == 'attributev')
		{
			attribute += c;
			
			//lookahead for end of value
			if ((c == attributequotes) || ((n == ' ' || n == '/' || n == '>') && !attributequotes))
			{
				//if the attribute is allowed, add it to the output
				if (ae(attributen, aattr[tagname]))
					tag += attribute;
				
				attribute = '';
				attributen = '';
				attributeequals = false;
				attributequotes = '';
				expected = 'tag';
			}
		}
		
		//***Section for when the character is unknown but it is inside of a tag
		
		else if (expected == 'tag')
		{
			//if its a space
			if (c == ' ')
				tag += c;
			//if its a slash after the tagname, signalling a single tag.
			else if (c == '/' && tagname)
			{
				tag += c;
				tagtype = 'single';
			}
			//if its a slash before the tagname, signalling its an end tag
			else if (c == '/')
			{
				tag += c;
				tagtype = 'end';
			}
			//if its the end of a tag
			else if (c == '>')
			{
				tag += c;
				//if the tag is allowed, add it to the output
				if (ae(tagname, tags))
					o += tag;
				
				//if its a start tag
				if (tagtype == 'start')
				{
					//if the tag is supposed to have its contents deleted
					if (ae(tagname, dctags))
					{
						//if there is an end tag, skip to it in order to delete the tags contents
						if (-1 != (endpos = d.indexOf('</' + tagname, i)))
						{
							//have to make it one less because i gets incremented at the end of the loop
							i = endpos-1;
						}
						//if there isn't an end tag, then it was probably a non-compliant single tag
					}
				}
				
				tag = '';
				tagname = '';
				tagtype = 'start';
				expected = '';
			}
			//if its an attribute name
			else if (tagname && !attributen)
			{
				attributen += c.toLowerCase();
				expected = 'attributen';
				//lookahead for end of attribute name, in case its a one character attribute name
				if (n == ' ' || n == '>' || n == '/' || n == '=')
				{
					attribute += attributen;
					//check to see if its an attribute without an assigned value
					//determines whether there is anything but spaces between the attribute name and the next equals sign
					if (endOfAttr(i))
					{
						//if the attribute is allowed, add it to the output
						if (ae(attributen, attributen))
							tag += attribute;
						
						attribute = '';
						attributen = '';
						attributeequals = false;
						attributequotes = '';
					}
					expected = 'tag';
				}
			}
			//if its a start quote for an attribute value
			else if (ae(c, quotes) && attributeequals)
			{
				attribute += c;
				attributequotes = c;
				expected = 'attributev';
			}
			//if its an attribute value
			else if (attributeequals)
			{
				attribute += c;
				expected = 'attributev';
				
				//lookahead for end of value, in case its only one character
				if ((c == attributequotes) || ((n == ' ' || n == '/' || n == '>') && !attributequotes))
				{
					//if the attribute is allowed, add it to the output
					if (ae(attributen, attributen))
						tag += attribute;
					
					attribute = '';
					attributen = '';
					attributeequals = false;
					attributequotes = '';
					
					expected = 'tag';
				}
			}
			//if its an attribute equals
			else if (c == '=' && attributen)
			{
				attribute += c;
				attributeequals = true;
			}
			//if its the tagname
			else
			{
				tagname += c.toLowerCase();
				expected = 'tagname';
				
				//lookahead for end of tag name, in case its a one character tag name
				if (n == ' ' || n == '>' || n == '/')
				{
					tag += tagname;
					expected = 'tag';
				}
			}
		}
		//if nothing is expected
		else
		{
			//if its the start of a tag
			if (c == '<')
			{
				tag = c;
				expected = 'tag';
			}
			//anything else
			else
				o += htmlentities(c);
		}
	}
	
	//beautifying regexs
	//remove duplicate spaces
	o = o.replace(/\s+/g, ' ');
	//remove unneeded spaces in tags
	o = o.replace(/\s>/g, '>');
	//remove empty tags
	//this loops until there is no change from running the regex
	var remptys = rempty.join('|');
	var oo = o;
	while ((o = o.replace(new RegExp("\\s?<(" + remptys + ")>\s*<\\/\\1>", 'gi'), '')) != oo)
		oo = o;
	//make block tags regex string
	var btagss = btags.join('|');
	//add newlines after block tags
	o = o.replace(new RegExp("\\s?</(" + btagss+ ")>", 'gi'), "</$1>\n");
	//remove spaces before block tags
	o = o.replace(new RegExp("\\s<(" + btagss + ")", 'gi'), "<$1");
	
	//fix lists
	o = o.replace(/((<p.*>\s*(&middot;|&#9642;) .*<\/p.*>\n)+)/gi, "<ul>\n$1</ul>\n");//make ul for dot lists
	o = o.replace(/((<p.*>\s*\d+\S*\. .*<\/p.*>\n)+)/gi, "<ol>\n$1</ol>\n");//make ol for numerical lists
	o = o.replace(/((<p.*>\s*[a-z]+\S*\. .*<\/p.*>\n)+)/gi, "<ol style=\"list-style-type: lower-latin;\">\n$1</ol>\n");//make ol for latin lists
	o = o.replace(/<p(.*)>\s*(&middot;|&#9642;|\d+(\S*)\.|[a-z]+\S*\.) (.*)<\/p(.*)>\n/gi, "\t<li$1>$3$4</li$5>\n");//make li
	
	//extend outer lists around the nesting lists
	o = o.replace(/<\/(ul|ol|ol style="list-style-type: lower-latin;")>\n(<(?:ul|ol|ol style="list-style-type: lower-latin;")>[\s\S]*<\/(?:ul|ol|ol style="list-style-type: lower-latin;")>)\n(?!<(ul|ol|ol style="list-style-type: lower-latin;")>)/g, "</$1>\n$2\n<$1>\n</$1>\n");
	
	//nesting lists
	o = o.replace(/<\/li>\s+<\/ol>\s+<ul>([\s\S]*?)<\/ul>\s+<ol>/g, "\n<ul>$1</ul></li>");//ul in ol
	o = o.replace(/<\/li>\s+<\/ol>\s+<ol style="list-style-type: lower-latin;">([\s\S]*?)<\/ol>\s+<ol>/g, "\n<ol style=\"list-style-type: lower-latin;\">$1</ol></li>");//latin in ol
	o = o.replace(/<\/li>\s+<\/ul>\s+<ol>([\s\S]*?)<\/ol>\s+<ul>/g, "\n<ol>$1</ol></li>");//ol in ul
	o = o.replace(/<\/li>\s+<\/ul>\s+<ol style="list-style-type: lower-latin;">([\s\S]*?)<\/ol>\s+<ul>/g, "\n<ol style=\"list-style-type: lower-latin;\">$1</ol></li>");//latin in ul
	o = o.replace(/<\/li>\s+<\/ol>\s+<ol style="list-style-type: lower-latin;">([\s\S]*?)<\/ol>\s+<ol>/g, "\n<ol style=\"list-style-type: lower-latin;\">$1</ol></li>");//ul in latin
	o = o.replace(/<\/li>\s+<\/ul>\s+<ol style="list-style-type: lower-latin;">([\s\S]*?)<\/ol>\s+<ul>/g, "\n<ol style=\"list-style-type: lower-latin;\">$1</ol></li>");//ul in latin
	//remove empty tags. this is needed a second time to delete empty lists that were created to fix nesting, but weren't needed
	o = o.replace(new RegExp("\\s?<(" + remptys + ")>\s*<\\/\\1>", 'gi'), '');
	
	return o;
}

//array equals
//loops through all the elements of an array to see if any of them equal the test.
function ae (needle, haystack)
{
	if (typeof(haystack) == 'object')
		for (var i = 0; i < haystack.length; i++)
			if (needle == haystack[i])
				return true;
	
	return false;
}

//get character
//return specified character from d
function getc (i)
{
	return d.charAt(i);
}

//end of attr
//determines if their is anything but spaces between the current character, and the next equals sign
function endOfAttr (i)
{
	var between = d.substring(i+1, d.indexOf('=', i+1));
	if (between.replace(/\s+/g, ''))
		return true;
	else
		return false;
}

function htmlentities (character)
{
	if (hents[character])
		return hents[character];
	else
		return character;
}



/**
 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.3
 * @dependencies prototype.js 1.5.1+, effects.js
 * @author Brandon Lis <knightar.artician.com>
 */
/* Edited for use with Ajax View Widget - Brandon Lis */
/*  Thanks to Andrew Dupont for refactoring help and code cleanup - http://andrewdupont.net/  */

Glider = Class.create();
Object.extend(Object.extend(Glider.prototype, Abstract.prototype), {
	initialize: function(wrapper, options){
		this.scrolling  = false;
		this.wrapper    = $(wrapper);
		this.scroller   = this.wrapper.down('div.scroller');
		this.sections   = this.wrapper.getElementsBySelector('div.section');
		this.content	= this.scroller.down('div.content');
		this.options    = Object.extend({ amount: 3, duration: 1.0, frequency: 3, totalindex: 1, csubmission: 0, user: 0, currentindex: 1, path: '/ajax/view_widget2/' }, options || {});
		
		var x = 1;
		while (x <= this.options.totalindex){
			$(this.content).insert({ bottom: '<div id="section'+x+'" class="section"></div>' });
			x++;
		}
		
		this.currentIndex = this.options.currentindex;
		this.options.initialSection='section'+this.currentIndex;
		
		this.ajaxNext = this._ajaxNext.bindAsEventListener(this);
		this.ajaxPrevious = this._ajaxPrevious.bindAsEventListener(this);
		this.unhide = this._unhide.bindAsEventListener(this);
		this.jumpto = this._jumpto.bindAsEventListener(this);
		this.ajaxJump = this._ajaxJump.bindAsEventListener(this);
		
		
		new Ajax.Updater($('section'+this.currentIndex),this.options.path, {
			method: 'post',
			parameters: {'a': this.options.amount, 'u': this.options.userid,'c': this.currentIndex, 's': this.options.csubmission, 'd': 'current'},
			onSuccess:this.unhide,
			onComplete:this.jumpto
		});
		
		this.sections.each( function(section, index) {
		  section._index = index;
		});

		this.events = {
		  click: this.click.bind(this)
		};

		this.addObservers();
		if(this.options.autoGlide) this.start();
	},
	_unhide: function() {
		$('section'+this.currentIndex).show()
	},
	
	_jumpto: function() {
		this.moveTo('section'+this.currentIndex, this.scroller, { duration:this.options.duration });
	},
	
	indexSections: function() {
		this.sections   = this.wrapper.getElementsBySelector('div.section');
		this.sections.each( function(section, index) {
		  section._index = index;
		});
	},
	addObservers: function() {
		var controls = this.wrapper.getElementsBySelector('div.controls a');
		controls.invoke('observe', 'click', this.events.click);
	},	

	click: function(event) {
		this.stop();
		var element = Event.findElement(event, 'a');
		if (this.scrolling) this.scrolling.cancel();

		this.moveTo(element.href.split("#")[1], this.scroller, { duration:this.options.duration });     
		Event.stop(event);
	},

	moveTo: function(element, container, options){
		this.current = $(element);
		Position.prepare();
		var containerOffset = Position.cumulativeOffset(container),
		elementOffset = Position.cumulativeOffset($(element));

		this.scrolling 	= new Effect.SmoothScroll(container, 
		{duration:options.duration, x:(elementOffset[0]-containerOffset[0]), y:(elementOffset[1]-containerOffset[1])});
		return false;
	},
	
	jump: function(section) {
		if (section > 0 && section <= this.options.totalindex) {
			if ($('section'+section).empty()) {
				this.jumptosection = section;
				new Ajax.Updater($('section'+section),this.options.path, {
					method: 'post',
					parameters: {'a': this.options.amount, 'u': this.options.userid, 's': this.options.csubmission, 'c': section, 'd': 'next'},
					onSuccess: this.ajaxJump,
					onComplete: this.jumpto
				});
				
			}
			else {
				this.currentIndex=section;
				this.moveTo('section'+this.currentIndex, this.scroller, { duration:this.options.duration });
			}
			
		}
	},
	
	_ajaxJump: function() {
		this.currentIndex=this.jumptosection;
		this.moveTo('section'+this.jumptosection, this.scroller, { duration:this.options.duration });
	},
	
	next: function(){
		var currentindex = this.currentIndex;
		
		var users = $('section'+currentindex).select('a');
		var id = users[users.length-1];
		var lastid = $(id).readAttribute('ref').replace('glider-','');
		
		currentindex++;
		if (this.currentIndex <= (this.options.totalindex-1)) {
			if ($('section'+currentindex).empty()) {
				new Ajax.Updater($('section'+currentindex),this.options.path, {
					method: 'post',
					parameters: {'l': lastid, 'a': this.options.amount, 'u': this.options.userid, 's': this.options.csubmission, 'c': currentindex,'d': 'next'},
					onSuccess: this.ajaxNext,
					onComplete: this.jumpto
				});
			}
			else {
				this.currentIndex++;
				this.moveTo('section'+this.currentIndex, this.scroller, { duration:this.options.duration });
			}
		}
		else {
			this.jump(1);
		}
	},
	
	previous: function(){
		var currentindex = this.currentIndex;
		var users = $('section'+currentindex).select('a');
		var id = users[users.length-1];
		var lastid = $(id).readAttribute('ref').replace('glider-','');
		
		currentindex--;
		if (currentindex > 0) {
			if ($('section'+currentindex).empty()) {
				new Ajax.Updater($('section'+currentindex),this.options.path, {
					method: 'post',
					parameters: {'l': lastid, 'a': this.options.amount, 'u': this.options.userid, 's': this.options.csubmission, 'c': currentindex,'d': 'prev'},
					onSuccess: this.ajaxPrevious,
					onComplete: this.jumpto
				});
			}
			else {
				this.currentIndex--;
				this.moveTo('section'+this.currentIndex, this.scroller, { duration:this.options.duration });
			}
		}
		else { this.jump(this.options.totalindex); }
	},
	
	_ajaxPrevious: function(transport){
		this.currentIndex--;
	},
	
	_ajaxNext: function(transport){
		this.currentIndex++;
	},
	
	stop: function()
	{
		clearTimeout(this.timer);
	},
	
	start: function()
	{
		this.periodicallyUpdate();
	},
		
	periodicallyUpdate: function()
	{ 
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);
	}

});


function setScout(override) {
    data = $('scoutForm').serialize(true);
    new Ajax.Request('/modules/sys/scout/postscout.php' + (override==1?'?override=1':''), {
        method: 'post',
        parameters: data,
        onSuccess: function(result) {
            Control.Modal.close();
        },
        onFailure: function(result) {
            alert(result.responseText);
        }
    });
}

function cancelFeatured(id) {
    if(confirm("Are you sure you want to remove this submission as a featured artwork?")) {
         new Ajax.Request('/modules/sys/scout/cancel.php?id='+id, {
            method: 'get',
            onSuccess: function(result) {
                alert(result.responseText);
            },
            onFailure: function(result) {
                alert(result.responseText);
            }
         });
    }   
}