PageRenderTime 162ms CodeModel.GetById 57ms app.highlight 46ms RepoModel.GetById 55ms app.codeStats 0ms

/calfSystem.js

http://fallenswordhelper.googlecode.com/
JavaScript | 366 lines | 267 code | 35 blank | 64 comment | 64 complexity | 5b73d54358105040427c704c83bab537 MD5 | raw file
  1// System functions
  2
  3var System = {
  4	init: function() {
  5		Date.prototype.toFormatString = System.formatDate;
  6
  7		Number.prototype.padZero = System.padZero;
  8		String.prototype.repeat = System.repeatString;
  9		if (!String.trim) {
 10			String.prototype.trimLeft  = System.trimLeft;
 11			String.prototype.trimRight = System.trimRight;
 12			String.prototype.trim      = System.trim;
 13		}
 14		Array.prototype.filterBy = System.filterBy;
 15
 16		System.server           = document.location.protocol + "//" + document.location.host + "/";
 17		System.browserVersion   = parseInt(navigator.userAgent.match(/(Firefox|Minefield|IceWeasel)\/(\d+)/i)[2],10);
 18
 19		var imgurls = System.findNode("//img[contains(@src, '/skin/')]");
 20		if (!imgurls) return; //login screen or error loading etc.
 21		var idindex             = imgurls.src.indexOf("/skin/");
 22		System.imageServer      = imgurls.src.substr(0,idindex);
 23		System.imageServerHTTP  = "http://72.29.91.222";
 24
 25		Array.prototype.removeDuplicates = System.removeDuplicates;
 26	},
 27
 28	getValueJSON: function(name) {
 29		var resultJSON=GM_getValue(name);
 30		var result;
 31		if (resultJSON) {
 32			var reviver = function (key, value) {
 33				if (typeof value === 'string') {
 34					var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
 35					if (a) {
 36						return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
 37					}
 38				}
 39				return value;
 40			};
 41			result = JSON.parse(resultJSON, reviver);
 42		}
 43		return result;
 44	},
 45
 46	setValueJSON: function(name, value) {
 47		GM_setValue(name, JSON.stringify(value));
 48	},
 49
 50	findNode: function(xpath, doc) {
 51		var nodes=System.findNodes(xpath, doc);
 52		if (!nodes) return null;
 53		return (nodes[0]);
 54	},
 55
 56	findNodes: function(xpath, doc) {
 57			if (!doc) {
 58				doc=document;
 59			}
 60			var nodes=[];
 61			var findQ = document.evaluate(xpath, doc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
 62			if (findQ.snapshotLength===0) return null;
 63			for (var i=0; i<findQ.snapshotLength; i++) {
 64				nodes.push(findQ.snapshotItem(i));
 65			}
 66			return nodes;
 67	},
 68
 69	findNodeText: function(xpath, doc) {
 70		var node=System.findNode(xpath, doc);
 71		if (!node) return null;
 72		return node.textContent;
 73	},
 74
 75	findNodeInt: function(xpath, doc) {
 76		var node=System.findNode(xpath, doc);
 77		if (!node) return null;
 78		return System.intValue(node.textContent);
 79	},
 80
 81	createDocument: function(details) {
 82		var doc=document.createElement("HTML");
 83		doc.innerHTML=details;
 84		return doc;
 85	},
 86
 87	//~ createDocument: function(str) { // chrome extension must use this createDocument (which not work under Firefox :( )
 88		//~ if (document.documentElement.nodeName != 'HTML') {
 89		    //~ return new DOMParser().parseFromString(str, 'application/xhtml+xml');
 90		//~ }
 91		//~ // FIXME
 92		//~ var html = str.replace(/<script(?:[ \t\r\n][^>]*)?>[\S\s]*?<\/script[ \t\r\n]*>|<\/?(?:i?frame|html|script|object)(?:[ \t\r\n][^<>]*)?>/gi, ' ')
 93		//~ var htmlDoc = document.implementation.createHTMLDocument ?
 94			//~ document.implementation.createHTMLDocument('fsh') :
 95			//~ document.implementation.createDocument(null, 'html', null)
 96		//~ var range = document.createRange()
 97		//~ range.selectNodeContents(document.documentElement)
 98		//~ htmlDoc.documentElement.appendChild(range.createContextualFragment(html))
 99		//~ return htmlDoc
100	//~ },
101
102	formatDateTime: function(aDate) {
103		var result=aDate.toDateString();
104		result += " ";
105		var hh=aDate.getHours();
106		if (hh<10) hh = "0" + hh;
107		var mm=aDate.getMinutes();
108		if (mm<10) mm = "0" + mm;
109		result += hh + ":" + mm;
110		return result;
111	},
112
113	formatDate: function(dateFormat) {
114	    if (!this.valueOf()) return;
115		var months = ['January', 'February', 'March', 'April', 'May', 'June',
116			'July', 'August', 'September', 'October', 'November', 'December'];
117		var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
118
119		var theDate=this;
120		var h;
121
122		return dateFormat.replace(/(yyyy|MMMM|MMM|MM|dddd|ddd|dd|hh|HH|mm|ss|a)/g,
123			function($1) {
124				switch ($1) {
125					case 'yyyy': return theDate.getFullYear();
126					case 'MMMM': return months[theDate.getMonth()];
127					case 'MMM':  return months[theDate.getMonth()].substr(0, 3);
128					case 'MM':   return (theDate.getMonth() + 1).padZero(2);
129					case 'dddd': return days[theDate.getDay()];
130					case 'ddd':  return days[theDate.getDay()].substr(0, 3);
131					case 'dd':   return theDate.getDate().padZero(2);
132					case 'HH':   return theDate.getHours().padZero(2);
133					case 'hh':   return ((h = theDate.getHours() % 12) ? h : 12).padZero(2);
134					case 'mm':   return theDate.getMinutes().padZero(2);
135					case 'ss':   return theDate.getSeconds().padZero(2);
136					case 'a':  return theDate.getHours() < 12 ? 'am' : 'pm';
137				}
138			}
139		);
140	},
141
142	padZero: function(zeroes) {
143		var s=this.toString();
144		var result="0".repeat(zeroes-s.length) + s;
145		return result;
146	},
147
148	filterBy: function(property, value) {
149		return this.filter(function(element, index, array) {return element[property]==value;});
150	},
151
152	repeatString: function(times) {
153		var s = '';
154		for (var i=0; i<times; i++) {
155			s += this;
156		}
157		return s;
158	},
159
160	saveValueForm: function(oForm, name) {
161		var formElement = System.findNode("//input[@name='" + name + "']", oForm);
162		if (formElement.getAttribute("type")=="checkbox") {
163			GM_setValue(name, formElement.checked);
164		} else if (formElement.getAttribute("type")=="radio") {
165			var radioElements = System.findNodes("//input[@name='" + name + "']", 0, oForm);
166			for (var i=0; i<radioElements.length; i++) {
167				var radioElement = radioElements[i];
168				if (radioElement.checked) {
169					GM_setValue(name, radioElement.value);
170				}
171			}
172		} else {
173			GM_setValue(name, formElement.value);
174		}
175	},
176
177	setDefault: function(name, value) {
178		if (GM_getValue(name)==undefined) GM_setValue(name, value);
179	},
180
181	xmlhttp: function(theUrl, func, theCallback) {
182		theUrl=theUrl.replace(System.server, "");
183		if (theUrl.indexOf("http://")<0)
184			theUrl = System.server + theUrl;
185		GM_xmlhttpRequest({
186			method: 'GET',
187			url: theUrl,
188			callback: theCallback,
189			headers: {
190				"User-Agent" : navigator.userAgent,
191				"Referer": document.location,
192				"Cookie" : document.cookie
193			},
194			onload: function(responseDetails) {
195				if (func) {
196					func.call(this, responseDetails.responseText, this.callback);
197				}
198			}
199		});
200	},
201
202	intValue: function(theText) {
203		if (!theText) return 0;
204		return parseInt(theText.replace(/,/g,""),10);
205	},
206
207	getIntFromRegExp: function(theText, rxSearch) {
208		var matches = theText.match(rxSearch);
209		if (matches) {
210			result = parseInt(matches[1],10);
211		} else {
212			result = 0;
213		}
214		return result;
215	},
216
217	addCommas: function(nStr) {
218		var x, x1, x2;
219		nStr += '';
220		x = nStr.split('.');
221		x1 = x[0];
222		x2 = x.length > 1 ? '.' + x[1] : '';
223		var rgx = /(\d+)(\d{3})/;
224		while (rgx.test(x1)) {
225			x1 = x1.replace(rgx, '$1' + ',' + '$2');
226		}
227		return x1 + x2;
228	},
229
230	trim: function() {
231	    return this.trimLeft().trimRight();
232	},
233
234	trimLeft: function() {
235	    return this.replace(/^\s+/,"");
236	},
237
238	trimRight: function() {
239	    return this.replace(/\s+$/,"");
240	},
241
242	removeDuplicates: function (removeBy){
243		var temp=new Array();
244		if (removeBy) {
245			Helper.sortBy = removeBy;
246			this.sort();
247			for(i=0;i<this.length;i++) {
248				var first = this[i];
249				var second = (this[i+1]?this[i+1]:"abc");
250				if(i != this.length && first[removeBy]==second[removeBy]) {continue;}
251				temp[temp.length]=this[i];
252			}
253		} else {
254			this.sort();
255			for(i=0;i<this.length;i++) {
256				var first = this[i];
257				var second = (this[i+1]?this[i+1]:"abc");
258				if(i != this.length && first==second) {continue;}
259				temp[temp.length]=this[i];
260			}
261		}
262		return temp;
263	},
264
265	convertTextToHtml: function(inputText) {
266		return inputText.
267			replace(/</g,"&lt").
268			replace(/>/g,"&gt").
269			replace(/\n/g,"<br>").
270			replace(/\[\/([a-z])]/g,"<\/\$1>").
271			replace(/\[([a-z])\]/g,"<\$1>");
272	},
273
274	generateLiveTable: function(dataArray, outputElement, itemProperty) {
275		throw new Exception("Not ready yet!");
276		/*if (!dataArray) return;
277		var result='<table id="Helper:LiveTableOutput"><tr>' +
278			'<th align="left" sortkey="guildId" sortType="number">Guild</th>' +
279			'<th sortkey="name">Name</th>' +
280			'<th sortkey="level" sortType="number">Level</th></tr>';
281		var item, color;
282		for (var i=0; i<dataArray[itemProperty].length;i++) {
283			item=dataArray[itemProperty][i];
284
285			result+='<tr class="HelperTableRow' + (1 + i % 2) +'">' +
286				'<td><a href="index.php?cmd=guild&amp;subcmd=view&amp;guild_id=' + player.guildId + '">'+
287					'<img width="16" border="0" height="16" src="' + System.imageServerHTTP + '/guilds/' + player.guildId + '_mini.jpg"></a></td>'+
288				'<td><a href="index.php?cmd=profile&player_id='+player.id+'">'+ player.name+'</a></td>' +
289				'<td align="right">' + player.level + '</td>' +
290				'</tr>';
291		}
292		result+='</table>';
293		outputElement.innerHTML=result;
294
295		var theTable=document.getElementById('Helper:OnlinePlayersTable');
296		for (var i=0; i<theTable.rows[0].cells.length; i++) {
297			var cell=theTable.rows[0].cells[i];
298			cell.style.textDecoration="underline";
299			cell.style.cursor="pointer";
300			cell.addEventListener('click', Helper.sortOnlinePlayersTable, true);
301		}*/
302	},
303
304	sortLiveTable: function(evt) {
305		throw new Exception("Not ready yet!");
306		/*Helper.onlinePlayers=System.getValueJSON("onlinePlayers");
307		var headerClicked = evt.target.getAttribute("sortKey");
308		var sortType = evt.target.getAttribute("sortType");
309		if (!sortType) sortType="string";
310		GM_log(headerClicked);
311		// GM_log(Helper.sortBy);
312		GM_log(sortType);
313		// numberSort
314		if (Helper.sortAsc==undefined) Helper.sortAsc=true;
315		if (Helper.sortBy && Helper.sortBy==headerClicked) {
316			Helper.sortAsc=!Helper.sortAsc;
317		}
318		Helper.sortBy=headerClicked;
319
320		switch(sortType) {
321			case "string":
322				Helper.onlinePlayers.players.sort(Helper.stringSort);
323				break;
324			case "number":
325				Helper.onlinePlayers.players.sort(Helper.numberSort);
326				break;
327		}
328		System.generateOnlinePlayersTable();*/
329	},
330
331	parseDate: function(textDate) {
332		timeText = textDate.split(" ")[0];
333		dateText = textDate.split(" ")[1];
334		dayText = dateText.split("/")[0];
335		monthText = dateText.split("/")[1];
336		if (monthText == "Jan") fullMonthText = "January";
337		if (monthText == "Feb") fullMonthText = "February";
338		if (monthText == "Mar") fullMonthText = "March";
339		if (monthText == "Apr") fullMonthText = "April";
340		if (monthText == "May") fullMonthText = "May";
341		if (monthText == "Jun") fullMonthText = "June";
342		if (monthText == "Jul") fullMonthText = "July";
343		if (monthText == "Aug") fullMonthText = "August";
344		if (monthText == "Sep") fullMonthText = "September";
345		if (monthText == "Oct") fullMonthText = "October";
346		if (monthText == "Nov") fullMonthText = "November";
347		if (monthText == "Dec") fullMonthText = "December";
348		yearText = dateText.split("/")[2];
349		dateAsDate = new Date(fullMonthText + " " + dayText + ", " + yearText + " " + timeText + ":00");
350		return dateAsDate;
351	},
352
353	toggleVisibilty: function(evt) {
354		var anItemId=evt.target.getAttribute("linkto");
355		var anItem=document.getElementById(anItemId);
356		var currentVisibility=anItem.style.visibility;
357		anItem.style.visibility=(currentVisibility=="hidden")?"visible":"hidden";
358		anItem.style.display=(currentVisibility=="hidden")?"block":"none";
359		if (GM_getValue(anItemId)) {
360			GM_setValue(anItemId, "");
361		} else{
362			GM_setValue(anItemId, "ON");
363		}
364	}
365};
366System.init();