/* Copyright (c) 2006-2009, Envapower Inc. All rights reserved. */
/*
** This file contains funtions used in Power Console application
*/

// Retrieve the absolute coordinates of an element.
function getAbsolutePosition(element) {
  if(element){
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
  }
}

// ZNIPPets.com, "Zprime.js", by DocOzone...
function makeZflag() {
	this.NS = document.layers ? 1:0;
	this.IE = document.all ? 1:0;
	this.gecko = document.getElementById ? 1:0;
	this.mac = (navigator.appVersion.indexOf("Mac") > -1) ? 1:0;
	this.opera = (navigator.appName.indexOf("Opera") > -1) ? 1:0;
	this.netscape = (navigator.appName.indexOf("Netscape") > -1) ? 1:0;
}
Zflag = new makeZflag();

function makeZbrowse() { this.id = "Zbrowse";}

makeZbrowse.prototype.width = function() {return Zflag.IE?document.body.clientWidth:window.innerWidth;}
makeZbrowse.prototype.height = function() {return Zflag.IE?document.body.clientHeight:window.innerHeight;}
makeZbrowse.prototype.scrollY = function() {return Zflag.IE?document.body.scrollTop:pageYOffset;}
makeZbrowse.prototype.scrollX = function() {return Zflag.IE?document.body.scrollLeft:pageXOffset;}

Zbrowse = new makeZbrowse();

// Handles a Save As process for graphlet enlarge
function saveAsGraphEnlarge(graphletName){
    var formButton = document.getElementById('btnSaveAs');
    var formElement = document.getElementById('hdnGraphletName');
    if (graphletName != null) {        
        formElement.value = graphletName;
        formButton.click();
    }
}

// Opens a graphlet when Graphlet is selected from the Menu.
function openGraphlet(graphletId) {
    window.location = "graphletenlarge.aspx?id=" + graphletId;
}

// Opens a popup window
function openPopup(url, windowName, width, height) {
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	var features = new String("width=" + width + ",height=" + height + ",left="+ left + ",top=" + top);
	features += ",menubar=no,toolbar=no,location=no,status=no,scrollbars=no,resizable=no";
	
	var popup = window.open(url, windowName, features);
	popup.focus();
}

// Opens the help window
function openHelp(url, windowName) {
    var width = 1024;
    var height = 768;
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	var features = new String("width=" + width + ",height=" + height + ",left="+ left + ",top=" + top);
	features += ",menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
	
	var popup = window.open(url, windowName, features);
	popup.focus();
}

/*This function determinates if the Browser is IE6*/
   function isIE6(){
     var is_major = parseInt(navigator.appVersion);
     var agt=navigator.userAgent.toLowerCase();
     var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
     var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
     return is_ie6;
   }

/** Sets focus on the elem */
function setFocus(idElem){
	var elem = document.getElementById(idElem);
	if (elem && elem.style.display != 'none' && elem.style.visibility != 'hidden') elem.focus();
}

/* Show hide a div popup */
function showHide(element, visibility) {
    var div = document.getElementById(element);
    var width = 0;
    var height = 0;
    
    if (typeof( window.innerWidth ) == 'number') {
        //Non-IE
        width = window.innerWidth;
        height = window.innerHeight;
    } else if (document.documentElement) {
        //IE 6+ in 'standards compliant mode'
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }
    
    var left = ((width - extractSize(div.style.width)) / 2);
    var top = ((height - extractSize(div.style.height)) / 2);
    
    div.style.left = left;
    div.style.top = top;
    div.style.visibility = visibility;
}

/* Return a number representing the element size */
function extractSize(size) {
    var sizeString = new String(size);
    sizeString = sizeString.substr(0, sizeString.indexOf('px'));
    
    var sizeInNumbers = parseInt(sizeString);
    
    if (!isNaN(sizeInNumbers)) {
        return sizeInNumbers;
    }
    
    return 0;
}

/** Validates email  */
function validateEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,5})+$/.test(email)){ 
		return true;
	}  
	return false;
}

/** Clicks the specified button when Enter key is pressed*/
function KeyDownHandler(btn) {
    // process only the Enter key
    if (event.keyCode == 13)
    {
        // cancel the default submit
        event.returnValue=false;
        event.cancel = true;
        // submit the form by programmatically clicking the specified button
        btn.click();
    }
}

