User:AndyZ/peerreviewer.js

From Wikipedia, the free encyclopedia

Note: After saving, you have to bypass your browser's cache to see the changes. Mozilla/Safari: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Internet Explorer: press Ctrl-F5, Opera/Konqueror: press F5.

//[[User talk:AndyZ/peerreviewer.js]] <pre>
/* 

 //Semi-automatic javascript peer reviewer 
 // note that this is NOT a [[WP:BOT]] 
 // (though it may be considered a [[WP:SBOTS|semi-bot]]) 

 /////////////////////////////////////////////
 // See [[User:AndyZ/peerreviewer]] or talk //
 //      for details                        //
 // Quick installation -                    //
 // Add to your monobook.js:                //
 // {{subst:js|User:AndyZ/peerreviewer.js}} //
 //                                         //
 //     Written by AndyZ                    //
 /////////////////////////////////////////////
*/

//	start code

////// addlink script, from User:Omegatron
// 	Script from [[User:Omegatron/monobook.js/addlink.js]]
document.write('<script type="text/javascript" src="' 
             + 'http://en.wikipedia.org/w/index.php?title=User:Omegatron/monobook.js/addlink.js' 
             + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');

             /////////////////////////
             //configurable options //
             /////////////////////////
             //details on talk page //
             /////////////////////////
             
//most, if they dont exist, are set to false
//should be declared in a different fashion, but this is the only method
//I can think of as of now
	////variables for: functionality

	//input and output (ids):
	//input_PR is the source id for the input
	//output_PR is the output id for the output
	
var input_PR;
if(!input_PR) input_PR = "wpTextbox1";
var output_PR;
if(!output_PR) output_PR = "theResponse";	
	
	//other configurable options, see talk page for details
var allSpaces_PR;             // if true, "peer review" link will appear on all article pages
if(!allSpaces_PR) allSpaces_PR = false;
var defaultView_PR;			  // options: 0 - normal, in prose;  1 - template form;  2 - with references;  (for now)
if(!defaultView_PR) defaultView_PR = 0;
var select_PR;                            // selects text 
if(!select_PR) select_PR = false;         
var popup_PR;					// feature not available yet
if(!popup_PR) popup_PR = false;
var sendTo_PR;				// if true, removes send to tab
if(!sendTo_PR) sendTo_PR = false;
var toolbarLink_PR;
if(!toolbarLink_PR) toolbarLink_PR = false;
var toolbar_PR;				// accepted values = "personal", "cactions", "navigation" -- possibly later "toolbar"
if(!toolbar_PR) toolbar_PR = "personal";
var directRef_PR;
if(!directRef_PR) directRef_PR = false;
var cat_PR;
if(!cat_PR) cat_PR = false;
var alpha_PR;
if(!alpha_PR) alpha_PR = false;
var userSandbox_PR;
if(!userSandbox_PR) userSandbox_PR = "User:" + wgUserName + "/sandbox"
var initMsg_PR;
if(!initMsg_PR) initMsg_PR = "The following suggestions were generated by a semi-automatic [[User:AndyZ/peerreviewer|javascript program]], and might not be applicable for the article in question."
var endMsg_PR;
if(!endMsg_PR) endMsg_PR = "\nYou may wish to browse through [[User:AndyZ/Suggestions]] for further ideas. Thanks, ~~"+"~~\n\n\n";
var noXHR_PR;				// allow [[ajax]] ([[XMLHTTPrequest]]) or not
if(!noXHR_PR) noXHR_PR = false;
var maintain_PR;				//for maintainers of [[WP:PR/A]] and its subpages
if(!maintain_PR) maintain_PR = false;
var spellcheck_PR;			//spell checker, takes long time though
if(!spellcheck_PR) spellcheck_PR = false;
var showHeading_PR;
if(!showHeading_PR) showHeading_PR = false;
var showInstaview_PR;
if(!showInstaview_PR) showInstaview_PR = false;
var instaview_PR;			//instaview button!! released under BSD license by Pilaf
if(instaview_PR == undefined) instaview_PR = true;
var width_PR;
if(!width_PR) width_PR = 1200;
var width4_PR = width_PR + 4;
var imgCheck_PR;
if(imgCheck_PR == undefined) imgCheck_PR = false;

width_PR = width_PR.toString(); width4_PR = width4_PR.toString();

	////colors, style
var restoreText_PR;				// text for restoration button
if(!restoreText_PR) restoreText_PR = "[restore]";
var restoreStyle_PR;			// style for restoration button (background:yellow, fixed position, 5 px from left and 120 px from top
if(!restoreStyle_PR) restoreStyle_PR = "background:yellow; position:absolute; margin-left:5px; margin-top:120px;";
var toolbarLink_PR;			// simple link to PR, from article mode
var topBarColor_PR;			  // color of top bar of suggestions
if(!topBarColor_PR) topBarColor_PR = "red";
var botBarColor_PR;			  // color of bottom bar of suggestions
if(!botBarColor_PR) botBarColor_PR = "#cccccc";
				//end configurable options

if(wgNamespaceNumber == 0 || wgNamespaceNumber == 4 || allSpaces_PR){		//only if namespace is main (or wp)
					//the actual output location of the suggestions
					
	//feedbackid = "theFeedback";
	//drag_PR = 'onmousedown="StartDrag(document.getElementById('+feedbackid+'))" onmouseup="CancelDrag()" onmouseout="CancelDrag()"'
	
	var instaview_button_txt;
	if(instaview_PR)
		instaview_button_txt = '<input type="button" value="Instaview" name="instaview_button" id="instaview_button" style="width:150" onclick="instaPreview();" onMouseOver="window.status=\'Preview the suggestions using Live Preview ((C)2006 Pilaf, BSD) without having to copy+paste and using diff. button\'; return true;" onMouseOut="window.status=\'\'">' 	
	else
		instaview_button_txt = "";
					
					//add new button for <span onclick="addToPage()">move to</span> soon
document.write('<div id="theFeedback" style="position:absolute; width:'+width_PR+'px; margin-top:150px; margin-left:40px; border:2px solid #000000; background:55ff55; visibility:hidden; z-index:20;"><div id="topBar" style="background:'+topBarColor_PR+'; text-align:right; width:'+width4_PR+'px"><span onclick="popreview();" onMouseOver="window.status=\'Shows current suggestions in new window, so that they do not interfere with editing\'" onMouseOut="window.status=\'\'">new window</span> | <span onclick="thehide()" onMouseOver="window.status=\'Hides suggestions so you can continue editing\'" onMouseOut="window.status=\'\'">close</span></div><form name="theForm"><textarea style="width:'+width_PR+'px" rows="20" name="theResponse" id="theResponse">'+initMsg_PR+'</textarea>'+
	'<div style="background:'+botBarColor_PR+'; width:' + width4_PR + 'px">'+instaview_button_txt+' <input type="button" value="Readonly" name="switch_readonly" onclick="determineReadonly()"> | <input type="button" value="Template form" name="switch_temp" onclick="determineReplace();" style="width:150" onMouseOver="window.status=\'Displays suggestions in templates, not prose, ensuring that after copy+pasting+saving, the resulting text is updated.\'" onMouseOut="window.status=\'\'"> <input type="button" value="Add footnotes" name="switch_foot" onclick="determineFoot();" style="width:150" onMouseOver="window.status=\'Shows footnotes, which usually are links to footnotes on User:AndyZ/PRnotes\'" onMouseOut="window.status=\'\'"> <a href="http://en.wikipedia.org/wiki/User talk:AndyZ/peerreviewer.js" target="_blank" onMouseOver="window.status=\'All feedback is appreciated\'" onMouseOut="window.status=\'\'">Questions/comments/errors?</a><br></div><div id="InstaViewResponse" style="background:white; visibility:hidden"></div>'
	+'</form></div>'
	+'<div id="restore" style="z-index:19; visibility:hidden;'+restoreStyle_PR+'" onclick="theshow()" onMouseOver="window.status=\'Show suggestions\'" onMouseOut="window.status=\'\'">'+restoreText_PR+'</div>')	
}

if(toolbar_PR == "personal" || toolbar_PR == "navigation" || toolbar_PR == "cactions"){
if((wgNamespaceNumber == 0 || wgNamespaceNumber == 4 || allSpaces_PR) && !toolbarLink_PR){
//adds peer review link to top bar (with your username, talk page, preferences, watchlist, etc.)
addOnloadHook(function () {
    if(document.forms.editform) {
        addLink('p-'+toolbar_PR, 'javascript:review1()', 'peer review', 'ca-peerreviewer', 'Semi-automatic peer reviewer by javascript', '', '');
    }
});	
}

if((wgNamespaceNumber == 0 || allSpaces_PR) && toolbarLink_PR){
addOnloadHook(function () {
	addLink('p-'+toolbar_PR, 'javascript:toReview1()', 'peer review', 'ca-peerreviewer', 'Semi-automatic peer reviewer by javascript', '', '');
});	
}
}

///////////////////////////////// Toolbar code failing
/* addOnloadHook fails to work... 
else if(toolbar_PR == "toolbar" && document.getElementById("toolbar")){
	//image file: http://upload.wikimedia.org/wikipedia/en/a/a9/AZbutton_PR.PNG	
	addOnloadHook(function () {
		alert("creating button");
		//document.getElementById('toolbar').innerHTML = document.getElementById('toolbar').innerHTML + "<a href='javascript:review1();'><img src='http://upload.wikimedia.org/wikipedia/en/a/a9/AZbutton_PR.PNG' alt='JavaScript peer reviewer' title='JS peer review' style='CURSOR: pointer' border=0></a>"
		
		AZbutton_PR = document.createElement("img");
		AZbutton_PR.setAttribute("src","http://upload.wikimedia.org/wikipedia/en/a/a9/AZbutton_PR.PNG");
		AZbutton_PR.setAttribute("width","23");
		AZbutton_PR.setAttribute("height","22");
		AZbutton_PR.setAttribute("alt","uses JavaScript to suggest corrections to the article");
		AZbutton_PR.setAttribute("style","CURSOR: pointer");
		AZbutton_PR.setAttribute("border",0);
		AZbutton_PR.setAttribute("onclick","review1()");
		document.getElementById("toolbar").appendChild(AZbutton_PR);  
		alert("done");
	})
} ///////////////////////////////// end commented code
*/

//global variable declarations, not configurable
var temp_mem, foot_mem;
var imgFU = false;
var imgFUstr = "";
var imgNT = false;
var imgNTstr = "";
var PRtemplateData;
var tempPRdata;
var outputText_PR = initMsg_PR;	//actual output text

	//////////
	// Note: variables tend to be declared:
 	// check_??? are usually T/F
 	// list_??? generally array for comparing (indexOf())
 	//////////

function review1(){
	//wpTxt is the variable for the text of a document, input_PR is the id
if(document.getElementById(input_PR)){
	wpTxt = document.getElementById(input_PR).value;
	theLength = wpTxt.length;
}
else{
	alert("Error: Could not locate text\n" + input_PR);
	return;
}

if(!document.getElementById(output_PR)){
	alert("Error: Unable to access output location\n" + output_PR);
	return;	
}

// --------------------
// determine title name
theTitle = wgTitle;

if(wgPageName.indexOf(":") != -1)
	theTitle2 = wgPageName.replace(/\_/gi," ").split(":")[1];

if(outputText_PR.indexOf("~~"+"~~")!=-1){
	var existingPR = confirm("There are already suggestions here.\nContinuing will cause the old suggestions to be overwritten.\nDo you wish to proceed?");	
	if(!existingPR) return;
	else{
		outputText_PR = initMsg_PR;		//reset global variables
		var imgFU = false;
		var imgFUstr = "";
		var imgNT = false;
		var imgNTstr = "";
	}
}

	//heading on output (at top)
if(showHeading_PR)
        outputText_PR = "===[["+theTitle+"]]===\n"+outputText_PR;

// -------------------- 
// lead stuff //
// determine the number of paragraphs in the lead
// -------------------- 

wpTxtlead = wpTxt.substring(0,wpTxt.indexOf("=="))
newLine = /\n[A-Z]/g

if(newLine.test(wpTxtlead)){
	NumPara = wpTxtlead.match(newLine);
	theNumPara = NumPara.length;
	theNumPara++;		//count the first paragraph
}
else theNumPara=1

if(theNumPara==1)
	outputText_PR+="\n{{subst:User:AndyZ/PR/lead}}"
if((theNumPara==2) && (theLength>=30000))
	outputText_PR+="\n{{subst:User:AndyZ/PR/lead}}"
if((theNumPara==3) && (theLength<=15000))
	outputText_PR+="\n{{subst:User:AndyZ/PR/leadlong}}"
if((theNumPara==4) && (theLength<=30000))
	outputText_PR+="\n{{subst:User:AndyZ/PR/leadlong}}"
if(theNumPara>=5){
	outputText_PR+="\n{{subst:User:AndyZ/PR/leadlong}}"
	outputText_PR+="\n{{subst:User:AndyZ/PR/leaddetail}}"
}

// -------------------- 
//checks linking in comparison to # of words (see [[WP:LINK]] suggestions)
// -------------------- 
words = wpTxt.split(" ");
links = wpTxt.split("[[");
if(.03 * words.length >= links.length)
	outputText_PR+="\n{{subst:User:AndyZ/PR/underlink}}";
else if(.1* words.length <= links.length)
	outputText_PR+="\n{{subst:User:AndyZ/PR/overlink}}";

// -------------------- 
//checks if document follows WP:CONTEXT / WP:MOSDATE guidelines
// -------------------- 
var check_contxt = false;	//if it is changed to true, one of the date guidelines has been violated

//looks for year
regex_yr = /[^,\]]\s\[\[\d{4}\]\]/gi;

//array for days of the week
var list_day = new Array(/\[\[Monday\]\]/gi,/\[\[Tuesday\]\]/gi,/\[\[Wednesday\]\]/gi, /\[\[Thursday\]\]/gi,/\[\[Friday\]\]/gi,/\[\[Saturday\]\]/gi,/\[\[Sunday\]\]/gi);

//array for months
var list_month = new Array(/\[\[January\]\]/gi,/\[\[February\]\]/gi,/\[\[March\]\]/gi,/\[\[April\]\]/gi,/\[\[May\]\]/gi,/\[\[June\]\]/gi,/\[\[July\]\]/gi,/\[\[August\]\]/gi,/\[\[September\]\]/gi,/\[\[October\]\]/gi,/\[\[November\]\]/gi,/\[\[December\]\]/gi);

if (regex_yr.test(wpTxt)) check_contxt = true;
for(i=0;i<list_day.length;i++){if(list_day[i].test(wpTxt)) check_contxt = true;}
for(i=0;i<list_month.length;i++){if(list_month[i].test(wpTxt)) check_contxt = true;}

if(check_contxt) outputText_PR+="\n{{subst:User:AndyZ/PR/contxt}}"

// -------------------- 
//about [[WP:MOS#Time]]
// -------------------- 
// needs // cleanup //

var mostime = new Array(); var mostime2 = new Array(); 	//declare [[WP:MOSTIME]] arrays
mostimestring = ""						//to hold page parameters
goodmostime = true;						//if false, give message
mostime[0] = /recently/gi
mostime2[0] = "recently"
mostime[1] = /last month.[^o]/gi
mostime2[1] = "last month"
mostime[2] = /last year.[^o]/gi
mostime2[2] = "last year"
mostime[3] = /yesterday/gi
mostime2[3] = "yesterday"
mostime[4] = /\.\ssoon/gi
mostime2[4] = "soon"
mostime[5] = /last week.[^o]/gi
mostime2[5] = "last week"
mostime[6] = /previous (month|year|day|week)/gi
mostime2[6] = "previous [day/week/month/year]"
mostime[7] = /(\.\s|\n)next (week|month|year)/gi
mostime2[7] = "next [week/month/year]"

for(i=0;i<mostime.length;i++){
	if(mostime[i].test(wpTxt)){
		goodmostime = false;
		mostimestring += "|" + mostime2[i];		//add parameters
	}
}

if(!goodmostime)
	outputText_PR+="\n{{subst:User:AndyZ/PR/time"+mostimestring+"}}"

// -------------------- 
//searches for images
// -------------------- 
regex_img = /\[\[Image:/gi
if(!regex_img.test(wpTxt)) outputText_PR+="\n{{subst:User:AndyZ/PR/noimg}}"

//sees if lead image exists (may not be accurate if template is at front
if(!((wpTxt.substring(0,100).indexOf("[[Image")!=-1)||(wpTxt.substring(0,100).indexOf("[[image")!=-1)||(wpTxt.substring(0,1)=="{")||(wpTxt.substring(0,2)=="<!")||(wpTxt.substring(0,3)==":''"))){
outputText_PR+="\n{{subst:User:AndyZ/PR/leadimg}} <!--Note that if something is in front of a lead image, it will not render by this javascript suggestion peer reviewer (like a disambig link or a lead comment-->"
}

// -------------------- 
//searches for images without captions
// -------------------- 
var list_cap = new Array(/\d{2}px\]\]/i,/\|none\]\]/i,/\|left\]\]/i,/\|center\]\]/i,/\|right\]\]/i,/\|thumb\]\]/i,/\|thumbnail\]\]/i,/\|frame\]\]/i,/\.jpg\]\]/i,/\.png\]\]/i,/\.svg\]\]/i)
check_cap = false;		//if check_cap == true, then captions are needed

