/** Common.js script for webchecklinks ******************************
 * 
 * Maintainer: [[User:Dispenser]]
 *
 */
var today = new Date()

// Localizable
if(true || lang=="en") {
	var BreakFreeMsg  = "Something is trying to navigate away.  This would cause you to lose your current work."
	var WindowBlocked = "Could not create window, popup blocker?  Try holding down ctrl or shift while clicking."

	var Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
}

var Tools = new Array(
// $1 = Language
// $2 = Domain (family name)
// $3 = "Namespace" (before including ":")
// $4 = Page name (after :)
	// Wikipedia
	'Talk page', 'http://$1.$2.org/wiki/Talk:$3',
	'Edit', 'http://$1.$2.org/w/index.php?title=$3$4&action=edit',
	'History', 'http://$1.$2.org/w/index.php?title=$3$4&action=history',
	'----',
	'Dablinks', 'http://toolserver.org/~dispenser/cgi-bin/dablinks.py?page=$1:$3$4',
	'History statistics', 'http://vs.aka-online.de/cgi-bin/wppagehiststat.pl?lang=$1&page=$3$4',
	'Traffic', 'http://stats.grok.se/$1/'+today.getUTCFullYear()+(today.getUTCMonth()<9?'0':'')+(today.getUTCMonth()+1)+'/$3$4',
	'WikiBlame', 'http://wikipedia.ramselehof.de/wikiblame.php?lang=$1&project=$2&article=$3$4',
'')

// Varibles
var iframe, displayrow, activeLink
var fired = false			// used to prevent double firings, it needs to be this complicated
var warnOnLeave = false
var Last_row = 0

/* Notes:
    <a> javascript properties
	article:	Name of the article
	action:	0=Do nothing
			1=Replace
			2=append
	str:	Addition string information
	
Can't use setAttribute before the element is on the page
*/
// Library of function
//
function toogleVisible(idName){with(document.getElementById(idName).style){display=(display!=''?'':'none');return (display=='')}}
function trDisplay(a,b){classVisible(a,b);updateFragment();}
function insertAfter(a, b){	return a.parentNode.insertBefore(b, a.nextSibling)	}
function isRegex(s) { return s.match(/[^\\][$^()\[\].|?*+{}]|\\[AZdwsDWSbB]/) && true || false; }
function getNodeText(node){	return node.innerHTML.replace(/<\/?\w+.*?>/g, '').replace(/^\s*|\s*$/g, '')	}
function translate(dict, dlang){
	dlang = dlang.replace(/^([wmnbqsv]:|wikt:|commons:|)([a-z]{2}):.*$/g, "$2")
	return (typeof dict[dlang] != 'undefined' ? dict[dlang] : dict.en)
}

var loadedScripts = {}; // included-scripts tracker
function importScriptURI(url) {
	if (loadedScripts[url]) {
		return null;
	}
	loadedScripts[url] = true;
	var s = document.createElement('script');
	s.setAttribute('src',url);
	s.setAttribute('type','text/javascript');
	document.getElementsByTagName('head')[0].appendChild(s);
	return s;
}

function getCookie(name, defaultValue) {
	cookie = document.cookie.match(name + '=\s*(.*?)(;|$)')
	if(cookie && cookie[1])
		return unescape(cookie[1])
	else
		return defaultValue
}
function setCookie(name, value, expires) {
	if(!expires) expires = 'Jan 1 2037 00:00:00 UTC'
	if(expires == "seesion"){
		document.cookie = name+'='+escape(value)+'; path=/'
	} else {
	document.cookie = name+'='+escape(value)+'; expires='+expires+'; path=/';
	}
}

