//2628==================== iecanvas.js ===============================


/*----------------------------------------------------------------------------\
|                                IE Canvas 1.0                                |
|                       Emulation Initialization Script                       |
|-----------------------------------------------------------------------------|
|                          Created by Emil A Eklund                           |
|                        (http://eae.net/contact/emil)                        |
|-----------------------------------------------------------------------------|
| Implementation of the canvas API for Internet Explorer. Uses VML.           |
|-----------------------------------------------------------------------------|
|                      Copyright (c) 2005 Emil A Eklund                       |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| This program is  free software;  you can redistribute  it and/or  modify it |
| under the terms of the MIT License.                                         |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| Permission  is hereby granted,  free of charge, to  any person  obtaining a |
| copy of this software and associated documentation files (the "Software"),  |
| to deal in the  Software without restriction,  including without limitation |
| the  rights to use, copy, modify,  merge, publish, distribute,  sublicense, |
| and/or  sell copies  of the  Software, and to  permit persons to  whom  the |
| Software is  furnished  to do  so, subject  to  the  following  conditions: |
| The above copyright notice and this  permission notice shall be included in |
| all copies or substantial portions of the Software.                         |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| THE SOFTWARE IS PROVIDED "AS IS",  WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| IMPLIED,  INCLUDING BUT NOT LIMITED TO  THE WARRANTIES  OF MERCHANTABILITY, |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| AUTHORS OR  COPYRIGHT  HOLDERS BE  LIABLE FOR  ANY CLAIM,  DAMAGES OR OTHER |
| LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT OR  OTHERWISE,  ARISING |
| FROM,  OUT OF OR  IN  CONNECTION  WITH  THE  SOFTWARE OR THE  USE OR  OTHER |
| DEALINGS IN THE SOFTWARE.                                                   |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
|                         http://eae.net/license/mit                          |
|-----------------------------------------------------------------------------|
| Dependencies: canvas.htc          - Actual implementation                   |
|-----------------------------------------------------------------------------|
| 2005-12-27 | Work started.                                                  |
| 2005-12-29 | First version posted.                                          |
| 2006-01-03 | Added htcFile argument to ieCanvasInit method.                 |
|-----------------------------------------------------------------------------|
| Created 2005-12-27 | All changes are in the log above. | Updated 2006-01-03 |
\----------------------------------------------------------------------------*/


function ieCanvasInit(htcFile) {
	var ie, opera, a, nodes, i, oVml, oStyle, newNode;

	/*
	 * Only proceed if browser is IE 6 or later (as all other major browsers
	 * support canvas out of the box there is no need to try to emulate for
	 * them, and besides only IE supports VML anyway.
	 */
	ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
	opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
	if ((!ie) || (ie[1] < 6) || (opera)) {
		return;
	}

	/*
	 * Recreate elements, as there is no canvas tag in HTML
	 * The canvas tag is replaced by a new one created using createElement,
	 * even though the same tag name is given the generated tag is slightly
	 * different, it's created prefixed with a XML namespace declaration
	 * <?XML:NAMESPACE PREFIX ="PUBLIC" NS="URN:COMPONENT" />
	 */
	nodes = document.getElementsByTagName('canvas');
	for (i = 0; i < nodes.length; i++) {
		node = nodes[i];
		if (node.getContext) { return; } // Other implementation, abort
		newNode = document.createElement('canvas');
		newNode.id = node.id;
		newNode.style.width  = node.width;
		newNode.style.height = node.height;
		node.parentNode.replaceChild(newNode, node);
	}

	/* Add VML includes and namespace */
	document.namespaces.add("v");
	oVml = document.createElement('object');
	oVml.id = 'VMLRender';
	oVml.codebase = 'vgx.dll';
	oVml.classid = 'CLSID:10072CEC-8CC1-11D1-986E-00A0C955B42E';
	document.body.appendChild(oVml);

	/* Add required css rules */
	if ((!htcFile) || (htcFile == '')) { htcFile = 'scripts/iecanvas.htc'; }
	oStyle = document.createStyleSheet();
	oStyle.addRule('canvas', "behavior: url('" + htcFile + "');");
	oStyle.addRule('v\\:*', "behavior: url(#VMLRender);");
}


//2628==================== utils.js ===============================

function format_as_money(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}
function money_to_float(str)
{
	var pos = str.indexOf(",");
	var str1 = str.substring(0, pos);
	var str2 = str.substring(pos + 1);
	str = str1 + str2;
	if(str.indexOf(",") == -1 && is_numeric(str))
		return parseFloat(str);
	else if(str.indexOf(",") >= 0)
		return money_to_float(str);
	else
		return 0.0;
}
function is_numeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
 
   	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
   return IsNumber;
   
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd-mm-yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
//2628==================== title_scroller.js ===============================


/*
	Copyright 2006 www.cashmain.com. All Rights Reserved
*/

var scroller_should_repeat=true;
var scroller_title="";
var scroller_length=scroller_title.length;
var scroller_start=1;
var scroller_started = false;
var scroller_id = -1;
function scroll_message(message)
{
	scroller_title = message;
	
	scroller_length=scroller_title.length;
	scroller_start=1;
	if(document.title && !scroller_started)
		scroll_title();
}

function scroll_title() {
	scroller_started = true;
	var message = scroller_title.substring(scroller_start, scroller_length) + scroller_title.substring(0, scroller_start);
	document.title = message;
  	scroller_start++;
	if (scroller_start==scroller_length+1){
		scroller_start=0;
		if(!scroller_should_repeat)
			return;
  	} 
	scroller_id  = window.setTimeout("scroll_title()",200)
}


function clear_scroll()
{
	if(scroller_id  != -1){
		window.clearTimeout(scroller_id);
		scroller_started = false;
	}
}

//2628==================== cookies.js ===============================

/*
	Copyright 2006 www.cashmain.com. All Rights Reserved
*/
if (navigator.cookieEnabled == 0) {
  alert("You need to enable cookies for this site to load properly!");
}  
  
  
/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  
  document.cookie = curCookie;
}

/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}


//2628==================== htmlrequest.js ===============================


/*
	Copyright 2006 www.cashmain.com. All Rights Reserved
*/
var READY_STATE_UNINITIALIZED=0;
var READY_STATE_LOADING=1;         
var READY_STATE_LOADED=2;          
var READY_STATE_INTERACTIVE=3;     
var READY_STATE_COMPLETE=4;      
var XHTTP_request = null;
var g_XHTTP_callback;
var g_XHTTP_arg1, g_XHTTP_arg2;

