var Utils = new Object();
STATUS_OK="ok";
STATUS_UPGRADE = "upgrade";
STATUS_FREEZE = "freeze";
STATUS_DISABLED = "disabled";
STATUS_EXISTS="exists";
TEST_STATUS_OK_STRING="OK";
TEST_STATUS_NOK_STRING="NOK";
TEST_STATUS_NA_STRING="NA";
TEST_STATUS_WARNING_STRING="WARN";
TEST_FAIL_POINT=10000;
TYPE_CURRENT=0;
TYPE_FIXED=1;
TYPE_PREVIOUS=2;
INTERVAL_MONTHLY=0;
INTERVAL_DAILY=1;
INTERVAL_HOURLY=2;
intervals=eval("("+"{'"+INTERVAL_MONTHLY+"':'monthly','"+INTERVAL_DAILY+"':'daily','"+INTERVAL_HOURLY+"':'hourly'}"+")");
AGENT_TYPE_PROCESS="1";
AGENT_TYPE_DRIVE="2";
AGENT_TYPE_MEMORY="3";
AGENT_TYPE_HTTP="4";
AGENT_TYPE_PING="5";
AGENT_TYPE_LOAD_AVERAGE="6";
AGENT_TYPE_CPU="7";
AGENT_TYPE_NAMES={};
AGENT_TYPE_NAMES[AGENT_TYPE_PROCESS]="process"
AGENT_TYPE_NAMES[AGENT_TYPE_DRIVE]="drive";
AGENT_TYPE_NAMES[AGENT_TYPE_MEMORY]="memory";
AGENT_TYPE_NAMES[AGENT_TYPE_HTTP]="test";
AGENT_TYPE_NAMES[AGENT_TYPE_PING]="test";
SORT_TYPE_ASC="asc";
SORT_TYPE_DESC="desc";
OS_WINDOWS=1;
OS_LINUX=2;
SMSPRICE=0.25;
HTTP_GET=1;
HTTP_POST=2;
// Major version of Flash required
var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 0;
//////////////////////////////////
HTTP_PUT=3;
HTTP_DELETE=4;
USER_AGENTS=[];

function newTag(elName){
	return document.createElement(elName);
}

function newText(text){
	return document.createTextNode(text);
}

function checkStatus(response){
	var json_obj = eval("("+response.responseText+")");
	if (json_obj.status != STATUS_OK)
		console.log(json_obj.status);
}

function getValidID( startId )
{
	var obj = $id( startId );
	while( obj != null )
	{
		startId += String.fromCharCode(97 + Math.round(Math.random() * 25));;
		obj = $id( startId );
	}
	return startId;
}

function disableSelecting( event )
{
	return false;
}

function changeStyle(newTheme){
		var links = document.getElementsByTagName("link");
		var newStylePath = '/themes/'+newTheme+'/'+newTheme+'.css';
		var currentStylePath = 'themes/'+OPTIONS.theme+'/'+OPTIONS.theme+'.css';

		for(var i = 0; i < links.length; i++)
		{
			if( links[i].href == (Framework.serverPath + currentStylePath) ||
			    links[i].href == (Framework.serverPath + "/"+ currentStylePath) ||
			    links[i].href == currentStylePath ||
				links[i].href == "/"+currentStylePath)
			{
				links[i].href = (Framework.serverPath + newStylePath);
				break;
			}
		}


		THEME_IMG_ROOT = "themes/" + newTheme + "/";
		PortletLoader.changePortletHeaderImg();
		changeRadioCheckImg();
		$id(OPTIONS.theme + "_skin").className = "";
		$id(newTheme + "_skin").className = " selected";
		OPTIONS.theme = newTheme;
		RequestDispatcher.send(Framework.optionsURL + User.userId + "/theme/" + OPTIONS.theme, "PUT", "", checkStatus, null);
}



