/* 
	Copyright (c) 2008 EmpireGP Services / Russell Brown / EmpireGP.com
*/

function infoMessage(type, message, msgId, displayType) {
	var icon = "";
	var enabled = getCookie("InfoMessage_" + msgId);
	var msgArea = document.getElementById("info-message");

	if (!displayType)
		displayType = 0;

	if (new String(enabled) == "false")
		return;

	if (type == "error")
		icon = "<img src='./assets/icons/exclamation.gif' border='0' width='16' height='16' style='padding-right: 10px;' />";
	else
		icon = "<img src='./assets/icons/error.gif' border='0' width='16' height='16' style='padding-right: 10px;' />";

	msgArea.innerHTML = icon + message;
	msgArea.style.display = "block";

	if (msgId != null) {
		if (displayType == 0) {
			msgArea.innerHTML += "<br><a href='JavaScript: infoMessageNoRemind(\"" + msgId + "\");'>Don't Remmind Me Again</a>";
			msgArea.innerHTML += " | <a href='JavaScript: infoMessageClose();'>OK</a>";
		} else if (displayType == 1) {
			msgArea.innerHTML += "<br><a href='JavaScript: infoMessageClose();'>OK</a>";
		} else if (displayType == 3) {
			// DO NOTHING
		} else if (displayType.length > 0) {
			msgArea.innerHTML += "<br><a href='JavaScript: infoMessageClose();'>" + displayType + "</a>";
		}
	}
}

function infoMessageNoRemind (msgId) {
	setCookie("InfoMessage_" + msgId, false)
	infoMessageClose();
}

function infoMessageClose () {
	var msgArea = document.getElementById("info-message");
	msgArea.style.display = "none";
	msgArea.innerHTML = "";
}

function rsListTableHover(o,d) {
	if (d == 1)
		o.className = o.className + " result_hover";
	else
		o.className = o.className.replace(" result_hover", "");
}

// Extend the all Array's to have a find function
String.prototype.replaceAll = function(substring1, substring2) {
    var retVar = this.toString();
    while (retVar.indexOf(substring1) > -1)
       retVar = retVar.replace(substring1, substring2);

    return retVar;
};

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

// This will extend all objects that extend Object to have the isArray function
Object.prototype.isArray = function() {
   if (this.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
};

// Extend the all Array's to have a find function
Array.prototype.find = function(str) {
	for(var i=0; i < this.length; i++) {
        if (this[i] == str) {
            return i;
        }
    }

    return -1
};

Array.prototype.insert = function(value, pos) {
	if (!pos || pos > this.length) {
		this.push(this);
		return this.length - 1;
	} else {
		for (var x=this.length; x > pos; x--) {
			this[x] = this[x-1];
		}
		this[pos] = value;
		return pos;
	}
};

// Extend the all Array's to have a find function
Array.prototype.exists = function(ref) {
	for(var i=0; i < this.length; i++) {
        if (this[i] == ref) {
            return i;
        }
    }

    return -1
};

// Extend the all Array's to have a delete at function
Array.prototype.deleteAt = function(pos) {
    if (this.length >= pos-1 && pos > -1)
        this.splice(pos, 1);

    return true
};

// Extend the all Array's to have a delete matching function
Array.prototype.deleteMatching = function(str) {
    var x;
    while ((x=this.find(str)) > -1)
        this.splice(x, 1);

    return true
};

// Extend the all Array's to have a find function
Array.prototype.sortNumeric = function(dir) {
    if (dir && dir == 'desc')
        this.sort(function(a, b){ return (b-a); });
    else
        this.sort(function(a, b){ return (a-b); });
};

YAHOO.namespace("YAHOO.EGPS.util.loadingIndicator");
YAHOO.EGPS.util.loadingIndicator = function() {};
YAHOO.EGPS.util.loadingIndicator.prototype.onCancel = new YAHOO.util.CustomEvent("onCancel", this); 
YAHOO.EGPS.util.loadingIndicator.prototype.show = function() { this.popUp.show(); };
YAHOO.EGPS.util.loadingIndicator.prototype.hide = function() { this.popUp.hide(); };
YAHOO.EGPS.util.loadingIndicator.prototype.init = function() {
	var x = (YAHOO.util.Dom.getClientWidth() / 2) - 120;
	var y = 150;

	this.popUp = new YAHOO.widget.Panel(
		"wait",  
		{
			width: "240px", 
			x: x,
			y: y,
			close: false, 
			draggable: false, 
			zindex:50,
			modal: true,
			visible: false,
			appendtodocumentbody: true
		} 	
	)

	var body = "<img src=\"./assets/images/wait.gif\"/>";
	body += "<br><div style='text-align: center;'>";
		body += "<input type='button' value='cancel' id='loadingIndicatorCancelButton'";
			body += " style='font-size: 1.2em;'";
			body += " onClick='loadingIndicator.hide(); window.stop();'";
		body += "/>";
	body += "</div>";

    this.popUp.setHeader("Loading, please wait...");
    this.popUp.setBody(body);
    this.popUp.render(document.body);

	onCancel = function (e) {
		loadingIndicator.onCancel.fire()
	}

	var liCancelButton = document.getElementById("loadingIndicatorCancelButton");
	YAHOO.util.Event.addListener(liCancelButton, "click", onCancel); 

    return this;
};

// CONNECTION OBJECT
YAHOO.namespace("YAHOO.EGPS.Service.Connection");

YAHOO.EGPS.Service.Connection = function() {};

YAHOO.EGPS.Service.Connection.prototype.successEvent = new YAHOO.util.CustomEvent("successEvent");
YAHOO.EGPS.Service.Connection.prototype.failureEvent = new YAHOO.util.CustomEvent("failureEvent");

YAHOO.EGPS.Service.Connection.prototype.success = function(){
    this.successEvent.fire(arguments[0]);
},

YAHOO.EGPS.Service.Connection.prototype.failure = function(){
    this.failureEvent.fire(arguments[0]);
},

YAHOO.EGPS.Service.Connection.prototype.send = function (url) {
    var conn, request;

    if (!url) { 
        alert("You did not provide a URL.");
        return;
    }

    YAHOO.util.Connect.asyncRequest('GET', url, this);
};


YAHOO.namespace("YAHOO.EGPS.Utils.UUID");

// on creation of a UUID object, set it's initial value
YAHOO.EGPS.Utils.UUID = function(){
	this.id = this.createUUID();
}

// When asked what this Object is, lie and return it's value
YAHOO.EGPS.Utils.UUID.prototype.valueOf = function(){ return this.id; }
YAHOO.EGPS.Utils.UUID.prototype.toString = function(){ return this.id; }


// INSTANCE SPECIFIC METHODS
YAHOO.EGPS.Utils.UUID.prototype.createUUID = function(){
	// Loose interpretation of the specification DCE 1.1: Remote Procedure Call
	// described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
	// since JavaScript doesn't allow access to internal systems, the last 48 bits 
	// of the node section is made up using a series of random numbers (6 octets long).
	var dg = this.timeInMs(new Date(1582, 10, 15, 0, 0, 0, 0));
	var dc = this.timeInMs(new Date());
	var t = dc - dg;
	var h = '-';
	var tl = this.getIntegerBits(t,0,31);
	var tm = this.getIntegerBits(t,32,47);
	var thv = this.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2
	var csar = this.getIntegerBits(this.randrange(0,4095),0,7);
	var csl = this.getIntegerBits(this.randrange(0,4095),0,7);

	// since detection of anything about the machine/browser is far to buggy, 
	// include some more random numbers here
	// if nic or at least an IP can be obtained reliably, that should be put in
	// here instead.
	var n = this.getIntegerBits(this.randrange(0,8191),0,7) + 
			this.getIntegerBits(this.randrange(0,8191),8,15) + 
			this.getIntegerBits(this.randrange(0,8191),0,7) + 
			this.getIntegerBits(this.randrange(0,8191),8,15) + 
			this.getIntegerBits(this.randrange(0,8191),0,15); // this last number is two octets long
	return tl + h + tm + h + thv + h + csar + csl + h + n; 
}


// GENERAL METHODS (Not instance specific)

// Pull out only certain bits from a very large integer, used to get the time
// code information for the first part of a UUID. Will return zero's if there 
// aren't enough bits to shift where it needs to.
YAHOO.EGPS.Utils.UUID.prototype.getIntegerBits = function(val,start,end){
	var base16 = this.returnBase(val,16);
	var quadArray = new Array();
	var quadString = '';
	var i = 0;
	for(i=0;i<base16.length;i++){
		quadArray.push(base16.substring(i,i+1));	
	}
	for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
		if(!quadArray[i] || quadArray[i] == '') quadString += '0';
		else quadString += quadArray[i];
	}
	return quadString;
}

