/** Checklinks.js ******************************
 * 
 * Maintainer: [[User:Dispenser]]
 */
// Interface message texts
//if(lang == 'XX' && false) {
//  alert("XX isn't a valid langauge!")
//	// Copy tranlated version from bellow
//	
//	} else {
	var AccessdateMsg = "Would you like to update the accessdate parameter on citation templates? \n\n NOTE!: You should only do this if you know that the external links have not changed since the labeled accessdate (i.e. they still contain the cited facts)."
	var AnchorGoneMsg = "The fragment ($1) has been changed or removed from the former value.  Would you like to restore the old value."
	var ArchiveUrlMsg = "Enter in an Internet Archive URL or timestamp"
	var EditMsg       = ""
	var NewUrlMsg     = "Paste in the new URL"
	var NoChangesMsg  = "No changes will be maded.  Continue?"
	var ReflinksMsg   = "Would you like to run reflinks.py bot script to attempt to add missing titles for external links and to combine identical references?"
	
//	}

function showGroup(form, n) {
	nodes = form.getElementsByTagName('ul')
	for(i=0; (d=nodes[i]); i++){
		if(d.className && d.className != 'indentonly')
			d.style.display = (n==d.className?'':'none');
	}
}
// Toolbar code
function createTools(node) {
	node.innerHTML = '<form action="javascript:alert(\'ERROR\');" id="something" style="font-size:88%;">\
<fieldset style="margin-top:0;">\
<legend>Operation <font color=red>[under development]</font></legend>\
<ul class="indentonly" style="font-size:92%;">\
<li><label><input disabled type="radio" name="action" onchange="showGroup(this.form); " />Unchanged</label></li>\
<li><label><input type="radio" name="action" onchange="showGroup(this.form, &quot;tagging&quot;); " />Tag as...</label>\
<ul class="tagging" style="display:none;">\
	<li><label><input disabled type="radio" name="tag" checked="checked" />{{Dead link}}</label></li>\
	<li><label><input disabled type="radio" name="tag" />{{Spam link}}</label></li>\
	<li><label><input disabled type="radio" name="tag" /><input type="text" value="{{custom tag}}" style="width:80%;" /></label></li>\
</ul></li>\
<li><label><input type="radio" name="action" onchange="showGroup(this.form, &quot;replacing&quot;); " />Replace URL...</label>\
<ul class="replacing" style="display:none;">\
	<li><input disabled type="text" name="urlreplace" value="http://" style="width:95%;" /></li>\
	<li><label><input disabled type="checkbox" name="accessdate" /> Update accessdate</label></li>\
	<li><select><option>Wayback Machine</option></select></li>\
	<li><select><option>WebCite</option></select></li>\
</ul></li>\
<li><label><input disabled type="radio" name="action" onchange="showGroup(this.form); " />Unlink</label></li>\
<li><label><input disabled type="radio" name="action" onchange="showGroup(this.form); " />Add accessdate (input)</label></li>\
<li><label><input disabled type="radio" name="action" onchange="showGroup(this.form); " />Remove completely</label></li>\
</ul>\
</fieldset>\
\
<fieldset>\
<legend>Search tools</legend>\
<select name="service">\
	<option value="http://www.google.com/search?hl=$1&q=">Google</option>\
	<option value="http://search.live.com/results.aspx?mkt=$1-$1&q=">Bing</option>\
	<option value="http://scholar.google.com/scholar?hl=$1&q=">Google Scholar</option>\
</select>\
<button onclick="changeLink(this, loadResults(this.form)); return false;">Search</button>\
<select name="lookfor">\
	<option>URL</option>\
	<option>File or Ids</option>\
	<option>Filename</option>\
	<option selected="selected">Link title</option>\
	<option>Article title</option>\
</select>\
<select name="domain">\
	<option value="">Anywhere</option>\
	<option value=" site:$3">TLD (*.com)</option>\
	<option value=" site:$2$3" selected="selected">Domain</option>\
	<option value=" site:$1$2$3">Sub-domain</option>\
</select>\
</fieldset>\
\
<fieldset>\
<legend>Quick links</lengend>\
<ol class="quicklinks" style="">\
<li><a href="http://wikipedia.ramselehof.de/wikiblame.php?uselang=$1&lang=$1&project=wikipedia&article=$3&limit=4096&searchmethod=int&tags_present=true&needle=$0" onclick="changeLink(this, ReplaceVars(this.href, this)); return false;">Find the access date</a></li>\
<li><a href="/~dispenser/cgi-bin/url_info.py?archivesearch=$5&accessdate=$6&url=$0" onclick="changeLink(this, ReplaceVars(this.href, this)); return false;">Headers and redirects</a></li>\
<li><a href="http://web.archive.org/archive_request_ng?url=$0" onclick="changeLink(this, ReplaceVars(this.href, this)); return false;">Internet Archive</a></li>\
<li><a href="http://www.webcitation.org/query.php?date=$6&url=$0" onclick="changeLink(this, ReplaceVars(this.href, this)); return false;">WebCite</a></li>\
<!--li><a href="http://www.google.com/search?hl=$1&q=$3" onclick="changeLink(this, ReplaceVars(this.href, this)); return false;">Google article title</a>(broken)</li-->\
</ol>\
</fieldset>\
<!--p>This link is being used on # articles, # Talk pages, # Wikipedia pages, # user pages, [if # = 21 then] more than 20 pages (see all).</p-->\
</form>';
}