/*   functions to open window */
function openSearch(width,height,url,showScroll){ 
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	var parameters = "width="+width + ",height="+ height +",left="+ left +",top="+ top +",resizable=no,menubar=no, scrollbars=yes";
	if(showScroll=='no'){
		parameters = "width="+width + ",height="+ height +",left="+ left +",top="+ top +",resizable=yes,menubar=no";
	}
	newWin = window.open(url, "newWindow", parameters);
	newWin.focus();
}
function openWin(width,height,url){ 
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	newWin = window.open(url, "newWindow","width="+ width + ",height="+ height +",left="+ left +",top="+ top +",resizable=no,scrollbars=yes,menubar=no,status=yes");
	newWin.focus();
}

/** Shows propt to get a new name */
function getNewName(prompTitle, elemId) {
	var name = prompt("Please enter a new name", prompTitle);
	if (null != name){
		var elem = document.getElementById(elemId);
		// if the page name length is greater than 100, then we take only 100 characters
		if(name.length > 100){
			name = name.substring(0,100);			
		}
		elem.value = name;
	}
	return name;
}
				
/** Returns true if the text doesn't contain anything significant */
function isEmpty(text) {
	if (!text) return true;
	text = text.match(/\b\w+\b/);
	return !text || text.length < 1;
}

						

function trim(text){
	text = leftTrim(text);
	return rightTrim(text);
}

function rightTrim(text){
	while(text.charAt((text.length -1))==" " || text.charAt((text.length -1))=="	"){
		text = text.substring(0,text.length-1);
	}
	return text;
}

function leftTrim(text){
	while(text.charAt(0)==" " || text.charAt(0)=="	"){
		text = text.replace(text.charAt(0),"");
	}
	return text;
}

function leftWhiteSpace(txt){
   return txt.charAt(0) == " ";
}

function rightWhiteSpace(txt){
   return txt.charAt(txt.length - 1) == " ";
}

/** This function checks/unchecks all checkboxes that matches controlName */
function selectAll(controlName, check) {
	var theForm = document.forms[0];
	
	for (var i = 0; i < theForm.length; i ++) {
		if ((theForm[i].type == "checkbox") && (theForm[i].id.indexOf(controlName) >= 0)) {
			theForm[i].checked = check;
		}
	}
}

/** This function checks/unchecks controlName if all controlToValidate checkboxes are checked */
function selectParent(controlName, controlToValidate) {
	var theForm = document.forms[0];
	var allSelected = false;
	
	for (var i = 0; i < theForm.length; i ++) {
		if ((theForm[i].type == "checkbox") && (theForm[i].id.indexOf(controlToValidate) >= 0)) {
			if (theForm[i].checked) {
				allSelected = true;
			} else {
				allSelected = false;
				break;
			}
		}
	}
	
	var theCheckBox = document.getElementById(controlName);
	theCheckBox.checked = allSelected;
}

/**
 * Begin data values display region for graphlets 
 */
/** Displays the chart coordinate of the click pixel */
function showCoords(event, chart, xCoord, yCoord, width, height, xMax, xMin, yMax, yMin, y2Max, y2Min, isEuro)
{
	var output = "";
	var xAxis = new Axis(xCoord, width, Date.parse(xMax), Date.parse(xMin));
	var yAxis = new Axis(yCoord, height, yMax, yMin);
	var y2Axis = new Axis(yCoord, height, y2Max, y2Min);
	var elementPosition = getElementPosition(document.getElementById(chart));
    var absPosX = 0;
    var absPosY = 0;

	if(event) {
	    absPosX = event.clientX + jQuery(document).scrollLeft();
	    absPosY = event.clientY + jQuery(document).scrollTop();
	}
	
	var x = getAxisCoord(xAxis, absPosX, elementPosition.x, false);
	var y = (yMax != yMin)? getAxisCoord(yAxis, absPosY, elementPosition.y, true) : NaN;
	var y2 = (y2Max != y2Min)? getAxisCoord(y2Axis, absPosY, elementPosition.y, true) : NaN;
	var date = new Date(x);
	output = " X = " + getDateStr(date, isEuro);
	
	if (!isNaN(y)) {
		output += "\n Y = " + y;
	}

	if (!isNaN(y2)) {
		output += "\n Y2 = " + y2;
	}
	
	return output;
}

/** This function is used as an Axis object constructor */
function Axis(position, size, max, min) {
	this.position = position;
	this.size = size;
	this.max = max;
	this.min = min;
}