function changeStyle2( i, path )
{

	if( changeStyle2.STEPS > 0)
	{
		node = document.getElementsByTagName("link")[i];
		node.href = (Framework.serverPath + path);
		changeStyle2.STEPS --;
		if( Browser.isIE )
		{
			setTimeout( "changeStyle2( "+ i +", \""+ path +"\" )", 1000 );
		}
	}
}
changeStyle2.STEPS = 5;


	function parseXMLStr(stringToParse) {
		var Browser = checkBrowserVersion();
		var rootTag = null;

		if (Browser.isIE) {
			var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
			xmlDocument.async = false;
			xmlDocument.loadXML(stringToParse);
			var rootTag = xmlDocument.documentElement;
		}
		else
		if (Browser.isMozilla) {
			var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(stringToParse,"text/xml");
			var rootTag = xmlDocument.documentElement;
		}
		else
		{
		var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(stringToParse,"text/xml");
			var rootTag = xmlDocument.documentElement;
		}
		return rootTag;
	}

function parseBool( str ){
	if( str == "false" || str == false)
		return false;
	else if( str == "true" || str == true)
		return true;
	return null;
}

function makeKeyValue( domNode , arr)
{
		if( arr == null  )arr = {};

		domNode = domNode.childNodes;
		for( var i=0; i<domNode.length; i++ )
		{
			if( domNode[i].nodeType != 1 )continue;
			var attrName  = domNode[i].nodeName;
			var attrValue = domNode[i].firstChild.nodeValue;

			var parsedBool = parseBool(attrValue);

			arr[ attrName ] = attrValue;
		}
		return arr;
}

function findPosXY( obj )
{
	var curleft = 0;
	var curtop = 0;

	try
	{

			if (obj.offsetParent) {

				while (obj.offsetParent) {

					if(obj.offsetParent.offsetParent==null)
						break;

					curleft += obj.offsetLeft;
					curtop  += obj.offsetTop;
					obj = obj.offsetParent;

				}
			}
			else
			{
				if (obj.x) curleft += obj.x;
				if (obj.y) curtop  += obj.y;
			}
	}catch(ex){}

	var retObj = new Object();
	retObj.left = curleft;
	retObj.top  = curtop;

	return retObj;
}

function findPosX(obj)
{
	var curleft = 0;

	try
	{
			if (obj.offsetParent) {
				while (obj.offsetParent) {
					if(obj.offsetParent.offsetParent==null)
						break;
					curleft += obj.offsetLeft;
					obj = obj.offsetParent;
				}
			} else if (obj.x) curleft += obj.x;
	}catch(ex){}

	return curleft;
}

function parseStylePX( size )
{
	if( typeof(size) == "string" )
	{
		if( size.charAt(size.length -2) + "" + size.charAt(size.length -1) == "px" )
			size = parseInt(size.substr( 0, size.length -2 ));
		else
			size = parseInt(size);
	}
	if( isNaN(size) ) size = 0;
	return 	size;
}


function findPosY(obj) {
	var curtop = 0;

	try
	{
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				if(obj.offsetParent.offsetParent.offsetParent==null)
						break;
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		} else if (obj.y) curtop += obj.y;
	}catch(ex){}
	return curtop;
}

function createElementVsClassName( tagName, className , id )
{
	var element = document.createElement( tagName );

	if( className != null ) element.className = className;
	if( id        != null ) element.setAttribute( "id", id );
	return element;
}


function getObjectRealPosition(object,topLeft)
{
	if(topLeft)value = object.offsetTop;
	else value = object.offsetLeft;

	while(object.offsetParent !=null)
	{
		if(topLeft)value = value + object.offsetParent.offsetTop;
		else value = value + object.offsetParent.offsetLeft;
		object = object.offsetParent;
	}
	return value;
}


	var Browser;

	 modulesCount=6;
	maxHeight = 0;
	 counter = 1;
	modulesIds = new Array();

	function checkBrowserVersion() {
		Browser = new Object();

		Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined');
		Browser.isIE 	  = window.ActiveXObject ? true : false;
		Browser.isIE6 = ( Browser.isIE&& /msie 6\.0/i.test(navigator.userAgent) );
		Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1);
		Browser.isOpera   = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);
		Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari")!=-1);
		Browser.isChrome = (navigator.userAgent.toLowerCase().indexOf("chrome")!=-1);
		var agt=navigator.userAgent.toLowerCase();
		var is_major = parseInt(navigator.appVersion);
		Browser.isIE6 =(Browser.isIE && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
		return Browser;
	}
browserVersion = checkBrowserVersion();