// Wiki messages
var DATE = 'date='+Months[today.getUTCMonth()]+' '+today.getUTCFullYear()
deadLinkTag = {'ar':'وصلة مكسورة',
			   'es':'Enlace roto',
			   'fa':'پیوند مرده',
               'fr':'lien mort',
               'hu':'halott link',
			   'id':'Dead link',
			   'it':'collegamento interrotto',
			   'lv':'Dead link',
			   'ja':'リンク切れ',
               'ko':'죽은 바깥 고리',
			   'ms':'dead link',
			   'pt':'dead link',
			   'simple':'dead link',
               'en':'dead link'}
var factTag = {'en':'Fact'}

var MergePath    = "/~dispenser/cgi-bin/mergeChanges.py"
var WinFeatures  = "scrollbars, resizable, menubar, location, dependent"
var openViewers = 0; // Number of open iframes
// Event Handlers
//
function aClick(e) {
	(e?e:event).cancelBubble=true
	openLink(this, this.href)
	return false;
}
function buttonClick(e) {
	(e?e:event).cancelBubble=true
	// go into the next cell to get the link
	a=this.parentNode.getElementsByTagName('a')[0];
	// Make sure the user see the page they've just updated the accessdate on 
	openLink(a, a.href)
	setAction(a, 3);
	return false;
}
function infoClick(e) {
	(e?e:event).cancelBubble=true
	var tr = this;
	while(tr!=document.body && tr.nodeName!='TR')
		tr = tr.parentNode;
	openLink(tr.entryLink, ReplaceVars("/~dispenser/cgi-bin/url_info.py?archivesearch=$5&accessdate=$6&url=$0", tr))
	return false;
}