function getXMLHTTPRequest(){
	var xRequest = null;
	if(window.XMLHttpRequest){//Mozilla
		xRequest = new XMLHttpRequest();
	}else if(typeof ActiveXObject != "undefined"){
		xRequest = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xRequest;
}
function onReadyStateChange()
{
	var data = null;
	if (XHTTP_request && XHTTP_request.readyState == READY_STATE_COMPLETE){
		data = XHTTP_request.responseText;
		if(g_XHTTP_callback)
			g_XHTTP_callback(data, g_XHTTP_arg1, g_XHTTP_arg2);
	}
}

function http_request(url, params, httpMethod, callback, arg1, arg2){
	XHTTP_request = getXMLHTTPRequest();
	if (XHTTP_request){
		g_XHTTP_callback = callback;
		g_XHTTP_arg1 = arg1;
		g_XHTTP_arg2 = arg2;
		XHTTP_request.onreadystatechange = onReadyStateChange;
		XHTTP_request.open(httpMethod , url, true);
		XHTTP_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		XHTTP_request.send(params);
	}
}

//2628==================== barchart.js ===============================

var g_barchart_graphics = new Array();

var g_barchart_colors = new Array("#9acd32", "#F9AD11", "#BB0004", "#17BF0F", "#60E8FF", 
							  	  "#C0C0C0", "#FA8072", "#FFC0CB", "#708090", "#B0E0E6");

function get_barchart_graphics(id)
{
	for(var i = 0 ; i < g_barchart_graphics.length; i++){
		if(g_barchart_graphics[i].id == id)
			return g_barchart_graphics[i];
	}
	g_barchart_graphics[g_barchart_graphics.length] = new jsGraphics(id);
	return g_barchart_graphics[g_barchart_graphics.length - 1];
}

var BARCHART_BOTTOM_MARGIN = 30;
var BARCHART_TOP_MARGIN = 5;
var BARCHART_LEFT_MARGIN = 80;
var BARCHART_RIGHT_MARGIN = 5;

var BARCHART_GRIDLINE_COLOR = "#d2f48e";
var BARCHART_ZERO_LINE_COLOR = "#888888";
var BARCHART_TEXT_COLOR = "#000000";

function render_barchart(id, width, height, barchart)
{
	var graphics = get_barchart_graphics(id);
	
	if(graphics == null) return;
	
	graphics.clear();
	
	graphics.setPrintable(false);
	
	graphics.setFont("verdana","10px",Font.NORMAL);
	
	graphics.setColor(BARCHART_GRIDLINE_COLOR);
	graphics.setStroke(1);
	
	graphics.drawRect(BARCHART_LEFT_MARGIN , BARCHART_TOP_MARGIN, 
					  width - BARCHART_LEFT_MARGIN - BARCHART_RIGHT_MARGIN,
					  height - BARCHART_TOP_MARGIN - BARCHART_BOTTOM_MARGIN);
	
	var max_value = barchart.get_maximum_value();
	var min_value = barchart.get_minimum_value();
	
	
	if(max_value == "N/A" || min_value == "N/A") return;	
	if(min_value > 0) 			min_value = 0;
	if(max_value < 0)			max_value = 0;
	
	
	var grid_step = barchart.get_grid_step(5);
	
	var step = (max_value - min_value) / (height - BARCHART_TOP_MARGIN - BARCHART_BOTTOM_MARGIN);
	
	
	
	graphics.setStroke(2);
	graphics.setColor(BARCHART_ZERO_LINE_COLOR);
	if(min_value == 0){
		//draw the zero line
		graphics.drawLine(BARCHART_LEFT_MARGIN, 			height - BARCHART_BOTTOM_MARGIN,
						  width - BARCHART_RIGHT_MARGIN, 	height - BARCHART_BOTTOM_MARGIN);
		
		graphics.setStroke(1);
		graphics.setColor(BARCHART_TEXT_COLOR);

		graphics.drawStringRect(barchart.format_as_money(0) , 0, height - BARCHART_BOTTOM_MARGIN - 5, BARCHART_LEFT_MARGIN - 5,"right");
		
		
		for(var i = grid_step; i < max_value; i += grid_step){
			graphics.setColor(BARCHART_GRIDLINE_COLOR);
			graphics.drawLine(BARCHART_LEFT_MARGIN, 			height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step,
						  	  width - BARCHART_RIGHT_MARGIN, 	height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step);			  	  
			graphics.setColor(BARCHART_TEXT_COLOR);
			graphics.drawStringRect(barchart.format_as_money(i) , 0, height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step - 5, BARCHART_LEFT_MARGIN - 5,	"right");
		}
		
	}else{
		graphics.drawLine(BARCHART_LEFT_MARGIN, 			height - BARCHART_BOTTOM_MARGIN - (0 - min_value) / step,
						  width - BARCHART_RIGHT_MARGIN, 	height - BARCHART_BOTTOM_MARGIN - (0 - min_value) / step);

		graphics.setStroke(1);
		graphics.setColor(BARCHART_TEXT_COLOR);
		
		graphics.drawStringRect(barchart.format_as_money(0) , 0, height - BARCHART_BOTTOM_MARGIN - (0 - min_value) / step - 5, BARCHART_LEFT_MARGIN - 5,	"right");
		
		for(var i = grid_step; i < max_value; i += grid_step){
			graphics.setColor(BARCHART_GRIDLINE_COLOR);
			graphics.drawLine(BARCHART_LEFT_MARGIN, 			height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step,
						  	  width - BARCHART_RIGHT_MARGIN, 	height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step);
			graphics.setColor(BARCHART_TEXT_COLOR);
			graphics.drawStringRect(barchart.format_as_money(i) , 0, height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step - 5, BARCHART_LEFT_MARGIN - 5,	"right");
		}
		for(var i = -grid_step; i > min_value; i -= grid_step){
			graphics.setColor(BARCHART_GRIDLINE_COLOR);
			graphics.drawLine(BARCHART_LEFT_MARGIN, 			height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step,
						  	  width - BARCHART_RIGHT_MARGIN, 	height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step);
			graphics.setColor(BARCHART_TEXT_COLOR);
			graphics.drawStringRect(barchart.format_as_money(i) , 0, height - BARCHART_BOTTOM_MARGIN - (i - min_value) / step - 5, BARCHART_LEFT_MARGIN - 5,	"right");
		}
	}
	

	var barWidth = ((width - BARCHART_RIGHT_MARGIN - BARCHART_LEFT_MARGIN) / 
						(barchart.values[0].length * (barchart.values.length + 1) ));

	for(var i = 0 ; i < barchart.values.length; i++){
		
		for(var j = 0 ; j < barchart.values[0].length; j++){
			
			var barheight = barchart.values[i][j] / step;
			
			
			var offset_x = BARCHART_LEFT_MARGIN + barWidth/2 + (j * (barchart.values.length + 1) + i) * barWidth;
			
			var offset_y = 0;
			
			if(min_value == 0)
				offset_y = height - BARCHART_BOTTOM_MARGIN - barheight;
			else
			{
				if(barheight >= 0)
					offset_y = height - BARCHART_BOTTOM_MARGIN - (0 - min_value) / step - barheight;
				else
				{
					barheight = -barheight;
					offset_y = height - BARCHART_BOTTOM_MARGIN - (0 - min_value) / step;
				}
			}
			
			graphics.setColor(g_barchart_colors[i]);
			
			graphics.fillRect(offset_x, offset_y, barWidth, barheight);
			
			
			//graphics.drawString(barchart.values[i][j] , offset_x, height - 40 - barheight, barWidth,"center");
			if(i == 0){
				graphics.setFont("verdana","10px",Font.NORMAL);
				graphics.setColor(BARCHART_TEXT_COLOR);
				graphics.drawStringRect(barchart.labels[j] , 
										 BARCHART_LEFT_MARGIN + barWidth/2 + barWidth * (barchart.values.length + 1) * j, 
										 height - BARCHART_BOTTOM_MARGIN, 
										 barWidth * (barchart.values.length),"center");
			}
		}
	}
	/*for(var i = 0 ; i < barchart.values.length; i++){
		for(var j = 0 ; j < barchart.values[0].length; j++){
			var barheight = barchart.values[i][j] / step;
			var offset_x = (j * (barchart.values.length + 1) + i) * barWidth;
			//graphics.setColor(g_barchart_colors[i]);
			//graphics.setFont("verdana","12px",Font.NORMAL);
			//graphics.drawString(barchart.values[i][j] , offset_x, height - 40 - barheight, barWidth,"center");
		}
	}*/
	
	graphics.paint();
}

function BarChart(id)
{
	this.id = id;
	this.values = new Array();
	this.labels = new Array();
}

BarChart.prototype.setValues = function (index, values)
{
	this.values[index] = values;
}

BarChart.prototype.getValues = function (index)
{
	if(index >= 0 && index < this.values.length)
		return this.values[index];
	else 
		return null;
}

BarChart.prototype.setLabels = function (label)
{
	this.labels = label;
}

BarChart.prototype.getLabels = function ()
{
	return this.labels;
}

BarChart.prototype.get_minimum_value = function()
{
	var min_value = "N/A";
	for(var i = 0 ; i < this.values.length; i++)
		for(var j = 0 ; j < this.values[i].length; j++)
			if(this.values[i][j] != null && 
					(min_value == "N/A" || min_value > this.values[i][j]))
				min_value =  this.values[i][j];
	return min_value;
}

BarChart.prototype.get_maximum_value = function()
{
	var max_value = "N/A";
	for(var i = 0 ; i < this.values.length; i++)
		for(var j = 0 ; j < this.values[i].length; j++)
			if(this.values[i][j] != null && 
					(max_value == "N/A" || max_value < this.values[i][j]))
				max_value =  this.values[i][j];
	return max_value;
}

BarChart.prototype.get_grid_step = function(number_of_steps)
{
	
	var max = this.get_maximum_value();
	var min = this.get_minimum_value();
	
	if(min >= 0) 	min = 0;
	if(max < 0) 	max = 0;
	
	var step = (max - min)/number_of_steps;
	
	if(step <= 0.0001) 			step = 0.0001;
	else if(step <= 0.0002)		step = 0.0002;
	else if(step <= 0.0005)		step = 0.0005;
	else if(step <= 0.001) 		step = 0.001;
	else if(step <= 0.002)		step = 0.002;
	else if(step <= 0.005)		step = 0.005;
	else if(step <= 0.01)		step = 0.01;
	else if(step <= 0.02)		step = 0.02;
	else if(step <= 0.05)		step = 0.05;
	else if(step <= 0.1)		step = 0.1;
	else if(step <= 0.2)		step = 0.2;
	else if(step <= 0.5)		step = 0.5;
	else if(step <= 1)			step = 1;
	else if(step <= 2)			step = 2;
	else if(step <= 5)			step = 5;
	else if(step <= 10)			step = 10;
	else if(step <= 20)			step = 20;
	else if(step <= 50)			step = 50;
	else if(step <= 100)		step = 100;
	else if(step <= 200)		step = 200;
	else if(step <= 500)		step = 500;
	else if(step <= 1000)		step = 1000;
	else if(step <= 2000)		step = 2000;
	else if(step <= 5000)		step = 5000;
	else if(step <= 10000)		step = 10000;
	else if(step <= 20000)		step = 20000;
	else if(step <= 50000)		step = 50000;
	else if(step <= 100000)		step = 100000;
	else if(step <= 200000)		step = 200000;
	else if(step <= 500000)		step = 500000;
	else if(step <= 1000000)	step = 1000000;
	else if(step <= 2000000)	step = 2000000;
	else if(step <= 5000000)	step = 5000000;
	else if(step <= 10000000)	step = 10000000;
	else if(step <= 20000000)	step = 20000000;
	else if(step <= 50000000)	step = 50000000;
	else step = 100000000;
	return step;
}

BarChart.prototype.format_as_money = function (num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}



//2628==================== piechart_canvas.js ===============================


var g_graphics_map = new Array();
var g_piechart_colors = new Array("#9ACD32", "#F5DEB3", "#D8BFD8", "#D2B48C", "#8CB4D2", 
							  	  "#C0C0C0", "#FA8072", "#FFC0CB", "#708090", "#B0E0E6");



function get_graphics(canvasid)
{
	for(var i = 0 ; i < g_graphics_map.length; i++){
		if(g_graphics_map[i].id == "i_" + canvasid)
			return g_graphics_map[i];
	}
	g_graphics_map[g_graphics_map.length] = new jsGraphics("i_" + canvasid);
	return g_graphics_map[g_graphics_map.length - 1];
}

function drawpie_with_color(canvasid, radius, values, labels, width, height, colors)
{
	try{
		var cum_angle = 0;
		var total_value = 0;
		var canvas = document.getElementById(canvasid);
		
		if(canvas == null) return;
		
		var ctx;
	
		ctx = canvas.getContext('2d');
		
		
		for(var i = 0 ; i < values.length && i< colors.length; i++)
			total_value += values[i];
		ctx.strokeStyle = '#ffffff';
		
		ctx.fillStyle = '#FFDA51';
		ctx.beginPath();
		ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
		ctx.closePath();
		ctx.fill();
		for(var i = 0; i < values.length && i< colors.length; i++){
			var angle = (Math.PI * 2 * values[i]) / total_value;
			if(angle <= (Math.PI * 2 / 360))
				continue;
			if(angle == 0)
				continue;
			if(i < colors.length)
				ctx.fillStyle = colors[i];
			else
				ctx.fillStyle = '#dddddd';
			ctx.beginPath();
			
			ctx.arc(radius, radius, radius - 5, cum_angle + angle, cum_angle, true);
			ctx.lineTo(radius,radius);
			ctx.closePath();
			ctx.fill();
			ctx.stroke();
			cum_angle += angle;
		}
		ctx.save();
		
		var graphics = get_graphics(canvasid);
		if(graphics == null){
			alert("Graphics is null");
			return true;
		}
		
		graphics.clear();
		graphics.setPrintable(true);
		graphics.setColor('black');
		graphics.setFont("verdana","10px",Font.NORMAL);
		
		
		
		for(var i = 0 ; i < labels.length && i< colors.length; i++){
			
			var max_length = ((labels.length > colors.length) ? colors.length: labels.length);
			
			graphics.setColor(colors[max_length - i - 1]);
			graphics.fillRect(radius * 2 + 20, height-i*15 - 15, 13, 13);
			graphics.setColor('black');
			
			if(labels.length > colors.length && i == 0){
				var others_value = 0;
				for(var k = max_length - 1 ; k < labels.length; k++)
					others_value += values[k];
				var percentage = others_value * 100 / total_value;
				percentage = Math.round(percentage * 100) / 100;
				graphics.drawStringRect("Other" + "(" + percentage + "%)", 
										radius * 2 + 50 , height - i * 15 - 15 ,  
										width - (radius * 2), 15 ,"left");
			}else{
				var percentage = values[max_length - i - 1] * 100 / total_value;
				percentage = Math.round(percentage * 100) / 100;
				graphics.drawStringRect(labels[max_length - i - 1] + "(" + percentage + "%)", 
										radius * 2 + 50 , height - i * 15 - 15 ,  
										width - (radius * 2), 15 ,"left");
			}
		}
	
		ctx.save();
		graphics.paint();
		return true;
	}catch(e){
		return true;
	}
}

function drawpie(canvasid, radius, values, labels, width, height)
{
	return drawpie_with_color(canvasid, radius, values, labels, width, height, g_piechart_colors);
}


//2628==================== wz_jsgraphics.js ===============================


/* This notice must be untouched at all times.

wz_jsgraphics.js    v. 2.33
The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de

Copyright (c) 2002-2004 Walter Zorn. All rights reserved.
Created 3. 11. 2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 24. 10. 2005

Performance optimizations for Internet Explorer
by Thomas Frank and John Holdsworth.
fillPolygon method implemented by Matthieu Haller.

High Performance JavaScript Graphics Library.
Provides methods
- to draw lines, rectangles, ellipses, polygons
	with specifiable line thickness,
- to fill rectangles and ellipses
- to draw text.
NOTE: Operations, functions and branching have rather been optimized
to efficiency and speed than to shortness of source code.

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA,
or see http://www.gnu.org/copyleft/lesser.html
*/


var jg_ihtm, jg_ie, jg_fast, jg_dom, jg_moz,
jg_n4 = (document.layers && typeof document.classes != "undefined");


function chkDHTM(x, i)
{
	x = document.body || null;
	jg_ie = x && typeof x.insertAdjacentHTML != "undefined";
	jg_dom = (x && !jg_ie &&
		typeof x.appendChild != "undefined" &&
		typeof document.createRange != "undefined" &&
		typeof (i = document.createRange()).setStartBefore != "undefined" &&
		typeof i.createContextualFragment != "undefined");
	jg_ihtm = !jg_ie && !jg_dom && x && typeof x.innerHTML != "undefined";
	jg_fast = jg_ie && document.all && !window.opera;
	jg_moz = jg_dom && typeof x.style.MozOpacity != "undefined";
}


function pntDoc()
{
	this.wnd.document.write(jg_fast? this.htmRpc() : this.htm);
	this.htm = '';
}


function pntCnvDom()
{
	var x = document.createRange();
	x.setStartBefore(this.cnv);
	x = x.createContextualFragment(jg_fast? this.htmRpc() : this.htm);
	this.cnv.appendChild(x);
	this.htm = '';
}


function pntCnvIe()
{
	this.cnv.insertAdjacentHTML("BeforeEnd", jg_fast? this.htmRpc() : this.htm);
	this.htm = '';
}


function pntCnvIhtm()
{
	this.cnv.innerHTML += this.htm;
	this.htm = '';
}


function pntCnv()
{
	this.htm = '';
}


function mkDiv(x, y, w, h)
{
	this.htm += '<div style="position:absolute;'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:' + w + 'px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
}


function mkDivIe(x, y, w, h)
{
	this.htm += '%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';
}


function mkDivPrt(x, y, w, h)
{
	this.htm += '<div style="position:absolute;'+
		'border-left:' + w + 'px solid ' + this.color + ';'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:0px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
}


function mkLyr(x, y, w, h)
{
	this.htm += '<layer '+
		'left="' + x + '" '+
		'top="' + y + '" '+
		'width="' + w + '" '+
		'height="' + h + '" '+
		'bgcolor="' + this.color + '"><\/layer>\n';
}


var regex =  /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;
function htmRpc()
{
	return this.htm.replace(
		regex,
		'<div style="overflow:hidden;position:absolute;background-color:'+
		'$1;left:$2;top:$3;width:$4;height:$5"></div>\n');
}


function htmPrtRpc()
{
	return this.htm.replace(
		regex,
		'<div style="overflow:hidden;position:absolute;background-color:'+
		'$1;left:$2;top:$3;width:$4;height:$5;border-left:$4px solid $1"></div>\n');
}


function mkLin(x1, y1, x2, y2)
{
	if (x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1;

	if (dx >= dy)
	{
		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx,
		ox = x;
		while ((dx--) > 0)
		{
			++x;
			if (p > 0)
			{
				this.mkDiv(ox, y, x-ox, 1);
				y += yIncr;
				p += pru;
				ox = x;
			}
			else p += pr;
		}
		this.mkDiv(ox, y, x2-ox+1, 1);
	}

	else
	{
		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy,
		oy = y;
		if (y2 <= y1)
		{
			while ((dy--) > 0)
			{
				if (p > 0)
				{
					this.mkDiv(x++, y, 1, oy-y+1);
					y += yIncr;
					p += pru;
					oy = y;
				}
				else
				{
					y += yIncr;
					p += pr;
				}
			}
			this.mkDiv(x2, y2, 1, oy-y2+1);
		}
		else
		{
			while ((dy--) > 0)
			{
				y += yIncr;
				if (p > 0)
				{
					this.mkDiv(x++, oy, 1, y-oy);
					p += pru;
					oy = y;
				}
				else p += pr;
			}
			this.mkDiv(x2, oy, 1, y2-oy+1);
		}
	}
}


function mkLin2D(x1, y1, x2, y2)
{
	if (x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1;

	var s = this.stroke;
	if (dx >= dy)
	{
		if (dx > 0 && s-3 > 0)
		{
			var _s = (s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy) / dx;
			_s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;
		}
		else var _s = s;
		var ad = Math.ceil(s/2);

		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx,
		ox = x;
		while ((dx--) > 0)
		{
			++x;
			if (p > 0)
			{
				this.mkDiv(ox, y, x-ox+ad, _s);
				y += yIncr;
				p += pru;
				ox = x;
			}
			else p += pr;
		}
		this.mkDiv(ox, y, x2-ox+ad+1, _s);
	}

	else
	{
		if (s-3 > 0)
		{
			var _s = (s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy) / dy;
			_s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;
		}
		else var _s = s;
		var ad = Math.round(s/2);

		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy,
		oy = y;
		if (y2 <= y1)
		{
			++ad;
			while ((dy--) > 0)
			{
				if (p > 0)
				{
					this.mkDiv(x++, y, _s, oy-y+ad);
					y += yIncr;
					p += pru;
					oy = y;
				}
				else
				{
					y += yIncr;
					p += pr;
				}
			}
			this.mkDiv(x2, y2, _s, oy-y2+ad);
		}
		else
		{
			while ((dy--) > 0)
			{
				y += yIncr;
				if (p > 0)
				{
					this.mkDiv(x++, oy, _s, y-oy+ad);
					p += pru;
					oy = y;
				}
				else p += pr;
			}
			this.mkDiv(x2, oy, _s, y2-oy+ad+1);
		}
	}
}


function mkLinDott(x1, y1, x2, y2)
{
	if (x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1,
	drw = true;
	if (dx >= dy)
	{
		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx;
		while ((dx--) > 0)
		{
			if (drw) this.mkDiv(x, y, 1, 1);
			drw = !drw;
			if (p > 0)
			{
				y += yIncr;
				p += pru;
			}
			else p += pr;
			++x;
		}
		if (drw) this.mkDiv(x, y, 1, 1);
	}

	else
	{
		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy;
		while ((dy--) > 0)
		{
			if (drw) this.mkDiv(x, y, 1, 1);
			drw = !drw;
			y += yIncr;
			if (p > 0)
			{
				++x;
				p += pru;
			}
			else p += pr;
		}
		if (drw) this.mkDiv(x, y, 1, 1);
	}
}


function mkOv(left, top, width, height)
{
	var a = width>>1, b = height>>1,
	wod = width&1, hod = (height&1)+1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	ox = 0, oy = b,
	aa = (a*a)<<1, bb = (b*b)<<1,
	st = (aa>>1)*(1-(b<<1)) + bb,
	tt = (bb>>1) - aa*((b<<1)-1),
	w, h;
	while (y > 0)
	{
		if (st < 0)
		{
			st += bb*((x<<1)+3);
			tt += (bb<<1)*(++x);
		}
		else if (tt < 0)
		{
			st += bb*((x<<1)+3) - (aa<<1)*(y-1);
			tt += (bb<<1)*(++x) - aa*(((y--)<<1)-3);
			w = x-ox;
			h = oy-y;
			if (w&2 && h&2)
			{
				this.mkOvQds(cx, cy, -x+2, ox+wod, -oy, oy-1+hod, 1, 1);
				this.mkOvQds(cx, cy, -x+1, x-1+wod, -y-1, y+hod, 1, 1);
			}
			else this.mkOvQds(cx, cy, -x+1, ox+wod, -oy, oy-h+hod, w, h);
			ox = x;
			oy = y;
		}
		else
		{
			tt -= aa*((y<<1)-3);
			st -= (aa<<1)*(--y);
		}
	}
	this.mkDiv(cx-a, cy-oy, a-ox+1, (oy<<1)+hod);
	this.mkDiv(cx+ox+wod, cy-oy, a-ox+1, (oy<<1)+hod);
}


function mkOv2D(left, top, width, height)
{
	var s = this.stroke;
	width += s-1;
	height += s-1;
	var a = width>>1, b = height>>1,
	wod = width&1, hod = (height&1)+1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	aa = (a*a)<<1, bb = (b*b)<<1,
	st = (aa>>1)*(1-(b<<1)) + bb,
	tt = (bb>>1) - aa*((b<<1)-1);

	if (s-4 < 0 && (!(s-2) || width-51 > 0 && height-51 > 0))
	{
		var ox = 0, oy = b,
		w, h,
		pxl, pxr, pxt, pxb, pxw;
		while (y > 0)
		{
			if (st < 0)
			{
				st += bb*((x<<1)+3);
				tt += (bb<<1)*(++x);
			}
			else if (tt < 0)
			{
				st += bb*((x<<1)+3) - (aa<<1)*(y-1);
				tt += (bb<<1)*(++x) - aa*(((y--)<<1)-3);
				w = x-ox;
				h = oy-y;

				if (w-1)
				{
					pxw = w+1+(s&1);
					h = s;
				}
				else if (h-1)
				{
					pxw = s;
					h += 1+(s&1);
				}
				else pxw = h = s;
				this.mkOvQds(cx, cy, -x+1, ox-pxw+w+wod, -oy, -h+oy+hod, pxw, h);
				ox = x;
				oy = y;
			}
			else
			{
				tt -= aa*((y<<1)-3);
				st -= (aa<<1)*(--y);
			}
		}
		this.mkDiv(cx-a, cy-oy, s, (oy<<1)+hod);
		this.mkDiv(cx+a+wod-s+1, cy-oy, s, (oy<<1)+hod);
	}

	else
	{
		var _a = (width-((s-1)<<1))>>1,
		_b = (height-((s-1)<<1))>>1,
		_x = 0, _y = _b,
		_aa = (_a*_a)<<1, _bb = (_b*_b)<<1,
		_st = (_aa>>1)*(1-(_b<<1)) + _bb,
		_tt = (_bb>>1) - _aa*((_b<<1)-1),

		pxl = new Array(),
		pxt = new Array(),
		_pxb = new Array();
		pxl[0] = 0;
		pxt[0] = b;
		_pxb[0] = _b-1;
		while (y > 0)
		{
			if (st < 0)
			{
				st += bb*((x<<1)+3);
				tt += (bb<<1)*(++x);
				pxl[pxl.length] = x;
				pxt[pxt.length] = y;
			}
			else if (tt < 0)
			{
				st += bb*((x<<1)+3) - (aa<<1)*(y-1);
				tt += (bb<<1)*(++x) - aa*(((y--)<<1)-3);
				pxl[pxl.length] = x;
				pxt[pxt.length] = y;
			}
			else
			{
				tt -= aa*((y<<1)-3);
				st -= (aa<<1)*(--y);
			}

			if (_y > 0)
			{
				if (_st < 0)
				{
					_st += _bb*((_x<<1)+3);
					_tt += (_bb<<1)*(++_x);
					_pxb[_pxb.length] = _y-1;
				}
				else if (_tt < 0)
				{
					_st += _bb*((_x<<1)+3) - (_aa<<1)*(_y-1);
					_tt += (_bb<<1)*(++_x) - _aa*(((_y--)<<1)-3);
					_pxb[_pxb.length] = _y-1;
				}
				else
				{
					_tt -= _aa*((_y<<1)-3);
					_st -= (_aa<<1)*(--_y);
					_pxb[_pxb.length-1]--;
				}
			}
		}

		var ox = 0, oy = b,
		_oy = _pxb[0],
		l = pxl.length,
		w, h;
		for (var i = 0; i < l; i++)
		{
			if (typeof _pxb[i] != "undefined")
			{
				if (_pxb[i] < _oy || pxt[i] < oy)
				{
					x = pxl[i];
					this.mkOvQds(cx, cy, -x+1, ox+wod, -oy, _oy+hod, x-ox, oy-_oy);
					ox = x;
					oy = pxt[i];
					_oy = _pxb[i];
				}
			}
			else
			{
				x = pxl[i];
				this.mkDiv(cx-x+1, cy-oy, 1, (oy<<1)+hod);
				this.mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);
				ox = x;
				oy = pxt[i];
			}
		}
		this.mkDiv(cx-a, cy-oy, 1, (oy<<1)+hod);
		this.mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);
	}
}


function mkOvDott(left, top, width, height)
{
	var a = width>>1, b = height>>1,
	wod = width&1, hod = height&1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	aa2 = (a*a)<<1, aa4 = aa2<<1, bb = (b*b)<<1,
	st = (aa2>>1)*(1-(b<<1)) + bb,
	tt = (bb>>1) - aa2*((b<<1)-1),
	drw = true;
	while (y > 0)
	{
		if (st < 0)
		{
			st += bb*((x<<1)+3);
			tt += (bb<<1)*(++x);
		}
		else if (tt < 0)
		{
			st += bb*((x<<1)+3) - aa4*(y-1);
			tt += (bb<<1)*(++x) - aa2*(((y--)<<1)-3);
		}
		else
		{
			tt -= aa2*((y<<1)-3);
			st -= aa4*(--y);
		}
		if (drw) this.mkOvQds(cx, cy, -x, x+wod, -y, y+hod, 1, 1);
		drw = !drw;
	}
}


function mkRect(x, y, w, h)
{
	var s = this.stroke;
	this.mkDiv(x, y, w, s);
	this.mkDiv(x+w, y, s, h);
	this.mkDiv(x, y+h, w+s, s);
	this.mkDiv(x, y+s, s, h-s);
}


function mkRectDott(x, y, w, h)
{
	this.drawLine(x, y, x+w, y);
	this.drawLine(x+w, y, x+w, y+h);
	this.drawLine(x, y+h, x+w, y+h);
	this.drawLine(x, y, x, y+h);
}


function jsgFont()
{
	this.PLAIN = 'font-weight:normal;';
	this.BOLD = 'font-weight:bold;';
	this.ITALIC = 'font-style:italic;';
	this.ITALIC_BOLD = this.ITALIC + this.BOLD;
	this.BOLD_ITALIC = this.ITALIC_BOLD;
}
var Font = new jsgFont();


function jsgStroke()
{
	this.DOTTED = -1;
}
var Stroke = new jsgStroke();


function jsGraphics(id, wnd)
{
	this.setColor = new Function('arg', 'this.color = arg.toLowerCase();');

	this.setStroke = function(x)
	{
		this.stroke = x;
		if (!(x+1))
		{
			this.drawLine = mkLinDott;
			this.mkOv = mkOvDott;
			this.drawRect = mkRectDott;
		}
		else if (x-1 > 0)
		{
			this.drawLine = mkLin2D;
			this.mkOv = mkOv2D;
			this.drawRect = mkRect;
		}
		else
		{
			this.drawLine = mkLin;
			this.mkOv = mkOv;
			this.drawRect = mkRect;
		}
	};


	this.setPrintable = function(arg)
	{
		this.printable = arg;
		if (jg_fast)
		{
			this.mkDiv = mkDivIe;
			this.htmRpc = arg? htmPrtRpc : htmRpc;
		}
		else this.mkDiv = jg_n4? mkLyr : arg? mkDivPrt : mkDiv;
	};


	this.setFont = function(fam, sz, sty)
	{
		this.ftFam = fam;
		this.ftSz = sz;
		this.ftSty = sty || Font.PLAIN;
	};


	this.drawPolyline = this.drawPolyLine = function(x, y, s)
	{
		for (var i=0 ; i<x.length-1 ; i++ )
			this.drawLine(x[i], y[i], x[i+1], y[i+1]);
	};


	this.fillRect = function(x, y, w, h)
	{
		this.mkDiv(x, y, w, h);
	};


	this.drawPolygon = function(x, y)
	{
		this.drawPolyline(x, y);
		this.drawLine(x[x.length-1], y[x.length-1], x[0], y[0]);
	};


	this.drawEllipse = this.drawOval = function(x, y, w, h)
	{
		this.mkOv(x, y, w, h);
	};


	this.fillEllipse = this.fillOval = function(left, top, w, h)
	{
		var a = (w -= 1)>>1, b = (h -= 1)>>1,
		wod = (w&1)+1, hod = (h&1)+1,
		cx = left+a, cy = top+b,
		x = 0, y = b,
		ox = 0, oy = b,
		aa2 = (a*a)<<1, aa4 = aa2<<1, bb = (b*b)<<1,
		st = (aa2>>1)*(1-(b<<1)) + bb,
		tt = (bb>>1) - aa2*((b<<1)-1),
		pxl, dw, dh;
		if (w+1) while (y > 0)
		{
			if (st < 0)
			{
				st += bb*((x<<1)+3);
				tt += (bb<<1)*(++x);
			}
			else if (tt < 0)
			{
				st += bb*((x<<1)+3) - aa4*(y-1);
				pxl = cx-x;
				dw = (x<<1)+wod;
				tt += (bb<<1)*(++x) - aa2*(((y--)<<1)-3);
				dh = oy-y;
				this.mkDiv(pxl, cy-oy, dw, dh);
				this.mkDiv(pxl, cy+y+hod, dw, dh);
				ox = x;
				oy = y;
			}
			else
			{
				tt -= aa2*((y<<1)-3);
				st -= aa4*(--y);
			}
		}
		this.mkDiv(cx-a, cy-oy, w+1, (oy<<1)+hod);
	};


/* fillPolygon method, implemented by Matthieu Haller.
This javascript function is an adaptation of the gdImageFilledPolygon for Walter Zorn lib.
C source of GD 1.8.4 found at http://www.boutell.com/gd/

THANKS to Kirsten Schulz for the polygon fixes!

The intersection finding technique of this code could be improved
by remembering the previous intertersection, and by using the slope.
That could help to adjust intersections to produce a nice
interior_extrema. */
	this.fillPolygon = function(array_x, array_y)
	{
		var i;
		var y;
		var miny, maxy;
		var x1, y1;
		var x2, y2;
		var ind1, ind2;
		var ints;

		var n = array_x.length;

		if (!n) return;


		miny = array_y[0];
		maxy = array_y[0];
		for (i = 1; i < n; i++)
		{
			if (array_y[i] < miny)
				miny = array_y[i];

			if (array_y[i] > maxy)
				maxy = array_y[i];
		}
		for (y = miny; y <= maxy; y++)
		{
			var polyInts = new Array();
			ints = 0;
			for (i = 0; i < n; i++)
			{
				if (!i)
				{
					ind1 = n-1;
					ind2 = 0;
				}
				else
				{
					ind1 = i-1;
					ind2 = i;
				}
				y1 = array_y[ind1];
				y2 = array_y[ind2];
				if (y1 < y2)
				{
					x1 = array_x[ind1];
					x2 = array_x[ind2];
				}
				else if (y1 > y2)
				{
					y2 = array_y[ind1];
					y1 = array_y[ind2];
					x2 = array_x[ind1];
					x1 = array_x[ind2];
				}
				else continue;

				 // modified 11. 2. 2004 Walter Zorn
				if ((y >= y1) && (y < y2))
					polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);

				else if ((y == maxy) && (y > y1) && (y <= y2))
					polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);
			}
			polyInts.sort(integer_compare);
			for (i = 0; i < ints; i+=2)
				this.mkDiv(polyInts[i], y, polyInts[i+1]-polyInts[i]+1, 1);
		}
	};


	this.drawString = function(txt, x, y)
	{
		this.htm += '<div style="position:absolute;white-space:nowrap;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'font-family:' +  this.ftFam + ';'+
			'font-size:' + this.ftSz + ';'+
			'color:' + this.color + ';' + this.ftSty + '">'+
			txt +
			'<\/div>';
	};


/* drawStringRect() added by Rick Blommers.
Allows to specify the size of the text rectangle and to align the
text both horizontally (e.g. right) and vertically within that rectangle */
	this.drawStringRect = function(txt, x, y, width, halign)
	{
		this.htm += '<div style="position:absolute;overflow:hidden;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'width:'+width +'px;'+
			'text-align:'+halign+';'+
			'font-family:' +  this.ftFam + ';'+
			'font-size:' + this.ftSz + ';'+
			'color:' + this.color + ';' + this.ftSty + '">'+
			txt +
			'<\/div>';
	};


	this.drawImage = function(imgSrc, x, y, w, h, a)
	{
		this.htm += '<div style="position:absolute;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'width:' +  w + ';'+
			'height:' + h + ';">'+
			'<img src="' + imgSrc + '" width="' + w + '" height="' + h + '"' + (a? (' '+a) : '') + '>'+
			'<\/div>';
	};


	this.clear = function()
	{
		this.htm = "";
		if (this.cnv) this.cnv.innerHTML = this.defhtm;
	};


	this.mkOvQds = function(cx, cy, xl, xr, yt, yb, w, h)
	{
		this.mkDiv(xr+cx, yt+cy, w, h);
		this.mkDiv(xr+cx, yb+cy, w, h);
		this.mkDiv(xl+cx, yb+cy, w, h);
		this.mkDiv(xl+cx, yt+cy, w, h);
	};

	this.setStroke(1);
	this.setFont('verdana,geneva,helvetica,sans-serif', String.fromCharCode(0x31, 0x32, 0x70, 0x78), Font.PLAIN);
	this.color = '#000000';
	this.htm = '';
	this.wnd = wnd || window;

	if (!(jg_ie || jg_dom || jg_ihtm)) chkDHTM();
	if (typeof id != 'string' || !id) this.paint = pntDoc;
	else
	{
		this.cnv = document.all? (this.wnd.document.all[id] || null)
			: document.getElementById? (this.wnd.document.getElementById(id) || null)
			: null;
		this.defhtm = (this.cnv && this.cnv.innerHTML)? this.cnv.innerHTML : '';
		this.paint = jg_dom? pntCnvDom : jg_ie? pntCnvIe : jg_ihtm? pntCnvIhtm : pntCnv;
	}

	this.setPrintable(false);
	this.id = id;
}