function setZIndex( obj, zIndex )
{
	if( obj != null && obj.nodeType != 3)obj.style.zIndex = zIndex;
	for( var i=0; i<obj.childNodes.length; i++ )
		setZIndex( obj.childNodes[i], zIndex );
}

	function parseXMLStr(stringToParse) {
		var Browser = checkBrowserVersion();
		var rootTag = null;

		if (Browser.isIE) {
			var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
			xmlDocument.async = false;
			xmlDocument.loadXML(stringToParse);
			var rootTag = xmlDocument.documentElement;
		}
		else
		if (Browser.isMozilla) {
			var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(stringToParse,"text/xml");
			var rootTag = xmlDocument.documentElement;
		}
		else
		{
		var domParser = new DOMParser();
			var xmlDocument = domParser.parseFromString(stringToParse,"text/xml");
			var rootTag = xmlDocument.documentElement;
		}
		return rootTag;
	}


function testForObject(Id)
{
  var o = $id(Id);
  if (o)
  {
 	return true;
  }
  return false;
}


	 function setModCount(c){
		modulesCount = c;
	}

	function setXSizesLast(){
		counter++;
		if(counter==modulesCount)
		{
			setXSizes();
		}
	}

	function setIsMax(id, qsize){
	var qmaxHeight = $id("maxHeight").value;
		modulesIds.push(id);
		if(qmaxHeight<qsize-40){
			$id("maxHeight").value = qsize-40;
		}
	}

	function setXSizes()
	{
	var xSize = $id("maxHeight").value
	var i=0;
		for(i=0; i < modulesIds.length; i++)
		{
			if(testForObject(modulesIds[i]+"_table"))
			{
				$id(modulesIds[i]+"_table").style.height= xSize + "px";
			}
		}

	}

	function resetXSizes()
	{
		var i=0;
		for(i=0; i < modulesIds.length; i++)
		{
			if(testForObject(modulesIds[i]) && ($id(modulesIds[i]+"_table").offsetHeight > $id("maxHeight").value))
			{
				 $id("maxHeight").value = $id(modulesIds[i]+"_table").offsetHeight;
			}
		}


		downsize();
		setXSizes();
	}

	function downsize()
	{
		var i=0;
		var max=0;
		for(i=0; i < modulesIds.length; i++)
		{
			var obj = $id( modulesIds[i] + '_table' );
			if( obj != null && max < obj.offsetHeight)
			{
				max = obj.offsetHeight;
			}

		}

		max+=5;
		var maxHeightOBJ = $id("maxHeight");

		if( maxHeightOBJ == null )
		{
			maxHeightOBJ = document.createElement("INPUT");
			maxHeightOBJ.setAttribute( "id", "maxHeight" );
			maxHeightOBJ.setAttribute( "type", "hidden" );
			if(document.body )
			document.body.appendChild( maxHeightOBJ );
		}

		if(maxHeightOBJ.value > max)
		{
			maxHeightOBJ.value = max;
		}

		for(i=0; i < modulesIds.length; i++)
		{

				if(testForObject(modulesIds[i]))
				{
					$id(modulesIds[i]+"_table").style.height= max + "px";
				}

		}

		var xSize = $id("maxHeight").value;


		for(i=0; i < modulesIds.length; i++)
		{
			if(testForObject(modulesIds[i]))
			{
				$id(modulesIds[i]+"_table").style.height= xSize + "px";
			}
		}

	}

bSaf = (navigator.userAgent.indexOf('Safari') != -1);
 bOpera = (navigator.userAgent.indexOf('Opera') != -1);
 bMoz = (navigator.appName == 'Netscape');
function execJS(node) {
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;
  for(var i=0;i<st.length; i++) {
    if (bSaf) {
      strExec = st[i].innerHTML;
    }
    else if (bOpera) {
      strExec = st[i].text;
    }
    else if (bMoz) {
      strExec = st[i].textContent;
    }
    else {
      strExec = st[i].text;
    }
    try {
      eval(strExec.split("<!--").join("").split("-->").join(""));
    } catch(e) {
    }
  }
}

function evalScripts( text )
{

   var scripts = [];
   var script_sources = text.split(/<script.*?>/);
   counter = 0;
   for (var i=1; i < script_sources.length; i++)
      scripts[counter++] = script_sources[i].split(/<\/script>/)[0];

   for (var i=0; i < counter; i++)
   eval( scripts[i] );
}

curWidth=0;
curHeight = 0;
window.onresize = function() {
	afterResize();
	//if (!DEMO) Layouter.carouselTabs();
}

