PageRenderTime 54ms CodeModel.GetById 2ms app.highlight 43ms RepoModel.GetById 1ms app.codeStats 1ms

/static/scripts/helper_functions.js

https://bitbucket.org/cistrome/cistrome-harvard/
JavaScript | 817 lines | 415 code | 38 blank | 364 comment | 108 complexity | 675341a4304fe144d75ebf35ba25a977 MD5 | raw file
  1/**
  2 * @fileoverview
  3 * 
  4 * ECMAScript <a href="http://www.carto.net/papers/svg/resources/helper_functions.html">helper functions</a>, main purpose is to serve in SVG mapping or other SVG based web applications
  5 *
  6 * This ECMA script library is free software; you can redistribute it and/or
  7 * modify it under the terms of the GNU Lesser General Public
  8 * License as published by the Free Software Foundation; either
  9 * version 2.1 of the License, or (at your option) any later version.
 10 *
 11 * This library is distributed in the hope that it will be useful,
 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 14 * Lesser General Public License for more details.
 15 *
 16 * You should have received a copy of the GNU Lesser General Public
 17 * License along with this library (http://www.carto.net/papers/svg/resources/lesser_gpl.txt); if not, write to the Free Software
 18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 19 *
 20 * Please report bugs and send improvements to neumann@karto.baug.ethz.ch
 21 * If you use these scripts, please link to the original (http://www.carto.net/papers/svg/resources/helper_functions.html)
 22 * somewhere in the source-code-comment or the "about" of your project and give credits, thanks!
 23 * 
 24 * See <a href="js_docs_out/overview-summary-helper_functions.js.html">documentation</a>. 
 25 * 
 26 * @author Andreas Neumann a.neumann@carto.net
 27 * @copyright LGPL 2.1 <a href="http://www.gnu.org/copyleft/lesser.txt">Gnu LGPL 2.1</a>
 28 * @credits Bruce Rindahl, numerous people on svgdevelopers@yahoogroups.com
 29 */
 30
 31//global variables necessary to create elements in these namespaces, do not delete them!!!!
 32
 33/**
 34 * This variable is a shortcut to the full URL of the SVG namespace
 35 * @final
 36 * @type String
 37 */
 38var svgNS = "http://www.w3.org/2000/svg";
 39
 40/**
 41 * This variable is a shortcut to the full URL of the XLink namespace
 42 * @final
 43 * @type String
 44 */
 45var xlinkNS = "http://www.w3.org/1999/xlink";
 46
 47/**
 48 * This variable is a shortcut to the full URL of the attrib namespace
 49 * @final
 50 * @type String
 51 */
 52var cartoNS = "http://www.carto.net/attrib";
 53
 54/**
 55 * This variable is a alias to the full URL of the attrib namespace
 56 * @final
 57 * @type String
 58 */
 59var attribNS = "http://www.carto.net/attrib";
 60
 61/**
 62 * This variable is a alias to the full URL of the Batik extension namespace
 63 * @final
 64 * @type String
 65 */
 66var batikNS = "http://xml.apache.org/batik/ext";
 67
 68/**
 69 * Returns the polar direction from a given vector
 70 * @param {Number} xdiff	the x-part of the vector
 71 * @param {Number} ydiff	the y-part of the vector
 72 * @return direction		the direction in radians
 73 * @type Number
 74 * @version 1.0 (2007-04-30)
 75 * @see #toPolarDist
 76 * @see #toRectX
 77 * @see #toRectY
 78 */
 79function toPolarDir(xdiff,ydiff) {
 80   var direction = (Math.atan2(ydiff,xdiff));
 81   return(direction);
 82}
 83
 84/**
 85 * Returns the polar distance from a given vector
 86 * @param {Number} xdiff	the x-part of the vector
 87 * @param {Number} ydiff	the y-part of the vector
 88 * @return distance			the distance
 89 * @type Number
 90 * @version 1.0 (2007-04-30)
 91 * @see #toPolarDir
 92 * @see #toRectX
 93 * @see #toRectY
 94 */
 95function toPolarDist(xdiff,ydiff) {
 96   var distance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
 97   return(distance);
 98}
 99
