/*this file contains functions to sort the rows from MyMafia*/
var ver="MMS 0.023", gc=0, DWLIM= 1000, loadfin = false, l,
	mw_url='http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller',
	 view_url = mw_url + '=stats&xw_action=view&xw_city=1&user=' ,
	 promo_url = mw_url + '=group&xw_action=view&xw_city=1&promote=yes&uid=' ,
	 gift_url = mw_url + '=gift&xw_action=view&xw_city=1&target_id=' ,
	 energy_url = mw_url +'=group&xw_action=energy&xw_city=1&p=' ,
	 dummy
	 
	 ;
function $(a) {return document.getElementById(a);}

function nogt(a)
     	{ /*replace < > with & lt;  & gt; for HTML*/
     	a=a.replace(RegExp("<","g"),"&lt;");
     	a=a.replace(RegExp(">","g"),"&gt;");
     	/*alert("nogt:"+a);*/
     	return a
     	}

blKyAr =[ function (r) {
		/*return facebook name from 1st <a href */		
		var a = /"\>(.*?)\<\/a\>/.exec(r);
		if (a) {return a[1];} else {return "";} 
		return gc--;
		}
	,

 function (r) {
		/*return Mafia Wars name from after 1st <a href */		
		var a = /\<\/a\>\<br\>(.*?)\<br\>Level/.exec(r);
		if (a) {return a[1];} else {return "";} 
		}
	,
 function (r) {
		/*return Mafia Wars level */		
		var a = /Level\s+(\d+)\s+\<\/div\>/.exec(r);
		if (a) {return parseInt(a[1]);} else {return 0 ;}
		}
	,
 function (r) {
		/*return fights won */		
		var a = /\<div class\=num\>\<br\>(\d+)\<\/div\>\<div class\=num\>\<br\>(\d+)\<\/div\>\<div class\=num\>\<br\>(\d+)\<\/div\>/.exec(r);
		if (a) {return parseInt(a[1]);} else {return 0 ;}
		}
	,
		
 function (r) {
		/*return Successful Heists */		
		var a = /\<div class\=num\>\<br\>(\d+)\<\/div\>\<div class\=num\>\<br\>(\d+)\<\/div\>\<div class\=num\>\<br\>(\d+)\<\/div\>/.exec(r);
		if (a) {return parseInt(a[2]);} else {return 0 ;}
		}
	,
 function (r) {
		/*return jobs completed */		
		var a = /\<div class\=num\>\<br\>(\d+)\<\/div\>\<div class\=num\>\<br\>(\d+)\<\/div\>\<div class\=num\>\<br\>(\d+)\<\/div\>/.exec(r);
		if (a) {return parseInt(a[3]);} else {return 0 ;}
		}
	,
	bldKeyPN];

	
function bldKeyPN(r) {
	/*return page number */		
	var a = /\<div class\=PN\>\<br\>(\d+)\<\/div\>/.exec(r);
	if (a) {return parseInt(a[1]);} else 
		{alert("bldkeyPN " + r);return 0 ;}
	}

function dosortOLD(bldKey,a2) {
	/*sort the contents of  div id="MMSROWS" by some field */
	var ta = [], ra=[], r, i1, i2, dz="</div>" ,
	p1 = /\<div class\=rowtop\>/,
	p2 = /\<\/a\>\<\/div\>\<div style\="float\: right\; width\: 32px\; padding\-right\: 6px\;"\>/;
	p2 = /\<\/a\>\<\/div\>\<\/div\>\<\/div\>\<\/div\>/ ;
	if ( a2 ) {a=a2; /*special for domerge*/}
	else { a=$("MMSROWS").innerHTML; /*a2 is usually omitted*/} 
	i1 = a.search(p1); /*alert("AdosortOLD first char 1st row="+a.charAt(i1));*/
	while (-1 != i1) {
		i2 = 34+a.search(p2);
		/*alert("i1="+i1+"  i2="+i2);*/
		r = a.substring(i1,i2); /* one row*/
		ta.push([bldKey(r),"\n"+r]);
	/*	if (1 == ta.length) alert("BdosortOLD first char 1st row="+ta[0][1].charAt(0)); */
		a = a.substr(i2);  /*remove row which we just found*/
		i1 = a.search(p1);
		}
	return ta;
	ta.sort( function (a,b) 
		{ /*comparison a<b --> -1  a==b --> 0   a>b --> 1 */
		if (a[0] < b[0]) {return -1;}
		else {if (a[0] == b[0] ) {return 0;}}
		return 1;}
			);
	if (a2) {return ta; /*special for domerge*/}
	for (i1=0; i1 < ta.length; i1++) {ta[i1] = ta[i1][1];}
	$("MMSROWS").innerHTML = ta.join("\n");
}