window.onresizeend = function()
{
	afterResize();
	Controller.fixModuleSizes();
	if (!DEMO) Layouter.carouselTabs();
}



function afterResize(){
	try{
	var resized = false;
	newHeight = ("tab_"+Layouter.getActiveTabId()).offsetHeight;
	newWidth = $id( PortletLoader.getAvailableTabId()+"_body1").offsetWidth;
	if(Controller.tabWidth != newWidth)
	{
		resized = true;
		Controller.tabWidth = newWidth;
		if(browserVersion.isIE)
		{
			var newWidth = document.documentElement.clientWidth;
			if( newWidth - curWidth !=0)
			{
				curWidth = newWidth;
				resetXSizes();

			}
		}
		else
		{
			resetXSizes();
		}
	}

	 if(newHeight != Controller.tabHeight){
	 	resized = true;
		if(!DEMO && Layouter.getActiveTab().mode == "max"){
			for( var i=0; i<PORTLETS.length; i++ )
				{
					if(PORTLETS[i] == null  || PORTLETS[i].mode != "max")continue;
					PORTLETS[i].portlet_C_DOMOBJ.style.height=PORTLETS[i].portlet_FRAME.offsetHeight - 20 + "px";
					break;
				}
		}

		if(browserVersion.isIE){
			var newHeight = document.documentElement.clientHeight;
			if( newHeight - curHeight !=0)
			{
				curHeight = newHeight;
				resetXSizes();
			}
		}else{
			resetXSizes();
		}
		Controller.tabHeight = newHeight;
	}
	if (!resized){
		setTimeout(afterResize, 500);
		}
		else{
			Controller.fixModuleSizes();
			if (!DEMO) Layouter.carouselTabs();
			Controller.callModulesListener( "onPageResize", true );
		}
	}catch(ex){}
}


try
{


	Form.makeKeyValue = function(form)
	{		
	    var elements = Form.getElements($id(form));
	    var queryComponents = new Array();
		var inputType;
		var queryComponentKey;
	    for (var i = 0; i < elements.length; i++) {
	      var queryComponent = Form.Element.serialize(elements[i]);		  
	      if (queryComponent) {
				var index = queryComponent.indexOf("=");
				queryComponentKey = queryComponent.substr(0, index);
				if("checkbox" == elements[i].type){					
					if(queryComponents[queryComponentKey] == null){
						queryComponents[queryComponentKey] = new Array();
					}
					queryComponents[queryComponentKey][queryComponents[queryComponentKey].length] = queryComponent.substr(index+1);					
				} else {
		  	    	queryComponents[queryComponentKey] = queryComponent.substr(index+1);
				}
		  }
	    }

	    return queryComponents;
	}
}catch(ex){}



function resize(size){
 if (navigator.appName=="Netscape") {
  $id("tablewidth").width=window.innerWidth;
 }
 if (navigator.appName.indexOf("Microsoft")!=-1) {
  $id("tablewidth").style.width=document.documentElement.clientWidth;
 }

 }

function sleep( msec)
{
	var currentdate = new Date();

	document.getElementById("log").innerHTML += currentdate + "<br />";

	currentdate = Math.round(currentdate.getTime());

	if( !sleep.started  ){ sleep.start = currentdate; sleep.started =  true; }

	if( sleep.start + msec > currentdate )
		sleep( msec);
	else
	{
		sleep.started = false;
	}
}
sleep.start = null;
sleep.started = false;

function evalScripts( text )
{
   var scripts = [];
   var script_sources = text.split(/<script.*?>/);
   counter = 0;
   for (var i=1; i < script_sources.length; i++)
      scripts[counter++] = script_sources[i].split(/<\/script>/)[0];

   for (var i=0; i < counter; i++)
   eval( scripts[i] );
}
function encode(str)
{
	var tokens = str.split("/");
	var result = encodeURIComponent(tokens[0]);
	for(var i=1; i< tokens.length; ++i)
	{
		result += "/" + encodeURIComponent(tokens[i]) ;
	}
	return result;
}