wpTxt_captions = wpTxt.replace(/\|\s?=.+/gi,"")
for(i=0;i<list_cap.length;i++){if(list_cap[i].test(wpTxt_captions)) check_cap = true;}

if(check_cap)
	outputText_PR+="\n{{subst:User:AndyZ/PR/caption}}";

// -------------------- 	
// Discourage galleries, per [[WP:IG]]
// -------------------- 

if(/<gallery>/i.test(wpTxt)) outputText_PR+="\n{{subst:User:AndyZ/PR/ig}}";

// -------------------- 
// image licensing: as of now, cannot check licensing of WikiMedia Commons images
//  assumes images on commons are properly sourced
// -------------------- 
 
var imgCode = /\[\[image:(.+?)(\||\])/gi
var imgList = new Array();
if(imgCode.test(wpTxt) && !noXHR_PR && imgCheck_PR){
	imgList = wpTxt.match(imgCode);
	for(i=0;i<imgList.length;i++) {
		imgList[i] = imgList[i].replace(/\[\[image:(.+?)(\||\])/gi,"Image:$1");
		wpajax.download({url:'http://en.wikipedia.org/w/index.php?title='+imgList[i]+'&action=raw',
	    		onSuccess: checkImgLicense, onFailure: wikiImg, message: "raw," + imgList[i] });
	}
}
		//output for image licensing prolems
if(imgNT) outputText_PR+="\n{{subst:User:AndyZ/PR/imgtag"+imgNTstr+"}} <!--Listed images do not have licensing information-->";
if(imgFU) outputText_PR+="\n{{subst:User:AndyZ/PR/imgfu"+imgFUstr+"}} <!--List images are fair use without rationale-->";

// -------------------- 
//searches for infobox
// -------------------- 
var list_ibox = new Array(/\{\{infobox/gi,/\{\{taxobox/gi,/\{\{.{1,}infobox(\s|)\|/gi,/\{\{[^or]/i)
check_ibox = false; 

for(i=0;i<list_ibox.length;i++){
	if(list_ibox[i].test(wpTxt)) check_ibox = true;
}

if(!check_ibox)
	outputText_PR+="\n{{subst:User:AndyZ/PR/infobox}} (Note that there might not be an applicable infobox; remember that these suggestions are not generated manually)"

// -------------------- 
//searches for <nowiki> {{persondata}} </nowiki>
// -------------------- 
catbirth = /\[\[Category\:\d{1,}\s(BC\s|)births/gi							//category:xxxx births
catdeath = /\[\[Category\:\d{1,}\s(BC\s|)deaths/gi							//category:xxxx deaths
infobio = /\{\{Infobox(\_|\s)(biography|philosopher|Military\sPerson)/gi	//major person infoboxes
persondata = /\{\{persondata/gi												//persondata template

if((catbirth.test(wpTxt) || catdeath.test(wpTxt) || infobio.test(wpTxt)) && (!persondata.test(wpTxt)))
	outputText_PR+="\n{{subst:User:AndyZ/PR/persondata}}"

// -------------------- --------------------
//[[WP:MOSNUM]] and [[WP:MOSDATE]]:
// -------------------- --------------------
//   NOTE: Following sections need cleanup
//    to become easily readable
//list of units, NEEDS CLEANUP!! + ADDITIONS!!
// -------------------- --------------------

// --------------------
//nbsp checker: distances
// --------------------

list_unitnbsp = /((\d+)(\s|)(km|kilometer|kilometre|mi[\s\)]|miles?|ft|foot\s|feet|yd|yards?|in(ch|ches)|cm|centi|dm|decim|nm|nano|lb|pounds?|tons?\s|metric ton|g\s|gram|g\)|in<sup>2<\/sup>|squared inches|ft<sup>2<\/sup>|squared feet|m<sup>2<\/sup>|squared meter|km<sup>2<\/sup>|squared kilo|cm<sup>2<\/sup>|squared centi|mi<sup>2<\/sup>|squared mile|in<sup>3<\/sup>|cubic inch|ft<sup>3<\/sup>|cubic feet|m<sup>3<\/sup>|cubic meter|km<sup>3<\/sup>|cubic kilo|cm<sup>3<\/sup>|cubic centi|mi<sup>3<\/sup>|cubic mile))/gi;

if(list_unitnbsp.test(wpTxt)){
	temp_unitnbsp = wpTxt.match(list_unitnbsp);	
	outputText_PR+="\n{{subst:User:AndyZ/PR/nbsp|"+RegExp.$1+"|"+RegExp.$2+"&nbsp;"+RegExp.$4+"|"+RegExp.$2+"&amp;nbsp;"+RegExp.$4+"}}";
}

// --------------------
//checks for usage of standard abbreviations in parentheses (for conversions)
// --------------------
kmSA = /(kilometer|kilometer|kilometers|kilometres)\)/gi
miSA = /mile(s|)\)/gi
ftSA = /(foot|feet)\)/gi
ydSA = /yard(s|)\)/gi
inchSA = /(inch|inches)\)/gi
cmSA = /centimeter(s|)\)/gi
dmSA = /decimeter(s|)\)/gi
nmSA = /nanometer(s|)\)/gi

//weights/mass
lbSA = /(pound|pounds)\)/gi
gramSA = /(gram|grams)\)/gi
kgSA = /(kilogram|kilograms)\)/gi

//area
sqinSA = /squared inch(es|)\)/gi
sqftSA = /squared feet\)/gi
sqmtSA = /squared meter(s|)\)/gi
sqkmSA = /squared (kilometer|kilometer|kilometers|kilometres)\)/gi
sqcmSA = /squared centimeter(s|)\)/gi
sqmiSA = /squared mile(s|)\)/gi

//volume
cuinSA = /cubic inch(es|)\)/gi
cuftSA = /cubic (foot|feet)\)/gi
cumtSA = /cubic meter(s|)\)/gi
cukmSA = /cubic kilometer(s|)\)/gi
cucmSA = /cubic centimeter(s|)\)/gi
cumiSA = /cubic mile(s|)\)/gi

if(kmSA.test(wpTxt) || miSA.test(wpTxt) || ftSA.test(wpTxt) || ydSA.test(wpTxt) || cmSA.test(wpTxt) || nmSA.test(wpTxt) || inchSA.test(wpTxt) || dmSA.test(wpTxt) || lbSA.test(wpTxt) || gramSA.test(wpTxt) || kgSA.test(wpTxt) || sqinSA.test(wpTxt) || sqftSA.test(wpTxt) || sqmtSA.test(wpTxt) || sqkmSA.test(wpTxt) || sqcmSA.test(wpTxt) || sqmiSA.test(wpTxt) || cuinSA.test(wpTxt) || cuftSA.test(wpTxt) || cumtSA.test(wpTxt) || cukmSA.test(wpTxt) || cucmSA.test(wpTxt) || cumiSA.test(wpTxt)){
outputText_PR+="\n{{subst:User:AndyZ/PR/abbrev}}"
}

// --------------------
//checks that units are spelled out in text
// --------------------
list_SN = /([\d\.]+\s(kms?|mi|yds?|fts?|in\.|cms?|dms?|nms?|oz|lbs?|kgs?|mgs?|dag|dg|ng|(in|ft|yd|mi|m|km|cm|mm|dm|nm)<sup>[23]<\/sup>|ha|hl|dl|cl|ml)\s)/gi;

if(list_SN.test(wpTxt)){
	temp_SN = wpTxt.match(list_SN);
	outputText_PR+="\n{{subst:User:AndyZ/PR/spellnum}} " + "Specifically, an example is " + RegExp.$1.substring(0,RegExp.$1.length-1) + ".";
}

// --------------------
//checks for usage of standard abbreviations in parentheses (without 's') (for conversions)
// --------------------
kmSN2 = /kms(\s|\))/gi
miSN2 = /mis(\s|\))/gi
ftSN2 = /\sfts(\s|\))/gi
ydSN2 = /yds(\s|\))/gi
inchSN2 = /\sins(\s|\))/gi
cmSN2 = /cms(\s|\))/gi
dmSN2 = /dms(\s|\))/gi
nmSN2 = /nms(\s|\))/gi

//weights/mass
lbSN2 = /lbs(\s|\))/gi
gramSN2 = /\sgs(\s|\))/gi
kgSN2 = /kgs(\s|\))/gi

if(kmSN2.test(wpTxt) || miSN2.test(wpTxt) || ftSN2.test(wpTxt) || ydSN2.test(wpTxt) || cmSN2.test(wpTxt) || nmSN2.test(wpTxt) || inchSN2.test(wpTxt) || dmSN2.test(wpTxt) || lbSN2.test(wpTxt) || gramSN2.test(wpTxt) || kgSN2.test(wpTxt)){
outputText_PR+="\n*When writing standard abbreviations, the abbreviations should not have a 's' to demark plurality (change kms to km and lbs to lb)."
}

// --------------------
// does not work; currently fixing
// --------------------
/*
km2 = /\d(\s|)(km|kilometer|kilometre)[^\}\s][^\(]/gi
mi2 = /\d(\s|)(mi|mile)[^\}\s][^\(]/gi
ft2 = /\d(\s|)(ft|foot|feet)[^\}\s][^\(]/gi
yd2 = /\d(\s|)(yd|yard)[^\}\s][^\(]/gi
//in2 = /\d(\s|)in[^\}\s][^\(]/gi
inch2 = /\d(\s|)in[^\}\s][^\(]/gi
cm2 = /\d(\s|)(cm|centi)[^\}\s][^\(]/gi
dm2 = /\d(\s|)(dm|decim)[^\}\s][^\(]/gi
nm2 = /\d(\s|)(nm|nano)[^\}\s][^\(]/gi

//weights/mass
lb2 = /\d(\s|)(lb|pound)[^\}\s][^\(]/gi
ton2 = /\d(\s|)(ton)[^\}\s][^\(]/gi
mton2 = /\d(\s|)(metric ton)[^\}\s][^\(]/gi
gram2 = /\d(\s|)(g\s|gram|g\))[^\}\s][^\(]/gi

//area
sqin2 = /\d(\s|)(in<sup>2<\/sup>|squared inches)[^\}\s][^\(]/gi
sqft2 = /\d(\s|)(ft<sup>2<\/sup>|squared feet)[^\}\s][^\(]/gi
sqmt2 = /\d(\s|)(m<sup>2<\/sup>|squared meter)[^\}\s][^\(]/gi
sqkm2 = /\d(\s|)(km<sup>2<\/sup>|squared kilo)[^\}\s][^\(]/gi
sqcm2 = /\d(\s|)(cm<sup>2<\/sup>|squared centi)[^\}\s][^\(]/gi
sqmi2 = /\d(\s|)(mi<sup>2<\/sup>|squared mile)[^\}\s][^\(]/gi

//volume
cuin2 = /\d(\s|)(in<sup>3<\/sup>|cubic inch)[^\}\s][^\(]/gi
cuft2 = /\d(\s|)(ft<sup>3<\/sup>|cubic feet)[^\}\s][^\(]/gi
cumt2 = /\d(\s|)(m<sup>3<\/sup>|cubic meter)[^\}\s][^\(]/gi
cukm2 = /\d(\s|)(km<sup>3<\/sup>|cubic kilo)[^\}\s][^\(]/gi
cucm2 = /\d(\s|)(cm<sup>3<\/sup>|cubic centi)[^\}\s][^\(]/gi
cumi2 = /\d(\s|)(mi<sup>3<\/sup>|cubic mile)[^\}\s][^\(]/gi

if(km2.test(wpTxt) || mi2.test(wpTxt) || ft2.test(wpTxt) || yd2.test(wpTxt) || cm2.test(wpTxt) || nm2.test(wpTxt) || inch2.test(wpTxt) || dm2.test(wpTxt) || lb2.test(wpTxt) || ton2.test(wpTxt) || gram2.test(wpTxt) || mton2.test(wpTxt) || sqin2.test(wpTxt) || sqft2.test(wpTxt) || sqmt2.test(wpTxt) || sqkm2.test(wpTxt) || sqcm2.test(wpTxt) || sqmi2.test(wpTxt) || cuin2.test(wpTxt) || cuft2.test(wpTxt) || cumt2.test(wpTxt) || cukm2.test(wpTxt) || cucm2.test(wpTxt) || cumi2.test(wpTxt)){
outputText_PR+="\n{{subst:User:AndyZ/PR/convert}}"
}
*/

// --------------------
//looks for unlinked dates, NEEDS CLEANUP
// --------------------
jan2= /\sJanuary\s(\d)(\d|)\D/gi
feb2= /\sFebruary\s(\d)(\d|)\D/gi
mar2= /\sMarch\s(\d)(\d|)\D/gi
apr2= /\sApril\s(\d)(\d|)\D/gi
may2= /\sMay\s(\d)(\d|)\D/gi
jun2= /\sJune\s(\d)(\d|)\D/gi
jul2= /\sJuly\s(\d)(\d|)\D/gi
aug2= /\sAugust\s(\d)(\d|)\D/gi
sep2= /\sSeptember\s(\d)(\d|)\D/gi
oct2= /\sOctober\s(\d)(\d|)\D/gi
nov2= /\sNovember\s(\d)(\d|)\D/gi
dec2= /\sDecember\s(\d)(\d|)\D/gi
if(jan2.test(wpTxt) || feb2.test(wpTxt) || mar2.test(wpTxt) || apr2.test(wpTxt) || may2.test(wpTxt) || jun2.test(wpTxt) || jul2.test(wpTxt) || aug2.test(wpTxt) || sep2.test(wpTxt) || oct2.test(wpTxt) || nov2.test(wpTxt) || dec2.test(wpTxt)){
outputText_PR+="\n{{subst:User:AndyZ/PR/linkdate}}"
}