function updateFragment() {
	flags=[]
	for(var i=0; i<=5; i++){
		flags[i] = (document.getElementById('cbxd'+i).checked?1:0);
	}
	location.hash = '#view='+flags.join(',')
}
function classVisible(trClass, visible) {
	var trs = document.getElementsByTagName('tr')
	for(var i=0; (tr = trs[i]); i++)
		if(tr.className.match(trClass))
			tr.style.display=(visible?'':'none')
	// We may inadvertently hide the attached row
	// A better solution would check if the nextSibling is the displayrow
	if(!visible)
		hideViewer()
}
//
// Support functions
//
function showViewer(tr, url) {
	warnOnLeave = true
	insertAfter(tr, displayrow)
	if(url) loadViewer(url, false)
}
function loadViewer(url, urlSafe) {
	warnOnLeave = !urlSafe	// Not very safe due to unloading scripts
	try{
		iframe.contentDocument.location.href = url
	}catch(e){
		iframe.src = url	// Safari wont let use setAttribute on SRC due to 'security issues'
	}
	document.getElementById('query').value = url
}
function hideViewer() {
	try{
		warnOnLeave = false
		displayrow.parentNode.removeChild(displayrow)
	}catch(e) {}
}
function page(title){
// REMOVE ME?
	document.getElementById('page').value=title;
}
function getTitle(s) {
	// TODO support &ndash; HTML entities
	s = unescape(decodeURI(s)) // FIXME: Double unescaping %2525 -> %25 not %
	s = s.replace(/.*?\[\[([^[\]{|}]+)(\|.*?|)\]].*/g, '$1')
	s = s.replace(/\w+:\/\/secure\.wikimedia\.org\/(\w+)\/([a-z\-]+)\//, 'http://$2.$1.org/')
	s = s.replace(/http:\/\/([a-z\-]+)\.(\w+)\.org\/wiki\/([^{|}\[\]]+).*/i, '$2:$1:$3')
	s = s.replace(/http:\/\/([a-z\-]+)\.(\w+)\.org\/.*?title=([^#&{|}\[\]]+).*/i, '$2:$1:$3')
	s = s.replace(/http:\/\/[a-z0-9\-.]+\/.{12,}?\?.*?page=([^;?&]*).*/i, '$1')
	s = s.replace(/^ *(?:wikimedia:(m)eta|wikimedia:(commons)|(wikt)ionary|wiki(n)ews|wiki(b)ooks|(w)ikipedia|wiki(q)uote|wiki(s)ource|wiki(v)ersity): *([a-z\-]+:) */i, '$1$2$3$4$5$6$7$8$9:$10')
	// Default site
	s = s.replace(/^(?:w:|(wikt:|n:|b:|q:|s:|v:|:|))(en:)?/, '$1')
	return s.replace(/[ _]+/g, ' ').replace(/^\s+|\s+$/g, '')
}
function fixTitle(node) {
	s = getTitle(node.value).replace(/#.*/, '')	// Remove anchor
	node.style.backgroundColor=(s.match(/[#<>\[\]|{}\n\u007F\u0000-\u001F]|%[0-9A-Fa-f]{2}|&\w{2,8};|&#[Xx]?\d{2,4};|^https?:\/\//)?"#F6DFE0":"")
	node.value = s
}
//
// Tools menu
//
function toolsMenu(link, idx, node) {
	div = document.getElementById('tools')
	if(!div){
		div = document.createElement('div')
		div.id = "tools"
		div.style.position = "relative"
		div.style.width  = "12em"
		div.style.height = 0
		div.style.fontWeight = "normal"
	}
	else{
		div.style.display=(div.style.display!=""?"":"none")
	}
	list_html = '<ul class="menu" name="menu" style="position:absolute; right:0; width:12em;" onclick="toolsMenu(\'\', '+idx+');">'
	for(i=0; (title=Tools[i],url=Tools[i+1]); i+=2){
		if(title=='----'){
			list_html += '<li class="hr"><hr/></li>'
			i--
			continue
		} else {
			list_html += link.replace(/\w+:\/*(\w*)\.(\w*)\.\w*\/wiki\/([^:]*)(:?.*)/i, '<li><a href="'+url+'" title="'+unescape(url)+'">'+title+'</a></li>\n')
		}
	}
	div.innerHTML = list_html + '</ul>'
	// attach to ...
	document.getElementById("cl_link"+idx).previousSibling.appendChild(div)
	document.body.onclick = new Function('div=document.getElementById(\'tools\'); if(div && div.style.display!=\'\')setTimeout("div.style.display=\'none\';", 200)')
}

function diffTable(){
	table = document.getElementById('difflib_chg_to0__top');
	wpTextbox1 = document.getElementById('wpTextbox1');
	if(table && (table.textContent || table.innerText)){
		trs = table.getElementsByTagName('TR');
		for(j=0; (tr=trs[j]); j++){
			tr.onclick = diffMenu
		}
	}
}
function diffMenu(e){
	if(!e)var e=window.event
	if(!e.target)e.target=e.srcElement
	var mx = e.pageX||e.clientX
	var my = e.pageY||e.clientY
	var line = this.childNodes[1].textContent

	menu = document.createElement('ul')
	menu.className = "menu"
	document.body.appendChild(menu)
	menu.style.cssText = "position:absolute;left:"+(mx+1)+"px;top:"+(my+1)+"px;width:9em;"

	item = document.createElement('a')
	item.appendChild(document.createTextNode("Select line "+line))
	item.href="javascript:"
	menu.appendChild(document.createElement('li').appendChild(item))

	item = document.createElement('a')
	item.appendChild(document.createTextNode("Undo line "+line))
	item.href="javascript:with(document.getElementById('difflib_chg_to0__top').rows["+this.rowIndex+"]){if(cells[0].textContent){wpTextbox1.value=wpTextbox1.value.replace(cells[5].textContent, cells[2].textContent);style.color='#ccc';}}"
	menu.appendChild(document.createElement('li').appendChild(item))

	tds = this.getElementsByTagName('TD');
//	if(tds[0].textContent && confirm('Would you like to revert line '+tds[1].textContent+'?')){
//		wpTextbox1.value=wpTextbox1.value.replace(tds[5].textContent, tds[2].textContent);
//		this.style.color='#ccc';
//	};

}
// onload initialize
function addOnloadHook(hook) {
	if( window.addEventListener ) {
		window.addEventListener( 'load', hook, false );
	} else if( window.attachEvent ) {
		window.attachEvent( 'onload', hook);
	}
}
// Prevent framebreaker script from taken effect
window.onbeforeunload = function() {
	if(warnOnLeave)
		return BreakFreeMsg 
}
addOnloadHook(function() {
	// add hooks to forms
	for(i=0; (form = document.forms[i]); i++)
		form.onsubmit=form.onsubmit || new Function("warnOnLeave=false");
	//diffTable();
	sortables_init();

	edittoken = location.search.match(/&wpEditToken=([0-9a-zA-Z]*)/)
	autoclick=location.search.match(/&autoclick=([0-9A-Za-z]+)/);
	if(edittoken && document.getElementById('editform')){
		// This probably should be moved into wikipedia.py
		document.getElementById('editform')['wpEditToken'].value = edittoken[1]+'+\\'
		document.getElementById('wpSave').disabled = false;
	}
	// auto submit script
	if(autoclick && document.getElementById(autoclick[1]))
		setTimeout('document.getElementById("'+autoclick[1]+'").click();')
	else 
		document.getElementById('load-msg').style.display = 'none'
})
document.write('<div id="load-msg"><span>Loading...</span></div>');