function isEmailValid(e) {
	var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.+@-_QWERTYUIOPASDFGHJKLZXCVBNM";
	for(var i=0; i<e.length; i++){
		if (ok.indexOf(e.charAt(i))<0) {
			return false;
		}
	}
	if (document.images) {
		var re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		var re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,8}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return -1;
		}
	}
}
function  checkName(str){
	if(str.indexOf("/") == -1)
	return true;
	return false;
}
validateContact=function(first, second, email, phone, key, im, accountType){
 	     if(first=='' || second=='')	return Framework.Lang.Contact_Empty_FLName;
    	 if(!checkName(first) || !checkName(second))	return Framework.Lang.Contact_NotValid_FLName;
		
         var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
         var phoneFilter = /^([\+])?([0-9])+$/;
         
         if(accountType == undefined || accountType =='Email')
       	 	if (!filter.test(email))  return Framework.Lang.Contact_notValidEmail;
  		 
  		 if(accountType == undefined || accountType =='SMS')
		 	if (phone != "" && !phoneFilter.test(phone))  return Framework.Lang.Contact_notValidPhone;
		 	
		 if(accountType == undefined || accountType =='IM')
		 	if(im.trim() == '')	return Framework.Lang.Contact_notValidIM;

         if(key != undefined && key.trim()=='')   return Framework.Lang.Contact_imageTextRequired;
	 
  		return "success";

}
var validateMail = function(first, second, email){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
     if (!filter.test(email))  return Framework.Lang.Contact_notValidEmail;
  	 return "success";
}
var validateIM = function(first, second, im){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 if(im.trim() == '')
	 	return Framework.Lang.Contact_notValidIM;
  	 return "success";
}
var validateSMS = function(first, second, phone){
	 if(first=='' || second=='')
	 	return Framework.Lang.Contact_Empty_FLName;
     if(!checkName(first) || !checkName(second))
     	return Framework.Lang.Contact_NotValid_FLName;
	 var phoneFilter = /^([\+])?([0-9])+$/;
	 if (phone != "" && !phoneFilter.test(phone))
	 	return Framework.Lang.Contact_notValidPhone;
  	 return "success";
}
Array.prototype.consistOf = function(compare, thisObj) {
    for ( var i=0, j=this.length; i < j;   i++ ) {
        if (this[i] == compare) {
            return true;
        }
    }
    return false;
};
Array.prototype.unique = function( b ) {
	 var a = [], i, l = this.length;
	 for( i=0; i<l; i++ ) {
	  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
	 }
	 return a;
};
Array.prototype.withoutArr = function(arr, thisObj) {
	var a = [];
    for ( var i=0; i < this.length;   i++ ) {
    	if (!arr.consistOf(this[i])) {
	       a.push( this[i] );
	    }
    }
    return a;
};
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
}
String.prototype.escapeHTML= function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  };

 String.prototype.unescapeHTML = function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0].nodeValue;
  };
  String.prototype.stripTags=function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  };
  String.prototype.replaceAll= function(s1, s2) {
 	return this.split(s1).join(s2)
	};
String.prototype.makeNBSP = function() {
  	var thisCopy = "";
	for( var i=0; i<this.length; i++ )
		thisCopy += ( this.charAt(i) == " ")?"&nbsp;":this.charAt(i);
	return thisCopy;
};
	cleanWhitespace = function(node){
	for (var x=0; x<node.childNodes.length; x++) {
		var child = node.childNodes[x];
		if ((child.nodeType == 3) && (!notspace.test(child.nodeValue)))	{
			node.removeChild(node.childNodes[x]);
			x--;
		}
		if(child.nodeType == 1) {
			Utils.cleanWhitespace(child);
		}
	}
}

function clone(obj,deep){
	var objectClone = new obj.constructor();
  for (var property in obj){
    if (!deep){
      objectClone[property] = obj[property];
	 }
    else if (typeof obj[property] == 'object'){
      	objectClone[property] = clone(obj[property],deep);
	}
	else if(obj[property]=='array'){
		objectClone[property]=[];
		var arr=obj[property];
		for(var i=0; i<arr.length; i++){
			objectClone[property].push(clone(arr[i],true));
		}
	}
    else{
      objectClone[property] = obj[property];
	}
  }
  return objectClone;
}

function getRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
        if (isW3C) {
            theObj = document.getElementById(obj);
        } else if (isIE4) {
            theObj = document.all(obj);
        } else if (isNN4) {
            theObj = seekLayer(document, obj);
        }
    } else {
        theObj = obj;
    }
    return theObj;
}