// --------------------
// date-th, could use cleanup
// --------------------
var dateth = new Array(); var check_th = false;
dateth[0] = /(january|february|march|april|may|june|july|august|september|october|november|december)\s\d(\d|)(th|st|nd|rd)/gi
dateth[1] = /\[\[(january|february|march|april|may|june|july|august|september|october|november|december)\s\d(\d|)\]\](th|st|nd|rd)/gi
dateth[2] = /(january|february|march|april|may|june|july|august|september|october|november|december)\s\d(\d|)<sup>(th|st|nd|rd)<\/sup>/gi
dateth[3] = /\[\[(january|february|march|april|may|june|july|august|september|october|november|december)\s\d(\d|)\]\]<sup>(th|st|nd|rd)<\/sup>/gi
dateth[4] = /\d(\d|)<sup>(th|st|nd|rd)<\/sup>\s(of\s|)(january|february|march|april|may|june|july|august|september|october|november|december)/gi
dateth[5] = /\d(\d|)(th|st|nd|rd)\s(january|february|march|april|may|june|july|august|september|october|november|december)/gi
		
for(i=0;i<dateth.length;i++){		//searches for above RegExps in document
	if(dateth[i].test(wpTxt)) check_th = true;
}

if(check_th)
	outputText_PR+="\n{{subst:User:AndyZ/PR/dateth}}";

// -------------------- --------------------
// checks for correct MOS heading styles ([[WP:MSH]])
// -------------------- --------------------

// --------------------
// occurence of "the" at beginning
// --------------------
if(wpTxt.indexOf("==The ")!= -1 || wpTxt.indexOf("== The ")!= -1) outputText_PR+="\n{{subst:User:AndyZ/PR/headingthe}}";

// --------------------
// existence of link in heading
// --------------------
regex_headlink = /==.{0,}\[\[.{1,}\]\].{0,}==/gi
if(regex_headlink.test(wpTxt))
	outputText_PR+="\n{{subst:User:AndyZ/PR/headinglink}}";

// --------------------
// checks if title is repeated in headings
// --------------------
wgT = wgTitle.replace(/\s\(.*\)/,"")								//remove parenthesis from title
var regex_headre = new RegExp("==.{0,}"+wgT+".{0,}==","gi")			//wgTitle is defined already as title of page
if(regex_headre.test(wpTxt))
	outputText_PR+="\n{{subst:User:AndyZ/PR/headingre}}";
	
// --------------------
// avoid special characters
// --------------------
regex_spchar = /==.{0,}([^\[]\[[^\[]|[^\]]\][^\]]|&|\+|\{|\}).{0,}==/gi;
if(regex_spchar.test(wpTxt))
	outputText_PR+="\n*Per [[Wikipedia:Manual of Style (headings)]], avoid using special characters (ex: &+{}[]) in headings.";

// --------------------
// looks at capitalization for guaranteed headings (see also, etc.)
// --------------------
regex_headcap = /==\s?(See\sAlso|External\sLinks?|Works?\sCited|Further\sReadings?|History\sOf\s.{2,}|.{2,}\sAnd\s.{2,})\s?==/g;
if(regex_headcap.test(wpTxt))
	outputText_PR+="\n*Per [[Wikipedia:Manual of Style (headings)]], avoid capitalizing words unless they are [[proper noun]]s or the first word of the heading.";

// --------------------
//checks for ==how to...==
// --------------------
if(/==\s?(how\sto\s.*)\s?==/i.test(wpTxt)) outputText_PR+="\n{{subst:User:AndyZ/PR/how}}";

// --------------------
//looks for ==trivia==, ==other facts==, ==miscellaneous==, etc.
// --------------------
var list_triv = new Array(/==(\s|)Trivia/gi,/==(\s|)Other\sf/gi,/==(\s|)Miscellaneous/gi,/==(\s|)Interesting\s/gi);
var check_triv = false;		//if true, found trivia section

for(i=0;i<list_triv.length;i++){if(list_triv[i].test(wpTxt)) check_triv = true;}	//for loop to ensure that each of the trivia
if(check_triv)																		//headings exist/don't exist
	outputText_PR+="\n{{subst:User:AndyZ/PR/trivia}}";

// --------------------
//double checks if last sections follow WP:GTL in terms of order (see also - references - external links)
// --------------------
isgtl = true 

var Refsection = new Array("==Reference","==Source","==Footnote","==Cit","==Note","== Reference","== Source","== Footnote","== Cit","== Note")		
		//array to hold different possible names of the "references" section

var extlink_s = new Array("External link","External Link");
var extlink;
for(i=0;i<extlink_s.length;i++){
	if(wpTxt.indexOf(extlink_s[i])!=-1) extlink = extlink_s[i];		
}

var seealso_s = new Array("==See also","== See also","==See Also","== See Also");	//names for see also section
var seealso;
for(i=0;i<seealso_s.length;i++){
	if(wpTxt.indexOf(seealso_s[i])!=-1) seealso = seealso_s[i];						//find section see also
}

	//searching for headings against [[WP:GTL]]
if((wpTxt.indexOf(seealso) > wpTxt.indexOf(extlink)) && seealso && extlink)
	isgtl = false
for(i=0;i<Refsection.length;i++){
	if(wpTxt.indexOf(seealso) > wpTxt.indexOf(Refsection[i]) && wpTxt.indexOf(Refsection[i])!=-1 && seealso)
		isgtl = false
	if(wpTxt.indexOf(extlink) < wpTxt.indexOf(Refsection[i]) && extlink)
		isgtl = false
}

if(isgtl==false)
	outputText_PR+="\n{{subst:User:AndyZ/PR/gtl}}"

// --------------------
//looks for section named "List of..."					//not in use due to inaccuracy
// --------------------	
/*
list = /==(\s|)List/gi
if(list.test(wpTxt))
	outputText_PR+="\n{{subst:User:AndyZ/PR/list}}"
*/

// --------------------	
//Checks if categories are in alphabetical order
// NEEDS FIXING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// --------------------	
self_alphabetic = [
    'aa','af','ak','als','am','ang','ab','ar','an','roa-rup','frp','as','ast','gn',
    'av','ay','az','bm','bn','zh-min-nan','map-bms','ba','be','bh','bi','bar','bo',
    'bs','br','bg','bxr','ca','cv','ceb','cs','ch','cbk-zam','ny','sn','tum','cho',
    'co','za','cy','da','pdc','de','dv','arc','nv','dz','mh','et','el','eml','en',
    'es','eo','eu','ee','fa','fo','fr','fy','ff','fur','ga','gv','gd','gl','ki',
    'glk','gu','got','zh-classical','xal','ko','ha','haw','hy','hi','ho','hsb','hr',
    'io','ig','ilo','bpy','id','ia','ie','iu','ik','os','xh','zu','is','it','he',
    'jv','kl','kn','kr','ka','ks','csb','kk','kw','rw','ky','rn','sw','kv','kg',
    'ht','kj','ku','lad','lbe','lo','la','lv','lb','lt','lij','li','ln','jbo','lg',
    'lmo','hu','mk','mg','ml','mt','mi','mr','mzn','ms','cdo','mo','mn','mus','my',
    'nah','na','fj','nl','nds-nl','cr','ne','new','ja','nap','ce','pih','no','nn',
    'nrm','nov','oc','or','om','ng','hz','ug','pa','pi','pam','pag','pap','ps','km',
    'pms','nds','pl','pt','ty','ksh','ro','rmy','rm','qu','ru','war','se','sm','sa',
    'sg','sc','sco','st','tn','sq','ru-sib','scn','si','simple','sd','ss','sk','cu',
    'sl','so','sr','sh','su','fi','sv','tl','ta','roa-tara','tt','te','tet','th',
    'vi','ti','tg','tpi','to','chr','chy','ve','tr','tk','tw','udm','bug','uk','ur',
    'uz','vec','vo','fiu-vro','wa','vls','wo','wuu','ts','ii','yi','yo','zh-yue',
    'diq','zea','bat-smg','zh','zh-tw','zh-cn']

cat1 = /\[\[Category:.{1,}\]\]/gi
alphed = true; alphed2 = true;				 //first for [[WP:CAT]]s, [[WP:IL]]s
if(cat1.test(wpTxt)){
	theCats = wpTxt.match(cat1)				 //array to hold categories
	for(i=0;i<theCats.length;i++)
		theCats[i]=theCats[i].toLowerCase(); //moves categories to lower case
	
	//compares all cats to see if in alphabetical order
	for(i=0;i<theCats.length-1;i++){	     //compares all of the categories
		if(!(theCats[i+1]>theCats[i]))
			alphed = false					 //if any categories out of order
	}										 //set variable to false
}
else{										
outputText_PR+="\n*This article does not have any [[WP:CAT|categories]]. Please categorize it with relevant <code><nowiki>[[Category:Categories]]</nowiki></code>."	 //if no categories
}
					
il1 = /\[\[(.{2}|als|ang|frp|ast|zh\-min\-nan|pdc|ilo|jbo|nah|nrm|nds|sco|scn|simple|tpi|chr|vec|zh\-yue|zh\-tw|zh\-cn|zh\-classical|cbk\-zam):.{1,}\]\]/gi		//interlanguage links with
										//more than 2 letters; please add more if anymore exist

if(il1.test(wpTxt)){
	theIL = wpTxt.match(il1)				 //array to hold ILs
	for(i=0;i<theIL.length-1;i++){
		if(theIL[i+1] <= theIL[i])			 //compares all categories
			alphed2 = false					
	}
	
	/*if(!alphed2){
		alphed3 = true;
		for(i=0;i<theIL.length;i++){
			if(!(theIL[i+1]>theIL[i]))	
				alphed3 = false;
		}
		
		if(alphed3) alphed2 = true;
	}*/
}
		//alphabetizing template (category template will only appear for those who desire it)
		//configurable variable: cat_PR (1/0)
if(!alphed && alphed2 && cat_PR)
	outputText_PR+="\n{{subst:User:AndyZ/PR/alpha|[[WP:CAT|categories]]}}"
if(!alphed2 && alphed && alpha_PR)
	outputText_PR+="\n{{subst:User:AndyZ/PR/alpha}}"
if(!alphed && !alphed2 && !cat_PR && alpha_PR)
	outputText_PR+="\n{{subst:User:AndyZ/PR/alpha}}"
if(!alphed && !alphed2 && cat_PR && !alpha_PR)
	outputText_PR+="\n{{subst:User:AndyZ/PR/alpha|[[WP:CAT|categories]]"+/*" and [[WP:IL|interlanguage links]]"*/+"}}"
if(!alphed && !alphed2 && cat_PR && alpha_PR)
	outputText_PR+="\n{{subst:User:AndyZ/PR/alpha|[[WP:CAT|categories]] and [[WP:IL|interlanguage links]]}}"
// --------------------	
//looks at length of article:
// --------------------	

// --------------------	
//summary style -ToC and entire article-
// --------------------	
theLength = wpTxt.length
newHeading = /\n==/g
if(newHeading.test(wpTxt)){
	theSections = wpTxt.match(/\n==/g)
if(theSections.length<=5)
	outputText_PR+="\n{{subst:User:AndyZ/PR/expand}}";
if(theSections.length>=24)
	outputText_PR+="\n{{subst:User:AndyZ/PR/toc}}";
if(theLength <= 7500 && theSections.length>5)
	outputText_PR+="\n{{subst:User:AndyZ/PR/expand}}";
}
else theSections = "none"

if(theLength<=7500 && theSections=="none")
	outputText_PR+="\n{{subst:User:AndyZ/PR/expand}}";