function cleanRows(a) {
	/*remove leading/trailing junk*/
	var r, i1;
	for (i1=0; i1<a.length; i1++)
		{ r= a[i1][1];
		r = r.substring(r.search("<"),1+r.lastIndexOf(">"))
		a[i1][1] = r;
		}
	return a;
	}

function dosort(a1,a2,a3) {
	/*sort the contents of  div id="MMSROWS" by some field */
	var ta = [], ra=[], r, i1, i2, dz="</div>" , st=new Date(), ft, DBG=false,
bldKRS = [ null,
	/"\>(.*?)\<\/a\>/, /\<\/a\>\<br\>(.*?)\<br\>Level/,
	/Level\s+(\d+)\<\/div\>/, /\<div class\="?num"?\>\<br\>(\d+)\<\/div\>/, 
	/\<div class\="?num"?\>\<br\>\d+\<\/div\>\<div class\="?num"?\>\<br\>(\d+)\<\/div\>/ ,
	/\<div class\="?num"?\>\<br>(\d+)\<\/div\>\<div class\="?PN"?>/,
	/\<div class\="?PN"?\>\<br\>(\d+)\<\/div\>/],
	p1 = /\<div class\=rowtop\>/,
	p2=	/\<\!\-\-R\-\-\>.*?\(.*?\)"\>(.*?)\<\/a\>\<br\>(.*?)\<br\>Level (\d+)\<\/div\>\<div class\="?num"? style.*?\<div class\="?num"?\>\<br\>(\d+)\<\/div\>\<div class\="?num"?\>\<br\>(\d+)\<\/div\>\<div class\="?num"?\>\<br\>(\d+)\<\/div\>.*?class\="?PN"?\>\<br\>(\d+)\<\/div.*?(?=\<\!\-\-R\-\-\>)/g;
	if (!loadfin) {alert("cannot sort until load of page is finished"); return;}
	
if ( a2 ) {a=a2; /*special for domerge*/}
	else { a=$("MMSROWS").innerHTML; /*a2 is usually omitted*/} 
	ta = a.split("<!--R-->"); ta.shift(); ta.pop();
	l = (a.replace(/\n/g, "")).replace(/\r/g, ""); /*kill NL before building key*/
if (a1<3) {
	for (i1=0; i1 < ta.length; i1++) {
		r = ta[i1]; 
		ta[i1] =[ (a=bldKRS[a1].exec(r)) ?a[1]:" ",r];
		}
} else
	for (i1=0; i1 < ta.length; i1++) {
		r = ta[i1]; 
		ta[i1] =[ (a=bldKRS[a1].exec(r)) ?parseInt(a[1]):0,r];
		}

if (DBG) {
	ta0 = dosortOLD(blKyAr[a1-1]);
	ta0 = cleanRows(ta0);
	ta = cleanRows(ta);
	/*alert("first rows old:"+ta0[0][1].substr(0,7)+"  new="+ta[0][1].substr(0,7) ); */
	if (ta.length != ta0.length) alert("dosort length mismat new="+ta.length+" old=ta0.length");
	for (i1=0; i1 < ta.length; i1++) {
		if (ta[i1][0] != ta0[i1][0] ) 
			{alert("dosort value mm ndx="+i1+" keynew="+ta[i1][0]+" oldkey="+ta0[i1][0]+" rowcmp="+(ta[i1][1] == ta0[i1][1]));
			$("RDMV1").innerHTML = nogt(ta[i1][1]);
			$("RDMV2").innerHTML = nogt(ta0[i1][1]);
			return;}
		if ( ta[i1][1] != ta0[i1][1]) {
			if (ta[i1][1].length != ta0[i1][1].length) {
				alert("length mismatch  old="+ta0[i1][1].length +" new="+ ta[i1][1].length);
				}
			for (i2=0; i2<ta.length; i2++)  if (ta[i1][1].charCodeAt(i2) != ta0[i1][1].charCodeAt(i2)) {
				alert("char mismatch at:"+i2+" old="+ta[i1][1].substr(i2,2)+" new="+ta0[i1][1].substr(i2,2) ); break;
				}
			$("RDMV1").innerHTML = nogt(ta[i1][1]);
			$("RDMV2").innerHTML = nogt(ta0[i1][1]);
			return;
		}
		}
}
if ( a1<3 || 7==a1 )
	ta.sort( function (a,b) 
		{ /*comparison a<b --> -1  a==b --> 0   a>b --> 1 */
		 return a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0 );
		})
