function stripslashes( str ) {
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}

function loadstart() {
	$('input').setOpacity(0.5);
	$('sources').setOpacity(0.5);
	$('loading').show();
}

function loadend() {
	$('loading').hide();
	$('input').setOpacity(1.0);
	$('sources').setOpacity(1.0);
}

function errorbox(a) {
	$('errorcontents').innerHTML=a;
	$('errordiv').toggle();
	$('input').setOpacity(0.5);
}

function errorboxbottom(a) {
	$('errorcontentsbottom').innerHTML=a;
	$('errordivbottom').toggle();
	$('bottomcontents').setOpacity(0.5);
}

function nameboxbottom(a) {
	$(a).toggle();
	$('bottomcontents').setOpacity(0.5);
}

function togglesource(input) {
	//Effect.toggle('sources','blind');
	if ((input=='top') && ($('sources').visible()===false)) {
		location.href='#sourcelist';
		Effect.toggle('sources','blind');
	}
	if ((input=='top') && ($('sources').visible())) {
		location.href='#sourcelist';
	}
	else Effect.toggle('sources','blind');
	//if ($('sources').visible()) $('sourcebtn').innerHTML="<img src='/citation/img/btn-changesource.png' onclick=\"togglesource()\" alt='Change Source'>";
	//else $('sourcebtn').innerHTML="<img src='/citation/img/btn-hidesourcelist.png' onclick=\"togglesource()\" alt='Hide Source List'>";
}

/*function checkformat(a,b) {
	var format=Form.getInputs(a,'radio','format').find(function(radio) { return radio.checked; }).value;
	if (b==0){
		if (format=='MLA') return true;
		else {
			$('input').setOpacity(0.5);
			$('upgradediv').toggle();
			return false;
		}
	}
	if (b==1){
		if (format!='ASA') return true;
		else {
			$('input').setOpacity(0.5);
			$('upgradediv').toggle();
			return false;
		}
	}
	return false;
}*/

function checkformat(a,b,c,d) {
	var lowercase=b.toLowerCase();
	var source=c.toLowerCase();
	source=source.replace(/\s+/g, '-');
	if (a==0) {
		if (b=='MLA') return window.location='/citation/'+lowercase+'/'+source+'/';
		else {
			$('input').setOpacity(0.5);
			$('upgradediv').toggle();
			document.getElementById('selectMLA').checked = true;
			return false;
		}
	}
	else if (a==1) {
		if ((d!='') && (b!='ASA')) return false;
		if (b!='ASA') return window.location='/citation/'+lowercase+'/'+source+'/';
		else {
			$('input').setOpacity(0.5);
			$('upgradediv').toggle();
			document.getElementById('selectMLA').checked = true;
			return false;
		}		
	}
	else if (a==2) {
		if (d!='') return false;
		else return window.location='/citation/'+lowercase+'/'+source+'/';
	}
	else return false;
}


function highlightsource(name) {
	var selectedlinks = $$('.column .selected');
	selectedlinks.each(function(r, index) {
		r.removeClassName('selected');
	});
	var namef = name.toLowerCase();
	namef=namef.replace('/', '_');
	namef=namef.replace(/\s+/g, '-');
	var linkname='link-'+namef;
	$(linkname).addClassName('selected');
}