function integer_compare(x,y)
{
	return (x < y) ? -1 : ((x > y)*1);
}

//2628==================== datetimepicker.js ==========================
//Javascript name: My Date Time Picker
//Date created: 16-Nov-2003 23:19
//Scripter: TengYong Ng
//Website: http://www.rainforestnet.com
//Copyright (c) 2003 TengYong Ng
//FileName: DateTimePicker.js
//Version: 0.8
//Contact: contact@rainforestnet.com
// Note: Permission given to use this script in ANY kind of applications if
//       header lines are left unchanged.

//Global variables

var winCal;
var dtToday=new Date();
var Cal;
var docCal;
var MonthName=["January", "February", "March", "April", "May", "June","July", 
				"August", "September", "October", "November", "December"];
var WeekDayName=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];	
var exDateTime;//Existing Date and Time

//Configurable parameters
var cnTop="200";//top coordinate of calendar window.
var cnLeft="300";//left coordinate of calendar window
var WindowTitle ="DateTime Picker";//Date Time Picker title.
var WeekChar=3;//number of character for week day. if 2 then Mo,Tu,We. if 3 then Mon,Tue,Wed.
var CellWidth=20;//Width of day cell.
var DateSeparator="-";//Date Separator, you can change it to "/" if you want.
var TimeMode=24;//default TimeMode value. 12 or 24