function trClick() {
	openLink(this.entryLink, this.entryLink.href);
	return false;
}
function ReplaceVars(str, tr) {
	while(tr!=document.body && tr.nodeName!='TR')
		tr = tr.parentNode;
	// FIXME Hack
	if(tr.entryLink){
		activeLink = tr.entryLink
	} else {
		activeLink = tr.previousSibling.getElementsByTagName('a')[0];
	}
	// FIXME remove url hack
	with(activeLink.parentNode){
		return str.replace(/\$1/g, wgContentLanguage || 'en').replace(/\$3/g, encodeURIComponent(wgPageName.replace(/_/g, ' '))).replace(/\$5/g, parentNode.className.match(/dead-\d/) || 0).replace(/\$6/g, innerHTML.replace(/.*?(?:accessdate=([\d\-]+)|Retrieved 20|accessed on 20).*/i, '$2')).replace(/\$0/g, encodeURIComponent(activeLink.href))
		}
}
function loadResults(form) {
	var tr = form;
	while(tr!=document.body && tr.nodeName!='TR')
		tr = tr.parentNode;
	activeLink = tr.previousSibling.getElementsByTagName('a')[0];
	
	option = form['service'].selectedIndex
	url = ReplaceVars(form['service'].value, tr)
	s = ''
	file = activeLink.href.replace(/\w*:\/\/([^\/]*).*\/([^\/]*)(\.[^\/.]*|\/)([?#]|$)*/, "$2")
	switch(form['lookfor'].selectedIndex) {
		case 0:
			s=activeLink.href
			break
		case 1:
			s=' allinurl: ('+file+'|'+activeLink.href.replace(/\D+/g, ' ') +')'
			break
		case 2:
			s=file
			break
		case 3:
			s=getNodeText(activeLink).replace(/(&#123;&#123;|\{\{).*?(&#125;&#125;|\}\})/g, '').replace(/&lt;!-- Bot generated title --&gt;/, '').replace(/&amp;/g, '&')
			break
		case 4:
			s=activeLink.pagename
			break
		default:
			s=activeLink.href
			break
	} 
	s += activeLink.href.replace(/.*?:\/\/([^\/]*?)([^\/.]+\.)([^\/\d]{2,6})(:\d+)?\/.*/, form['domain'].value)
	url += encodeURIComponent(s)
	return url
}
//
// "Action" field code
//
function iframeSetAction(frame, option, newURL){
	tr = frame
	while(tr!=document.body && tr.nodeName!='TR')
        tr = tr.parentNode
	linkNode = tr.previousSibling.getElementsByTagName('a')[0]
	setAction(linkNode, option, newURL)
}
function setAction(a, option, newURL) {
	/* Public API, needs rewriting/reworking
	 * Sets the modified action for the activelink
	 */
	color = 'transparent' // IE doesn't support inherit
	//actionGUI = document.getElementById('action')
//	actionGUI.selectedIndex = option
	ma = ''
	switch(option) {
		case 0: // unchanged
			a.str = ''
			a.action = 0
			ma = ''
			break
		case 8: // de title
			a.str = ''
			a.action = 8
			ma = 'replace'
			break
		case 1: // input url
			if(!newURL)
				newURL = prompt(NewUrlMsg, (a.action == 1)?a.str:a.href)
			if(newURL && newURL != '' && !newURL.match('\n')){
				oldanchor = a.href.replace(/[^#]*(#.*|)/, '$1')
				if(!newURL.match('://'))
					newURL = 'http://' + newURL
				if(newURL.replace(/[^#]*(#.*|)/, '$1') != oldanchor && confirm(AnchorGoneMsg.replace('$1', oldanchor)))
					newURL += oldanchor
				a.str = newURL
				a.action = 1
				color = '#4FA23D' //'green'
				ma = 'replace'
			} else {
				//actionGUI.selectedIndex = a.action
			}
			break
		case 4: // Tag URL with {{dead link}}
			a.str = '{{'+translate(deadLinkTag, a.pagename)+'|'+DATE+'}}'
			a.action = 4
			color = '#ce1f00' //'red'
			ma = 'append';
			break
		case 5: // Tag URL with {{dead link}} with Internet Archive option
			a.str = '{{'+translate(deadLinkTag, a.pagename)+'|url='+a.href+'|'+DATE+'}}'
			a.action = 5
			color = '#df9200' //'orange'
			ma = 'append'
			break
		case 2: // Replace with {{waybackdate}} or archiveURL
			if(!newURL)
				newURL = prompt(ArchiveUrlMsg, '')
			if(newURL) {
				a.str = newURL
				a.action = 2
				color = '#00988F' // light blue
				ma = 'archive'
			} else {
				//actionGUI.selectedIndex = a.action
				ma=a.ma
			}
			break
		case 7: // Delete the whole thing
			a.str = ' ' 
			a.action = 7
			ma = 'replacelink'
			break
		case 10:	// Replace with {{Fact}}
			a.str = '{{'+translate(factTag, a.pagename)+'|'+DATE+'}}'
			a.action = 10
			ma = 'replacelink'
			break
		case 6: // Tag URL with {{spam link}}
			a.str = '{{Spam link|'+DATE+'}}'
			a.action = 6
			color = '#cc99ff'
			ma = 'append'
			break
		case 3:	// Update accessdate
			a.str = ''
			a.action = 3
			color = "#BadBad"
			ma = 'updateaccessdate'
			break
		default:
			alert('unsepcified action : '+option)
			a.str = ''
			a.action = option

	}
	if(color)
		// Stupid mozilla, can't use childNodes(0) since non-renderable white-space is considered as a node
		tr = a
		while(tr!=document.body && tr.nodeName!='TR')
			tr = tr.parentNode
		tr.getElementsByTagName("td")[0].style.backgroundColor = color
	a.ma = ma
}
//
// WikiDiff & saving
//
function mergeChanges(action, row, rowLinkIndex) {
	var pagename = ''
	var found = false
	
	// crawls through table
	var a = document.getElementById('linktable').getElementsByTagName('a')
	for(i = 0; a[i]; i++) {
		if(a[i].parentNode.tagName.toLowerCase() == 'th') { // <th> node
			if(!found){
				var replacements = []
				var askReflinks  = 0
				var msgTag = 0
				var msgFix = 0
				var msgAcc = 0
			} else
				break
		} else { // <td> node
			tr = a[i].parentNode.parentNode // <a>.<td>.<tr>
			if(a[i].innerHTML.match(/http:|(\[|\&\#91;)\d[\]&]|INSERT TITLE/i))
				askReflinks += 1
			if(a[i].action){
				replacements.push(new Array(a[i].ma, a[i].href, a[i].str))

				if(a[i].action == 4 || a[i].action == 5 || a[i].action == 6)
					msgTag += 1
				else if(a[i].action == 1 || a[i].action == 2)
					msgFix += 1
				else if(a[i].action == 3)
					msgAcc += 1
				}
		}
		if(a[i] == document.getElementById('cl_link'+row))
			found = true
		if(a[i].pagename)
			pagename = a[i].pagename
	}
	
	// Ask questions
	if(replacements.length == 0 && !confirm(NoChangesMsg))
		return
	useReflinks = (askReflinks >= 1 && confirm(ReflinksMsg))
	
	// Open window
	//FIXME test for window variable and alert it was not able to close
	try{win.close()}catch(e){}
	try{
		win = open('', pagename.replace(/\W+/, ''), WinFeatures)
		if(!win){
			alert(WindowBlocked)
			return
		}
	}catch(e){
		alert('Exception: unable to open new window, is the old on still open?')
	}
	win.document.writeln('<html><body onload="document.forms[0].submit()">')
	
	win.document.writeln('<form action="' + MergePath + '" method="POST">')
	win.document.writeln('<button style="background:#c44;color:white;border:none;">Loading...</button>')
	win.addField = new Function("name", "value", 'this.document.writeln(\'<input type="hidden" name="\'+name+\'" value="\'+value+\'" accept-charset="utf-8" />\')')
	win.addField('title', unescape(pagename))
	win.addField('wpSection', "")

	// Dynamic edit summary code
	if(EditMsg = getCookie('EditMsg', EditMsg)){
		win.addField('wpSummary', EditMsg)
	}else{
		// Auto edit summary
		if(msgFix && msgTag)
			EditMsg = "Repairing "+msgFix+" and tagging "+msgTag+" external links"
		else if(msgFix && !msgTag)
			EditMsg = (msgFix==1?"Repairing external link":"Repairing "+msgFix+" external links")
		else if(!msgFix && msgTag)
			EditMsg = (msgTag==1?"Tagging dead link":"Tagging "+msgTag+" dead links")
		else if(msgAcc)
			EditMsg = (msgTag==1?"Adding accessdate":"Adding "+msgAcc+" accessdates")
		else
			EditMsg = "Changing external link" + (replacements.length != 1?"s":"")
		if(!pagename.match(/^[a-z][a-z]:/))
			EditMsg += " using [[WP:CHECKLINKS|Checklinks]]"
		else
			EditMsg += " using [[w:WP:CHECKLINKS|Checklinks]]"
		//HACK
		if(replacements.length==0)
			EditMsg = ""
		win.addField('wpSummary', EditMsg)
		EditMsg = null
	}
	win.addField(action, 'Submit')
	win.addField('addons', 'commonfixes')
	if(useReflinks)
		win.addField('addons', 'reflinks')
	
	for(i=0; i<replacements.length; i++) {
		if(replacements[i][0]){
			win.addField(replacements[i][0] + i, replacements[i][1])
			if(replacements[i][2])
				win.addField(replacements[i][0] + i, replacements[i][2])
		}
	}
	win.document.writeln('</form></body></html>')
	win.document.close()
}
// When clicking on links they should bring up the page itself
//
function openLink(element, url) {
	// Find parent row for the link
	tr = element
	while(tr!=document.body && tr.nodeName!='TR')
		tr = tr.parentNode
		
	//showViewer(tr)
	//loadViewer(url?url:element.getAttribute('href'))
	if(tr.nextSibling && tr.nextSibling.className == '') {
		viewer = tr.nextSibling;
	} else {
		viewer = buildGUI();
		insertAfter(tr, viewer);
	
		openViewers += 1;
		warnOnLeave = (openViewers==0?false:true);
	}
	frame = viewer.getElementsByTagName('iframe')[0]
	try{
		frame.contentDocument.location.href = url
	}catch(e){
		frame.src = url    // Safari wont let use setAttribute on SRC due to 'security issues'
	}

	// HACK: Restore the state for the drop downs
	viewer.getElementsByTagName('FORM')[0].action[element.action].checked = true
	
}
function changeLink(node, url) {
	while(node!=document.body && node.nodeName!='TR')
        node = node.parentNode;
	iframe = node.getElementsByTagName('iframe')[0]
	try{
		iframe.contentDocument.location.href = url
	}catch(e){
		iframe.src = url    // Safari wont let use setAttribute on SRC due to 'security issues'
	}

}
function closeLink(node) {
	while(node!=document.body && node.nodeName!='TR')
        node = node.parentNode;
	node.parentNode.removeChild(node)

	openViewers -= 1;
	warnOnLeave = (openViewers==0?false:true);

}
// Initializer, should be broken up into small parts
//
function buildGUI() {
	// Build stuff for iframe browsing
	gui_tr = document.createElement('tr')
	cell = gui_tr.appendChild(document.createElement('td'))

	// Side toolbox
	toolbox = cell.appendChild(document.createElement('div'))
	toolbox.className="toolbox"
	createTools(toolbox)
	
	// Close button
	btnClose = cell.appendChild(document.createElement('a')).appendChild(document.createElement('img'));
	btnClose.src = '../resources/close.gif';
	btnClose.alt = 'close';
	btnClose.parentNode.className="close-button";
	btnClose.parentNode.herf = '#';
	btnClose.parentNode.onclick = function(){closeLink(this)}

	// these are down here since IE barf if the elements don't exist on the page
	//iframe.setAttribute('style', 'width:100%; height:28em; border:none;')
	var frameContainer = cell.appendChild(document.createElement('div'))
	frameContainer.className = "displayframe"
	var iframe = frameContainer.appendChild(document.createElement('iframe'))
	iframe.setAttribute('frameBorder', 'no')
	cell.setAttribute('colSpan', 6)
	
	return gui_tr
}
function tableHooks(tr_start) {

	var tr_all = document.getElementsByTagName('tr')
	var pagename, pagelink

	// TODO: dymaiclly enable row
	for(var i=Last_row; (tr = tr_all[i]); i++) {
		a_all = tr.getElementsByTagName('a')
		for(var j = a_all.length-1; j >=0 && (a = a_all[j]); j--) {
			// IE brafs if we use other event setters
			// using on focus seem to case problem in browser of than firefox
			a.onclick = aClick;
			
			if(a.className.match("external")) {
				a.setAttribute('title', unescape(a.href));
				a.pagename = pagename;
				tr.entryLink = a;
				tr.onclick = trClick;
				a.action = 0;
				a.str = '';
				
				td = a
				while(td!=document.body && td.nodeName!='TD')
					td=td.parentNode
				// slashdot style [domain] after links
				// TODO add class
				insertAfter(a, document.createTextNode(
						a.href.replace(/^.*\/\/+([^\/]*?)([^\/.]*\.[^\/\d]{2,6}|\d+\.\d+\.\d+\.\d+)(:\d+)?(\/.*)$/, ' [$2]')
					)
				);
				node = insertAfter(a, document.createElement('A'))
				node.appendChild(document.createTextNode(' (info)'))
				node.onclick = infoClick
				// Prevent loading of non-HTTP urls
				// Add site icons
				if(a.href.match("http:") || true) {
					/*
					span = document.createElement('SPAN')
					span.setAttribute('style', 
						a.href.replace(/\w+:\/\/([^\/]*).+/, "background-image:url(http://$1/favicon.ico);")
					)
					span.className="siteicon"
					// Wrap the span element around another element
					a.parentNode.insertBefore(span, a)
					span.appendChild(a.parentNode.removeChild(a))
					*/
					img = a.parentNode.insertBefore(document.createElement('IMG'), a)
					img.alt=''
					img.width=16
					img.height=16
					img.className='siteicon'
					img.src=a.href.replace(/[\w+]+:\/\/([^\/]*).*/, "http://$1/favicon.ico")
				}
				if(tr.className.match('dead-0')) {
					if(getNodeText(tr).match('issing trailing')) // Missing trailing "/"
						setAction(a, 1, a.href+'/');
				} else if(tr.className.match('dead-5')) {
					if(!getNodeText(tr).match('dead link')) {
						setAction(a, 4);
					}
				}
				meta = tr.getElementsByTagName('td')[1];
				text = meta.textContent || meta.innerText || "";
				if(tr.className.match('dead-0') &&
				   !text.match(/(retreived|accessed) /i) && 
				   text.match(/(agency|author|coauthors|date|first|issue|journal|language|last|pages|publisher|quote|volume|work|year)=/) &&
				   !text.match(/(accessdate|archivedate|date|issue|journal|volume|quote)=[^\n<>]+/)) {

					button=document.createElement('button')
					button.onclick=buttonClick
					button.innerHTML="Add accessdate"
					meta.appendChild(button)
				}
			} else if(tr.className.match("page")) {
				pagename = a.title
				a.id = 'cl_link'+i

				var tooldrop  = document.createElement("a")
				tooldrop.setAttribute( "href", "javascript:")
				tooldrop.setAttribute( "onclick", 'toolsMenu("'+a.href+'", '+i+', this);return false')
				tooldrop.appendChild( document.createTextNode("Tools \u25bc ") )
				
				var check     = document.createElement("span")
				check.style.styleFloat = "right"
				check.style.cssFloat   = "right"	// Hate IE, HATE IE
				check.style.fontWeight = "normal"
				check.appendChild( tooldrop)

				// Hack 
				check.innerHTML += '<input type="button" onclick="mergeChanges(\'wpDiff\','+i+','+j+');" title="Show which changes you made to the text" value="Save changes" '+(i==0 && tr_all.length == 1 && "disabled" || '')+'/>'
				a.parentNode.insertBefore(check, a)
			}
		}
	}
	Last_row = i
}

// onload initialize
addOnloadHook(function(){
	try{clearInterval(PgUdt)}catch(e){}
	updateTable()
	if(document.getElementById('linktable') ) {
		//buildGUI();
		//insertAfter(document.getElementsByTagName('tr')[0], displayrow) // Hack prt1
		tableHooks()
		//hideViewer() // Hack prt2
	}
})
function updateTable() {
	if(!location.hash.match('#view='))return
	// Hide rows
	flags = location.hash.split(/\D*/)
	for(i=0; (box = document.getElementById('cbxd'+i)); i++) {
		if(flags && flags[i+1])
			box.checked = flags[i+1] & 1
		classVisible('dead-'+i, box.checked)
	}

}
PgUdt = setInterval("updateTable()", 2000)