100/**
101 * Returns the x-part of a vector from a given direction and distance
102 * @param {Number} direction	the direction (in radians)
103 * @param {Number} distance		the distance
104 * @return x					the x-part of the vector
105 * @type Number
106 * @version 1.0 (2007-04-30)
107 * @see #toPolarDist
108 * @see #toPolarDir
109 * @see #toRectY
110 */
111function toRectX(direction,distance) {
112   var x = distance * Math.cos(direction);
113   return(x);
114}
115
116/**
117 * Returns the y-part of the vector from a given direction and distance
118 * @param {Number} direction	the direction (in radians)
119 * @param {Number} distance		the distance
120 * @return y					the y-part of the vector
121 * @type Number
122 * @version 1.0 (2007-04-30)
123 * @see #toPolarDist
124 * @see #toPolarDir
125 * @see #toRectX
126 */
127function toRectY(direction,distance) {
128   y = distance * Math.sin(direction);
129   return(y);
130}
131
132/**
133 * Converts degrees to radians
134 * @param {Number} deg	the degree value
135 * @return rad			the radians value
136 * @type Number
137 * @version 1.0 (2007-04-30)
138 * @see #RadToDeg
139 */
140function DegToRad(deg) {
141     return (deg / 180.0 * Math.PI);
142}
143
144/**
145 * Converts radians to degrees
146 * @param {Number} rad	the radians value
147 * @return deg			the degree value
148 * @type Number
149 * @version 1.0 (2007-04-30)
150 * @see #DegToRad
151 */
152function RadToDeg(rad) {
153     return (rad / Math.PI * 180.0);
154}
155
156/**
157 * Converts decimal degrees to degrees, minutes, seconds
158 * @param {Number} dd	the decimal degree value
159 * @return degrees		the degree values in the following notation: {deg:degrees,min:minutes,sec:seconds}
160 * @type literal
161 * @version 1.0 (2007-04-30)
162 * @see #dms2dd
163 */
164function dd2dms(dd) {
165        var minutes = (Math.abs(dd) - Math.floor(Math.abs(dd))) * 60;
166        var seconds = (minutes - Math.floor(minutes)) * 60;
167        var minutes = Math.floor(minutes);
168        if (dd >= 0) {
169            var degrees = Math.floor(dd);
170        }
171        else {
172            var degrees = Math.ceil(dd);       
173        }
174        return {deg:degrees,min:minutes,sec:seconds};
175}
176
177/**
178 * Converts degrees, minutes and seconds to decimal degrees
179 * @param {Number} deg	the degree value
180 * @param {Number} min	the minute value
181 * @param {Number} sec	the second value
182 * @return deg			the decimal degree values
183 * @type Number
184 * @version 1.0 (2007-04-30)
185 * @see #dd2dms
186 */
187function dms2dd(deg,min,sec) {
188	if (deg < 0) {
189		return deg - (min / 60) - (sec / 3600);
190	}
191	else {
192		return deg + (min / 60) + (sec / 3600);
193	}
194}
195
196/**
197 * log function, missing in the standard Math object
198 * @param {Number} x	the value where the log function should be applied to
199 * @param {Number} b	the base value for the log function
200 * @return logResult	the result of the log function
201 * @type Number
202 * @version 1.0 (2007-04-30)
203 */
204function log(x,b) {
205	if(b==null) b=Math.E;
206	return Math.log(x)/Math.log(b);
207}
208
209/**
210 * interpolates a value (e.g. elevation) bilinearly based on the position within a cell with 4 corner values
211 * @param {Number} za		the value at the upper left corner of the cell
212 * @param {Number} zb		the value at the upper right corner of the cell
213 * @param {Number} zc		the value at the lower right corner of the cell
214 * @param {Number} zd		the value at the lower left corner of the cell
215 * @param {Number} xpos		the x position of the point where a new value should be interpolated
216 * @param {Number} ypos		the y position of the point where a new value should be interpolated
217 * @param {Number} ax		the x position of the lower left corner of the cell
218 * @param {Number} ay		the y position of the lower left corner of the cell
219 * @param {Number} cellsize	the size of the cell
220 * @return interpol_value	the result of the bilinear interpolation function
221 * @type Number
222 * @version 1.0 (2007-04-30)
223 */
224function intBilinear(za,zb,zc,zd,xpos,ypos,ax,ay,cellsize) { //bilinear interpolation function
225	var e = (xpos - ax) / cellsize;
226	var f = (ypos - ay) / cellsize;
227
228	//calculation of weights
229	var wa = (1 - e) * (1 - f);
230	var wb = e * (1 - f);
231	var wc = e * f;
232	var wd = f * (1 - e);
233
234	var interpol_value = wa * zc + wb * zd + wc * za + wd * zb;
235	return interpol_value;	
236}
237
238/**
239 * tests if a given point is left or right of a given line
240 * @param {Number} pointx		the x position of the given point
241 * @param {Number} pointy		the y position of the given point
242 * @param {Number} linex1		the x position of line's start point
243 * @param {Number} liney1		the y position of line's start point
244 * @param {Number} linex2		the x position of line's end point
245 * @param {Number} liney2		the y position of line's end point
246 * @return leftof				the result of the leftOfTest, 1 means leftOf, 0 means rightOf
247 * @type Number (integer, 0|1)
248 * @version 1.0 (2007-04-30)
249 */
250function leftOfTest(pointx,pointy,linex1,liney1,linex2,liney2) {
251	var result = (liney1 - pointy) * (linex2 - linex1) - (linex1 - pointx) * (liney2 - liney1);
252	if (result < 0) {
253		var leftof = 1; //case left of
254	}
255	else {
256		var leftof = 0; //case left of	
257	}
258	return leftof;
259}
260
261/**
262 * calculates the distance between a given point and a given line
263 * @param {Number} pointx		the x position of the given point
264 * @param {Number} pointy		the y position of the given point
265 * @param {Number} linex1		the x position of line's start point
266 * @param {Number} liney1		the y position of line's start point
267 * @param {Number} linex2		the x position of line's end point
268 * @param {Number} liney2		the y position of line's end point
269 * @return distance				the result of the leftOfTest, 1 means leftOf, 0 means rightOf
270 * @type Number
271 * @version 1.0 (2007-04-30)
272 */
273function distFromLine(xpoint,ypoint,linex1,liney1,linex2,liney2) {
274	var dx = linex2 - linex1;
275	var dy = liney2 - liney1;
276	var distance = (dy * (xpoint - linex1) - dx * (ypoint - liney1)) / Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2));
277	return distance;
278}
279
280/**
281 * calculates the angle between two vectors (lines)
282 * @param {Number} ax		the x part of vector a
283 * @param {Number} ay		the y part of vector a
284 * @param {Number} bx		the x part of vector b
285 * @param {Number} by		the y part of vector b
286 * @return angle			the angle in radians
287 * @type Number
288 * @version 1.0 (2007-04-30)
289 * @credits <a href="http://www.mathe-online.at/mathint/vect2/i.html#Winkel">Mathe Online (Winkel)</a>
290 */
291function angleBetwTwoLines(ax,ay,bx,by) {
292	var angle = Math.acos((ax * bx + ay * by) / (Math.sqrt(Math.pow(ax,2) + Math.pow(ay,2)) * Math.sqrt(Math.pow(bx,2) + Math.pow(by,2))));
293	return angle;
294}
295
296/**
297 * calculates the bisector vector for two given vectors
298 * @param {Number} ax		the x part of vector a
299 * @param {Number} ay		the y part of vector a
300 * @param {Number} bx		the x part of vector b
301 * @param {Number} by		the y part of vector b
302 * @return c				the resulting vector as an Array, c[0] is the x part of the vector, c[1] is the y part
303 * @type Array
304 * @version 1.0 (2007-04-30)
305 * @credits <a href="http://www.mathe-online.at/mathint/vect1/i.html#Winkelsymmetrale">Mathe Online (Winkelsymmetrale)</a>
306 * see #calcBisectorAngle
307 *  */
308function calcBisectorVector(ax,ay,bx,by) {
309	var betraga = Math.sqrt(Math.pow(ax,2) + Math.pow(ay,2));
310	var betragb = Math.sqrt(Math.pow(bx,2) + Math.pow(by,2));
311	var c = new Array();
312	c[0] = ax / betraga + bx / betragb;
313	c[1] = ay / betraga + by / betragb;
314	return c;
315}
316
317/**
318 * calculates the bisector angle for two given vectors
319 * @param {Number} ax		the x part of vector a
320 * @param {Number} ay		the y part of vector a
321 * @param {Number} bx		the x part of vector b
322 * @param {Number} by		the y part of vector b
323 * @return angle			the bisector angle in radians
324 * @type Number
325 * @version 1.0 (2007-04-30)
326 * @credits <a href="http://www.mathe-online.at/mathint/vect1/i.html#Winkelsymmetrale">Mathe Online (Winkelsymmetrale)</a>
327 * see #calcBisectorVector
328 * */
329function calcBisectorAngle(ax,ay,bx,by) {
330	var betraga = Math.sqrt(Math.pow(ax,2) + Math.pow(ay,2));
331	var betragb = Math.sqrt(Math.pow(bx,2) + Math.pow(by,2));
332	var c1 = ax / betraga + bx / betragb;
333	var c2 = ay / betraga + by / betragb;
334	var angle = toPolarDir(c1,c2);
335	return angle;
336}
337
338/**
339 * calculates the intersection point of two given lines
340 * @param {Number} line1x1	the x the start point of line 1
341 * @param {Number} line1y1	the y the start point of line 1
342 * @param {Number} line1x2	the x the end point of line 1
343 * @param {Number} line1y2	the y the end point of line 1
344 * @return interSectPoint	the intersection point, interSectPoint.x contains x-part, interSectPoint.y the y-part of the resulting coordinate
345 * @type Object
346 * @version 1.0 (2007-04-30)
347 * @credits <a href="http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/">P. Bourke</a>
348 */
349function intersect2lines(line1x1,line1y1,line1x2,line1y2,line2x1,line2y1,line2x2,line2y2) {
350	var interSectPoint = new Object();
351	var denominator = (line2y2 - line2y1)*(line1x2 - line1x1) - (line2x2 - line2x1)*(line1y2 - line1y1);
352	if (denominator == 0) {
353		alert("lines are parallel");
354	}
355	else {
356		var ua = ((line2x2 - line2x1)*(line1y1 - line2y1) - (line2y2 - line2y1)*(line1x1 - line2x1)) / denominator;
357		var ub = ((line1x2 - line1x1)*(line1y1 - line2y1) - (line1y2 - line1y1)*(line1x1 - line2x1)) / denominator;
358	}
359	interSectPoint["x"] = line1x1 + ua * (line1x2 - line1x1);
360	interSectPoint["y"] = line1y1 + ua * (line1y2 - line1y1);
361	return interSectPoint;
362}
363
364/**
365 * reformats a given number to a string by adding separators at every third digit
366 * @param {String|Number} inputNumber	the input number, can be of type number or string
367 * @param {String} separator			the separator, e.g. ' or ,
368 * @return newString					the intersection point, interSectPoint.x contains x-part, interSectPoint.y the y-part of the resulting coordinate
369 * @type String
370 * @version 1.0 (2007-04-30)
371 */
372function formatNumberString(inputNumber,separator) {
373	//check if of type string, if number, convert it to string
374	if (typeof(inputNumber) == "Number") {
375		var myTempString = inputNumber.toString();
376	}
377	else {
378		var myTempString = inputNumber;
379	}
380	var newString="";
381	//if it contains a comma, it will be split
382	var splitResults = myTempString.split(".");
383	var myCounter = splitResults[0].length;
384	if (myCounter > 3) {
385		while(myCounter > 0) {
386			if (myCounter > 3) {
387				newString = separator + splitResults[0].substr(myCounter - 3,3) + newString;
388			}
389			else {
390				newString = splitResults[0].substr(0,myCounter) + newString;
391			}
392			myCounter -= 3;
393		}
394	}
395	else {
396		newString = splitResults[0];
397	}
398	//concatenate if it contains a comma
399	if (splitResults[1]) {
400		newString = newString + "." + splitResults[1];
401	}
402	return newString;
403}
404
405/**
406 * writes a status text message out to a SVG text element's first child
407 * @param {String} statusText	the text message to be displayed
408 * @version 1.0 (2007-04-30)
409 */
410 function statusChange(statusText) {
411	document.getElementById("statusText").firstChild.nodeValue = "Statusbar: " + statusText;
412}
413
414/**
415 * scales an SVG element, requires that the element has an x and y attribute (e.g. circle, ellipse, use element, etc.)
416 * @param {dom::Event} evt		the evt object that triggered the scaling
417 * @param {Number} factor	the scaling factor
418 * @version 1.0 (2007-04-30)
419 */
420function scaleObject(evt,factor) {
421	//reference to the currently selected object
422	var element = evt.currentTarget;
423	var myX = element.getAttributeNS(null,"x");
424	var myY = element.getAttributeNS(null,"y");
425	var newtransform = "scale(" + factor + ") translate(" + (myX * 1 / factor - myX) + " " + (myY * 1 / factor - myY) +")";
426	element.setAttributeNS(null,'transform', newtransform);
427}
428
429/**
430 * returns the transformation matrix (ctm) for the given node up to the root element
431 * the basic use case is to provide a wrapper function for the missing SVGLocatable.getTransformToElement method (missing in ASV3)
432 * @param {svg::SVGTransformable} node		the node reference for the SVGElement the ctm is queried
433 * @return CTM								the current transformation matrix from the given node to the root element
434 * @type svg::SVGMatrix
435 * @version 1.0 (2007-05-01)
436 * @credits <a href="http://www.kevlindev.com/tutorials/basics/transformations/toUserSpace/index.htm">Kevin Lindsey (toUserSpace)</a>
437 * @see #getTransformToElement
438 */
439function getTransformToRootElement(node) {
440 	try {
441		//this part is for fully conformant players (like Opera, Batik, Firefox, Safari ...)
442		var CTM = node.getTransformToElement(document.documentElement);
443	}
444	catch (ex) {
445		//this part is for ASV3 or other non-conformant players
446		// Initialize our CTM the node's Current Transformation Matrix
447		var CTM = node.getCTM();
448		// Work our way through the ancestor nodes stopping at the SVG Document
449		while ( ( node = node.parentNode ) != document ) {
450			// Multiply the new CTM to the one with what we have accumulated so far
451			CTM = node.getCTM().multiply(CTM);
452		}
453	}
454	return CTM;
455}
456
457/**
458 * returns the transformation matrix (ctm) for the given dom::Node up to a different dom::Node
459 * the basic use case is to provide a wrapper function for the missing SVGLocatable.getTransformToElement method (missing in ASV3)
460 * @param {svg::SVGTransformable} node			the node reference for the element the where the ctm should be calculated from
461 * @param {svg::SVGTransformable} targetNode	the target node reference for the element the ctm should be calculated to
462 * @return CTM									the current transformation matrix from the given node to the target element
463 * @type svg::SVGMatrix
464 * @version 1.0 (2007-05-01)
465 * @credits <a href="http://www.kevlindev.com/tutorials/basics/transformations/toUserSpace/index.htm">Kevin Lindsey (toUserSpace)</a>
466 * @see #getTransformToRootElement
467 */
468function getTransformToElement(node,targetNode) {
469    try {
470        //this part is for fully conformant players
471        var CTM = node.getTransformToElement(targetNode);
472    }
473    catch (ex) {
474  		//this part is for ASV3 or other non-conformant players
475		// Initialize our CTM the node's Current Transformation Matrix
476		var CTM = node.getCTM();
477		// Work our way through the ancestor nodes stopping at the SVG Document
478		while ( ( node = node.parentNode ) != targetNode ) {
479			// Multiply the new CTM to the one with what we have accumulated so far
480			CTM = node.getCTM().multiply(CTM);
481		}
482    }
483    return CTM;
484}
485
486/**
487 * converts HSV to RGB values
488 * @param {Number} hue		the hue value (between 0 and 360)
489 * @param {Number} sat		the saturation value (between 0 and 1)
490 * @param {Number} val		the value value (between 0 and 1)
491 * @return rgbArr			the rgb values (associative array or object, the keys are: red,green,blue), all values are scaled between 0 and 255
492 * @type Object
493 * @version 1.0 (2007-05-01)
494 * @see #rgb2hsv
495 */
496function hsv2rgb(hue,sat,val) {
497	var rgbArr = new Object();
498	if ( sat == 0) {
499		rgbArr["red"] = Math.round(val * 255);
500		rgbArr["green"] = Math.round(val * 255);
501		rgbArr["blue"] = Math.round(val * 255);
502	}
503	else {
504		var h = hue / 60;
505		var i = Math.floor(h);
506		var f = h - i;
507		if (i % 2 == 0) {
508			f = 1 - f;
509		}
510		var m = val * (1 - sat); 
511		var n = val * (1 - sat * f);
512		switch(i) {
513			case 0:
514				rgbArr["red"] = val;
515				rgbArr["green"] = n;
516				rgbArr["blue"] = m;
517				break;
518			case 1:
519				rgbArr["red"] = n;
520				rgbArr["green"] = val;
521				rgbArr["blue"] = m;
522				break;
523			case 2:
524				rgbArr["red"] = m;
525				rgbArr["green"] = val;
526				rgbArr["blue"] = n;
527				break;
528			case 3:
529				rgbArr["red"] = m;
530				rgbArr["green"] = n;
531				rgbArr["blue"] = val;
532				break;
533			case 4:
534				rgbArr["red"] = n;
535				rgbArr["green"] = m;
536				rgbArr["blue"] = val;
537				break;
538			case 5:
539				rgbArr["red"] = val;
540				rgbArr["green"] = m;
541				rgbArr["blue"] = n;
542				break;
543			case 6:
544				rgbArr["red"] = val;
545				rgbArr["green"] = n;
546				rgbArr["blue"] = m;
547				break;
548		}
549		rgbArr["red"] = Math.round(rgbArr["red"] * 255);
550		rgbArr["green"] = Math.round(rgbArr["green"] * 255);
551		rgbArr["blue"] = Math.round(rgbArr["blue"] * 255);
552	}
553	return rgbArr;
554}
555
556/**
557 * converts RGB to HSV values
558 * @param {Number} red		the hue value (between 0 and 255)
559 * @param {Number} green	the saturation value (between 0 and 255)
560 * @param {Number} blue		the value value (between 0 and 255)
561 * @return hsvArr			the hsv values (associative array or object, the keys are: hue (0-360),sat (0-1),val (0-1))
562 * @type Object
563 * @version 1.0 (2007-05-01)
564 * @see #hsv2rgb
565 */
566function rgb2hsv(red,green,blue) {
567	var hsvArr = new Object();
568	red = red / 255;
569	green = green / 255;
570	blue = blue / 255;
571	myMax = Math.max(red, Math.max(green,blue));
572	myMin = Math.min(red, Math.min(green,blue));
573	v = myMax;
574	if (myMax > 0) {
575		s = (myMax - myMin) / myMax;
576	}
577	else {
578		s = 0;
579	}
580	if (s > 0) {
581		myDiff = myMax - myMin;
582		rc = (myMax - red) / myDiff;
583		gc = (myMax - green) / myDiff;
584		bc = (myMax - blue) / myDiff;
585		if (red == myMax) {
586			h = (bc - gc) / 6;
587		}
588		if (green == myMax) {
589			h = (2 + rc - bc) / 6;
590		}
591		if (blue == myMax) {
592			h = (4 + gc - rc) / 6;
593		}
594	}
595	else {
596		h = 0;
597	}
598	if (h < 0) {
599		h += 1;
600	}
601	hsvArr["hue"] = Math.round(h * 360);
602	hsvArr["sat"] = s;
603	hsvArr["val"] = v;
604	return hsvArr;
605}
606
607/**
608 * populates an array such that it can be addressed by both a key or an index nr,
609 * note that both Arrays need to be of the same length
610 * @param {Array} arrayKeys		the array containing the keys
611 * @param {Array} arrayValues	the array containing the values
612 * @return returnArray			the resulting array containing both associative values and also a regular indexed array
613 * @type Array
614 * @version 1.0 (2007-05-01)
615 */
616function arrayPopulate(arrayKeys,arrayValues) {
617	var returnArray = new Array();
618	if (arrayKeys.length != arrayValues.length) {
619		alert("error: arrays do not have the same length!");
620	}
621	else {
622		for (i=0;i<arrayKeys.length;i++) {
623			returnArray[arrayKeys[i]] = arrayValues[i];
624		}
625	}
626	return returnArray;
627}
628
629/**
630 * Wrapper object for network requests, uses getURL or XMLHttpRequest depending on availability
631 * The callBackFunction receives a XML or text node representing the rootElement
632 * of the fragment received or the return text, depending on the returnFormat. 
633 * See also the following <a href="http://www.carto.net/papers/svg/network_requests/">documentation</a>.
634 * @class this is a wrapper object to provide network request functionality (get|post)
635 * @param {String} url												the URL/IRI of the network resource to be called
636 * @param {Function|Object} callBackFunction						the callBack function or object that is called after the data was received, in case of an object, the method 'receiveData' is called; both the function and the object's 'receiveData' method get 2 return parameters: 'node.firstChild'|text (the root element of the XML or text resource), this.additionalParams (if defined) 
637 * @param {String} returnFormat										the return format, either 'xml' or 'json' (or text)
638 * @param {String} method											the method of the network request, either 'get' or 'post'
639 * @param {String|Undefined} postText								the String containing the post text (optional) or Undefined (if not a 'post' request)
640 * @param {Object|Array|String|Number|Undefined} additionalParams	additional parameters that will be passed to the callBackFunction or object (optional) or Undefined
641 * @return a new getData instance
642 * @type getData
643 * @constructor
644 * @version 1.0 (2007-02-23)
645 */
646function getData(url,callBackFunction,returnFormat,method,postText,additionalParams) {
647	this.url = url;
648	this.callBackFunction = callBackFunction;
649	this.returnFormat = returnFormat;
650	this.method = method;
651	this.additionalParams = additionalParams;
652	if (method != "get" && method != "post") {
653		alert("Error in network request: parameter 'method' must be 'get' or 'post'");
654	}
655	this.postText = postText;
656	this.xmlRequest = null; //@private reference to the XMLHttpRequest object
657} 
658
659/**
660 * triggers the network request defined in the constructor
661 */
662getData.prototype.getData = function() {
663	//call getURL() if available
664	if (window.getURL) {
665		if (this.method == "get") {
666			getURL(this.url,this);
667		}
668		if (this.method == "post") {
669			postURL(this.url,this.postText,this);
670		}
671	}
672	//or call XMLHttpRequest() if available
673	else if (window.XMLHttpRequest) {
674		var _this = this;
675		this.xmlRequest = new XMLHttpRequest();
676		if (this.method == "get") {
677			if (this.returnFormat == "xml") {
678				this.xmlRequest.overrideMimeType("text/xml");
679			}
680			this.xmlRequest.open("GET",this.url,true);
681		}
682		if (this.method == "post") {
683			this.xmlRequest.open("POST",this.url,true);
684		}
685		this.xmlRequest.onreadystatechange = function() {_this.handleEvent()};
686		if (this.method == "get") {
687			this.xmlRequest.send(null);
688		}
689		if (this.method == "post") {
690			//test if postText exists and is of type string
691			var reallyPost = true;
692			if (!this.postText) {
693				reallyPost = false;
694				alert("Error in network post request: missing parameter 'postText'!");
695			}
696			if (typeof(this.postText) != "string") {
697				reallyPost = false;
698				alert("Error in network post request: parameter 'postText' has to be of type 'string')");
699			}
700			if (reallyPost) {
701				this.xmlRequest.send(this.postText);
702			}
703		}
704	}
705	//write an error message if neither method is available
706	else {
707		alert("your browser/svg viewer neither supports window.getURL nor window.XMLHttpRequest!");
708	}	
709}
710
711/**
712 * this is the callback method for the getURL() or postURL() case
713 * @private
714 */
715getData.prototype.operationComplete = function(data) {
716	//check if data has a success property
717	if (data.success) {
718		//parse content of the XML format to the variable "node"
719		if (this.returnFormat == "xml") {
720			//convert the text information to an XML node and get the first child
721			var node = parseXML(data.content,document);
722			//distinguish between a callback function and an object
723			if (typeof(this.callBackFunction) == "function") {
724				this.callBackFunction(node.firstChild,this.additionalParams);
725			}
726			if (typeof(this.callBackFunction) == "object") {
727				this.callBackFunction.receiveData(node.firstChild,this.additionalParams);
728			}
729		}
730		if (this.returnFormat == "json") {
731			if (typeof(this.callBackFunction) == "function") {
732				this.callBackFunction(data.content,this.additionalParams);
733			}
734			if (typeof(this.callBackFunction) == "object") {
735				this.callBackFunction.receiveData(data.content,this.additionalParams);
736			}			
737		}
738	}
739	else {
740		alert("something went wrong with dynamic loading of geometry!");
741	}
742}
743
744/**
745 * this is the callback method for the XMLHttpRequest case
746 * @private
747 */
748getData.prototype.handleEvent = function() {
749	if (this.xmlRequest.readyState == 4) {
750		if (this.returnFormat == "xml") {
751			//we need to import the XML node first
752			var importedNode = document.importNode(this.xmlRequest.responseXML.documentElement,true);
753			if (typeof(this.callBackFunction) == "function") {
754				this.callBackFunction(importedNode,this.additionalParams);
755			}
756			if (typeof(this.callBackFunction) == "object") {
757				this.callBackFunction.receiveData(importedNode,this.additionalParams);
758			}			
759		}
760		if (this.returnFormat == "json") {
761			if (typeof(this.callBackFunction) == "function") {
762				this.callBackFunction(this.xmlRequest.responseText,this.additionalParams);
763			}
764			if (typeof(this.callBackFunction) == "object") {
765				this.callBackFunction.receiveData(this.xmlRequest.responseText,this.additionalParams);
766			}			
767		}		
768	}	
769}
770
771/**
772 * Serializes an XML node and returns a string representation. Wrapper function to hide implementation differences. 
773 * This can be used for debugging purposes or to post data to a server or network resource.
774 * @param {dom::Node} node		the DOM node reference
775 * @return textRepresentation	the String representation of the XML node
776 * @type String
777 * @version 1.0 (2007-05-01)
778 * @see getData
779 */
780function serializeNode(node) {
781  if (typeof XMLSerializer != 'undefined') {
782    return new XMLSerializer().serializeToString(node);
783  }
784  else if (typeof node.xml != 'undefined') {
785    return node.xml;
786  }
787  else if (typeof printNode != 'undefined') {
788    return printNode(node);
789  }
790  else if (typeof Packages != 'undefined') {
791    try {
792      var stringWriter = new java.io.StringWriter();
793      Packages.org.apache.batik.dom.util.DOMUtilities.writeNode(node,stringWriter);
794      return stringWriter.toString();
795    }
796    catch (e) {
797       alert("Sorry, your SVG viewer does not support the printNode/serialize function.");
798       return '';
799    }
800  }
801  else {
802    alert("Sorry, your SVG viewer does not support the printNode/serialize function.");
803    return '';
804  }
805}
806
807/**
808 * Starts a SMIL animation element with the given id by triggering the '.beginElement()' method. 
809 * This is a convenience (shortcut) function. 
810 * @param {String} id		a valid id of a valid SMIL animation element
811 * @version 1.0 (2007-05-01)
812 */
813//starts an animtion with the given id
814//this function is useful in combination with window.setTimeout()
815function startAnimation(id) {
816		document.getElementById(id).beginElement();
817}