function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
            result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}
function getObjectHeight(obj)  {

    var elem = getRawObject(obj);

    var result = 0;

    if (elem.offsetHeight) {

        result = elem.offsetHeight;

    } else if (elem.clip && elem.clip.height) {

        result = elem.clip.height;

    } else if (elem.style && elem.style.pixelHeight) {

        result = elem.style.pixelHeight;

    }

    return parseInt(result);

}
function removeNode_( obj )
{
	var objecttodestroy;
	if( typeof(obj) == "string" )
	objecttodestroy = document.getElementById( obj );
	else
	objecttodestroy = obj;

	if( objecttodestroy == null )
	return;

	objecttodestroy.parentNode.removeChild(objecttodestroy);
}

function fixModule( id ){
	try{
		if(!PortletLoader.headersPermanent && Layouter.getActiveTab().mode != "max"){
			PortletLoader.getPortlet(id).hideHeaderIcons();
		}
	}catch(ex){}
}

function setCookie(aName, aValue, aLifetime) {
 var now = new Date();
 var expiry = new Date(now.getTime() + aLifetime*24*60*60*1000);
 if ((aValue != null) && (aValue != ""))
 document.cookie=aName + "=" + escape(aValue) + "; expires=" + expiry.toGMTString() + "; path=/";
 return getCookie(aName) != null;
}

function getCookie(aName) {
 var aStart, anEnd;
 if (document.cookie) {
  aStart = document.cookie.indexOf(aName+"=");
  if (aStart < 0) return null;
  aStart = document.cookie.indexOf("=", aStart) + 1;
  anEnd = document.cookie.indexOf(";", aStart);
  if (anEnd < 0) anEnd = document.cookie.length;
  return unescape(document.cookie.substring(aStart, anEnd));
 }
 else return null;
}

function deleteCookie(aName) {
 var now = new Date();
 var expired = new Date(now.getTime() - 2*24*60*60*1000);
 document.cookie=aName + "=null; expires=" + expired.toGMTString();
}

function statusColumnRenderer(val){
				var retString;
				var imgUrl;
				switch(val){
					case TEST_STATUS_OK_STRING:
						imgUrl="images/snapshot/state-ok.gif";
					break;
					case TEST_STATUS_NA_STRING:
						imgUrl="images/snapshot/state-NA.gif";
					break;
					case TEST_STATUS_NOK_STRING:
						imgUrl="images/snapshot/state-notok.gif";
					break;
				}
					retString="<img title='"+val+"' src='"+imgUrl+"'</img>";
				return retString;
}

Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
 }
 return a;
};

function Timer(){
	this.obj = (arguments.length)?arguments[0]:window;
	return this;
}

Timer.prototype.setInterval = function(func, msec){
	var i = Timer.getNew();
	var t = Timer.buildCall(this.obj, i, arguments);
	Timer.set[i].timer = window.setInterval(t,msec);
	return i;
}
Timer.prototype.setTimeout = function(func, msec){
	var i = Timer.getNew();
	Timer.buildCall(this.obj, i, arguments);
	Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
	return i;
}
Timer.prototype.clearInterval = function(i){
	if(!Timer.set[i]) return;
	window.clearInterval(Timer.set[i].timer);
	Timer.set[i] = null;
}
Timer.prototype.clearTimeout = function(i){
	if(!Timer.set[i]) return;
	window.clearTimeout(Timer.set[i].timer);
	Timer.set[i] = null;
}


Timer.set = new Array();
Timer.buildCall = function(obj, i, args){
	var t = "";
	Timer.set[i] = new Array();
	if(obj != window){
		Timer.set[i].obj = obj;
		t = "Timer.set["+i+"].obj.";
	}
	t += args[0]+"(";
	if(args.length > 2){
			Timer.set[i][0] = args[2];
			t += "Timer.set["+i+"][0]";
			for(var j=1; (j+2)<args.length; j++){
			Timer.set[i][j] = args[j+2];
			t += ", Timer.set["+i+"]["+j+"]";
			}
	}
	t += ");";
	Timer.set[i].call = t;
	return t;
}
Timer.callOnce = function(i){
	if(!Timer.set[i]) return;
	eval(Timer.set[i].call);
	Timer.set[i] = null;
}
Timer.getNew = function(){
	var i = 0;
	while(Timer.set[i]) i++;
	return i;
}