function addcontrib(s,a,b) {
	var divname = 'contributors-'+a;
	var classname = '.'+a+'-contribs';
	var num = $$(classname).length;
	var newfields = "<div class='"+a+"-contribs' id='"+a+"-contribs-"+num+"' style='clear:both;'>\n\
				<div class='remove'><a onclick=\"$('"+a+"-contribs-"+num+"').remove();\">x</a></div>\n\
				<div class='multipleinputsl'>\n\
					<select name='"+b+"-type["+num+"]'>\n\
				";
	if (s=='Email') {
    newfields+="<option>Author</option>\n\
    			<option>To</option>\n\
    			";
	}
	else if ((s=='Chapter_Anthology') || (s=='Preface_Foreward')) {
		newfields+="<option value='Author'>Section author</option>\n\
					<option value='Section Editor'>Section editor</option>\n\
					<option value='Section Compiler'>Section compiler</option>\n\
					<option value='Section Translator'>Section translator</option>\n\
					<option value='Source Author'>Author</option>\n\
					<option value='Editor'>Editor</option>\n\
					<option value='Compiler'>Compiler</option>\n\
					<option value='Translator'>Translator</option>\n\
					";
	}
	else if (s=='Film_Movie') {
		newfields+="<option value='Director'>Director</option>\n\
					<option value='Producer'>Producer</option>\n\
					<option value='Writer'>Writer</option>\n\
					<option value='Screenwriter'>Screenwriter</option>\n\
					<option value='Adapter'>Adapter</option>\n\
					";
	}
	else if (s=='Interview') {
		newfields+="<option value='Interviewer'>Interviewer</option>\n\
					<option value='Author'>Interviewee</option>\n\
					";
	}
	else if (s=='Personal Interview') {
		newfields+="<option value='Author'>Interviewee</option>\n\
					";
	}
	else if (s=='Live Performance') {
		newfields+="<option value='Writer'>Writer</option>\n\
					<option value='Choreographer'>Choreographer</option>\n\
					<option value='Conductor'>Conductor</option>\n\
					<option value='Director'>Director</option>\n\
					<option value='Narrator'>Narrator</option>\n\
					<option value='Translator'>Translator</option>\n\
					";
	}
	else if ((s=='Musical Recording') || (s=='Song')) {
		newfields+="<option value='Author'>Singer</option>\n\
					<option value='Writer'>Writer</option>\n\
					<option value='Conductor'>Conductor</option>\n\
					<option value='Orchestrator'>Orchestrator</option>\n\
					<option value='Performer'>Performer</option>\n\
					";
	}
	else if (s=='Painting') {
		newfields+="<option value='Author'>Artist</option>\n\
					<option>Editor</option>\n\
				    <option>Compiler</option>\n\
				    <option>Translator</option>\n\
				    ";
	}
	else if (s=='Congressional Publication') {
		newfields+="<option value='List Author'>Author</option>\n\
					<option>Editor</option>\n\
				    <option>Compiler</option>\n\
				    <option>Translator</option>\n\
				    ";
	}
	else if (s=='Photograph') {
		newfields+="<option value='Author'>Photographer</option>\n\
					<option>Editor</option>\n\
				    <option>Compiler</option>\n\
				    <option>Translator</option>\n\
				    ";
	}
	else if (s=='Patent') {
		newfields+="<option value='Author'>Inventor</option>\n\
					";
	}
	else if (s=='Review') {
		newfields+="<option value='Author'>Reviewer</option>\n\
					<option value='Source Author'>Source Author</option>\n\
					";
	}
	else if (s=='Television_Radio'){ 
		newfields+="<option value='Author'>Writer</option>\n\
					<option value='Director'>Director</option>\n\
					<option value='Producer'>Producer</option>\n\
					";
	}
	else if (s=='Web Site') {
		newfields+="<option value='Author'>Article Author</option>\n\
					<option value='Source Editor'>Source Editor</option>\n\
					";
	}
	else if (s=='Blog_Podcast') {
		newfields+="<option value='Author'>Author</option>\n\
					<option value='Editor'>Site Editor</option>\n\
					<option value='Source Author'>Source Author</option>\n\
					<option value='Interviewer'>Interviewer</option>\n\
					";
	}
	else if ((s=='Lecture_Speech') || (s=='Digital Image') || (s=='Letter') || (s=='Manuscript') || (s=='Mailing List') || (s=='Newsgroup') || (s=='Raw Data') || (s=='Software')) {
		newfields+="<option value='Author'>Author</option>\n\
					";
	}
	else {
	    newfields+="<option>Author</option>\n\
				    <option>Editor</option>\n\
				    <option>Compiler</option>\n\
				    <option>Translator</option>\n\
				    ";
	}
	newfields+="</select>\n\
				</div>\n\
				<div class='multipleinputsl'>\n\
					<input type='text' name='"+b+"-first["+num+"]' class='regular'/><br/>\n\
					<span class='small red'>First Name</span>\n\
				</div>\n\
				<div class='multipleinputsl'>\n\
					<input type='text' name='"+b+"-mi["+num+"]' class='tiny' /><br/>\n\
					<span class='small red'>M.I.</span>\n\
				</div>\n\
				<div class='multipleinputsl'>\n\
					<input type='text' name='"+b+"-last["+num+"]' class='regular'/><br/>\n\
					<span class='small red'>Last Name</span>\n\
				</div>\n\
			</div>";
	new Insertion.Bottom(divname, newfields);
}