// Numeric Base Conversion algorithm from irt.org In base 16: 0=0, 5=5, 10=A, 15=F
YAHOO.EGPS.Utils.UUID.prototype.returnBase = function(number, base){
	var convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    if (number < base) var output = convert[number];
    else {
        var MSD = '' + Math.floor(number / base);
        var LSD = number - MSD*base;
        if (MSD >= base) var output = this.returnBase(MSD,base) + convert[LSD];
        else var output = convert[MSD] + convert[LSD];
    }
    return output;
}

// This is approximate but should get the job done for general use.
YAHOO.EGPS.Utils.UUID.prototype.timeInMs = function(d){
	var ms_per_second = 100; // constant
	var ms_per_minute = 6000; // ms_per second * 60;
	var ms_per_hour   = 360000; // ms_per_minute * 60;
	var ms_per_day    = 8640000; // ms_per_hour * 24;
	var ms_per_month  = 207360000; // ms_per_day * 30;
	var ms_per_year   = 75686400000; // ms_per_day * 365;
	return Math.abs((d.getUTCFullYear() * ms_per_year) + (d.getUTCMonth() * ms_per_month) + (d.getUTCDate() * ms_per_day) + (d.getUTCHours() * ms_per_hour) + (d.getUTCMinutes() * ms_per_minute) + (d.getUTCSeconds() * ms_per_second) + d.getUTCMilliseconds());
}

// pick a random number within a range of numbers
// int c randrange(int a, int b); where a <= c <= b
YAHOO.EGPS.Utils.UUID.prototype.randrange = function(min,max){
	var num = Math.round(Math.random() * max);
	if(num < min){ 
		num = min;
	} else if (num > max) {
		num = max;
	}
	return num;
}
// end of YAHOO.EGPS.Utils.UUID


// other util functions

function showErr() {
	document.getElementById('errorButton').style.display = "none";
	document.getElementById('errorDetails').style.display = "block";
};
	
//
function showHideDiv(divId){
 	var div = document.getElementById(divId);
 	div.style['display'] = (div.style['display']=="none")? "":"none";
}

function showHiddenChildren(container, childrenElementTypes, toggleId){
	var containerEl = document.getElementById(container);
 	var tags = childrenElementTypes.split(',');
 	for(var t=0;t<tags.length;t++){
 		var children = containerEl.getElementsByTagName(tags[t]);
 		for(var i = 0 ; i < children.length; i++){
 			children[i].style['display'] = "";	
 		}
 	}
 	var toggle = document.getElementById(toggleId);
 	toggle.style['display'] = "none";
 	
}

function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