var compare=function(first, second , type){
	if(type==SORT_TYPE_ASC)   return first<second;
	else if(type==SORT_TYPE_DESC)  return first>second;
}
	var heapSort=function(numbers, col, type){
  		var i, temp;
  		for (i = parseInt(numbers.length / 2)-1; i >= 0; i--)
    		siftDown(numbers, i, numbers.length-1, col, type);

  		for (i = numbers.length-1; i >= 1; i--){
    		temp = numbers[0];
    		numbers[0] = numbers[i];
    		numbers[i] = temp;
    		siftDown(numbers, 0, i-1, col, type);
  		}
	}

	var siftDown=function(numbers, root,  bottom, col, type){
  		var done, maxChild, temp;

  		done = 0;
  		while ((root*2 <= bottom) && (done==0)){
    		if (root*2 == bottom)
      			maxChild = root * 2;
    		else if (!compare(numbers[root * 2][col] , numbers[root * 2 + 1][col], type))
      			maxChild = root * 2;
    		else
      			maxChild = root * 2 + 1;
    		if (compare(numbers[root][col], numbers[maxChild][col], type)){
      			temp = numbers[root];
      			numbers[root] = numbers[maxChild];
      			numbers[maxChild] = temp;
      			root = maxChild;
    		}
    		else
      			done = 1;
  		}
	}

var YAHOO = {};
YAHOO.util = {};
var CN = YAHOO.util.Connect;


function ankapFunction( val )
{
	//alert("aaaaaaaaa");
}



function $id() {
//  for (var i = 0; i < arguments.length; i++){
    var element = arguments[0];
    if (typeof element == 'string')
      element = document.getElementById(element);

	if( !!arguments[1] )
	{
	  try{
			var obj = element._ext_object;
	  		if( obj != null) element = obj;
	  }catch(ex){}
	}
//    elements.push(element);
//  }
  return element;

}
/*
Object.extend(String.prototype, {
  makeNBSP: function() {
  	var thisCopy = "";
	for( var i=0; i<this.length; i++ )
		thisCopy += ( this.charAt(i) == " ")?"&nbsp;":this.charAt(i);
	return thisCopy;
  }
});

*/

function flashCheckboxCallback(functionName, elId, index,contactId, checked){
	var el=$id(elId);
	var selfNot=el.self;
	eval("selfNot."+functionName+"("+index+","+contactId+","+checked+")");
}
function flashCheckboxHeaderCallback(functionName,elId, index, checked){
	var el=$id(elId);
	var selfNot=el.self;
	eval("selfNot."+functionName+"("+index+","+checked+")");
}
function flashImageCallback(functionName, elId, index,contactId){
	var el=$id(elId);
	var selfNot = el.self;
	eval("selfNot." + functionName + "("+contactId+")");
}
function flashCellCallback(functionName, elId, index,contactId){
	var el=$id(elId);
	var selfNot=el.self;
	eval("selfNot." + functionName + "(" + contactId + ")");
}