function existingformdata(formname,old) {
	var formdata=$(old).serialize(true);
	var data = Object.toJSON(formdata);
	data=data.evalJSON();
	var form = $(formname);
	for (var i in data){
		if ((i!='sourcetype') && (i!='source')) {
			var input = form[i];
			if (i=='contributors-type') {
				var contribnum=data['contributors-type'].length;
				for (var num=1;num<contribnum;num++) {
					addcontrib('',typein,'contributors');
				}
			}
			if ((i=='contributors-first') || (i=='contributors-mi') || (i=='contributors-last') || (i=='contributors-type')){
				for (var c = 0; c < citation['contributors-type'].length; c++ ) {
					var temp = data[i][c];
					var input=document.forms[formname].elements[i+"["+c+"]"];
					if (input!=undefined) input.value=temp;
				}
			}
			else {
				var temp = stripslashes(data[i]);
				if (temp!='') {
					if ($(input)!=undefined)$(input).value=temp;
					if (($(input)!=undefined) && ($(input).type==undefined)) {
						$(formname).select('input[type="radio"][name="'+i+'"]').each(function(elm){
						        elm.checked = false;
						        if (elm.value == temp) elm.checked = 'checked';
						
						}); 
					}
				}
			}
		}
	}
}

function choosesource(name,type,id) {
	namein=name.replace('/', '_');
	new Ajax.Updater('input','/citation/showform.php', {
		method: 'get',
		parameters: {a:namein,b:type,id:id},
		onLoading: function() {
			loadstart();
		},
		onFailure: function() {errorbox('This page has failed to load.');},
		onComplete: function() {
			highlightsource(name);
			if (type==undefined) togglesource();
			$('citationtype').innerHTML=name;
			loadend();
		}
	});
}

function changesourcetype(changeto) {
	changeto=changeto.replace(/\s+/g, '-');
 	divname='switch-'+changeto;
	var allswitches = $$('.switchsource');
	Effect.toggle(divname,'appear');
	allswitches.each(function(r, index) {
		//r.hide();
		if (r.visible()) {
			var oldname=r.identify();
			oldname=oldname.replace(/switch-/, 'citation-');
			existingformdata('citation-'+changeto,oldname);
			r.hide();
		}
	});
}