if(!/\{\{main/gi.test(wpTxt)){ if(theLength>=50000)
	outputText_PR+="\n{{subst:User:AndyZ/PR/SS}}";}
else if(wpTxt.match(/\{\{main/gi).length<=2 && theLength>=50000)
	outputText_PR+="\n{{subst:User:AndyZ/PR/SS}}";

// --------------------	
//looks for section-stub template
// --------------------	
//Template:sectstub, section stub, section-stub, sect-stub, stub-section
nosectstub = true;
var tempsectstub = new Array(/\{\{sectstub\}\}/gi,/\{\{sect-stub\}\}/gi,/\{\{section stub\}\}/gi,/\{\{section-stub\}\}/gi,/\{\{stub-section\}\}/gi);

for(s=0;s<tempsectstub.length;s++){
	if(tempsectstub[s].test(wpTxt)) nosectstub = false;
}

if(nosectstub==false)
	outputText_PR+="\n{{subst:User:AndyZ/PR/sectexpand}}";

//	
var wpTxt_noquotes = wpTxt.replace(/"(.+?)"/gi,"").replace(/\[\[.{4,50}?\|/gi,"")
// --------------------	
//looks for weasel words
// --------------------	

var ww = new Array(); var ww2 = new Array();
isww = false; awtstring = "";
ww[0] = "some people sa"
ww[1] = "it has been"
ww[2] = "many people have"
ww[3] = "many scientists believe"
ww[4] = "allege"
ww[5] = "many people sa"
ww[6] = "many people believe"
ww[7] = "arguably"
ww[8] = "it is claimed"
ww[9] = "correctly"
ww[10] = "apparently"
ww[11] = "people considered"
ww[12] = "many considered"
ww[13] = "is considered"
ww[14] = "are considered"

for(i=0;i<ww.length;i++) ww2[i] = new RegExp(ww[i],"gi")

Ref_regex = /(<ref|\{\{ref|\{\{fn|\{\{harv)/gi

wpTxtawt = wpTxt_noquotes; 	wwref = 350;	//wwref refers to the max. distance to search for a citation

for(i=0;i<ww.length;i++){
	while(ww2[i].test(wpTxtawt)){
		wpTxtawt = wpTxtawt.substring(wpTxtawt.indexOf(ww[i])+1,wpTxtawt.length);
		if(!(Ref_regex.test(wpTxtawt.substring(0,wwref)))){
			isww = true;
			if(awtstring.indexOf(ww[i]) == -1) awtstring=awtstring+"|''"+ww[i]+"''"
		}
	}
}

if(isww==true){
outputText_PR+="\n{{subst:User:AndyZ/PR/awt"+awtstring+"}} <!--This javascript cannot determine if a citation is provided; if all weasel terms are covered by citations, please strike this-->"
}

// --------------------
// American/British English spellings (ize/ise, ization/isation, or/our, er/re, etc)

var check_amer = 0, check_brit = 0;
var ab_ex = "";

AmSpell = new Array("flavor","honor","armor","behavior","harbor","neighbor","favorite","aluminum","mustache","tidbit","meter","fiber","saber","defense","offense","pretense","organize","recognize","realize","colonize","criticize","categorize","ization","analyze","catalyze","hydrolyze","paralyze","anemia","anesthesia","cesium","diarrhea","gynecology","hemophilia","leukemia","esophagus","estrogen","orthopedic","pediatric","counterattack","counselor","equaling","modeling","quarreled","signaling","traveled","enrollment","fulfillment","installment","skillful"," aging","routing","anymore","paycheck","cozy"," gray","jewelry","curb","licorice","mold","molt","pajamas","program ","skeptic","sulfur");
BrSpell = new Array("flavour","honour","armour","behaviour","harbour","neighbour","favourite","aluminium","moustache","titbit","metre","fibre","sabre","defence","offence","pretence","organise","recognise","realise","colonise","criticise","categorise","isation","analyse","catalyse","hydrolyse","paralyse","anaemia","anaesthesia","caesium","diarrhoea","gynaecology","haemophilia","leukaemia","oesophagus","oestrogen","orthopaedic","paediatric","counter-attack","counsellor","equalling","modelling","quarrelled","signalling","travelled","enrolment","fulfilment","instalment","skilful"," ageing","routeing","any more","pay cheque","cosy"," grey","jewellery","kerb","liquorice","mould","moult","pyjamas","programme","sceptic","sulphur");

for(i=0;i<AmSpell.length;i++){
	if(wpTxt_noquotes.indexOf(AmSpell[i]) != -1 && wgTitle.indexOf(AmSpell[i]) == -1){
		check_amer++;
		ab_ex += "''" + AmSpell[i] + "'' (A) (British: ''" + BrSpell[i] + "''), "; 	
	}
	if(wpTxt_noquotes.indexOf(BrSpell[i]) != -1 && wgTitle.indexOf(BrSpell[i]) == -1){
		check_brit++;
		ab_ex += "''" + BrSpell[i] + "'' (B) (American: ''" + AmSpell[i] + "''), ";	
	}
}

if(check_amer >= 2 && check_brit >= 2) outputText_PR+="\n*Please make the spelling of English words consistent with either [[American and British English spelling differences|American or British spelling]], depending upon the subject of the article. Examples include: " + ab_ex.substring(0,ab_ex.length-2) + ".";

// --------------------	
// spell check function - load [[Wikipedia:Lists of common misspellings/For machines]]
// --------------------	
if(!noXHR_PR && spellcheck_PR && wgTitle.indexOf("Peer review") == -1){
	wpajax.download({url:'http://en.wikipedia.org/w/index.php?title=Wikipedia:Lists_of_common_misspellings/For_machines&action=raw',
			onSuccess: spellCheckReview, OnFailure: spellCheckReview_fail, message: 'Wikipedia:Lists of common misspellings/For machines'});
}

// --------------------	
//checks for redundancies - based on [[User:Tony1/How_to_satisfy_Criterion_2a#Redundancy]]
//			--more should be added if possible
// --------------------	

redun1 = new Array()
redun1[0] = ""; redun1[1] = ""; redun1[2] = ""; redun1[3] = "";

additive = /(also|in\saddition|additionally|moreover|furthermore)/gi
if(additive.test(wpTxt_noquotes)){
	theaddnum = wpTxt.match(additive)
	if((theaddnum.length>=8)&&(theaddnum.length >= wpTxt.length/2000)) redun1[0] = "1"	
}

vaguesize = /(some\s|a\svariety\sof|a\snumber\sof|a\smajority\sof|several|a\sfew|\smany|\sany\s|\sall\s)/gi
if(vaguesize.test(wpTxt_noquotes)){
	thevsnum = wpTxt.match(vaguesize)
	if((thevsnum.length>=8)&&(thevsnum.length >= wpTxt.length/2000)) redun1[1] = "1"	
}

temporal = /(over\sthe\syears|currently|\snow\s|from\stime\sto\stime)/gi
if(temporal.test(wpTxt_noquotes)){
	thetempnum = wpTxt.match(temporal)
	if(thetempnum.length>=6 && thetempnum.length >= wpTxt.length/2500) redun1[2] = "1"	
}

intheyear = /(in\sthe\syear|in\sthe\syear\sof)\s(\[\[|)(\d\d\d\d)/gi
if(intheyear.test(wpTxt_noquotes)) redun1[3] = "1"; //exyear = RegExp.$3		

if((redun1[0]=="1") || (redun1[1]=="1") || (redun1[2]=="1") || (redun1[3]=="1")){
outputText_PR+="\n*Watch for [[User:Tony1/How_to_satisfy_Criterion_2a#Redundancy|redundancies]] that make the article too wordy instead of being crisp and concise. (You may wish to try Tony1's [[User:Tony1/How to satisfy Criterion 2a: redundancy exercises|redundancy exercises]].)"	
	
if(redun1[0]=="1")
	outputText_PR+="\n**While additive terms like “also”, “in addition”, “additionally”, “moreover”, and “furthermore” may sometimes be useful, overusing them when they aren't necessary can instead detract from the brilliancy of the article. This article has "+theaddnum.length+" additive terms, a bit too much."
	
if(redun1[1]=="1")
	outputText_PR+="\n**Vague terms of size often are unnecessary and redundant -  “some”, “a variety/number/majority of”, “several”, “a few”, “many”, “any”, and “all”. For example, “<font color='red'><s>All</s></font> pigs are pink, so we thought of <font color='red'><s>a number of</s></font> ways to turn them green.”"

if(redun1[2]=="1")
	outputText_PR+="\n**Temporal terms like “over the years”, “currently”, “now”, and “from time to time” often are too vague to be useful, but occasionally may be helpful. “I am <font color='red'><s>now</s></font> using a semi-bot to generate your peer review.”"

if(redun1[3]=="1")
	outputText_PR+="\n**“In <font color='red'><s>the year [of]</s></font> 1990”"
}

// --------------------	
//searches for footnotes
// --------------------	
var list_ref = new Array(/\<ref/gi,/\<ref/gi,/<ref/gi,/\{\{ref/gi,/\{\{fn/gi,/\{\{harv/gi,/\{\{Harv/gi);
var check_ref = 0;

if(list_ref[0].test(wpTxt) || list_ref[1].test(wpTxt)) check_ref=1;
else if(list_ref[2].test(wpTxt) || list_ref[3].test(wpTxt) || list_ref[4].test(wpTxt) || list_ref[5].test(wpTxt)) check_ref=2;
else check_ref=0

if(!check_ref)						// no footnotes
	outputText_PR+="\n{{subst:User:AndyZ/PR/foot}}"
else if(check_ref==2)				//a method outside of the cite.php
	outputText_PR+="\n*You may wish to convert your form of references to the cite.php footnote system that [[WP:WIAFA]] 2(c) highly recommends."


// --------------------	
//checks footnote spacing following a period
// --------------------	
var list_sref = new Array(/<\/ref>\./gi,/\.\s<ref>/gi,/\{\{ref\|.{1,}\}\}\./gi,/\.\s\{\{ref\|.{1,}\}\}/gi,/\.\s\{\{fn\|.{1,}\}\}/gi,/\{\{fn\|.{1,}\}\}\./gi);
var check_sref = false;

for(i=0;i<list_sref.length;i++){
	if(list_sref[i].test(wpTxt)){check_sref=true; break;}
}

if(check_sref)
	outputText_PR+="\n{{subst:User:AndyZ/PR/footspace}}"

// --------------------	
//searches for reference section
// --------------------	
var list_refsect = new Array(/==(\s|)Reference/gi,/==(\s|)Source/gi,/==(\s|)Footnote/gi,/==(\s|)Cit/gi,/==(\s|)Note/gi);
var check_refsect = false;		//if check_refsect == true, then a reference section exists

for(i=0;i<list_refsect.length;i++){
	if(list_refsect[i].test(wpTxt)){check_refsect = true; break;}
}

if(!check_refsect)
	outputText_PR+="\n{{subst:User:AndyZ/PR/ref}}"

// --------------------	
// looks for <nowiki>{{fact}} and {{citation needed}} </nowiki>	
// --------------------	
var list_fact = new Array(/\{\{fact\}\}/gi,/\{\{citation needed\}\}/gi);
var check_fact = false;

for(i=0;i<list_fact.length;i++){
	if(list_fact[i].test(wpTxt)){check_fact = true; break;}	
}

if(check_fact)
	outputText_PR+="\n*Please provide citations for all of the <code><nowiki>{{fact}}</nowiki></code>s.";

//all articles can always use copyediting:
outputText_PR+="\n{{subst:User:AndyZ/PR/copyedit}}"

//closing + signature
outputText_PR+=endMsg_PR;

document.getElementById(output_PR).value = outputText_PR;

// --------------------
// replacing template format with actual words; still in progress.
// replacing footnotes, still in progress
temp_mem = document.getElementById(output_PR).value;
if(wgUserName != "AZPR"){
	if(defaultView_PR == 0){
		replaceTemp();
		replaceFoot();
	}
	else if(defaultView_PR == 2) replaceTemp();
}
document.getElementById('instaview_button').style.width = 150;
document.theForm.switch_readonly.style.width = 150;
// --------------------	

//show feedback
document.getElementById("theFeedback").style.visibility = "visible";

if(select_PR)				//selects suggestions, for easy copy+pasting
	document.getElementById(output_PR).select();

//current date variables
    var current_date = new Date();
    var cur_month = current_date.getMonth();
    var cur_year = current_date.getFullYear();
    var y_abbrev = cur_year.toString().substring(2,4);
    var m_abbrev = new Array("J","F","M","A","MY","JN","JL","AU","S","O","N","D");
    var m_full = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

// --------------------	
//<nowiki> Messages on WP:PR 
// --------------------	

if((wgTitle.indexOf("Peer review") != -1 
 || wgTitle.indexOf("WikiProject Military history/Peer review/") != -1
 || wgTitle.indexOf("WikiProject Biography/Peer review/") != -1
 || wgTitle.indexOf("WikiProject Films/Peer review/") != -1)
 && wgTitle.indexOf("/Automated") == -1
 && document.editform.wpTextbox1.value.indexOf("User:AndyZ/peerreviewer") == -1){
document.editform.wpTextbox1.value += "\n*Please see [[User:AndyZ/peerreviewer|automated]] peer review suggestions [[Wikipedia:Peer review/Automated/"+m_full[cur_month]+" "+cur_year+"#"+ wgTitle.split("Peer review/")[1] +"|here]]. Thanks, ~~~~"

// Add a tag to the summary box - ''stolen'' from [[User:Bobblewik]] 
    var txt = document.editform.wpSummary;
    var summary = "Automated peer review at [[WP:PRA/"+m_abbrev[cur_month]+y_abbrev+"#"+wgTitle.split("Peer review/")[1]+"]]";
	if (txt.value.indexOf(summary) == -1) {
		if (txt.value.match(/[^\*\/\s][^\/\s]?\s*$/)) {
			txt.value += " | ";
		}
		txt.value += summary;
	}

thehide();
}

// --ending brace for first function
}
// --

// --------------------
// image licensing check functions:
// --------------------
// XMLHTTPrequest function by [[User:Zocky]], on [[WP:US]]

wpajax={
        download:function(bundle) {
                // mandatory: bundle.url
                // optional:  bundle.onSuccess (xmlhttprequest, bundle)
                // optional:  bundle.onFailure (xmlhttprequest, bundle)
                // optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
                
                var x = window.XMLHttpRequest ? new XMLHttpRequest()
                : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP")
                : false;
                
                if (x) {
                        x.onreadystatechange=function() {
                                x.readyState==4 && wpajax.downloadComplete(x,bundle);
                        };
                        x.open("GET",bundle.url,true);
                        x.send(null);
                }
                return x;
        },

        downloadComplete:function(x,bundle) {
                x.status==200 && ( bundle.onSuccess && bundle.onSuccess(x,bundle) || true )
                || ( bundle.onFailure && bundle.onFailure(x,bundle) || checkpage(x,bundle));
        }
};

// Example:
//wpajax.download({url:'http://en.wikipedia.org/w/index.php?title=Thresher&action=raw',
//                   onSuccess: dlComplete, message: "Here's what we got:\n\n" });

function wikiImg(xmlreq,data){
// Generally for images in Wikimedia Commons, still looking for method to fix	
	
//	wpajax.download({url:'http://en.wikpedia.org/wiki/'+imgName,
//					onSuccess: checkImgLicense, message: "htm," + imgName});	
//	alert("Error in loading " + data.message.substring(4,data.message.length) + "\n" + xmlreq.responseText);
}

function checkImgLicense(xmlreq, data) {
//   alert(data.message + xmlreq.responseText);
	 var imgTxt = xmlreq.responseText;
	 
	 imgData = data.message.split(",");
	 if(imgData.length > 2){
	       for(i=2;i<imgData.length;i++) imgData[1] += imgData[i];
	 }
	 
	 if(imgData[0] == "raw"){
		   imgNTtemplates = /\{\{(nolicense|nosource|no\ssource|no\slicense|nld|nsd|untagged)/gi
		 
	       if(imgTxt.indexOf("{{") == -1 || imgNTtemplates.test(imgTxt)){
	            imgNT = true; imgNTstr += "|" + imgData[1];
       	   }
	       
	       templFU = /\{\{.{0,}(Music sample|Speech|Sheet music|Albumcover|Boardgamecover|Book cover|Comiccover|DVDcover|Gamecover|Softwarecover|Magazinecover|Time|Newspapercover|Video tape cover|Logo|Computer hardware logo|Disneylogo|PreK12\-logo|Restaurant|Radiologo|Schoolboard\-logo|Scoutlogo|Sports\-logo|Hqfl logo|Olympics\-logo|Tv\-logo|Tv\-program\-logo|Univ\-logo|Symbol|Seal|Icon|Game\-icon|Wayfinding|Stamp|USPSstamp|Money|Promotional|DisneyAttractionPoster|Eventposter|Sportsposter|Movie poster|Political poster|Film\-screenshot|Machinima\-screenshot|Musicpromo\-screenshot|Tv\-screenshot|Video\-screenshot|Game\-screenshot|Cvg\-titlescreen|screen|photo|sign|cover|artwork|Digimonimage|DisneyCharacter|Pokeimage|Yugiohimage|Comicpanel|comicscene|Public Library images|Otto Perry image|Robert Richardson image|Parody|Smithsonian|Standard test|Fair use in|Fairusein\d|no\srationale|nrd|Replaceable\sfair\suse|refu|orfud|or\-fu\-re)/gi
		   FUrat = /(rationale|fair\suse)/gi
		   
		   if(templFU.test(imgTxt) && !FUrat.test(imgTxt)){
				imgFU = true; imgFUstr += "|" + imgData[1];
		   }
 	 }
 	 else if(imgData[0] == "htm"){
	 	 if(imgTxt.indexOf("Template:") == -1){
		 	alert(imgData[1] + "\n" + "\nNo licensing information (HTML check)");	 
	 	 }
 	 }
}

function checkpage(xmlreq, data){
	if(xmlreq.statusText != "Not Found")
		alert(xmlreq.statusText + "\n" + data.url);	
}

// --------------------
// END img license checking
// --------------------

// --------------------
// START spell check, based on [[Wikipedia:Lists of common misspellings/For machines]]
// --------------------

function spellCheckReview(xmlreq, data){
	var spell_string = "";
	list_wordpairs = xmlreq.responseText.substring(0,xmlreq.responseText.lastIndexOf("zebra")+5)	// remove category
	list_wordpairs = list_wordpairs.split("\n");			// find all pairs of mispellings + actual words
	var misspelled_words = new Array(); var spellchecked_words = new Array();
	for(i=0;i<list_wordpairs.length;i++){
		list_wordpairs[i] = list_wordpairs[i].substring(1,list_wordpairs[i].length);
																// remove spaces
		try{
			temp_spellarray = list_wordpairs[i].split("->");
			misspelled_words[i] = temp_spellarray[0];
			spellchecked_words[i] = temp_spellarray[1];
		}
		catch(e){
			misspelled_words[i] = list_wordpairs[i].substring(0,list_wordpairs[i].indexOf("->"));
			spellchecked_words[i] = list_wordpairs[i].substring(list_wordpairs[i].indexOf("->")+2,list_wordpairs[i].length);
		}
		
		if(document.getElementById(input_PR).value.indexOf(" " + misspelled_words[i] + " ") != -1){
			spell_string += "''" + misspelled_words[i] + "'' (" + spellchecked_words[i] + ")" + ",";
		}
	}
												
	if(spell_string.length > 2)		//if mispelled_list exists																		
		outputText_PR+="\n*Please check through the article for possible misspellings (see [[WP:SPELL]]). Examples of possible misspellings include: " + spell_string.substring(0,spell_string.length-1) + ".";
}

function spellCheckReview_fail(xmlreq,data){
	alert("Error: Unable to start spellcheck");
}

// --------------------
// END spell check
// --------------------

// --------------------	
// the following functions determine the 
// presentation of the suggestions (template/prose, w/(o) footnotes, popups, etc.)
// --------------------	

var temporprose = 0;     //if 0, convert to template, else, convert to prose
function determineReplace(){
     if(!temporprose) replaceProse();
     else replaceTemp();
     temporprose = !temporprose;
}

var footorremove = 0;      //if 0, add footnote, else remove them
function determineFoot(){
     if(!footorremove) replaceNoFoot();
     else replaceFoot();
     footorremove = !footorremove;
}

function replaceTemp(){			//replacing the textbox with the actual content of the templates, not just [[User:AndyZ/PR]] form
//temp_mem = document.getElementById(output_PR).value;
//<nowiki>format: 
//document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/}}","g"),"{{subst:User:AndyZ/PR/}}"); 
//</nowiki>

//all templates containing parser functions have been commented temporarily 

// --------------------	
//  replace templates (using ajax if allowed)
// --------------------	

/*
if(!noXHR_PR && !PRtemplateData){
	PRtemplateData = new Array();
	prtemp_regex = /\{\{subst:(User:AndyZ\/PR\/.*)\}\}/gi
	if(prtemp_regex.test(document.getElementById(output_PR))){
		var PRtemplates = document.getElementById(output_PR).value.match(prtemp_regex);	
		for(i=0;i<PRtemplates.length;i++){
			PRtemplates[i] = PRtemplates[i].replace(prtemp_regex,"$1");
			wpajax.download({url:'http://en.wikipedia.org/w/index.php?title=' + PRtemplates[i] + '&action=raw',
					 onSuccess: replacesubstInOutput, onFailure: errorInReplaceSubst, message: PRtemplates[i]});
			PRtemplateData[i] = PRtemplates[i] + ",,," + tempPRdata;
		}
	}	
}
else if(PRtemplateData){
	var PRtemplateName, PRtemplateContent;
	for(i=0;i<PRtemplateData.length;i++){
		PRtemplateName = PRtemplateData[i].split(',,,')[0];
		PRtemplateContent = PRtemplateData[i].split(',,,')[1];
		document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace("{{"+PRtemplateName+"}}",PRtemplateContent);
	}
}
else if(noXHR_PR){                     */

						////////////////////////////////////////////////////
						////////// NNEEEEDDSS CLEANUP !!!!
						////////////////////////////////////////////////////
						// convert to array

document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/lead}}","g"),"*Please expand the lead to conform with guidelines at [[Wikipedia:Lead]]. The article should have an appropriate number of paragraphs as is shown on [[WP:LEAD]], and should adequately summarize the article.");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/leadlong}}","g"),"*The lead of this article may be too long, or may contain too many paragraphs. Please follow guidelines at [[WP:LEAD]]; be aware that the lead should adequately summarize the article.");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/leaddetail}}","g"),"*The lead is for summarizing the rest of the article, and should not introduce new topics not discussed in the rest of the article, as per [[WP:LEAD]]. Please ensure that the lead adequately summarizes the article.");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/infobox}}","g"),"*There may be an applicable [[WP:INFOBOX|infobox]] for this article. For example, see [[Template:Infobox Biography]], [[Template:Infobox School]], or [[Template:Infobox City]].");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/contxt}}","g"),"*Per [[Wikipedia:Only make links that are relevant to the context|Wikipedia:Context]] and [[Wikipedia:Manual of Style (dates and numbers)|Wikipedia:Manual of Style (dates)]], months and days of the week generally should not be linked. Years, decades, and centuries can be linked if they provide [[WP:CONTEXT|context]] for the article.");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/linkdate}}","g"),"*Per [[Wikipedia:Only make links that are relevant to the context|Wikipedia:Context]] and [[Wikipedia:Build the web]], years with full dates should be linked; for example, link [[January 15]], [[2006]].<ref name='linkdate'>See footnote</ref>");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/dateth}}","g"),"*As per [[Wikipedia:Manual of Style (dates and numbers)|Wikipedia:Manual of Style (dates)]], dates shouldn't use <sup>th</sup>; for example, instead of using ''[[January 30|January 30<sup>th</sup>]] was a great day'', use ''[[January 30]] was a great day''."); 
//document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/time}}","g"),"*Per [[WP:MOS#Time|WP:MOS]], avoid using words/phrases that indicate time periods relative to the current day. {{#if:{{{1|}}}|For example, ''{{{1}}}''}}{{#if:{{{2|}}}|{{#if:{{{3|}}}| ,|&nbsp;and}} ''{{{2}}}''}}{{#if:{{{3|}}}|{{#if:{{{4|}}}|,|, and}} ''{{{3}}}''}}{{#if:{{{4|}}}|{{#if:{{{5|}}}|,|, and}} ''{{{4}}}''}}{{#if:{{{5|}}}|{{#if:{{{6|}}}|,|, and}} ''{{{5}}}''}}{{#if:{{{6|}}}|, and ''{{{6}}}''}} {{#if:{{{1|}}}|might be terms that should be replaced with specific dates/times.}}<ref name='time'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/nbsp}}","g"),"*Per [[Wikipedia:Manual of Style (dates and numbers)#Units of measurement|Wikipedia:Manual of Style (numbers)]], there should be a non-breaking space - <code>&amp;nbsp;</code> between a number and the unit of measurement. For example, instead of ''{{{1|18mm}}}'', use ''{{{2|18&nbsp;mm}}}'', which when you are editing the page, should look like: <tt>{{{3|18&amp;nbsp;mm}}}</tt>.<ref name='nbsp'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/spellnum}}","g"),"*Per [[Wikipedia:Manual of Style (dates and numbers)#Units of measurement|Wikipedia:Manual of Style (numbers)]], please spell out source units of measurements in text; for example, ''the Moon is 380,000 kilometres (240,000 mi) from Earth''.<ref name='spellnum'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/abbrev}}","g"),"*Per [[Wikipedia:Manual of Style (dates and numbers)#Units of measurement|Wikipedia:Manual of Style (numbers)]], when doing conversions, please use standard abbreviations: for example, miles -> mi, kilometers squared -> km<sup>2</sup>, and pounds -> lb."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/headingthe}}","g"),"*Per [[Wikipedia:Manual of Style (headings)]], headings generally do not start with the word 'The'. For example, ''<nowiki>==The Biography==</nowiki>'' would be changed to ''<nowiki>==Biography==</nowiki>''."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/headingre}}","g"),"*Per [[Wikipedia:Manual of Style (headings)]], headings generally should not repeat the title of the article. For example, if the article was [[Ferdinand Magellan]], instead of using the heading ''<nowiki>==Magellan's journey==</nowiki>'', use ''<nowiki>==Journey==</nowiki>''."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/headinglink}}","g"),"*As per [[Wikipedia:Manual of Style (headings)]], please do not [[WP:LINK|link]] words in headings."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/gtl}}","g"),"*Please reorder/rename the last few sections to follow guidelines at [[Wikipedia:Guide to layout]]."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/overlink}}","g"),"*Consider removing links that add little to the article or that have been repeated in close proximity to other links to the same article, as per [[Wikipedia:Manual of Style (links)]] and [[WP:CONTEXT]]."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/underlink}}","g"),"*Consider adding more [[WP:LINK|links]] to the article; per [[Wikipedia:Manual of Style (links)]] and [[Wikipedia:Build the web]], create links to relevant articles."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/footspace}}","g"),"*As done in [[WP:FOOTNOTE]], footnotes usually are located right after a punctuation mark (as recommended by the [[The Chicago Manual of Style|CMS]], but not mandatory), such that there is no space inbetween. For example, ''the sun is larger than the moon [2].'' is usually written as ''the sun is larger than the moon.[2]''"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/alpha}}","g"),"*Please alphabetize the [[WP:IL|interlanguage links]].<ref name='alpha'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/alpha|[[WP:CAT|categories]]}}","g"),"*Please alphabetize the [[WP:CAT|categories]].<ref name='alpha'>See footnote</ref>");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/alpha|[[WP:CAT|categories]] and [[WP:IL|interlanguage links]]}}","g"),"*Please alphabetize the [[WP:CAT|categories]] and [[WP:IL|interlanguage links]].<ref name='alpha'>See footnote</ref>");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/ref}}","g"),"*The article will need references. See [[WP:CITE]] and [[WP:V]] for more information."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/foot}}","g"),"*This article needs [[WP:FOOTNOTE|footnotes]], preferably in the [http://meta.wikimedia.org/wiki/Cite/Cite.php cite.php] format recommended by [[WP:WIAFA]]. Simply, enclose inline citations, with [[WP:CITE]] or [[WP:CITE/ES]] information, with <nowiki><ref>THE FOOTNOTE</ref></nowiki>. At the bottom of the article, in a section named “References” or “Footnotes”, add <code><nowiki><div class=\"references-small\"><references/></div></nowiki></code>.<ref name='foot'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/noimg}}","g"),"*This article has no [[WP:IMAGE|images]]. Please see if there are any [[WP:IT|free use]] images that fall under the [[Wikipedia:Image use policy]] and fit under one of the [[Wikipedia:Image copyright tags]] that can be uploaded. To upload images on Wikipedia, go to [[Special:Upload]]; to upload non-[[WP:FU|fair use]] images on the [[Wikimedia Commons]], go to [[commons:special:upload]].<ref name='noimg'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/leadimg}}","g"),"*See if possible if there is a [[WP:IT|free use]] image that can go on the top right corner of this article.<ref name='leadimg'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/caption}}","g"),"*Per [[Wikipedia:What is a featured article?]], [[WP:IMAGE|Images]] should have concise captions.<ref name='caption'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/toc}}","g"),"*Per [[WP:WIAFA]], this article's table of contents (ToC) may be too long- consider shrinking it down by merging short sections or using a proper system of daughter pages as per [[Wikipedia:Summary style]].<ref name='toc'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/expand}}","g"),"*This article is a bit too short, and therefore may not be as comprehensive as [[WP:WIAFA]] critera 1(b) is looking for. Please see if anything can be expanded upon."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/SS}}","g"),"*This article may need to undergo [[WP:SS|summary style]], where a series of appropriate subpages are used. For example, if the article is [[United States]], than an appropriate subpage would be [[History of the United States]], such that a summary of the subpage exists on the mother article, while the subpage goes into more detail."); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/copyedit}}","g"),"*Please ensure that the article has gone through a thorough copyediting so that it exemplifies some of [[WP:WIAFA|Wikipedia's best work]]. See also [[User:Tony1/How to satisfy Criterion 1a]].<ref name='copyedit'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/list}}","g"),"*This article may be a bit list-weighty; in other words, some of the lists should be converted to prose (paragraph form).<ref name='list'>See footnote</ref>"); 
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/trivia}}","g"),"*Generally, trivia sections are looked down upon; please either remove the trivia section or incorporate any important facts into the rest of the article.");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/persondata}}","g"),"*If this article is about a person, please add <code><nowiki>{{persondata}}</nowiki></code> along with the required parameters to the article - see [[Wikipedia:Persondata]] for more information.");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/how}}","g"),"*Please avoid including instruction manuals, tutorials, etc. or other 'how-to's per [[WP:NOT#Wikipedia is not an indiscriminate collection of information|WP:NOT]].");
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(new RegExp("{{sub"+"st:User:AndyZ/PR/ig}}","g"),"*Avoid including [[WP:IG|galleries]] in articles, as per [[Wikipedia:Galleries#Policy|Wikipedia:Galleries]]. Common solutions to this problem include moving the gallery to a separate page, like [[Gallery of "+wgTitle+"]].");

if(/\{\{subst:User:AndyZ\/PR\/.*\}\}/i.test(document.getElementById(output_PR).value)){
	replaceTemplatesWithParams();	
}

//}

//for footnote showing/hiding function:
foot_mem = document.getElementById(output_PR).value;

// change the button's value
document.theForm.switch_temp.value = "Template form";
document.theForm.switch_temp.style.width = 150;
}

function replaceTemplatesWithParams(){
output_txt = document.getElementById(output_PR).value;
list_utemps = output_txt.match(/\{\{subst:User:AndyZ\/PR\/(.*)\}\}/gi);
var list_params = new Array();
for(i=0;i<list_utemps.length;i++){
	list_utemps[i] = list_utemps[i].substring(22,list_utemps[i].length-2);
	list_params = list_utemps[i].split("|");
	if(list_params.length == 1) continue;
	uTN_PR = list_params[0];
	
	list_paramsStr = "";
	for(j=1;j<list_params.length;j++){
		if(j==list_params.length-1) list_paramsStr += list_params[j];
		else list_paramsStr += list_params[j] + ",,";	
	}
		
		//if statements
	if(uTN_PR == "time"){
		document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(/\{\{subst:User:AndyZ\/PR\/time.*\}\}/gi,"*Per [[WP:MOS#Time|WP:MOS]], avoid using words/phrases that indicate time periods relative to the current day. For example, ''" + list_paramsStr.replace(/\,\,/g,"'', ''") + "'' might be terms that should be replaced with specific dates/times.<ref name='time'>See footnote</ref>");
	}
	if(uTN_PR == "awt"){
		document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(/\{\{subst:User:AndyZ\/PR\/awt.*\}\}/gi,"*There are a few occurrences of [[weasel word]]s in this article- please observe [[WP:AWT]]. Certain phrases should specify exactly who supports, considers, believes, etc., such a view.\n**" + list_paramsStr.replace(/\,\,/g,"\n**") + "\n**might be weasel words, and should be provided with proper [[WP:FOOTNOTE|citations]] (if they already do, or are not weasel terms, please <strike>strike</strike> this comment).<ref name='awt'>See footnote</ref>");
	}
	if(uTN_PR == "nbsp"){
		document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(/\{\{subst:User:AndyZ\/PR\/nbsp.*\}\}/gi,"*Per [[Wikipedia:Manual of Style (dates and numbers)#Units of measurement|Wikipedia:Manual of Style (numbers)]], there should be a non-breaking space - <code>&amp;nbsp;</code> between a number and the unit of measurement. For example, instead of ''"+list_params[1]+"'', use ''"+list_params[2]+"'', which when you are editing the page, should look like: <tt>"+list_params[3]+"</tt>.<ref name='nbsp'>See footnote</ref>");
	}
	/*if(uTN_PR == "imgfu"){
		document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(/\{\{subst:User:AndyZ\/PR\/imgfu.*\}\}/gi,"*Images with [[fair use]] tags need [[WP:FU|fair use rationales]] - please see [[WP:FUC]]. Specifically, [[:" + list_paramsStr.replace(/\,\,/gi,"]], [[:") + "]] need(s) proper fair use rationales.");
	}
	if(uTN_PR == "imgtag"){
		document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(/\{\{subst:User:AndyZ\/PR\/imgtag.*\}\}/gi,"*Images need proper [[WP:IMAGE|image]] [[WP:IT|copyright tags]] and source information. Specifically, [[:" + list_paramsStr.replace(/\,\,/gi,"]], [[:") + "]] need(s) proper image copyright tags.");
	}*/
}	
}

function replaceProse(){
document.getElementById(output_PR).value = temp_mem;
document.theForm.switch_temp.value = "Prose form";
document.theForm.switch_temp.style.width = 150;
}

function replaceSubstInOutput(xmlreq,data){
	document.getElementById(output_PR).replace("{{subst:" + data.message + "}}",xmlreq.responseText.replace(/<noinclude>.*<\/noinclude>/gi,"").replace(/<(\/|)includeonly>/gi,""));
	tempPRdata = xmlreq.responseText;
}
	
function errorInReplaceSubst(xmlreq,data){
	alert("Error: Unable to locate information at " + data.message);	
}

function replaceFoot(){					// removes the footnotes
//temp_mem = document.getElementById(output_PR).value;	
//<nowiki>
document.getElementById(output_PR).value = document.getElementById(output_PR).value.replace(/<ref name='(\w{1,})'>See footnote<\/ref>/gi,"").replace(/<sup>\[\[User:AndyZ\/PRnotes#_note-(.{1,})\|(.{1,})\]\]<\/sup>/gi,"");
////																																										
// use link to WP:PR/A's footnotes: "<sup>[[User:AndyZ/PRnotes#_note-$1|$1]]</sup>"
////
//</nowiki>
document.theForm.switch_foot.value = "Show footnotes";
document.theForm.switch_foot.style.width = 150;
}

function replaceNoFoot(){				// shows the footnotes
if(wgUserName != "AZPR" || directRef_PR)				// will make into a configurable option
	document.getElementById(output_PR).value = foot_mem.replace(/<ref name='(\w{1,})'>See footnote<\/ref>/gi,"<sup>[[User:AndyZ/PRnotes#_note-$1|$1]]</sup>");
else 
	document.getElementById(output_PR).value = foot_mem;
document.theForm.switch_foot.value = "Remove footnotes";
document.theForm.switch_foot.style.width = 150;
}

function determineReadonly(){		//readonly, to prevent accidental editing of the text
	if(document.getElementById(output_PR).readOnly) {
		document.getElementById(output_PR).readOnly = false; 	
		document.theForm.switch_readonly.value = "Readonly";		//button properties 
		document.theForm.switch_readonly.style.width = 150;
	}
	else {
		document.getElementById(output_PR).readOnly = true; 
		document.theForm.switch_readonly.value = "Edit-able";		//button properties 
		document.theForm.switch_readonly.style.width = 150;
	}
}

function popreview(){
	PRresult = "<script type='text/javascript' src='http://en.wikipedia.org/w/index.php?title=User:AndyZ/peerreviewer.js&action=raw&ctype=text/javascript&dontcountme=s'>wgUserName = \"" + wgUserName + "\"; temp_mem = \"" + temp_mem + "\";</script>Return to <a href='http://en.wikipedia.org/wiki/" + wgPageName + "'>" + wgTitle + "</a> (<a href='http://en.wikipedia.org/w/index.php?title="+wgPageName+"&action=edit'>edit</a> | <a href='http://en.wikipedia.org/w/index.php?title="+wgPageName+"&action=history'>history</a>) <br><br><form name='theForm'><!--<input type='button' value='Template form' name='switch_temp' onclick='determineReplace();' style='width:150'> <input type='button' value='Add footnotes' name='switch_foot' onclick='determineFoot();' style='width:150'> --><input type='button' value='Readonly' name='switch_readonly' onclick='determineReadonly()' style='width:150'><br><textarea id='theResponse' name='theResponse' cols='120' rows='50'>" + document.getElementById(output_PR).value + "</textarea></form>";
	var newPage_PR = window.open("http://en.wikipedia.org/","winName");
	newPage_PR.document.write(PRresult)
	newPage_PR.document.close()
}

// --------------------	
// show and hide results 
// --------------------	

function thehide(){
	document.getElementById("theFeedback").style.visibility = "hidden"
	document.getElementById("restore").style.visibility = "visible"
}

function theshow(){
	document.getElementById("theFeedback").style.visibility = "visible"
	document.getElementById("restore").style.visibility = "hidden"
}

/* not in use now
// --------------------
// dragging PR box around
// --------------------

var IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false

if(wgNamespaceNumber == 0 || allSpaces_PR){	
	if(!IE) document.captureEvents(Event.MOUSEMOVE)
	document.onmousemove = getMouseXY;
}

var posX, posY, elemPosX, elemPosY, difX, difY, cur_drag = false, theSpotX = 0, theSpotY = 0;

function getMouseXY(e){
	if(IE){
		posX = event.clientX + document.body.scrollLeft;
		posY = event.clientY + document.body.scrollTop;
	}
	else {
		posX = e.pageX;
		posY = e.pageY;
	}
	return true;
}

function getObjectXY(theElement){
	try{
	elemPosX = 40;
	}
	catch(e){
		alert("X - error");	
	}
	
	try{
		elemPosY = 150;
	}
	catch(e){
		alert("Y - error");	
	}
	
	try{
	theElement = document.getElementsByTagName("HTML")[0];
	}
	catch(e){
		alert("Error2");	
	}

	while(theElement != null){	
		elemPosX += theElement.offsetLeft; elemPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
}

function StartDrag(elem){
	getObjectXY(elem);
	difX = elemPosX - posX; difY = elemPosY - posY;
	cur_drag = setInterval("DragIt(" + elem.id + ")",1);
}

function DragIt(elem){				//new position of element
	elem.style.left = posX + difX; elem.style.top = posY + difY;		
}

function CancelDrag(){				//stop the dragging 
	if(cur_drag) window.clearInterval(cur_drag);
}
*/

// --------------------	
// not in usage: allows user to move results to a different page
// fails to work (unable to access popup?)
// --------------------	

//ideally the following function can be replaced by a menu
function addToPage(){
	replaceProse();	
	var faketarget;	//<nowiki>
	results_PR = document.getElementById(output_PR).value;
	results_PR = results_PR.match(/\{\{subst:User:AndyZ\/PR\/(.*)\}\}/gi);
	for(i=0;i<results_PR.length;i++) results_PR[i] = results_PR[i].replace(/\{\{subst:User:AndyZ\/PR\/(.*)\}\}/gi,"$1");
								//</nowiki>
	
	var newPageName;
	var moveToPrompt = prompt("Move PR to: 1 - talk page  2 - article's peer review page  3 - personal sandbox  0 - Auto-PR page\tOr enter pagename","Enter the destination page name or a menu option")
	
	if(moveToPrompt.length == 1){ 
		faketarget = moveToPrompt + "," + wgTitle + "," + results_PR.join(",");
		fakeaction = "movePR";
	}
	else if(moveToPrompt.length > 1){
		faketarget = "9," + wgTitle + "," + results_PR.join(",");
	}
	
	if(moveToPrompt == "0"){		//add it to WP:PRA/?0?
		var cur_d = new Date(); var cur_yr = d.getFullYear(); var cur_m = d.getMonth();			//date elements
		newPageName = "Wikipedia:Peer_review/Automated/" + cur_m + "_" + cur_yr + "&section=2&fakeaction=movePR&faketarget="+faketarget;			
	}
	else if(moveToPrompt == "1")
		newPageName = "Talk:" + wgPageName +"&section=new&fakeaction=movePR&faketarget="+faketarget;
	else if(moveToPrompt == "2")
		newPageName = "Wikipedia:Peer review/" + wgPageName + "&fakeaction=movePR&faketarget="+faketarget;
	else if(moveToPrompt == "3")
		newPageName = userSandbox_PR + "&fakeaction=movePR&faketarget="+faketarget;	
	else if(moveToPrompt == null || moveToPrompt == "" || moveToPrompt == " " || moveToPrompt == "Enter the destination page name or a menu option") return;
	else
		newPageName = moveToPrompt + "&fakeaction=movePR&faketarget=" + faketarget;
	
	var newPage = window.open("http://en.wikipedia.org/w/index.php?title="+newPageName+"&action=edit")
	
		//do stuff on new pages
		/*
	if(moveToPrompt == "0"){
		newPage.document.getElementById('wpTextbox1').value = document.getElementById(input_PR).value + newPage.document.getElementById('wpTextbox1').value;
		newPage.document.editform.wpSummary.value += " [["+wgTitle+"]]" 	
	}
	else if(moveToPrompt == "1"){
		newPage.document.getElementById('wpTextbox1').value = document.getElementById(input_PR).value.replace(/===.*===/gi,"");
		newPage.document.editform.wpSummary.value = "JavaScript peer review suggestions";
	}
	else if(moveToPrompt == "2"){
		newPage.document.getElementById('wpTextbox1').value += document.getElementById(input_PR).value.replace(/===.*===/gi,"===JavaScript suggestions===");
		newPage.document.editform.wpSummary.value = "JavaScript peer review suggestions";
	}
	else if(moveToPrompt == "3"){
		newPage.document.getElementById('wpTextbox1').value += document.getElementById(input_PR).value;
		newPage.document.editform.wpSummary.value = "JavaScript peer review suggestions";		
	}
	else{
		if(wgNamespaceNumber!=0){
			newPage.document.getElementById('wpTextbox1').value += document.getElementById(input_PR).value;
			newPage.document.editform.wpSummary.value = "JavaScript peer review suggestions";
		}
		else alert("These suggestions should not be on an article page; please move them to a discussion page.");
	}	*/
}

function toReview1(){
	if(document.title.indexOf("Editing ") == 0) review1();
	else window.open('http://en.wikipedia.org/w/index.php?title='+wgPageName+'&action=edit&fakeaction=displayPR','Edit');	
}

// --------------------	
// these functions auto-submit articles for WP:PR, modified from AutoVFD script 
// --------------------	

function pr()
{
  var pagename = document.editform.action.substring(pagename.indexOf('title=') + 6,pagename.lastIndexOf('&action=submit'));

  window.open('http://en.wikipedia.org/w/index.php?title=Talk:' + unescape(pagename) + '&action=edit&fakeaction=prtemp','Talk', 'status,toolbar,location,menubar,directories,resizeable,scrollbars');          
  window.open('/w/index.php?title=Wikipedia:Peer_review/' + unescape(pagename) + '&action=edit&fakeaction=prsub&faketarget=' + unescape(pagename),'PRnom', 'status,toolbar,location,menubar,directories,resizeable,scrollbars');
  window.open('/w/index.php?title=Wikipedia:Peer_review&action=edit&fakeaction=prlist&faketarget=' + unescape(pagename), 'PRlisting', 'status,toolbar,location,menubar,directories,resizeable,scrollbars');
}

function autopr()
{
  if (document.title.indexOf('Editing ') == 0)
    {
      var theaction = '';
      var target = '';
      if (location.search)
        {
          var l = location.search.substring(1).split('&');
          for (var i = 0; i < l.length; ++i)
            {
              var eq = l[i].indexOf('=');
              var name = l[i].substring(0, eq);
              if (name == 'fakeaction')
                theaction = l[i].substring(eq + 1);
              else if (name == 'faketarget')
                target = unescape(l[i].substring(eq + 1)).replace(/_/g, ' ');
            }
        }
      if (theaction == 'prlist')
        {
          req = document.editform.wpTextbox1.value.indexOf("{{Wikipedia:Peer review/");
          document.editform.wpTextbox1.value = document.editform.wpTextbox1.value.substring(0,req) + '{{Wikipedia:Peer review/' + target + '}}\n' + document.editform.wpTextbox1.value.substring(req,document.editform.wpTextbox1.value.length);
          document.editform.wpSummary.value = '[[Wikipedia:Peer review/' + target + ']]';
        }
      else if (theaction == 'prsub'){
          if (document.editform.wpTextbox1.value.length > 0)
              window.alert("There's an old peer review at the default location already.\n\n" +
                           'Please either move it out of the way (and update existing links to it), or file the PR by hand in another location (such as [[Wikipedia:Peer review/' + wgTitle.split("/")[1] + ' 2]]).');
          else
            document.editform.wpTextbox1.value += '===[[' + target + ']]===\n' +
              '<!--Reason for nomination.--> ~~' + '~~';
      }
      else if (theaction == 'prtemp'){
          if (document.editform.wpTextbox1.value.indexOf('{{peerreview}}') != -1)     
              window.alert("There has already been a peer review.");
          else{
              document.editform.wpTextbox1.value = '{{peerreview}}\n\n' + document.editform.wpTextbox1.value;
              document.editform.wpSummary.value = 'peer reviewing - [[Wikipedia:Peer review/' + target + ']]';
            }
        }
      else if (theaction == 'displayPR')
	    	    review1();
	  else if (theaction == 'movePR'){
			/*list_PR = target.split(",");
			if(list_PR[0] == 0){
				cur_txt = document.getElementById('wpTextbox1').value;
				document.getElementById('wpTextbox1').value = "===[[" + list_PR[1] + "]]===\n" + initMsg_PR + "\n";
				for(i=2;i<list_PR.length;i++)	//<nowiki>
					document.getElementById('wpTextbox1').value += "{{subst:User:AndyZ/PR/"+list_PR[i]+"}}\n"	
					//</nowiki>
				document.getElementById('wpTextbox1').value += document.getElementById(output_PR).value+=endMsg_PR;
				document.getElementById('wpTextbox1').value += cur_txt;
				document.getElementById('wpSummary').value += "+ [["+list_PR[1]+"]]"
			}	  
			else if(list_PR[0] == 1){
				document.getElementById('wpTextbox1').value = "===[[" + list_PR[1] + "]]===\n" + initMsg_PR + "\n";
				for(i=2;i<list_PR.length;i++)	//<nowiki>
					document.getElementById('wpTextbox1').value += "{{subst:User:AndyZ/PR/"+list_PR[i]+"}}\n"	
					//</nowiki>
				document.getElementById('wpTextbox1').value +=endMsg_PR;
				document.getElementById('wpSummary').value = "JavaScript peer review suggestions"
			}
			else if(list_PR[0] == 2){
				document.getElementById('wpTextbox1').value += "\n\n===[[" + list_PR[1] + "]]===\n" + initMsg_PR + "\n";
				for(i=2;i<list_PR.length;i++)	//<nowiki>
					document.getElementById('wpTextbox1').value += "{{subst:User:AndyZ/PR/"+list_PR[i]+"}}\n"	
					//</nowiki>
				document.getElementById('wpTextbox1').value +=endMsg_PR;
				document.getElementById('wpSummary').value += "JavaScript-generated suggestions"
			}
			else if(list_PR[0] == 3){
				document.getElementById('wpTextbox1').value += "\n\n===[[" + list_PR[1] + "]]===\n" + initMsg_PR + "\n";
				for(i=2;i<list_PR.length;i++)	//<nowiki>
					document.getElementById('wpTextbox1').value += "{{subst:User:AndyZ/PR/"+list_PR[i]+"}}\n"	
					//</nowiki>
				document.getElementById('wpTextbox1').value += endMsg_PR;
				document.getElementById('wpSummary').value += "JavaScript-generated suggestions for [[" + list_PR[1] + "]]";
			}
			else if(list_PR[0] == 9){
				if(wgNamespaceNumber == 0) alert("Please do not add these comments to an article; move them instead to a discussion page");
				else {
					document.getElementById('wpTextbox1').value += "\n\n===[[" + list_PR[1] + "]]===\n" + initMsg_PR + "\n";
					for(i=2;i<list_PR.length;i++)	//<nowiki>
						document.getElementById('wpTextbox1').value += "{{subst:User:AndyZ/PR/"+list_PR[i]+"}}\n"	
						//</nowiki>
					document.getElementById('wpTextbox1').value += endMsg_PR;
					document.getElementById('wpSummary').value += "JavaScript-generated suggestions for [[" + list_PR[1] + "]]";
				}	
			}*/
		  
	  }
      else
        pr();
    }
}

if(sendTo_PR){
	addOnloadHook(function () {
	    if(document.forms.editform) {
	        addLink('p-cactions', 'javascript:autopr()', 'send to WP:PR', 'ca-peerreview', 'Submits article for peer review', '', '');
	    }
	});
}

if(document.location.href.indexOf("fakeaction") != -1)
	addOnloadHook(autopr);

//</pre> end

// -- <pre> Specific to: User:AZPR (this simplifies the process of maintaining [[WP:PR/A]] - 
// to use this, inquire on [[User talk:AndyZ/peerreviewer.js]])
var mem;

if(wgUserName == "AZPR" || maintain_PR){
	if((document.location.href.indexOf("http://en.wikipedia.org/w/index.php?title=Wikipedia:Peer_review/")!=-1) && (document.location.href.indexOf("section=1")!=-1) && (document.location.href.indexOf("Automated")==-1)){
		addOnloadHook(function () {
		    mem = document.getElementById("wpTextbox1").value;
		    review1();
		    if(mem != document.getElementById("wpTextbox1").value) document.getElementById('wpSave').click();
		});
	}

	if(wgPageName.indexOf("Wikipedia:Peer_review/Automated/") != -1 && document.title.indexOf("Editing ") == 0){
		addOnloadHook(function () {
		    document.getElementById('wpSummary').value += "new automated PR requests"
		});
	}
	
	if((document.location.href.indexOf("action=edit")!=-1) && (wgNamespaceNumber == 0)){
		addOnloadHook(review1);
	}
}

//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// END PEER REVIEWING SCRIPT                        //
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////

var instaPRMode = false;	//0, not shown; 1, shown 
function instaPreview(){
	if(!instaPRMode){
		InstaViewPR.dump(output_PR, 'InstaViewResponse');
		document.getElementById('instaview_button').style.width = 150;
		document.getElementById('instaview_button').value = "Hide instaview";
		document.getElementById('InstaViewResponse').style.visibility = "visible";
		document.getElementById('InstaViewResponse').style.background = "white";
		document.getElementById('InstaViewResponse').style.border = "2px solid orange";
		document.getElementById('theFeedback').style.width = width4_PR+"px"
	}
	else{
		document.getElementById('instaview_button').style.width = 150;
		document.getElementById('instaview_button').value = "Instaview";
		document.getElementById('InstaViewResponse').innerHTML = "";
		document.getElementById('InstaViewResponse').style.visibility = "hidden";
	}
	
	instaPRMode = !instaPRMode;
}

if(showInstaview_PR){
	addOnloadHook(function(){
	  if (document.getElementById('editpage-copywarn')) {
	    var oldPreview = document.getElementById('wpPreview');
	    var newPreview = document.createElement('input');
	    newPreview.setAttribute('type', 'button');
	    newPreview.setAttribute('style', 'font-style: italic');
	    newPreview.setAttribute('value', 'InstaView');
	    newPreview.setAttribute('onclick', "InstaViewPR.dump('wpTextbox1', 'InstaViewDump')");
	    oldPreview.parentNode.insertBefore(newPreview, oldPreview);
	    oldPreview.parentNode.innerHTML += '<div style="margin: 5px 0 5px 0; padding: 5px; border: 2px solid orange;" id="InstaViewDump"></div>';
	    oldPreview.value = 'Classic Preview';
	    }
	});
}

// STARTFILE: livepreview.js

var InstaViewPR = {}

// options
InstaViewPR.conf =
{
	user: {},
	
	wiki: {
		lang: 'en',
		interwiki: 'ab|aa|af|ak|sq|als|am|ang|ar|an|arc|hy|roa-rup|as|ast|av|ay|az|bm|ba|eu|be|bn|bh|bi|bs|br|bg|my|ca|ch|ce|chr|chy|ny|zh|zh-tw|zh-cn|cho|cv|kw|co|cr|hr|cs|da|dv|nl|dz|en|eo|et|ee|fo|fj|fi|fr|fy|ff|gl|ka|de|got|el|kl|gn|gu|ht|ha|haw|he|hz|hi|ho|hu|is|io|ig|id|ia|ie|iu|ik|ga|it|ja|jv|kn|kr|csb|ks|kk|km|ki|rw|rn|tlh|kv|kg|ko|kj|ku|ky|lo|la|lv|li|ln|lt|jbo|nds|lg|lb|mk|mg|ms|ml|mt|gv|mi|minnan|mr|mh|zh-min-nan|mo|mn|mus|nah|na|nv|ne|se|no|nn|oc|or|om|pi|fa|pl|pt|pa|ps|qu|ro|rm|ru|sm|sg|sa|sc|gd|sr|sh|st|tn|sn|scn|simple|sd|si|sk|sl|so|st|es|su|sw|ss|sv|tl|ty|tg|ta|tt|te|th|bo|ti|tpi|to|tokipona|ts|tum|tr|tk|tw|uk|ur|ug|uz|ve|vi|vo|wa|cy|wo|xh|ii|yi|yo|za|zu',
		default_thumb_width: 180
	},
	
	paths: {
		articles: '/wiki/',
		math: '/math/',
		images: '',
		images_fallback: 'http://upload.wikimedia.org/wikipedia/commons/',
		magnify_icon: 'skins/common/images/magnify-clip.png'
	},
	
	locale: {
		user: 'User',
		image: 'Image',
		category: 'Category',
		months: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
	}
}

// options with default values or backreferences
with (InstaViewPR.conf) {
	user.name = user.name || wgUserName || 'Wikipedian'
	user.signature = '[['+locale.user+':'+user.name+'|'+user.name+']]'
	paths.images = 'http://upload.wikimedia.org/wikipedia/' + wiki.lang + '/'
}

// define constants
InstaViewPR.BLOCK_IMAGE = new RegExp('^\\[\\['+InstaViewPR.conf.locale.image+':.*?\\|.*?(?:frame|thumbnail|thumb|none|right|left|center)', 'i');

InstaViewPR.dump = function(from, to)
{
	if (typeof from == 'string') from = document.getElementById(from)
	if (typeof to == 'string') to = document.getElementById(to)
	to.innerHTML = this.convert(from.value)
}

InstaViewPR.convert = function(wiki)
{
	var 	ll = (typeof wiki == 'string')? wiki.replace(/\r/g,'').split(/\n/): wiki, // lines of wikicode
		o='',	// output
		p=0,	// para flag
		$r	// result of passing a regexp to $()
	
	// some shorthands
	function remain() { return ll.length }
	function sh() { return ll.shift() } // shift
	function ps(s) { o+=s } // push
	
	function f() // similar to C's printf, uses ? as placeholders, ?? to escape question marks
	{
		var i=1,a=arguments,f=a[0],o='',c,p
		for (;i<a.length; i++) if ((p=f.indexOf('?'))+1) {
			// allow character escaping
			i -= c=f.charAt(p+1)=='?'?1:0
			o += f.substring(0,p)+(c?'?':a[i])
			f=f.substr(p+1+c)
		} else break;
		return o+f
	}
	
	function html_entities(s) { return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;") }
	
	function max(a,b) { return (a>b)?a:b }
	function min(a,b) { return (a<b)?a:b }
	
	// return the first non matching character position between two strings
	function str_imatch(a, b)
	{
		for (var i=0, l=min(a.length, b.length); i<l; i++) if (a.charAt(i)!=b.charAt(i)) break
		return i
	}
	
	// compare current line against a string or regexp
	// if passed a string it will compare only the first string.length characters
	// if passed a regexp the result is stored in $r
	function $(c) { return (typeof c == 'string') ? (ll[0].substr(0,c.length)==c) : ($r = ll[0].match(c)) }
	
	function $$(c) { return ll[0]==c } // compare current line against a string
	function _(p) { return ll[0].charAt(p) } // return char at pos p
	
	function endl(s) { ps(s); sh() }
	
	function parse_list()
	{
		var prev='';
		
		while (remain() && $(/^([*#:;]+)(.*)$/)) {
			
			var l_match = $r
			
			sh()
			
			var ipos = str_imatch(prev, l_match[1])
			
			// close uncontinued lists
			for (var i=prev.length-1; i >= ipos; i--) {
				
				var pi = prev.charAt(i)
				
				if (pi=='*') ps('</ul>')
				else if (pi=='#') ps('</ol>')
				// close a dl only if the new item is not a dl item (:, ; or empty)
				else switch (l_match[1].charAt(i)) { case'':case'*':case'#': ps('</dl>') }
			}
			
			// open new lists
			for (var i=ipos; i<l_match[1].length; i++) {
				
				var li = l_match[1].charAt(i)
				
				if (li=='*') ps('<ul>')
				else if (li=='#') ps('<ol>')
				// open a new dl only if the prev item is not a dl item (:, ; or empty)
				else switch(prev.charAt(i)) { case'':case'*':case'#': ps('<dl>') }
			}
			
			switch (l_match[1].charAt(l_match[1].length-1)) {
			
				case '*': case '#':
					ps('<li>' + parse_inline_nowiki(l_match[2])); break
					
				case ';':
					ps('<dt>')
					
					var dt_match
					
					// handle ;dt :dd format
					if (dt_match = l_match[2].match(/(.*?) (:.*?)$/)) {
						
						ps(parse_inline_nowiki(dt_match[1]))
						ll.unshift(dt_match[2])
						
					} else ps(parse_inline_nowiki(l_match[2]))
					
					break
					
				case ':':
					ps('<dd>' + parse_inline_nowiki(l_match[2]))
			}
			
			prev=l_match[1]
		}
		
		// close remaining lists
		for (var i=prev.length-1; i>=0; i--)
			ps(f('</?>', (prev.charAt(i)=='*')? 'ul': ((prev.charAt(i)=='#')? 'ol': 'dl')))
	}
	
	function parse_table()
	{
		endl(f('<table?>', $(/^\{\|( .*)$/)? $r[1]: ''))
		
		for (;remain();) if ($('|')) switch (_(1)) {
			case '}': endl('</table>'); return
			case '-': endl(f('<tr ?>', $(/\|-*(.*)/)[1])); break
			default: parse_table_data()
		}
		else if ($('!')) parse_table_data()
		else sh()
	}
	
	function parse_table_data()
	{
		var td_line, match_i
		
		// 1: "|+", '|' or '+'
		// 2: ??
		// 3: attributes ??
		// TODO: finish commenting this regexp
		var td_match = sh().match(/^(\|\+|\||!)((?:([^[|]*?)\|(?!\|))?(.*))$/)
		
		if (td_match[1] == '|+') ps('<caption');
		else ps('<t' + ((td_match[1]=='|')?'d':'h'))
		
		if (typeof td_match[3] != 'undefined') {
			
			ps(' ' + td_match[3])
			match_i = 4
			
		} else match_i = 2
		
		ps('>')
		
		if (td_match[1] != '|+') {
			
			// use || or !! as a cell separator depending on context
			// NOTE: when split() is passed a regexp make sure to use non-capturing brackets
			td_line = td_match[match_i].split((td_match[1] == '|')? '||': /(?:\|\||!!)/)
			
			ps(parse_inline_nowiki(td_line.shift()))
			
			while (td_line.length) ll.unshift(td_match[1] + td_line.pop())
			
		} else ps(td_match[match_i])
		
		var tc = 0, td = []
		
		for (;remain(); td.push(sh()))
		if ($('|')) {
			if (!tc) break // we're at the outer-most level (no nested tables), skip to td parse
			else if (_(1)=='}') tc--
		}
		else if (!tc && $('!')) break
		else if ($('{|')) tc++
		
		if (td.length) ps(InstaViewPR.convert(td))
	}
	
	function parse_pre()
	{
		ps('<pre>')
		do endl(parse_inline_nowiki(ll[0].substring(1)) + "\n"); while (remain() && $(' '))
		ps('</pre>')
	}
	
	function parse_block_image()
	{
		ps(parse_image(sh()))
	}

	function parse_image(str)
	{
		// get what's in between "[[Image:" and "]]"
		var tag = str.substring(InstaViewPR.conf.locale.image.length + 3, str.length - 2);
		
		var width;
		var attr = [], filename, caption = '';
		var thumb=0, frame=0, center=0;
		var align='';
		
		if (tag.match(/\|/)) {
			// manage nested links
			var nesting = 0;
			var last_attr;
			for (var i = tag.length-1; i > 0; i--) {
				if (tag.charAt(i) == '|' && !nesting) {
					last_attr = tag.substr(i+1);
					tag = tag.substring(0, i);
					break;
				} else switch (tag.substr(i-1, 2)) {
					case ']]':
						nesting++;
						i--;
						break;
					case '[[':
						nesting--;
						i--;
				}
			}
			
			attr = tag.split(/\s*\|\s*/);
			attr.push(last_attr);
			filename = attr.shift();
			
			var w_match;
			
			for (;attr.length; attr.shift())
			if (w_match = attr[0].match(/^(\d*)px$/)) width = w_match[1]
			else switch(attr[0]) {
				case 'thumb':
				case 'thumbnail':
					thumb=true;
				case 'frame':
					frame=true;
					break;
				case 'none':
				case 'right':
				case 'left':
					center=false;
					align=attr[0];
					break;
				case 'center':
					center=true;
					align='none';
					break;
				default:
					if (attr.length == 1) caption = attr[0];
			}
			
		} else filename = tag;
		
		
		var o='';
		
		if (frame) {
		
			if (align=='') align = 'right';
			
			o += f("<div class='thumb t?'>", align);
			
			if (thumb) {
				if (!width) width = InstaViewPR.conf.wiki.default_thumb_width;
				
				o += f("<div style='width:?px;'>?", 2+width*1, make_image(filename, caption, width)) +
					f("<div class='thumbcaption'><div class='magnify' style='float:right'><a href='?' class='internal' title='Enlarge'><img src='?'></a></div>?</div>",
						InstaViewPR.conf.paths.articles + InstaViewPR.conf.locale.image + ':' + filename,
						InstaViewPR.conf.paths.magnify_icon,
						parse_inline_nowiki(caption)
					)
			} else {
				o += '<div>' + make_image(filename, caption) + f("<div class='thumbcaption'>?</div>", parse_inline_nowiki(caption))
			}
			
			o += '</div></div>';
			
		} else if (align != '') {
			o += f("<div class='float?'><span>?</span></div>", align, make_image(filename, caption, width));
		} else {
			return make_image(filename, caption, width);
		}
		
		return center? f("<div class='center'>?</div>", o): o;
	}
	
	function parse_inline_nowiki(str)
	{
		var start, lastend=0
		var substart=0, nestlev=0, open, close, subloop;
		var html='';
		
		while (-1 != (start = str.indexOf('<nowiki>', substart))) {
			html += parse_inline_wiki(str.substring(lastend, start));
			start += 8;
			substart = start;
			subloop = true;
			do {
				open = str.indexOf('<nowiki>', substart);
				close = str.indexOf('</nowiki>', substart);
				if (close<=open || open==-1) {
					if (close==-1) {
						return html + html_entities(str.substr(start));
					}
					substart = close+9;
					if (nestlev) {
						nestlev--;
					} else {
						lastend = substart;
						html += html_entities(str.substring(start, lastend-9));
						subloop = false;
					}
				} else {
					substart = open+8;
					nestlev++;
				}
			} while (subloop)
		}
		
		return html + parse_inline_wiki(str.substr(lastend));
	}
	
	function make_image(filename, caption, width)
	{
		// uppercase first letter in file name
		filename = filename.charAt(0).toUpperCase() + filename.substr(1);
		// replace spaces with underscores
		filename = filename.replace(/ /g, '_');
		
		caption = strip_inline_wiki(caption);
		
		var md5 = hex_md5(filename);
		
		var source = md5.charAt(0) + '/' + md5.substr(0,2) + '/' + filename;
		
		if (width) width = "width='" + width + "px'";
		
		var img = f("<img onerror=\"this.onerror=null;this.src='?'\" src='?' ? ?>", InstaViewPR.conf.paths.images_fallback + source, InstaViewPR.conf.paths.images + source, (caption!='')? "alt='" + caption + "'" : '', width);
		
		return f("<a class='image' ? href='?'>?</a>", (caption!='')? "title='" + caption + "'" : '', InstaViewPR.conf.paths.articles + InstaViewPR.conf.locale.image + ':' + filename, img);
	}
	
	function parse_inline_images(str)
	{
		var start, substart=0, nestlev=0;
		var loop, close, open, wiki, html;
		
		while (-1 != (start=str.indexOf('[[', substart))) {
			if(str.substr(start+2).match(RegExp('^' + InstaViewPR.conf.locale.image + ':','i'))) {
				loop=true;
				substart=start;
				do {
					substart+=2;
					close=str.indexOf(']]',substart);
					open=str.indexOf('[[',substart);
					if (close<=open||open==-1) {
						if (close==-1) return str;
						substart=close;
						if (nestlev) {
							nestlev--;
						} else {
							wiki=str.substring(start,close+2);
							html=parse_image(wiki);
							str=str.replace(wiki,html);
							substart=start+html.length;
							loop=false;
						}
					} else {
						substart=open;
						nestlev++;
					}
				} while (loop)
				
			} else break;
		}
		
		return str;
	}
	
	// the output of this function doesn't respect the FILO structure of HTML
	// but since most browsers can handle it I'll save myself the hassle
	function parse_inline_formatting(str)
	{
		var em,st,i,li,o='';
		while ((i=str.indexOf("''",li))+1) {
			o += str.substring(li,i);
			li=i+2;
			if (str.charAt(i+2)=="'") {
				li++;
				st=!st;
				o+=st?'<strong>':'</strong>';
			} else {
				em=!em;
				o+=em?'<em>':'</em>';
			}
		}
		return o+str.substr(li);
	}
	
	function parse_inline_wiki(str)
	{
		var aux_match;
		
		str = parse_inline_images(str);
		str = parse_inline_formatting(str);
		
		// math
		while (aux_match = str.match(/<(?:)math>(.*?)<\/math>/i)) {
			var math_md5 = hex_md5(aux_match[1]);
			str = str.replace(aux_match[0], f("<img src='?.png'>", InstaViewPR.conf.paths.math+math_md5));
		}
		
		// Build a Mediawiki-formatted date string
		var date = new Date;
		var minutes = date.getUTCMinutes();
		if (minutes < 10) minutes = '0' + minutes;
		var date = f("?:?, ? ? ? (UTC)", date.getUTCHours(), minutes, date.getUTCDate(), InstaViewPR.conf.locale.months[date.getUTCMonth()], date.getUTCFullYear());
		
		// text formatting
		return str.
			// signatures
			replace(/~{5}(?!~)/g, date).
			replace(/~{4}(?!~)/g, InstaViewPR.conf.user.name+' '+date).
			replace(/~{3}(?!~)/g, InstaViewPR.conf.user.name).
			
			// [[:Category:...]], [[:Image:...]], etc...
			replace(RegExp('\\[\\[:((?:'+InstaViewPR.conf.locale.category+'|'+InstaViewPR.conf.locale.image+'|'+InstaViewPR.conf.wiki.interwiki+'):.*?)\\]\\]','gi'), "<a href='"+InstaViewPR.conf.paths.articles+"$1'>$1</a>").
			replace(RegExp('\\[\\[(?:'+InstaViewPR.conf.locale.category+'|'+InstaViewPR.conf.wiki.interwiki+'):.*?\\]\\]','gi'),'').
			
			// [[/Relative links]]
			replace(/\[\[(\/[^|]*?)\]\]/g, f("<a href='?$1'>$1</a>", location)).
			
			// [[/Replaced|Relative links]]
			replace(/\[\[(\/.*?)\|(.+?)\]\]/g, f("<a href='?$1'>$2</a>", location)).
			
			// [[Common links]]
			replace(/\[\[([^|]*?)\]\](\w*)/g, f("<a href='?$1'>$1$2</a>", InstaViewPR.conf.paths.articles)).
			
			// [[Replaced|Links]]
			replace(/\[\[(.*?)\|([^\]]+?)\]\](\w*)/g, f("<a href='?$1'>$2$3</a>", InstaViewPR.conf.paths.articles)).
			
			// [[Stripped:Namespace|Namespace]]
			replace(/\[\[([^\]]*?:)?(.*?)( *\(.*?\))?\|\]\]/g, f("<a href='?$1$2$3'>$2</a>", InstaViewPR.conf.paths.articles)).
			
			// External links
			replace(/\[(https?|news|ftp|mailto|gopher|irc):(\/*)([^\]]*?) (.*?)\]/g, "<a href='$1:$2$3'>$4</a>").
			replace(/\[http:\/\/(.*?)\]/g, "<a href='http://$1'>[#]</a>").
			replace(/\[(news|ftp|mailto|gopher|irc):(\/*)(.*?)\]/g, "<a href='$1:$2$3'>$1:$2$3</a>").
			replace(/(^| )(https?|news|ftp|mailto|gopher|irc):(\/*)([^ $]*)/g, "$1<a href='$2:$3$4'>$2:$3$4</a>").
			
			replace('__NOTOC__','').
			replace('__NOEDITSECTION__','');
	}
	
	function strip_inline_wiki(str)
	{
		return str
			.replace(/\[\[[^\]]*\|(.*?)\]\]/g,'$1')
			.replace(/\[\[(.*?)\]\]/g,'$1')
			.replace(/''(.*?)''/g,'$1');
	}
	
	// begin parsing
	for (;remain();) if ($(/^(={1,6})(.*)\1(.*)$/)) {
		p=0
		endl(f('<h?>?</h?>?', $r[1].length, parse_inline_nowiki($r[2]), $r[1].length, $r[3]))
		
	} else if ($(/^[*#:;]/)) {
		p=0
		parse_list()
		
	} else if ($(' ')) {
		p=0
		parse_pre()
		
	} else if ($('{|')) {
		p=0
		parse_table()
		
	} else if ($(/^----+$/)) {
		p=0
		endl('<hr>')
		
	} else if ($(InstaViewPR.BLOCK_IMAGE)) {
		p=0
		parse_block_image()
		
	} else {
		
		// handle paragraphs
		if ($$('')) {
			if (p = (remain()>1 && ll[1]==(''))) endl('<p><br>')
		} else {
			if(!p) {
				ps('<p>')
				p=1
			}
			ps(parse_inline_nowiki(ll[0]) + ' ')
		}
		
		sh();
	}
	
	return o
}


/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2-alpha Copyright (C) Paul Johnston 1999 - 2005
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
function hex_hmac_md5(k, d)
  { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_md5(k, d)
  { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_md5(k, d, e)
  { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

/*
 * Calculate the MD5 of a raw string
 */
function rstr_md5(s)
{
  return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}

/*
 * Calculate the HMAC-MD5, of a key and some data (raw strings)
 */
function rstr_hmac_md5(key, data)
{
  var bkey = rstr2binl(key);
  if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
  return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}

/*
 * Convert a raw string to a hex string
 */
function rstr2hex(input)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var output = "";
  var x;
  for(var i = 0; i < input.length; i++)
  {
    x = input.charCodeAt(i);
    output += hex_tab.charAt((x >>> 4) & 0x0F)
           +  hex_tab.charAt( x        & 0x0F);
  }
  return output;
}

/*
 * Convert a raw string to a base-64 string
 */
function rstr2b64(input)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var output = "";
  var len = input.length;
  for(var i = 0; i < len; i += 3)
  {
    var triplet = (input.charCodeAt(i) << 16)
                | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
                | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > input.length * 8) output += b64pad;
      else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
    }
  }
  return output;
}

/*
 * Convert a raw string to an arbitrary string encoding
 */
function rstr2any(input, encoding)
{
  var divisor = encoding.length;
  var remainders = Array();
  var i, q, x, quotient;

  /* Convert to an array of 16-bit big-endian values, forming the dividend */
  var dividend = Array(input.length / 2);
  for(i = 0; i < dividend.length; i++)
  {
    dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
  }

  /*
   * Repeatedly perform a long division. The binary array forms the dividend,
   * the length of the encoding is the divisor. Once computed, the quotient
   * forms the dividend for the next step. We stop when the dividend is zero.
   * All remainders are stored for later use.
   */
  while(dividend.length > 0)
  {
    quotient = Array();
    x = 0;
    for(i = 0; i < dividend.length; i++)
    {
      x = (x << 16) + dividend[i];
      q = Math.floor(x / divisor);
      x -= q * divisor;
      if(quotient.length > 0 || q > 0)
        quotient[quotient.length] = q;
    }
    remainders[remainders.length] = x;
    dividend = quotient;
  }

  /* Convert the remainders to the output string */
  var output = "";
  for(i = remainders.length - 1; i >= 0; i--)
    output += encoding.charAt(remainders[i]);

  return output;
}

/*
 * Encode a string as utf-8.
 * For efficiency, this assumes the input is valid utf-16.
 */
function str2rstr_utf8(input)
{
  var output = "";
  var i = -1;
  var x, y;

  while(++i < input.length)
  {
    /* Decode utf-16 surrogate pairs */
    x = input.charCodeAt(i);
    y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
    if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
    {
      x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
      i++;
    }

    /* Encode output as utf-8 */
    if(x <= 0x7F)
      output += String.fromCharCode(x);
    else if(x <= 0x7FF)
      output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0xFFFF)
      output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0x1FFFFF)
      output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                                    0x80 | ((x >>> 12) & 0x3F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
  }
  return output;
}

/*
 * Encode a string as utf-16
 */
function str2rstr_utf16le(input)
{
  var output = "";
  for(var i = 0; i < input.length; i++)
    output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
                                  (input.charCodeAt(i) >>> 8) & 0xFF);
  return output;
}

function str2rstr_utf16be(input)
{
  var output = "";
  for(var i = 0; i < input.length; i++)
    output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                                   input.charCodeAt(i)        & 0xFF);
  return output;
}

/*
 * Convert a raw string to an array of little-endian words
 * Characters >255 have their high-byte silently ignored.
 */
function rstr2binl(input)
{
  var output = Array(input.length >> 2);
  for(var i = 0; i < output.length; i++)
    output[i] = 0;
  for(var i = 0; i < input.length * 8; i += 8)
    output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
  return output;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2rstr(input)
{
  var output = "";
  for(var i = 0; i < input.length * 32; i += 8)
    output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
  return output;
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length.
 */
function binl_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

// </nowiki>
// ENDFILE: livepreview.js
// STARTFILE: cookie.js
//  NOT needed as of now, could be useful in future though
/*
function createCookie(name,value,expdate){
		document.cookie = name + "=" + escape(value) + ";expires=" + expdate;	
}

function readCookie(name){
	if(document.cookie.length > 0){
		cookieIndex = document.cookie.indexOf(name+"=");	
		if(cookieIndex != -1){
			cookieIndex += name.length + 1;
			endCookieIndex = document.cookie.indexOf(";",cookieIndex);
			if(endCookieIndex == -1) endCookieIndex = document.cookie.length;	
			return unescape(document.cookie.substring(cookieIndex,endCookieIndex));
		}
	}	
	return null;
}

function saveReview(){
	 curdate = new Date();
	 PRarchiveTxt = wgTitle;
     PRarchiveTxt += "^t^" + document.getElementById('theResponse').value.replace(/\n/gi,"^n^");
	 PRarchiveTxt += "^d^" + curdate.getFullYear() + "," + curdate.getMonth() + "," + curdate.getDate();
	 
	 var thearchives = new Array(5); var thearchives_dates = new Array(5); var lowyear; var lowdate; var lowmonth; var lownum = 0;
	 for(i=0;i<5;i++){
	 	thearchives[i] = readCookie("archivePRA" + i.toString());
	 	thearchives_dates[i] = thearchives[i].split("^d^")[1];
	 	if(i==0){
		 	lowyear = thearchives_dates[i].split(",")[0];
		 	lowmonth = thearchives_dates[i].split(",")[1];
		 	lowdate = thearchives_dates[i].split(",")[2];	
	 	}
	 	else{
		 	if(parseInt(thearchives_dates[i].split(",")[0]) < parseInt(lowyear)){
				lowyear = thearchives_dates[i].split(",")[0];
		 		lowmonth = thearchives_dates[i].split(",")[1];
		 		lowdate = thearchives_dates[i].split(",")[2];	
		 		lownum = i;		
		 	}
		 	else if(parseInt(thearchives_dates[i].split(",")[0]) == parseInt(lowyear)){
			 	if(parseInt(thearchives_dates[i].split(",")[1]) < parseInt(lowmonth)){
					lowyear = thearchives_dates[i].split(",")[0];
			 		lowmonth = thearchives_dates[i].split(",")[1];
			 		lowdate = thearchives_dates[i].split(",")[2];	
			 		lownum = i;				 	
			 	}
			 	else if(parseInt(thearchives_dates[i].split(",")[1]) == parseInt(lowmonth)){
				 	if(parseInt(thearchives_dates[i].split(",")[2]) < parseInt(lowdate)){
						lowyear = thearchives_dates[i].split(",")[0];
				 		lowmonth = thearchives_dates[i].split(",")[1];
				 		lowdate = thearchives_dates[i].split(",")[2];	
				 		lownum = i;				 	
			 		}
			 	}
		 	}
	 	}
 	}
	 	
     expdate = new Date(); expdate.setDate(curdate.getDate()+30);	
     createCookie("archivePRA"+lownum,PRarchiveTxt,expdate);
}

function locateReview(){		
	scores = readCookie("highs");
	scoreChart = scores.split(",");
	
	theHTML = "";
	if(scoreChart.length>20){scoreChartLength=20;}
	else scoreChartLength = scoreChart.length; 
	
	for(i=0;i<scoreChartLength;i++){
		if(i<9){theHTML += "  " + (i+1) + ". " + "&nbsp;&nbsp;" + scoreChart[i] + "<br>";}
		else{theHTML += "  " + (i+1) + ".  " + scoreChart[i] + "<br>";}
	}
}
*/
// end unneeded stuff
// ENDFILE: cookie.js

//Comments and closing notes 
////////////////////////////////////////
// TO DO LIST
////////////////////////////////////////
/*List of things to do:
 // Determine the usage of commas with dates                    --
 // <s>Determine the length of a lead (number of paragraphs)</s>
 // <s>Figure out if the lead is too short (1 paragraph) or too long (>=4 paragraphs), depending upon size of article</s>
 // <s>Determine if no-break spaces (&nbsp;) are used </s>
 // Determine if conversions are included                       --
 // <s>Determine if standard abbreviations are used for conversions</s>
 // <s>Determine if units are spelled out in text</s>
 // <s>Determine if last few sections (see also, references, notes, external links) follow [[WP:GTL]]</s>
 //- not necessary to check - Determine if extraneous bolding is used
 // <s>Determine if categories and interlanguage links are alphabetized</s>
 //- not able to do (w/ JS): Determine if quotes have sources (due to huge amounts of ""s)
 //  Prove that images have proper image copyright tags
 //  Show that all fair use images have proper fair use rationales
 // <s>Determine if all images have captions</s>
 // <s>Find out the number of sections</s>
 //- not able to do (w/ JS): Determine if sections or paragraphs are too short, outside of {{sect-stub}} or {{sectionexpand}}, etc. 
 //- not able to do (w/ JS): Determine if a list is used
 // <s>Determine if footnote spacing standards are used (as in [[WP:FOOTNOTE]])</s>
 //- not able to do (w/ JS): Determine if words in headings are capitalized
 // Find common [[User:Tony1/How to satisfy Criterion 2a|redunancies]]
 //   *"in order to/for" -> to/for
 //   *
 // <s>Time/future issues</s>
 // Check w/ U:SUGG to see if any other things are missing     
 // <s>Automatic archiving</s>
 // <s>British/American English spellings</s>
 // Contractions, per MOS
 
 // Help out with [[WP:FL]]
 // Maybe [[WP:FPO]]?
 // simple links for easy copy+paste into sandboxes, talk pages, or [[WP:PR/A]] **
 // <s>instaview version (somewhat like [[User:Pilaf]]'s, possibly) </s>
 //- not important - improving look 
 // embedding solutions beneath text, possibly (using innerHTML, etc., property) **
 // more configurable options that will be helpful to users

Second priority issues:
 // Add to list of units (for units, conversions, and standard abbreviations)
 // Add to list of weasel words
 // <s>Improve the headingre function to exclude "the" and words in parentheses</s>
 // infoboxes...
*/

/*  ///////////////////////////////////////////////////
    // Note:
    // I am quite aware 
    // that the layout and documentation
    // of my coding is pretty terrible;
    // feel free to edit this page
    // and help clean it up
    // --------------
    // (for non-admins, leave a note on the talk page)
    // --------------
    // Please be aware that changes
    // may affect many users
    //  AS OF LAST COUNT: -- 134 -- users use this script
    ///////////////////////////////////////////////////
*/

//</pre> [[Category:Wikipedia tools|AndyZ/peerreviewer.js]]
//cut out code can be found at [[User:AndyZ/peerreviewer.js/comment]]