function getGridFlashNode( id, data, config )
{
var hasProductInstall = DetectFlashVer(6, 0, 65);
var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

// Check to see if a player with Flash Product Install is available and the version does not meet the requirements for playback
if ( hasProductInstall && !hasRequestedVersion ) {
	// MMdoctitle is the stored document.title value used by the installation process to close the window that started the process
	// This is necessary in order to close browser windows that are still utilizing the older version of the player after installation has completed
	// DO NOT MODIFY THE FOLLOWING FOUR LINES
	// Location visited after installation is complete if installation is required
	var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
	var MMredirectURL = window.location;
    document.title = document.title.slice(0, 47) + " - Flash Player Installation";
    var MMdoctitle = document.title;

	return AC_FL_RunContent(
		"src", "playerProductInstall",
		"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
		"width", "100%",
		"height", "100%",
		"align", "middle",
		"id", id,
		"quality", "high",
		"bgcolor", "#869ca7",
		"name", id,
		"allowScriptAccess","samedomain",
		"wmode","transparent",
		"type", "application/x-shockwave-flash",
		"pluginspage", "http://www.adobe.com/go/getflashplayer"
	);
} else if (hasRequestedVersion) {
	// if we've detected an acceptable version
	// embed the Flash Content SWF when all tests are passed
	return AC_FL_RunContent(
			"src", "grid3",
			"width", "100%",
			"height", "100%",
			"align", "middle",
			"id", id,
			"quality", "high",
			"bgcolor", "#869ca7",
			"name", id,
			"flashvars",'data=' + encode(data) + '&config='+ encode(config),
			"allowScriptAccess","samedomain",
			"wmode","transparent",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
	);
  } else {  // flash is too old or we can't detect the plugin
    var alternateContent = 'This content requires the Adobe Flash Player. <a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
    return alternateContent;
  }
}



  function toFlexJSONArrayString(arr) {
	var data_ = "[";
	var dataItem;

	for (var i=0; i<arr.length; i++ )
	{
		var item_ = arr[i];
		dataItem = "";
		dataItem += '{';
		for( var key in item_ )
		{
			if( typeof(item_[key]) == "function" )continue;
			if( typeof(item_[key]) == "object" )
				dataItem += '"'+ key +'": '+ toFlexJSONObjectString(item_[key]) +',';
			else
				dataItem += '"'+ key +'": "'+ item_[key] +'",';

		}
		dataItem = dataItem.substr(0, dataItem.length-1);

		dataItem += '}';
		if( i != arr.length -1 )dataItem += ',';
		data_ += dataItem;
	}
	data_ += "]";
	return data_;
  }



 function  toFlexJSONObjectString(obj) {
	var data_ = "{";
	var dataItem;
	for (var key in obj )
	{
		if( typeof(obj[key]) == "function" )continue;
		data_ += '"'+ key +'": "'+ obj[key] +'",';
	}
	data_ = data_.substr(0, data_.length-1);
	data_ += '}';
	return data_;
  }

function preloadimages(){
	var myimages=new Array();
	for (i=0;i<preloadimages.arguments.length;i++){
		myimages[i]=new Image();
		myimages[i].src=preloadimages.arguments[i];
	}
}

function decode(str)
{
 var tokens = str.split("/");
 var result = decodeURIComponent(tokens[0]);
 for(var i=1; i< tokens.length; ++i)
 {
  result += "/" + decodeURIComponent(tokens[i]) ;
 }
 return result;
}

Utils.url_validation = function(theurl) {
     var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
     if (tomatch.test(theurl)) {
             return true;
     } else {
           return false; 
     }
}
Utils.sort =  function(array, col, type){
	if (type == null) type = SORT_TYPE_ASC;
	for (var i=0; i < array.length-1; i++){
		index = i;
		for (var j=i;j<array.length;j++)
			if ( compare(array[index][col], array[j][col], type) ) index = j;
		var a = array[i];
		array[i] = array[index];
		array[index] = a;
	}
}
Utils.appendZero = function(str, length){
	var zeroStr = "";
	for(var i=0; i < length - str.length; i++){
		zeroStr += "0" 
	}
	zeroStr += str;
	return zeroStr;
}



function requestUserAgents(params,callback){
	if(typeof params=='undefined'){
		params=null;
	}
	if(typeof callback=='undefined' || callback==null){
		callback=initAgentData;
	}
	var moduleValueList=Controller.getFromCache("my_agents_list",true);
	if(moduleValueList==null){
		moduleValueList=[{"label":"loading...","value":"null"}];
		var url=Framework.Modules.SnmpWidget.serviceURL+'/'+User.userId+'/useragents';
		var response=Request.sendGET(url,callback,params);
	}
	return moduleValueList;
}

function initAgentData(response,params){
	USER_AGENTS=eval("("+response.responseText+")");
	var agents=[];
	for(var i=0; i<USER_AGENTS.length; i++){
		agents.push({"label":USER_AGENTS[i].key,"value":USER_AGENTS[i].key});
	}
	var cacheTimeout=7000;
	if(agents.length!=0){
		cacheTimeout=25000;
	}
	Controller.setInCache("my_agents_list",agents,cacheTimeout);
	ModuleManager.fillSelect(agents,params);
	return agents;
}

var showMessage = function(config){
	var dialog = new Dialog();
	var cont = document.createElement("div");
	cont.className = "text";
	cont.innerHTML = config.body;
	function handler(){
		config.okHandler(config.handlerParams);
		dialog.closeDialog();
	}
	dialog.openDialog(cont, handler, null, config.header, config.width, config.height);
}