function editcitation(source, sourcetype, id) {
	
	namein=source.replace('/', '_');
	new Ajax.Updater('input','/citation/showform.php', {
		method: 'get',
		parameters: {a:namein,b:sourcetype,id:id},
		onLoading: function() {
			loadstart();
		},
		onFailure: function() {errorbox('This page has failed to load.');},
		onComplete: function() {
			highlightsource(source);
			$('citationtype').innerHTML=source;
			
			//toggles the source list to make sure it's hidden
			if ($('sources').visible()) {
				new Effect.BlindUp($('sources'));
				$('sourcebtn').innerHTML="<img src='/citation/img/btn-changesource.png' onclick=\"togglesource()\" alt='Change Source'>";
			}
			
			new Ajax.Request('/citation/editcitation.php', {
					method:'get',
					parameters: {i:id},
					requestHeaders: {Accept: 'application/json'},
					onCreate: function() {
						loadstart();
					},
					onFailure: function() {errorbox('This page has failed to load.');},
					onSuccess: function(transport){
						var citation = transport.responseText.evalJSON(true);
						var typein = citation.sourcetype.toLowerCase();
						typein=typein.replace(/\s+/g, '-');
						var formname='citation-'+typein;
							var form = $(formname);
							//var contribregex=/^(contributors-type-).+/;
						for (var i in citation){
							var input = form[i];
							if (i=='contributors-type') {
								var contribnum=citation['contributors-type'].length;
								for (var num=1;num<contribnum;num++) {
									addcontrib(source,typein,'contributors');
								}
								
							}
							if ((i=='contributors-first') || (i=='contributors-mi') || (i=='contributors-last') || (i=='contributors-type')){
								for (var c = 0; c < citation['contributors-type'].length; c++ ) {
									var temp = citation[i][c];
									var input=document.forms[formname].elements[i+"["+c+"]"];
									if (input!=undefined) input.value=temp;
								}
							}
							else {
								var temp = stripslashes(citation[i]);
								if ($(input)!=undefined) {
									$(input).value=temp; //regular boxes
									if ($(input).type==undefined) {
										$(formname).select('input[type="radio"][name="'+i+'"]').each(function(elm){
										        elm.checked = false;
										        if (elm.value == temp) elm.checked = 'checked';
										
										}); 
									}
								}
							}
						}
						loadend();
					}
			});	
			
			loadend();
		}
	});	
}

function autofillisbn(a,b) {
   	if (a!='') {
		var classname = '.'+a+'-contribs';
		var num = $$(classname).length;
		if (num>1) {
			$$(classname).each(function(s, index) {
				if (index!=0) s.remove();
			});
		}

		var formname='citation-'+a;
		var form = $(formname);
		var input = form[b];
		var isbn=$(input).getValue();
		isbn=isbn.replace(/-/g, '');
		new Ajax.Request('/citation/autofill.php', {
			method:'get',
			parameters: {index1:'isbn',value1:isbn},
			requestHeaders: {Accept: 'application/json'},
			onLoading: function() {loadstart();},
			onFailure: function() {errorbox('This page has failed to load.');},
			onSuccess: function(transport){
				var book = transport.responseText.evalJSON(true);
				if (book.title=='') {
					errorbox("The ISBN number you have entered is invalid, or doesn't exist in the database.");
				}
				else {
					var title = form['book-title'];
						$(title).value=book.title;
					var city = form['publication-city'];
						if (book.publisher['city']!=undefined) $(city).value=book.publisher['city'];
					var publisher = form['publication-publisher'];
						$(publisher).value=book.publisher['company'];
					var year = form['publication-year'];
						if (book.publisher['year']!=undefined) $(year).value=book.publisher['year'];
					var authorsnum = book.author.length;
					var i=0;
					while (i<=authorsnum-1) {
						if (i!=0) addcontrib('',a,'contributors');
						/*var authorfirst = form['contributors-first['+i+']'];
							if (book.author[i]['first']!=undefined) $(authorfirst).value=book.author[i]['first'];
						var authormi = form['contributors-mi['+i+']'];
							if (book.author[i]['mi']!=undefined) $(authormi).value=book.author[i]['mi'];
						var authorlast = form['contributors-last['+i+']'];
							if (book.author[i]['last']!=undefined) $(authorlast).value=book.author[i]['last'];*/
							
						var temp = book.author[i]['first'];
						var c='contributors-first'; //there must be a better way to do this
							var input=document.forms[formname].elements[c+"["+i+"]"];
							if ((temp!=undefined) && (input!=undefined)) input.value=temp;	
						var temp = book.author[i]['mi'];
						var c='contributors-mi';
							var input=document.forms[formname].elements[c+"["+i+"]"];
							if ((temp!=undefined) && (input!=undefined)) input.value=temp;
						var temp = book.author[i]['last'];
						var c='contributors-last';
							var input=document.forms[formname].elements[c+"["+i+"]"];
							if ((temp!=undefined) && (input!=undefined)) input.value=temp;
							
							
						i=i+1;
					}
					loadend();
				}
			}
		});	
	}
}