else ta.sort( function (a,b) {return b[0]-a[0] ;} ); /*descending order for numerics except PN*/ 
	if (a2) {return ta; /*special for domerge*/}
	for (i1=0; i1 < ta.length; i1++)
		{ta[i1]= ta[i1][1];
		if (10 > ta[i1].length) alert ("dosort fin row ["+i1+"] is empty "+ta[i1].length);}
	ta.unshift(""); ta.push("");
	$("MMSROWS").innerHTML = ta.join("<!--R-->"); 
	ft = (new Date());
	mstat("sort time in ms:"+(ft.valueOf() - st.valueOf())+ "row count="+(ta.length-2));
	
	/*alert("end dosort ta.length"+ta.length);*/
}

document.mrgP.mrghide.onclick = function (ev) {
	document.mrgP.style.display="none"; 
	};
document.mrgP.start.onclick = function (ev) {
	domerge()
	};
document.mrgP.onsubmit = function (ev) {
	/*submit maybe*/
	/*alert("onsbit "+ document.mrgP.getElementsByTagName("div") );*/
	domerge();
	/*alert ("returned from domerge to onsubmit ");*/
//e.cancelBubble is supported by IE - this will kill the bubbling process.
	ev.cancelBubble = true;
	ev.returnValue = false;
	ev.preventDefault();
	//e.stopPropagation works only in Firefox.
	if (ev.stopPropagation) {
		ev.stopPropagation();
		
	}
	return false;
	};
/*document.mrgP.onsubmit.preventDefault();*/
function showmrgP(ev) { 
	document.mrgP.style.display="inline"; 
	document.mrgP.nufURL.focus();
	}
$("MMSV").innerHTML = ver;
window.onload = function (ev) {loadfin = true;};
$("SFBN").onclick = function (ev) {	dosort ( 1); } ;
$("SMWN").onclick = function (ev) {	dosort ( 2); } ;
$("SLVL").onclick = function (ev) {	dosort ( 3); } ;
$("SFIT").onclick = function (ev) {	dosort ( 4); } ;
$("SHEI").onclick = function (ev) {	dosort ( 5); } ;
$("SJOB").onclick = function (ev) {	dosort ( 6); } ;
$("SPAG").onclick = function (ev) {	dosort ( 7); } ;
	
function bldKeyPN(r) {
	/*return page number */		
	var a = /\<div class\=PN\>\<br\>(\d+)\<\/div\>/.exec(r);
	if (a) {return parseInt(a[1]);} else 
		{alert("bldkeyPN " + r);return 0 ;}
	}