var ShowLongMonth=true;//Show long month name in Calendar header. example: "January".
var ShowMonthYear=true;//Show Month and Year in Calendar header.
var MonthYearColor="#000000";//Font Color of Month and Year in Calendar header.
var WeekHeadBgColor="#FFDA51";//Background Color in Week header.
var WeekHeadFontColor="#000000";//Font Color in Week header.
var SundayColor="#FFCCFF";//Background color of Sunday.
var SaturdayColor="#eeeef0";//Background color of Saturday.
var WeekDayColor="#FFEA71";//Background color of weekdays.
var FontColor="blue";//color of font in Calendar day cell.
var TodayColor="#F5FFFA";//Background color of today.
var SelDateColor="#F5FFFA";//Backgrond color of selected date in textbox.
var YrSelColor="#blue";//color of font of Year selector.
var ThemeBg="#FFFBB2";//Background image of Calendar window.
//end Configurable parameters
//end Global variable

function NewCal(pCtrl,pFormat,pShowTime,pTimeMode)
{
	Cal=new Calendar(dtToday);
	if ((pShowTime!=null) && (pShowTime))
	{
		Cal.ShowTime=true;
		if ((pTimeMode!=null) &&((pTimeMode=='12')||(pTimeMode=='24')))
		{
			TimeMode=pTimeMode;
		}		
	}	
	if (pCtrl!=null)
		Cal.Ctrl=pCtrl;
	if (pFormat!=null)
		Cal.Format=pFormat.toUpperCase();
	
	exDateTime=document.getElementById(pCtrl).value;
	//exDateTime=document.getElementById(pCtrl).firstChild.nodeValue;
	
	if (exDateTime!="")//Parse Date String
	{
		var Sp1;//Index of Date Separator 1
		var Sp2;//Index of Date Separator 2 
		var tSp1;//Index of Time Separator 1
		var tSp1;//Index of Time Separator 2
		var strMonth;
		var strDate;
		var strYear;
		var intMonth;
		var YearPattern;
		var strHour;
		var strMinute;
		var strSecond;
		//parse month
		Sp1=exDateTime.indexOf(DateSeparator,0)
		Sp2=exDateTime.indexOf(DateSeparator,(parseInt(Sp1)+1));
		
		if ((Cal.Format.toUpperCase()=="DDMMYYYY") || (Cal.Format.toUpperCase()=="DDMMMYYYY"))
		{
			strMonth=exDateTime.substring(Sp1+1,Sp2);
			strDate=exDateTime.substring(0,Sp1);
		}
		else if ((Cal.Format.toUpperCase()=="MMDDYYYY") || (Cal.Format.toUpperCase()=="MMMDDYYYY"))
		{
			strMonth=exDateTime.substring(0,Sp1);
			strDate=exDateTime.substring(Sp1+1,Sp2);
		}
		if (isNaN(strMonth))
			intMonth=Cal.GetMonthIndex(strMonth);
		else
			intMonth=parseInt(strMonth,10)-1;	
		if ((parseInt(intMonth,10)>=0) && (parseInt(intMonth,10)<12))
			Cal.Month=intMonth;
		//end parse month
		//parse Date
		if ((parseInt(strDate,10)<=Cal.GetMonDays()) && (parseInt(strDate,10)>=1))
			Cal.Date=strDate;
		//end parse Date
		//parse year
		strYear=exDateTime.substring(Sp2+1,Sp2+5);
		YearPattern=/^\d{4}$/;
		if (YearPattern.test(strYear))
			Cal.Year=parseInt(strYear,10);
		//end parse year
		//parse time
		if (Cal.ShowTime==true)
		{
			tSp1=exDateTime.indexOf(":",0)
			tSp2=exDateTime.indexOf(":",(parseInt(tSp1)+1));
			strHour=exDateTime.substring(tSp1,(tSp1)-2);
			Cal.SetHour(strHour);
			strMinute=exDateTime.substring(tSp1+1,tSp2);
			Cal.SetMinute(strMinute);
			strSecond=exDateTime.substring(tSp2+1,tSp2+3);
			Cal.SetSecond(strSecond);
		}	
	}
	winCal=window.open("","DateTimePicker","modal=1,toolbar=0,status=0,menubar=0,fullscreen=no,width=220,height=260,resizable=0,top="+cnTop+",left="+cnLeft);
	docCal=winCal.document;
	RenderCal();
}