/** This function is used as an overridden toString() method for the Date object */
function getDateStr(date, isEuro) {
	var separator = " ";
	var dateSptr = "-";
	var timeSptr = ":";
	var month = (date.getMonth() < 9)? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
	var day = (date.getDate() < 10)? "0" + date.getDate() : date.getDate();
	var hour = (date.getHours() < 10)? "0" + date.getHours() : date.getHours();
	var minute = (date.getMinutes() < 10)? "0" + date.getMinutes() : date.getMinutes();
	
	if (isEuro.toLowerCase() == 'true') {
        return day + dateSptr + month + dateSptr + date.getFullYear() + separator + hour + timeSptr + minute;
	}

    return month + dateSptr + day + dateSptr + date.getFullYear() + separator + hour + timeSptr + minute;
}

/** Translate a pixel based axis coordinate to a meaningful chart axis coordinate */
function getAxisCoord(axis, eventCoord, elementCoord, isInverted) {
	var axisCoord = 0;
	var coordSize = (axis.max - axis.min) / axis.size;

	if (isInverted) {
		axisCoord = axis.size + 1 - (eventCoord - elementCoord - axis.position);
	} else {
		axisCoord = eventCoord - (elementCoord + axis.position);
	}

	axisCoord = axisCoord * coordSize + axis.min;

	if (Math.abs(axisCoord) <= 10) {
		return (Math.round(axisCoord * 10) / 10);
	}

	return Math.round(axisCoord);
}

/** Returns the exact chart position */
function getElementPosition(element) {
    var result = new Object();
    result.x = 0;
    result.y = 0;
    result.width = 0;
    result.height = 0;

    if (element.offsetParent) {
        result.x = element.offsetLeft;
        result.y = element.offsetTop;
        var parent = element.offsetParent;

        while (parent) {
            result.x += parent.offsetLeft;
            result.y += parent.offsetTop;
            var parentTagName = parent.tagName.toLowerCase();
			
            if ((parentTagName != "html") && (parentTagName != "body") && (parentTagName != "table") 
                && (parentTagName != "div") && (parent.clientTop && parent.clientLeft)) {
                result.x += parent.clientLeft;
                result.y += parent.clientTop;
            }
            parent = parent.offsetParent;
        }
    }
    else if (element.left && element.top) {
        result.x = element.left;
        result.y = element.top;
    }
    else {
        if (element.x) {
            result.x = element.x;
        }
        if (element.y) {
            result.y = element.y;
        }
    }

    if (element.offsetWidth && element.offsetHeight) {
        result.width = element.offsetWidth;
        result.height = element.offsetHeight;
    }
    else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
        result.width = element.style.pixelWidth;
        result.height = element.style.pixelHeight;
    }

    return result;
}
/**
 * End data values display region for graphlets 
 */
 
 
 /**
 * Begin funtions for SensorSearch
 */
 
 function saveOtherRegion(newRegion) {						   
		var hdnRegion = document.getElementById('hdnOtherRegion');
		hdnRegion.value = newRegion;					
 }
	
 function client_OnTreeNodeChecked()
 {
    var obj = window.event.srcElement;
    var treeNodeFound = false;
    var checkedState;
    if (obj.tagName == "INPUT" && obj.type == "checkbox") {
        var treeNode = obj;
        checkedState = treeNode.checked;
        do
        {
           obj = obj.parentElement;
        } 
        while (obj.tagName != "TABLE")
        var parentTreeLevel = obj.rows[0].cells.length;
        var parentTreeNode = obj.rows[0].cells[0];
        var tables = obj.parentElement.getElementsByTagName("TABLE");
        var numTables = tables.length
        if (numTables >= 1)
        {
            for (i=0; i < numTables; i++)
            {
                if (tables[i] == obj)
                {
                    treeNodeFound = true;
                    i++;
                    if (i == numTables)
                    {
                        return;
                    }
                }
                if (treeNodeFound == true)
                {
                    var childTreeLevel = tables[i].rows[0].cells.length;
                    if (childTreeLevel > parentTreeLevel)
                    {
                        var cell = tables[i].rows[0].cells[childTreeLevel - 1];
                        var inputs = cell.getElementsByTagName("INPUT");
                        inputs[0].checked = checkedState;
                    }
                    else
                    {
                        return;
                    }
                }
             }
        }
      }
   }
 /**
 * End funtions for SensorSearch
 */


// sound

// used to play the sound effect
function playSound(elemId, soundPath) {
 var soundElement = document.getElementById(elemId);
 soundElement.src = soundPath;
}