function doload(l) {
	/* load new window contents */
	if (document.winb.win[0].checked)
		{window.location = l;  /*new URL for this window*/ }
	else { /*load into new window*/
		intW = window.open("","RDM WINDOW");
		intW.location = l ;
		}
	}
function doP(u) { doload(promo_url+u);}
function doE(p,u) { doload(energy_url+p+"&fid="+u);}
function doG(u) { doload(gift_url+u);}

function mstat(a) 
	{/*display error.status message*/
	document.getElementById("stat").innerHTML = nogt(a);
	}

function showDWL() {mstat("DWLIM="+DWLIM);}
function getNewRows() {
	/*read new file which updates document.MMSROWS */
	var l, j, URL, i1;
	URL = document.mrgP.nufURL.value;
	if ("file:" != URL.substring(0,5) )
		{ mstat("URL must point to a file, quitting");
		return null;
		}
	mstat("URL is:"+URL);

	j = new XMLHttpRequest() ;
	j.open("GET",URL,false); /*syn request*/
	try { j.send(); }
	catch (ex){
		/* send failed*/
		mstat("unable to open update file:"+ex);
		return null;
		}
	if (j.status == 0)  /*ftp etc status code rather than HTTP */
		{l = j.responseText;
		}
	else {/*trouble with request */ mstat("attempt to read update file"+URL+ "\n+failed with status:"+j.status+" len ");
	
		return null;
		}
	return l.substring(l.search('<div id="MMSROWS" >'));
	}
function domerge() {
	/* merge this old file with supplementary new file. */
	/* invoked via onsubmit of new file URL (or START button) */
	/* method is to delete rows in old file with page nums which match new file. */
	var i1, r, g=[], prevPN= -1, m, nu, nufPN=[];
	if (!loadfin) {alert("wait for load of page to finish and then retry merge ");return;}
	if (  /Save the source of the new window/.test($("MMSROWS").innerHTML) ) return;
	nu = getNewRows(); /*MMSROWS <div> of new file*/
	if (!nu) return; /*trouble*/
	nu = dosort(7, nu);
/*	alert("nu[0] "+nu[0][0] +"  [1] "+nu[0][1]); */
	for (i1=0; i1<nu.length; i1++)
		if (nu[i1][0] != prevPN ) {prevPN=nu[i1][0]; nufPN.push(prevPN);};
	/*nufPN holds unique page numbers of new file*/
	m = dosort(7, $("MMSROWS").innerHTML); /*old rows sorted by PN */
/*	alert("nufPN is:" + nufPN+ " size of old MMSROWS "+m.length); */
copyold: while ( 0 < m.length)
		{ r= m.shift(); 
		for (i1=0; i1 < nufPN.length; i1++)
			{ if ( r[0] == nufPN[i1]) continue copyold; }
		g.push(r[1]); /*preserve this row*/
		}
	while ( 0 < nu.length) g.push( nu.shift()[1] );
	$("MMSROWS").innerHTML = '<div class="rowtop"><div style="font-size: x-large; font-weight: bolder;">Save the source of the new window</div></div>';
	winWrite(g.join("<!--R-->"), " merged");
	}
	
function winWrite(a, b) {
	var m = document.getElementsByTagName("html")[0].innerHTML;
	m = "<html>"+m.substr(0,document.getElementsByTagName("html")[0].innerHTML.search(/\<div id\="MMSROWS"/));
	m = m.replace(/(\<\/title\>)/,b+"$1")
	m=m+'\n<div id="MMSROWS" >';
	intW = window.open("",self.name+"X");
	intW.document.open();
	intW.document.write(m );
	intW.document.write(a);
	intW.document.write("\n</div></body></html>");
	intW.document.close();
	}

function makeCopy() {
	/*copy window contents into new window to allow save*/
	winWrite($("MMSROWS").innerHTML , " copy");
	}