function RenderCal()
{
	var vCalHeader;
	var vCalData;
	var vCalTime;
	var i;
	var j;
	var SelectStr;
	var vDayCount=0;
	var vFirstDay;

	docCal.open();
	docCal.writeln("<html><head><title>"+WindowTitle+"</title>");
	docCal.writeln("<script>var winMain=window.opener;</script>");
	docCal.writeln("</head><body bgcolor='"+ThemeBg+"' link="+FontColor+" vlink="+FontColor+"><hr style='color:#FFDA51;background-color:#FFDA51;height:5px;'><form name='Calendar'>");

	vCalHeader="<table border=0 cellpadding=1 cellspacing=1 width='100%' align=\"center\" valign=\"top\">\n";
	//Month Selector
	vCalHeader+="<tr>\n<td colspan='7'><table border=0 width='100%' cellpadding=0 cellspacing=0><tr><td align='left'>\n";
	vCalHeader+="<select name=\"MonthSelector\" onChange=\"javascript:winMain.Cal.SwitchMth(this.selectedIndex);winMain.RenderCal();\">\n";
	for (i=0;i<12;i++){
		if (i==Cal.Month)
			SelectStr="Selected";
		else
			SelectStr="";	
		vCalHeader+="<option "+SelectStr+" value >"+MonthName[i]+"\n";
	}
	vCalHeader+="</select></td>";
	//Year selector
	vCalHeader+="\n<td align='right'><a href=\"javascript:winMain.Cal.DecYear();winMain.RenderCal()\"><b><font color=\""+YrSelColor+"\"><</font></b></a><font face=\"Verdana\" color=\""+YrSelColor+"\" size=2><b> "+Cal.Year+" </b></font><a href=\"javascript:winMain.Cal.IncYear();winMain.RenderCal()\"><b><font color=\""+YrSelColor+"\">></font></b></a></td></tr></table></td>\n";
	vCalHeader+="</tr>";
	//Calendar header shows Month and Year
	if (ShowMonthYear)
		vCalHeader+="<tr><td colspan='7'><font face='Verdana' size='2' align='center' color='"+MonthYearColor+"'><b>"+Cal.GetMonthName(ShowLongMonth)+" "+Cal.Year+"</b></font></td></tr>\n";
	//Week day header
	vCalHeader+="<tr bgcolor="+WeekHeadBgColor+">";
	for (i=0;i<7;i++){
		vCalHeader+="<th align='center'>"
		vCalHeader+="<font color='"+WeekHeadFontColor+"' face='Verdana' size='2'>"
						+WeekDayName[i].substr(0,WeekChar)+"</font></th>";
	}
	vCalHeader+="</tr>";	
	docCal.write(vCalHeader);
	
	//Calendar detail
	CalDate=new Date(Cal.Year,Cal.Month);
	CalDate.setDate(1);
	vFirstDay=CalDate.getDay();
	vCalData="<tr>";
	for (i=0;i<vFirstDay;i++)
	{
		vCalData=vCalData+GenCell();
		vDayCount=vDayCount+1;
	}
	for (j=1;j<=Cal.GetMonDays();j++)
	{
		var strCell;
		vDayCount=vDayCount+1;
		if ((j==dtToday.getDate())&&(Cal.Month==dtToday.getMonth())&&(Cal.Year==dtToday.getFullYear()))
			strCell=GenCell(j,true,TodayColor);//Highlight today's date
		else
		{
			if (j==Cal.Date)
			{
				strCell=GenCell(j,true,SelDateColor);
			}
			else
			{	 
				if (vDayCount%7==0)
					strCell=GenCell(j,false,SaturdayColor);
				else if ((vDayCount+6)%7==0)
					strCell=GenCell(j,false,SundayColor);
				else
					strCell=GenCell(j,null,WeekDayColor);
			}		
		}						
		vCalData=vCalData+strCell;

		if((vDayCount%7==0)&&(j<Cal.GetMonDays()))
		{
			vCalData=vCalData+"</tr>\n<tr>";
		}
	}
	docCal.writeln(vCalData);	
	//Time picker
	if (Cal.ShowTime)
	{
		var showHour;
		showHour=Cal.getShowHour();		
		vCalTime="<tr>\n<td colspan='7' align='center'>";
		vCalTime+="<input type='text' name='hour' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+showHour+" onchange=\"javascript:winMain.Cal.SetHour(this.value)\">";
		vCalTime+=" : ";
		vCalTime+="<input type='text' name='minute' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+Cal.Minutes+" onchange=\"javascript:winMain.Cal.SetMinute(this.value)\">";
		vCalTime+=" : ";
		vCalTime+="<input type='text' name='second' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+Cal.Seconds+" onchange=\"javascript:winMain.Cal.SetSecond(this.value)\">";
		if (TimeMode==12)
		{
			var SelectAm =(parseInt(Cal.Hours,10)<12)? "Selected":"";
			var SelectPm =(parseInt(Cal.Hours,10)>=12)? "Selected":"";

			vCalTime+="<select name=\"ampm\" onchange=\"javascript:winMain.Cal.SetAmPm(this.options[this.selectedIndex].value);\">";
			vCalTime+="<option "+SelectAm+" value=\"AM\">AM</option>";
			vCalTime+="<option "+SelectPm+" value=\"PM\">PM<option>";
			vCalTime+="</select>";
		}	
		vCalTime+="\n</td>\n</tr>";
		docCal.write(vCalTime);
	}	
	//end time picker
	docCal.writeln("\n</table>");
	docCal.writeln("<div align='right'><font color='"+MonthYearColor+"' size='-2'>&copy;Copyright 2006 www.cashmain.com.</font></div>");
	docCal.writeln("<hr style='color:#FFDA51;background-color:#FFDA51;height:5px;'/>");
	docCal.writeln("</form></body></html>");
	docCal.close();
}

function GenCell(pValue,pHighLight,pColor)//Generate table cell with value
{
	var PValue;
	var PCellStr;
	var vColor;
	var vHLstr1;//HighLight string
	var vHlstr2;
	var vTimeStr;
	
	if (pValue==null)
		PValue="";
	else
		PValue=pValue;
	
	if (pColor!=null)
		vColor="bgcolor=\""+pColor+"\"";
	else
		vColor="";	
	if ((pHighLight!=null)&&(pHighLight))
		{vHLstr1="color='red'><b>";vHLstr2="</b>";}
	else
		{vHLstr1=">";vHLstr2="";}	
	
	if (Cal.ShowTime)
	{
		vTimeStr="winMain.document.getElementById('"+Cal.Ctrl+"').value+=' '+"+"winMain.Cal.getShowHour()"+"+':'+"+"winMain.Cal.Minutes"+"+':'+"+"winMain.Cal.Seconds";
		if (TimeMode==12)
			vTimeStr+="+' '+winMain.Cal.AMorPM";
	}	
	else
		vTimeStr="";		
	PCellStr="<td "+vColor+" width="+CellWidth+" align='center'><font face='verdana' size='2'"+vHLstr1+"<a href=\"javascript:winMain.dateOnChanged('"+Cal.Ctrl+"');winMain.document.getElementById('"+Cal.Ctrl+"').value='"+Cal.FormatDate(PValue)+"';"+vTimeStr+";window.close();\">"+PValue+"</a>"+vHLstr2+"</font></td>";
	return PCellStr;
}

function Calendar(pDate,pCtrl)
{
	//Properties
	this.Date=pDate.getDate();//selected date
	this.Month=pDate.getMonth();//selected month number
	this.Year=pDate.getFullYear();//selected year in 4 digits
	this.Hours=pDate.getHours();	
	
	if (pDate.getMinutes()<10)
		this.Minutes="0"+pDate.getMinutes();
	else
		this.Minutes=pDate.getMinutes();
	
	if (pDate.getSeconds()<10)
		this.Seconds="0"+pDate.getSeconds();
	else		
		this.Seconds=pDate.getSeconds();
		
	this.MyWindow=winCal;
	this.Ctrl=pCtrl;
	this.Format="ddMMyyyy";
	this.Separator=DateSeparator;
	this.ShowTime=false;
	if (pDate.getHours()<12)
		this.AMorPM="AM";
	else
		this.AMorPM="PM";	
}

function GetMonthIndex(shortMonthName)
{
	for (i=0;i<12;i++)
	{
		if (MonthName[i].substring(0,3).toUpperCase()==shortMonthName.toUpperCase())
		{	return i;}
	}
}
Calendar.prototype.GetMonthIndex=GetMonthIndex;

function IncYear()
{	Cal.Year++;}
Calendar.prototype.IncYear=IncYear;

function DecYear()
{	Cal.Year--;}
Calendar.prototype.DecYear=DecYear;
	
function SwitchMth(intMth)
{	Cal.Month=intMth;}
Calendar.prototype.SwitchMth=SwitchMth;

function SetHour(intHour)
{	
	var MaxHour;
	var MinHour;
	if (TimeMode==24)
	{	MaxHour=23;MinHour=0}
	else if (TimeMode==12)
	{	MaxHour=12;MinHour=1}
	else
		alert("TimeMode can only be 12 or 24");		
	var HourExp=new RegExp("^\\d\\d$");
	if (HourExp.test(intHour) && (parseInt(intHour,10)<=MaxHour) && (parseInt(intHour,10)>=MinHour))
	{	
		if ((TimeMode==12) && (Cal.AMorPM=="PM"))
		{
			if (parseInt(intHour,10)==12)
				Cal.Hours=12;
			else	
				Cal.Hours=parseInt(intHour,10)+12;
		}	
		else if ((TimeMode==12) && (Cal.AMorPM=="AM"))
		{
			if (intHour==12)
				intHour-=12;
			Cal.Hours=parseInt(intHour,10);
		}
		else if (TimeMode==24)
			Cal.Hours=parseInt(intHour,10);	
	}
}
Calendar.prototype.SetHour=SetHour;

function SetMinute(intMin)
{
	var MinExp=new RegExp("^\\d\\d$");
	if (MinExp.test(intMin) && (intMin<60))
		Cal.Minutes=intMin;
}
Calendar.prototype.SetMinute=SetMinute;

function SetSecond(intSec)
{	
	var SecExp=new RegExp("^\\d\\d$");
	if (SecExp.test(intSec) && (intSec<60))
		Cal.Seconds=intSec;
}
Calendar.prototype.SetSecond=SetSecond;

function SetAmPm(pvalue)
{
	this.AMorPM=pvalue;
	if (pvalue=="PM")
	{
		this.Hours=(parseInt(this.Hours,10))+12;
		if (this.Hours==24)
			this.Hours=12;
	}	
	else if (pvalue=="AM")
		this.Hours-=12;	
}
Calendar.prototype.SetAmPm=SetAmPm;

function getShowHour()
{
	var finalHour;
    if (TimeMode==12)
    {
    	if (parseInt(this.Hours,10)==0)
		{
			this.AMorPM="AM";
			finalHour=parseInt(this.Hours,10)+12;	
		}
		else if (parseInt(this.Hours,10)==12)
		{
			this.AMorPM="PM";
			finalHour=12;
		}		
		else if (this.Hours>12)
		{
			this.AMorPM="PM";
			if ((this.Hours-12)<10)
				finalHour="0"+((parseInt(this.Hours,10))-12);
			else
				finalHour=parseInt(this.Hours,10)-12;	
		}
		else
		{
			this.AMorPM="AM";
			if (this.Hours<10)
				finalHour="0"+parseInt(this.Hours,10);
			else
				finalHour=this.Hours;	
		}
	}
	else if (TimeMode==24)
	{
		if (this.Hours<10)
			finalHour="0"+parseInt(this.Hours,10);
		else	
			finalHour=this.Hours;
	}	
	return finalHour;	
}				
Calendar.prototype.getShowHour=getShowHour;		

function GetMonthName(IsLong)
{
	var Month=MonthName[this.Month];
	if (IsLong)
		return Month;
	else
		return Month.substr(0,3);
}
Calendar.prototype.GetMonthName=GetMonthName;

function GetMonDays()//Get number of days in a month
{
	var DaysInMonth=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	if (this.IsLeapYear())
	{
		DaysInMonth[1]=29;
	}	
	return DaysInMonth[this.Month];	
}
Calendar.prototype.GetMonDays=GetMonDays;

function IsLeapYear()
{
	if ((this.Year%4)==0)
	{
		if ((this.Year%100==0) && (this.Year%400)!=0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}
Calendar.prototype.IsLeapYear=IsLeapYear;

function FormatDate(pDate)
{
	if (this.Format.toUpperCase()=="DDMMYYYY")
		return (pDate+DateSeparator+(this.Month+1)+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="DDMMMYYYY")
		return (pDate+DateSeparator+this.GetMonthName(false)+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="MMDDYYYY")
		return ((this.Month+1)+DateSeparator+pDate+DateSeparator+this.Year);
	else if (this.Format.toUpperCase()=="MMMDDYYYY")
		return (this.GetMonthName(false)+DateSeparator+pDate+DateSeparator+this.Year);			
}
Calendar.prototype.FormatDate=FormatDate;

//2628==================== popupmenu.js ===============================

var ie	= document.all
var ns6	= document.getElementById&&!document.all

var isMenu 	= false ;

var menuSelObj = null ;
var overpopupmenu = false;

function document_on_mouse_down(e)
{
	var obj = ns6 ? e.target.parentNode : event.srcElement.parentElement;
	if( isMenu ){
		if( overpopupmenu == false )
		{
			isMenu = false ;
			overpopupmenu = false;
			var menudiv = document.getElementById('menudiv');
			menudiv.style.display = "none" ;
			var index = menudiv.getAttribute("index");
			if(index!=null){
				var shareElement = document.getElementById(SHARE_LABEL + index);
				if(shareElement != null){
					var rate = document.getElementById('rate').value;
					if(rate.length== "")
						rate = 1;
					var purchase_date = document.getElementById('purchase_date').value;
					
					if(purchase_date.length!=0 && isDate(purchase_date) == false){
						alert("Invalid Date: " + purchase_date);
						purchase_date = "";
					}
					if(is_numeric(rate) == false){
						alert("Invalid Exchange Rate: " + rate);
						rate = "1";
					}
					if(rate != null)
						shareElement.setAttribute(EXCHANGE_RATE_ATTRIBUTE, rate);
					if(purchase_date != null)
						shareElement.setAttribute(PURCHASE_DATE_ATTRIBUTE, purchase_date);
						
					renew_table_row(index);
					renew_total_profit();
					save_data_to_cookies();
					
				}
			}
		}
	}
	return true;
}

// POP UP MENU
function show_popup_menu(e)
{
	var	obj = ns6 ? e.target.parentNode : event.srcElement.parentElement;	
	menuSelObj = obj ;
	var menudiv = document.getElementById('menudiv');
	
	if (ns6){
		menudiv.style.left = e.clientX+document.body.scrollLeft;
		menudiv.style.top = e.clientY+document.body.scrollTop;
	}else{
		menudiv.style.pixelLeft = event.clientX+document.body.scrollLeft;
		menudiv.style.pixelTop = event.clientY+document.body.scrollTop;
	}
	menudiv.style.display = "";
	
	isMenu = true;
	return false ;
}

document.onmousedown 	= document_on_mouse_down;
//document.oncontextmenu 	= show_popup_menu;

function dateOnChanged(e)
{
}

//2628==================== sharewatch.js ===============================


var g_table_row_index = 0;
var TABLE_ROW_NAME = "share_row";
var NEWS_ROW_NAME = "news_row";
var NEWS_TD_NAME = "news_td";
var SYMBOL_LABEL = "symbol";
var SHARE_LABEL = "name";
var TIME_LABEL = "time";
var PRICE_LABEL = "price";
var CHANGE_LABEL = "change";
var PURCHASE_LABEL = "purchase";
var AMOUNT_LABEL = "amount";
var PROFIT_LABEL = "profit";

var PURCHASE_DATE_ATTRIBUTE = "purchase_date";
var EXCHANGE_RATE_ATTRIBUTE = "exchange_rate";
var SHARE_NAME_ATTRIBUTE 	= "share_name";

var update_interval = 61;
var g_updating = false;

var g_counter = update_interval;
var g_counterid = 0;

var g_accumulated_profit = 0;
var g_accumulated_loss = 0;
var g_accumulated_interest = 0;
var g_accumulated_fee = 0;

function stop_counter()
{
	var label = document.getElementById("counter");
	window.clearTimeout(g_counterid);
	g_counter = update_interval;
	label.firstChild.nodeValue = "";
}
function run_counter()
{
	var label = document.getElementById("counter");
	label.firstChild.nodeValue = ":" + (--g_counter) + "s";
	g_counterid = window.setTimeout("run_counter()", 1000);
	if(g_counter <= 0)
		updateTable();
}



/*function is_numeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber = true;
	var Char;
   
	for (i = 0; i < sText.length && IsNumber == true; i++){ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
   
}*/

/*<quote>
	<symbol>9522.HK</symbol>
	<companyName>AIR CHINA/MBL WT </companyName>
	<lastTrade>0.265</lastTrade>
	<lastTradeTime>2/22/2006 12:19pm</lastTradeTime>
	<change>-0.01 - -3.64%</change>
</quote>*/
function get_subnode_value(element, tagName)
{
	var elements = element.getElementsByTagName(tagName);
	if(elements.length == 1 && elements[0].getFirstChild() != null)
		return elements[0].getFirstChild().getNodeValue();
	else
		return null;
}
function is_updating()
{
	return g_updating;
}
function set_updating_state(state)
{
	var label = document.getElementById("in_progress");
	if(state == true){
		g_updating = true;
		label.firstChild.nodeValue = g_UPDATING_LABEL;
	}else{
		label.firstChild.nodeValue = g_IDLE_LABEL;
		g_updating = false;
	}
}

function sorting_pairs(pairs)
{
	for(var i = 0 ; i < pairs[0].length; i++){
		for(var j = i + 1 ; j < pairs[0].length; j++){
			if(pairs[1][j] > pairs[1][i]){
				var temp = pairs[1][i];
				pairs[1][i] = pairs[1][j];
				pairs[1][j] = temp;
				
				temp = pairs[0][i];
				pairs[0][i] = pairs[0][j];
				pairs[0][j] = temp;
			}
		}
	}
	return pairs;
}

function renew_total_profit()
{
	var TEXT_CURRENT_VALUE = "Current Value";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_VALUE = "現值";
	
	var TEXT_PROFIT = "Profit";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_PROFIT = "盈利";
	
	var TEXT_LOSS = "Loss";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_LOSS = "虧損";
	
	var TEXT_CAPITAL = "Capital";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CAPITAL = "本金";
	
	var TEXT_CURRENT_CAPITAL = "Current capital";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_CAPITAL = "現貨成本";
	var TEXT_CURRENT_CAPITAL_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Current capital&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_CAPITAL_COMPONENT = "　　(　現貨成本　)";
	
	
	var TEXT_CURRENT_PROFIT = "Current profit";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_PROFIT = "現貨盈利";
	var TEXT_CURRENT_PROFIT_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Current profit&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_PROFIT_COMPONENT = "　　(　現貨盈利　)";
	
	var TEXT_CURRENT_LOSS = "Current loss";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_LOSS = "現貨虧損"; 
	var TEXT_CURRENT_LOSS_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Current loss&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_CURRENT_LOSS_COMPONENT = "　　(　現貨虧損　)"; 

	var TEXT_ACCUMULATED_PROFIT = "Accumulated profit";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_ACCUMULATED_PROFIT = "過往累積盈利"; 
	var TEXT_ACCUMULATED_PROFIT_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Accumulated profit&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_ACCUMULATED_PROFIT_COMPONENT = "　　(過往累積盈利)"; 
	
	var TEXT_ACCUMULATED_LOSS = "Accumulated loss";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_ACCUMULATED_LOSS = "過往累積虧損"; 
	var TEXT_ACCUMULATED_LOSS_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Accumulated loss&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_ACCUMULATED_LOSS_COMPONENT = "　　(過往累積虧損)"; 
	
	var TEXT_ACCUMULATED_INTEREST = "Accumulated interest";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_ACCUMULATED_INTEREST = "過往累積利息"; 
	var TEXT_ACCUMULATED_INTEREST_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Accumulated interest)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_ACCUMULATED_INTEREST_COMPONENT = "　　(過往累積利息)"; 
	
	var TEXT_TRANSACTION_FEE = "Transaction fee";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_TRANSACTION_FEE = "交易成本"; 
	var TEXT_TRANSACTION_FEE_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Transaction fee&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_TRANSACTION_FEE_COMPONENT = "　　(　交易成本　)"; 

	var TEXT_OVERALL_PROFIT_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Overall profit&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_OVERALL_PROFIT_COMPONENT = "　　(　合計盈利　)"; 
	var TEXT_OVERALL_LOSS_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Overall loss&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_OVERALL_LOSS_COMPONENT = "　　(　合計虧損　)"; 
	var TEXT_OVERALL_CAPITAL_COMPONENT = "&nbsp;&nbsp;&nbsp;&nbsp;(&nbsp;Overall capital&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;)";
	if(LANGUAGE == "CHINESE_BIG5") TEXT_OVERALL_CAPITAL_COMPONENT = "　　(　合計成本　)"; 
	
	
	var total_profit = 0;
	var total_capital = 0;
	var total_value = 0;
	
	var profits_pairs = new Array(2);
	var loss_pairs = new Array(2);
	var values_pairs = new Array(2);
	var overall_gain_pairs = new Array(2);
	
	profits_pairs[0] = new Array();//label
	profits_pairs[1] = new Array();//value
	loss_pairs[0] = new Array();
	loss_pairs[1] = new Array();
	values_pairs[0] = new Array();
	values_pairs[1] = new Array();
	overall_gain_pairs[0] = new Array();
	overall_gain_pairs[1] = new Array();
	
	for(var i = 0 ; i < g_table_row_index; i++){
		if(document.getElementById(PURCHASE_LABEL + i) != null){
			var label = document.getElementById(SHARE_LABEL + i).getAttribute(SHARE_NAME_ATTRIBUTE);
			var purchase = document.getElementById(PURCHASE_LABEL + i).firstChild.nodeValue;
			var amount = document.getElementById(AMOUNT_LABEL + i).firstChild.nodeValue;
			var price = document.getElementById(PRICE_LABEL + i).firstChild.nodeValue;
			if(purchase.length > 0 && amount.length > 0 && price.length > 0){
				total_capital += parseFloat(purchase) * parseFloat(amount);
				total_value += parseFloat(price) * parseFloat(amount);
				
				var profit = (parseFloat(price) - parseFloat(purchase)) * parseFloat(amount);
				
				var share_label = document.getElementById(SHARE_LABEL + i);
				var rate = share_label.getAttribute(EXCHANGE_RATE_ATTRIBUTE);
				
				if(rate == null || rate.length == 0)
					rate = 1;
				profit *= parseFloat(rate);
				
				total_profit += profit;
				
				if(profit >= 0){ 	
					profits_pairs[0][profits_pairs[0].length] = label;
					profits_pairs[1][profits_pairs[1].length] = profit;
				}else{
					loss_pairs[0][loss_pairs[0].length] = label;
					loss_pairs[1][loss_pairs[1].length] = -profit;
				}
				
				values_pairs[0][values_pairs[0].length] = label;
				values_pairs[1][values_pairs[1].length] = parseFloat(price) * parseFloat(amount) * rate;
				
				overall_gain_pairs[0][overall_gain_pairs[0].length] = label;
				overall_gain_pairs[1][overall_gain_pairs[1].length] = profit;
			}
		}
	}
	
	profits_pairs = sorting_pairs(profits_pairs);
	values_pairs = sorting_pairs(values_pairs);
	
	var percentage = (total_profit/total_capital)*100;
	document.getElementById("total_profit").firstChild.nodeValue = 
		Math.round(total_profit * 100 ) / 100 + "("+ Math.round(percentage * 100 ) / 100 +"%)";
		
	drawpie("values", 75, values_pairs[1], values_pairs[0], 450, 150)
	drawpie("profit", 75, profits_pairs[1], profits_pairs[0], 450, 150)
	
	
	if(overall_gain_pairs[0].length != 0 && document.getElementById("profit_barchart")){
		var barchart = new BarChart("profit_barchart");
		barchart.setValues(0, overall_gain_pairs[1]);
		barchart.setLabels(overall_gain_pairs[0]);
		render_barchart("profit_barchart", 450, 150, barchart);
	}
	
	if(document.getElementById("origin_vs_profit")){
		if(total_profit >= 0){
			
			var values = new Array();
			var labels = new Array();
			var colors = new Array("#ADD8E6","#ADFF2F");
			values[0] = total_capital;
			values[1] = total_profit;
			labels[0] = TEXT_CAPITAL;
			labels[1] = TEXT_PROFIT;
			drawpie_with_color("origin_vs_profit", 75, values, labels, 450, 150, colors);
		}else{
			var values = new Array();
			var labels = new Array();
			var colors = new Array("#ADD8E6","#FF6347");
			values[0] = total_capital + total_profit;
			values[1] = -total_profit;
			labels[0] = TEXT_CURRENT_VALUE;
			labels[1] = TEXT_LOSS;
			drawpie_with_color("origin_vs_profit", 75, values, labels, 450, 150, colors);
		}
	}
	update_performace_link();	
	
	set_element_value("analysis_current_value", format_as_money(total_value));
	
	var current_components = format_as_money(total_capital) + TEXT_CURRENT_CAPITAL_COMPONENT;
	if(total_profit >= 0)
		current_components += "<br>+ " + format_as_money(total_profit) + TEXT_CURRENT_PROFIT_COMPONENT;
	else
		current_components += "<br>- " + format_as_money(-total_profit) + TEXT_CURRENT_LOSS_COMPONENT;
	set_element_html("analysis_current_components", current_components);
	
	var overall_capital = total_capital 
							+ g_accumulated_fee 
							- g_accumulated_interest
							- g_accumulated_profit 
							+ g_accumulated_loss;
							
	var overall_profit = total_profit 
							+ g_accumulated_profit 
							- g_accumulated_loss 
							+ g_accumulated_interest 
							- g_accumulated_fee;
							
	set_element_value("analysis_overall_capital", format_as_money(overall_capital));
						
	var components = format_as_money(total_capital) + TEXT_CURRENT_CAPITAL_COMPONENT;
	components += "<br>+ " + format_as_money(g_accumulated_fee) + TEXT_TRANSACTION_FEE_COMPONENT;
	components += "<br>- " + format_as_money(g_accumulated_interest) + TEXT_ACCUMULATED_INTEREST_COMPONENT;
	components += "<br>- " + format_as_money(g_accumulated_profit) + TEXT_ACCUMULATED_PROFIT_COMPONENT;
	components += "<br>+ " + format_as_money(g_accumulated_loss) + TEXT_ACCUMULATED_LOSS_COMPONENT;
	
	set_element_html("analysis_overall_capital_components", components);
	
	
	
	set_element_value("analysis_overall_profit", format_as_money(overall_profit));
	
	if(total_profit >= 0)
		components = format_as_money(total_profit) + TEXT_CURRENT_PROFIT_COMPONENT;
	else
		components = format_as_money(total_profit) + TEXT_CURRENT_LOSS_COMPONENT;
	

	components += "<br>+ " + format_as_money(g_accumulated_profit) + TEXT_ACCUMULATED_PROFIT_COMPONENT;
	components += "<br>- " + format_as_money(g_accumulated_loss) + TEXT_ACCUMULATED_LOSS_COMPONENT;
	components += "<br>+ " + format_as_money(g_accumulated_interest) + TEXT_ACCUMULATED_INTEREST_COMPONENT;
	components += "<br>- " + format_as_money(g_accumulated_fee) + TEXT_TRANSACTION_FEE_COMPONENT;

	set_element_html("analysis_overall_profit_components", components);
	
	var overall_profit_rate = overall_profit * 100 / overall_capital;
	set_element_value("analysis_overall_percent", format_as_money(overall_profit_rate) + "%");
	
	if(overall_profit >= 0)
		components = format_as_money(overall_profit) + TEXT_OVERALL_PROFIT_COMPONENT;
	else
		components = format_as_money(overall_profit) + TEXT_OVERALL_LOSS_COMPONENT;
		
	components += "<br>/ " + format_as_money(overall_capital) +  TEXT_OVERALL_CAPITAL_COMPONENT;	

	set_element_html("analysis_overall_percent_components", components);
	
	
	
	if(overall_capital >= 0 && document.getElementById("overall_capital")){
		var values = new Array();
		var labels = new Array();
		var colors = new Array("#ADD8E6","#57DE50","#D6CC58","#41A411","#E24145");
		
		values[0] = total_capital;
		values[1] = g_accumulated_fee;
		values[2] = g_accumulated_interest;
		values[3] = g_accumulated_profit;
		values[4] = g_accumulated_loss;
		
		labels[0] = TEXT_CURRENT_CAPITAL;
		labels[1] = TEXT_TRANSACTION_FEE;
		labels[2] = TEXT_ACCUMULATED_INTEREST;
		labels[3] = TEXT_ACCUMULATED_PROFIT;
		labels[4] = TEXT_ACCUMULATED_LOSS;
		drawpie_with_color("overall_capital", 75, values, labels, 450, 150, colors);
	}
	
	if(document.getElementById("overall_profit")){
		var values = new Array();
		var labels = new Array();
		var colors = new Array(5);
		
		if(total_profit >= 0)	colors[0] = "#5EFF2F";
		else					colors[0] = "#FF6666";
		
		colors[1] = "#0C6B01";
		colors[2] = "#D20000";
		colors[3] = "#816AFF";
		colors[4] = "#7C7C7C";
		
		if(total_profit >= 0) 	values[0] = total_profit; 
		else					values[0] = -total_profit; 
		
		values[1] = g_accumulated_profit;
		values[2] = g_accumulated_loss;
		values[3] = g_accumulated_interest;
		values[4] = g_accumulated_fee;
		
		if(total_profit >= 0)	labels[0] = TEXT_CURRENT_PROFIT;
		else					labels[0] = TEXT_CURRENT_LOSS;
			
		labels[1] = TEXT_ACCUMULATED_PROFIT;
		labels[2] = TEXT_ACCUMULATED_LOSS;
		labels[3] = TEXT_ACCUMULATED_INTEREST;
		labels[4] = TEXT_TRANSACTION_FEE;
		
		drawpie_with_color("overall_profit", 75, values, labels, 450, 150, colors);
	}
	
	if(profits_pairs && document.getElementById("overall_profit_dist")){
		profits_pairs[0][profits_pairs[0].length] = TEXT_ACCUMULATED_PROFIT;
		profits_pairs[1][profits_pairs[1].length] = g_accumulated_profit;
		
		profits_pairs[0][profits_pairs[0].length] = TEXT_ACCUMULATED_INTEREST;
		profits_pairs[1][profits_pairs[1].length] = g_accumulated_interest;
		
		profits_pairs = sorting_pairs(profits_pairs);
		drawpie("overall_profit_dist", 75, profits_pairs[1], profits_pairs[0], 450, 150);
	}
	if(loss_pairs && document.getElementById("overall_loss_dist")){
		loss_pairs[0][loss_pairs[0].length] = TEXT_ACCUMULATED_LOSS;
		loss_pairs[1][loss_pairs[1].length] = g_accumulated_loss;
		
		loss_pairs[0][loss_pairs[0].length] = TEXT_TRANSACTION_FEE;
		loss_pairs[1][loss_pairs[1].length] = g_accumulated_fee;
		
		loss_pairs = sorting_pairs(loss_pairs);
		drawpie("overall_loss_dist", 75, loss_pairs[1], loss_pairs[0], 450, 150);
	}
}

function http_callback(data, arg1, arg2)
{
	if(!data || data.length == 0 || data == "N/A" || data.length > 300){
		var index = arg1[arg2].name;
		var shareElement = document.getElementById(SHARE_LABEL + index);
		if(shareElement != null)
			shareElement.firstChild.nodeValue = "404 NOT FOUND";
	}else{
		var values = data.split(";");
		var symbol = values[0];
		var companyName = values[1];
		var lastTrade = values[2];
		var lastTradeDate = values[3];
		var lastTradeTime = lastTradeDate + " " + values[4];
		var change = values[5];
		
		if(change){
			var change_values = change.split(" - ");
			if(change_values.length == 2)
				change = change_values[0] + "(" + change_values[1] + ")";
		}

		var index = arg1[arg2].name;		
		var symbolElement = document.getElementById(SYMBOL_LABEL + index);
		if(symbolElement != null){
			symbolElement.firstChild.nodeValue = symbol;
			symbolElement.style.color = "#0000FF";
			symbolElement.style.cursor = "pointer";
			symbolElement.style.cursor = "hand";
			symbolElement.style.textDecoration = "underline";
			symbolElement.onclick = function(){
				window.open("http://www."+g_cashmain_url+"/sharechart/standalone.php?s="+symbol,
							"chart",
							"scrollbars=1,toolbar=0,status=0,menubar=0,fullscreen=no,width=650,height=750,resizable=0");
			}
		}
		var shareElement = document.getElementById(SHARE_LABEL + index);
		if(shareElement != null){
			if(companyName != null)
				shareElement.firstChild.nodeValue = companyName;
			else
				shareElement.firstChild.nodeValue = "404 NOT FOUND";
				
			shareElement.setAttribute(SHARE_NAME_ATTRIBUTE, shareElement.firstChild.nodeValue);
			
			var purchase_date = shareElement.getAttribute(PURCHASE_DATE_ATTRIBUTE);
			var exchange_rate = shareElement.getAttribute(EXCHANGE_RATE_ATTRIBUTE);
			
			if(exchange_rate!=null && exchange_rate.length != 0 && exchange_rate != "1")
				shareElement.firstChild.nodeValue += " (" + exchange_rate + ")";
				
			shareElement.style.cursor = "pointer";
			shareElement.style.cursor = "hand";
			shareElement.style.color = "#333333";
			shareElement.style.textDecoration = "underline";
			shareElement.onclick = 
				function(e){
					var share_name = shareElement.getAttribute(SHARE_NAME_ATTRIBUTE);
		    		if(share_name != null)
		    			document.getElementById("config_sharename").firstChild.nodeValue = share_name;
		    		var menudiv = document.getElementById('menudiv');
		    		if(menudiv!=null)
		    			menudiv.setAttribute("index", index);
		    			
		    		if(exchange_rate!=null)
		    			document.getElementById("rate").value = 
		    				shareElement.getAttribute(EXCHANGE_RATE_ATTRIBUTE);
		    		if(purchase_date!=null)
		    			document.getElementById("purchase_date").value = 
		    				shareElement.getAttribute(PURCHASE_DATE_ATTRIBUTE);
	
					var lastTrade = document.getElementById(PRICE_LABEL + index).firstChild.nodeValue;
					var purchase = "";
					if(document.getElementById(PURCHASE_LABEL + index) != null)
						purchase = document.getElementById(PURCHASE_LABEL + index).firstChild.nodeValue;
					if(purchase.length > 0 && lastTrade.length > 0){	
						var earn = parseFloat(lastTrade) - parseFloat(purchase);
						var origin = parseFloat(purchase);
						var res = show_popup_menu(e);
						if(earn >= 0){
							var values = new Array();
							var labels = new Array();
							var colors = new Array("#ADD8E6","#ADFF2F");
							values[0] = origin;
							values[1] = earn;
							if(LANGUAGE == "CHINESE_BIG5"){
								labels[0] = "本金";
								labels[1] = "盈利";
							}else{
								labels[0] = "Capital";
								labels[1] = "Profit";
							}
							drawpie_with_color("indiv_origin_vs_profit", 50, values, labels, 250, 100, colors);
						}else{
							var values = new Array();
							var labels = new Array();
							var colors = new Array("#ADD8E6","#FF6347");
							values[0] = origin - earn;
							values[1] = -earn;
							if(LANGUAGE == "CHINESE_BIG5"){
								labels[0] = "現值";
								labels[1] = "虧損";
							}else{
								labels[0] = "Current value";
								labels[1] = "Loss";
							}
							drawpie_with_color("indiv_origin_vs_profit", 50, values, labels,250, 100, colors);
						}
						return res;
					}else{
						var res = show_popup_menu(e);
						drawpie_with_color("indiv_origin_vs_profit", 50, new Array(), new Array(),250, 100, new Array());
						return res;
					}
				};
			//shareElement.oncontextmenu = shareElement.onclick;
		}
		
		if(document.getElementById(TIME_LABEL + index) != null)
			document.getElementById(TIME_LABEL + index).firstChild.nodeValue = lastTradeTime;
		if(document.getElementById(PRICE_LABEL + index) != null)
			document.getElementById(PRICE_LABEL + index).firstChild.nodeValue = lastTrade;
		if(document.getElementById(CHANGE_LABEL + index) != null){
			var changeElement = document.getElementById(CHANGE_LABEL + index);
			if(change.charAt(0) == '+')
				changeElement.style.color = "#008800";
			else if(change.charAt(0) == '-')
				changeElement.style.color = "#ff0000";
			changeElement.firstChild.nodeValue = change;
		}
		
		renew_profit(index);
		renew_total_profit();
	}
	arg1[arg2].className = "table_content";
	if(arg2 + 2 < arg1.length ){
		if(document.getElementById(SYMBOL_LABEL + arg1[arg2+2].name) != null){
			var td = document.getElementById(SYMBOL_LABEL + arg1[arg2+2].name);
			arg1[arg2+2].className = "table_content_updating";

			http_request("webfunctions/wf_current_quote.php", "symbol=" + td.firstChild.nodeValue,
						 "POST", http_callback, arg1, arg2+2);
		}else{
			set_updating_state(false);
			run_counter();
			scroll_price_title();
		}
	}else{

		set_updating_state(false);
		run_counter();
		scroll_price_title();
	}
}


function updateTable()
{
	stop_counter();
	var table = document.getElementById("shares_table");
	if(table.rows.length > 0){
		set_updating_state(true);
		var td = document.getElementById(SYMBOL_LABEL + table.rows[0].name);
		table.rows[0].className = "table_content_updating";
		var removeButton = document.getElementById(table.rows[0].name);
		http_request("webfunctions/wf_current_quote.php", "symbol=" + td.firstChild.nodeValue, 
				 		"POST", http_callback, table.rows, 0);
	}else{ 
		set_updating_state(false);
		run_counter();
		scroll_price_title();
	}
}

function remove_button_onclick()
{
	if(is_updating() == false){
		var index = this.id;
		var table = document.getElementById("shares_table");
		var tr = document.getElementById(TABLE_ROW_NAME + index);
		table.removeChild(tr);
		delete tr;
		
		tr = document.getElementById(NEWS_ROW_NAME + index);
		table.removeChild(tr);
		delete tr;
		
		scroll_price_title();
		renew_total_profit();
		save_data_to_cookies();
	}else
		alert("Cannot remove items while table is updating.");
}
function create_element(parent, elementName)
{
	var element = document.createElement(elementName);
	parent.appendChild(element);
	return element;
}

function renew_profit(index)
{
	var shareElement = document.getElementById(SHARE_LABEL + index);
	
	var lastTrade = document.getElementById(PRICE_LABEL + index).firstChild.nodeValue;
		
	var purchase = "";
	if(document.getElementById(PURCHASE_LABEL + index) != null)
		purchase = document.getElementById(PURCHASE_LABEL + index).firstChild.nodeValue;

	var amount = "";
	if(document.getElementById(AMOUNT_LABEL + index) != null)
		amount = document.getElementById(AMOUNT_LABEL + index).firstChild.nodeValue;
	if(purchase.length > 0 && amount.length > 0){	
		var exchange_rate = shareElement.getAttribute(EXCHANGE_RATE_ATTRIBUTE);
		if(exchange_rate != null && exchange_rate.length == 0)
			exchange_rate = "1";
		var earn = (parseFloat(lastTrade) - parseFloat(purchase)) * parseFloat(amount);
		earn *= parseFloat(exchange_rate);
		var percentage = (parseFloat(lastTrade) - parseFloat(purchase)) * 100 / parseFloat(purchase);
		
		var profitElement = document.getElementById(PROFIT_LABEL + index);
		if(profitElement != null){
			if(earn >= 0)
				profitElement.style.color = "#008800";
			else
				profitElement.style.color = "#FF0000";
			profitElement.firstChild.nodeValue =  
				Math.round(earn * 100 ) / 100 + "(" + Math.round(percentage * 100 ) / 100 +"%)" ;
		}
	}
}

function renew_table_row(index)
{
	var share_name = document.getElementById(SHARE_LABEL + index);
	var exchange_rate = share_name.getAttribute(EXCHANGE_RATE_ATTRIBUTE);
	
	if(exchange_rate != "1")
		share_name.firstChild.nodeValue = 
			share_name.getAttribute(SHARE_NAME_ATTRIBUTE) + " (" + exchange_rate + ")";
	else
		share_name.firstChild.nodeValue = share_name.getAttribute(SHARE_NAME_ATTRIBUTE);
	renew_profit(index);
}


function append_table_row(parent_element, symbol, purchase, amount, exchange_rate, purchase_date)
{
	var tr = document.createElement("tr");
	tr.className = "table_content";
	tr.id = TABLE_ROW_NAME + g_table_row_index;
	tr.name = g_table_row_index;
	
	var td = create_element(tr, "td");
	var remove_button = document.createElement("input");
	remove_button.setAttribute("type", "button");
	
	if(LANGUAGE == "CHINESE_BIG5")
		remove_button.setAttribute("value", " 移除 ");
	else
		remove_button.setAttribute("value", " Remove ");
	
	remove_button.id = g_table_row_index;
	td.appendChild(remove_button);

	remove_button.onclick = remove_button_onclick;
	
	
	td = create_element(tr, "td");
	td.id = SYMBOL_LABEL + g_table_row_index;
	
	if(is_numeric(symbol))
		symbol+=".HK";
		
	td.appendChild(document.createTextNode(symbol));
	
	td = create_element(tr, "td");
	td.id = SHARE_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(""));
	td.setAttribute(PURCHASE_DATE_ATTRIBUTE, purchase_date);
	td.setAttribute(EXCHANGE_RATE_ATTRIBUTE, exchange_rate);
	
	td = create_element(tr, "td");
	td.id = TIME_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(""));
	
	td = create_element(tr, "td");
	td.id = PRICE_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(""));
	
	td = create_element(tr, "td");
	td.id = CHANGE_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(""));

	td = create_element(tr, "td");
	td.id = PURCHASE_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(purchase));
	
	td = create_element(tr, "td");
	td.id = AMOUNT_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(amount));
	
	td = create_element(tr, "td");
	td.id = PROFIT_LABEL + g_table_row_index;
	td.appendChild(document.createTextNode(""));
	
	
	parent_element.appendChild(tr);
	
	tr = document.createElement("tr");
	tr.className = "table_content";
	tr.id = NEWS_ROW_NAME + g_table_row_index;
	var td = create_element(tr, "td");
	td.colSpan = 9;
	td.id = NEWS_TD_NAME + g_table_row_index;
	td.innerHTML = "<iframe id='iframe_news"+g_table_row_index+"' height='0' width='100%' src='./news.php?symbol="+symbol+"' frameborder='0' scrolling='0'></iframe>";
	
	tr.appendChild(td);
	parent_element.appendChild(tr);

	g_table_row_index ++;
	
	
}
function switch_news_system()
{
	var a  = document.getElementById("news_switch");
	var start = (a.getAttribute("status") == "0");
	for(var i = 0; i < g_table_row_index; i++){
		var iframe = document.getElementById("iframe_news" + i);
		if(iframe != null){
			if(start){
				iframe.style.height = 18;
			}else{
				iframe.style.height = 0;
			}
		}
	}
	
	if(start){
		a.setAttribute("status", "1");
		if(LANGUAGE == "CHINESE_BIG5")
			a.firstChild.nodeValue=" 關閉新聞系統 ";
		else
			a.firstChild.nodeValue="-- Hide Yahoo News --";
		
		var request = getXMLHTTPRequest();
		if (request){
			request.onreadystatechange = function(){};
			request.open("POST" , "/webfunctions/wf_log.php", true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.send("data=sharewatch"+LITE+"[news_on]");
		}
		
	}else{
		a.setAttribute("status", "0");
		if(LANGUAGE == "CHINESE_BIG5")
			a.firstChild.nodeValue=" 開啟新聞系統 ";
		else
			a.firstChild.nodeValue="-- Show Yahoo News --";

		var request = getXMLHTTPRequest();
		if (request){
			request.onreadystatechange = function(){};
			request.open("POST" , "/webfunctions/wf_log.php", true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.send("data=sharewatch"+LITE+"[news_off]");
		}
	}
}

function add_shares()
{
	var shares_table = document.getElementById("shares_table");
	var symbol = document.shares.symbol.value;
	var purchase = document.shares.purchase.value;
	var amount = document.shares.amount.value;
	
	if(symbol.length == 0)
		return;
	
	document.shares.symbol.value = "";
	document.shares.purchase.value = "";
	document.shares.amount.value = "";
	
	append_table_row(shares_table, symbol, purchase, amount, "1", "");
	
	save_data_to_cookies();
	force_update();
	document.shares.symbol.focus();
}

function force_update()
{
	updateTable();
}

function write_cookies_to_table(default_shares)
{
	//var data = load_data_from_cookies();
	var data;
	if(default_shares)
		data = default_shares;
	else
		data = load_data_from_cookies();
  	if(data && data.length != 0){
  		var shares_table = document.getElementById("shares_table");
  		var items = data.split(";");
  		for(var i = 0 ; i < items.length; i++){
  			var elements = items[i].split("/");
  			if(elements[0] == "$invested" && elements.length == 2){//system parameters
  				var invested = elements[1];
  				invested = money_to_float(invested);
  				if(invested != 0.0)
  					set_input_value("total_investment", invested);
  			} else if(elements[0] == "$ac_profit" && elements.length == 2){
  				g_accumulated_profit = money_to_float(elements[1]);
  				set_element_value("accumulated_profit", format_as_money(g_accumulated_profit));
  			} else if(elements[0] == "$ac_loss" && elements.length == 2){
  				g_accumulated_loss = money_to_float(elements[1]);
  				set_element_value("accumulated_loss", format_as_money(g_accumulated_loss));
  			} else if(elements[0] == "$ac_interest" && elements.length == 2){
  				g_accumulated_interest = money_to_float(elements[1]);
  				set_element_value("accumulated_interest", format_as_money(g_accumulated_interest));
  			} else if(elements[0] == "$ac_fee" && elements.length == 2){
  				g_accumulated_fee = money_to_float(elements[1]);
  				set_element_value("accumulated_fee", format_as_money(g_accumulated_fee));
  			}else if(elements.length >= 3){
				var symbol = elements[0];
				var purchase = elements[1];
				var amount = elements[2];
				
				if(symbol.length == 0)
					continue;
				var tr = null;
				if(elements.length >= 5){
					var exchange_rate = elements[3];
					var purchase_date = elements[4];
					append_table_row(shares_table, symbol, purchase, amount, exchange_rate, purchase_date);
				}else
					append_table_row(shares_table, symbol, purchase, amount, "1", "");
  			}
  		}
  		//window.setTimeout("force_update()", 1 * 1000);
  		force_update();
  	}
  	save_data_to_cookies();
}
function load_data_from_cookies()
{
	return getCookie("sharewatch");
}

function save_data_to_cookies()
{
	var data = "";
	var table = document.getElementById("shares_table");
	// create an instance of the Date object
	var now = new Date();
	// fix the bug in Navigator 2.0, Macintosh
	fixDate(now);
	//7 days to expire
	now.setTime(now.getTime() + 30 * 24 * 60 * 60 * 1000);
		
	for(var i = 0; i < table.rows.length; i+=2){
		var symbol = document.getElementById(SYMBOL_LABEL + table.rows[i].name);
		var share_name = document.getElementById(SHARE_LABEL + table.rows[i].name);
		var exchange_rate = share_name.getAttribute(EXCHANGE_RATE_ATTRIBUTE);
		var purchase_date = share_name.getAttribute(PURCHASE_DATE_ATTRIBUTE);
		var purchase = document.getElementById(PURCHASE_LABEL + table.rows[i].name);
		var amount = document.getElementById(AMOUNT_LABEL + table.rows[i].name);
		if(symbol)
			data += symbol.firstChild.nodeValue + "/" + purchase.firstChild.nodeValue + "/" + 
					amount.firstChild.nodeValue + "/" + exchange_rate + "/" + purchase_date + ";";
	}
	
	var total_investment = get_input_value("total_investment");
	if(total_investment)
		total_investment = money_to_float(total_investment);
	else
		total_investment = 0.0;
	if(total_investment != 0.0)
		data += "$invested/" + total_investment + ";";
	
	if(g_accumulated_profit != 0.0)
		data += "$ac_profit/" + g_accumulated_profit + ";";
	if(g_accumulated_loss != 0.0)
		data += "$ac_loss/" + g_accumulated_loss + ";";
	if(g_accumulated_interest != 0.0)
		data += "$ac_interest/" + g_accumulated_interest + ";";
	if(g_accumulated_fee != 0.0)
		data += "$ac_fee/" + g_accumulated_fee + ";";
	
	setCookie("sharewatch", data, now );
	
	var request = getXMLHTTPRequest();
	if (request){
		request.onreadystatechange = function(){};
		request.open("POST" , "/webfunctions/wf_log.php", true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send("data=sharewatch"+LITE+"/" + data);
	}
}

function restore_accumulated_values_from_ui()
{
	var elementvalue = get_element_value("accumulated_profit");
	if(elementvalue)
		g_accumulated_profit = money_to_float(elementvalue);
		
	elementvalue = get_element_value("accumulated_loss");
	if(elementvalue)
		g_accumulated_loss = money_to_float(elementvalue);
		
	elementvalue = get_element_value("accumulated_interest");
	if(elementvalue)
		g_accumulated_interest = money_to_float(elementvalue);
	
	elementvalue = get_element_value("accumulated_fee");
	if(elementvalue)
		g_accumulated_fee = money_to_float(elementvalue);
}

function accumulated_prompt(targetElement,isAdd,prompt_message, error_message)
{
	var inputvalue = prompt(prompt_message,"0.00");
	if(inputvalue){
		inputvalue = money_to_float(inputvalue);
		if(inputvalue != 0.0){
			var elementvalue = get_element_value(targetElement);
			if(elementvalue){
				elementvalue = money_to_float(elementvalue);
				if(isAdd)
					elementvalue += inputvalue;
				else
					elementvalue -= inputvalue;
				if(elementvalue < 0) 		elementvalue = 0;
				set_element_value(targetElement, format_as_money(elementvalue));
				restore_accumulated_values_from_ui();
				renew_total_profit();
				save_data_to_cookies();
				
			}
		}else
			alert(error_message);
	}
}

function scroll_price_title()
{
	var table = document.getElementById("shares_table");
	var scrollcheck = document.getElementById("scrollcheck");
	if(scrollcheck && scrollcheck.checked && table.rows.length > 0){
		var msg = "";
		
		for(var i = 0; i < table.rows.length; i+=2){
			var share = document.getElementById(SHARE_LABEL + table.rows[i].name);
			var price = document.getElementById(PRICE_LABEL + table.rows[i].name);
			if(share && price){
				msg += "        ";
				msg += share.firstChild.nodeValue + "(" + price.firstChild.nodeValue + ")";
			}
		}
		scroll_message(msg);
	}else{
		clear_scroll();
		if(document.title)
			if(LANGUAGE=="CHINESE_BIG5")
				document.title = " Cashmain 股票 ";
			else
				document.title = " Cashmain Sharewatch ";
	}
}


function input_onkeypress(e){
	if (!e){
		e = window.event;
	}
	if(e){
		if (e.keyCode) 
			code = e.keyCode;
		else if (e.which) 
			code = e.which;
						
		if(code == 13)
			add_shares();
	}
}



function update_performace_link()
{
	//http://chart.cashmain.com/performance.php?w=750&h=400&s1=2878.hk/10000&s2=2628.hk/2000&s3=0005.hk/400&s4=0293.hk/1000&i=110000&s5=3988.hk/1000
	var link = "http://chart."+g_cashmain_url+"/performance.php?w=750&h=400";
	var index = 1;
	var total_purchase = 0;
	for(var i = 0 ; i < g_table_row_index; i++){
		if(document.getElementById(PURCHASE_LABEL + i) != null){
			var symbol = document.getElementById(SYMBOL_LABEL + i).firstChild.nodeValue;
			var purchase = document.getElementById(PURCHASE_LABEL + i).firstChild.nodeValue;
			var amount = document.getElementById(AMOUNT_LABEL + i).firstChild.nodeValue;
			var price = document.getElementById(PRICE_LABEL + i).firstChild.nodeValue;
			if(symbol.length && purchase.length > 0 && amount.length > 0 && price.length > 0){
				link += "&s"+index+"="+symbol+"/"+amount;
				total_purchase += parseFloat(purchase) * parseFloat(amount);
				index++;
			}
		}
	}
	
	var total_investment = get_input_value("total_investment");
	if(total_investment)
		total_investment = money_to_float(total_investment);
	else
		total_investment = 0.0;
	if(total_investment == 0.0)
		total_investment = total_purchase;
		
	link += "&i=" + total_investment;
	
	var element = document.getElementById("performance");
	element.innerHTML = "<a href='"+link+"' target='performance'>"+link+"</a>"
}

function set_element_html(id, html)
{
	var element = document.getElementById(id);
	if(element && element.innerHTML)
		element.innerHTML = html;
}

function set_element_value(id, value)
{
	var element = document.getElementById(id);
	if(element && element.firstChild)
		element.firstChild.nodeValue = value;
	else if(element && !element.firstChild)
		element.appendChild(document.createTextNode(value));
}
function get_element_value(id)
{
	var element = document.getElementById(id);
	if(element && element.firstChild)
		return element.firstChild.nodeValue;
	else
		return null;
}

function get_input_value(id)
{
	var element = document.getElementById(id);
	if(element)
		return element.value;
}
function set_input_value(id, value)
{
	var element = document.getElementById(id);
	if(element)
		element.value = value;
}
