﻿var CONTENT_TYPE = "Content-Type";
var APP_JSON = "application/json";
var ORGANIZATION_CODE_KEY = "ORGANIZATION_CODE";
var HTTP_VERB = "POST";


// ------------------------------------ util -------------------------------------
function getreq()
{
	var r;
	if ( window.XMLHttpRequest )
	{
		r = new window.XMLHttpRequest();
	}
	else if ( window.ActiveXObject )
	{
		r = new ActiveXObject("Msxml2.XMLHTTP");
		if (!r)
			r = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return r;
}


function getxy(el) 
{
	var xy = {x:0,y:0};
	var element = ( typeof el == "object" ) ? el : document.getElementById(el);
	while (element) 
	{
		try
		{
			xy.x += element.offsetLeft;
			xy.y += element.offsetTop;
		}
		catch(err) { }
		element = element.offsetParent;
	}
	return xy;
}


// Add a trim method to all strings:
// i.e. " string surrounded with whitespace   ".trim() would return "string surrounded with whitespace";

String.prototype.trim = function(){
	var rx = new RegExp("(\\S+(\\s+\\S+)*)", "g");
	try
	{
		var rxo = rx.exec(this);
		return rxo[0];
	}
	catch(err) { return ""; }
};


// find current value in menu and sets it as selected
function set_selected_value(menu,itemvalue)
{
	var m = ( typeof menu == "object" ) ? menu : document.getElementById(menu);
	if (m)
	{
		for ( x = 0; x < m.options.length; x++ )
		{
			if (m && m.options[x].value == itemvalue )
			{
				m.selectedIndex = x;
				break;
			}
		}
	}
}


function get_menu_val(menu)
{
	var m = ( typeof menu == "object" ) ? menu : document.getElementById(menu);
	var retval = "";
	try
	{
		retval = m ? m.options[m.selectedIndex].value : "";
	}
	catch(err) { }
	return retval;
}


// returns an array of {K,V} objects
function getObjectChildrenInput(oParent)
{
	var retval = [];
	var count = 0;
	var p = ( typeof oParent == "object" ) ? oParent : document.getElementById(oParent);
	if (p)
	{
		var inputs = p.getElementsByTagName("input");
		for(var x=0; x < inputs.length; x++ )
		{
			var tObj = inputs[x];
			var arrobj = { };
			arrobj.K = tObj.name == null ? tObj.id : tObj.name;
			if (tObj.type == "text")
				arrobj.V = tObj.value;
			else if (tObj.type == "checkbox")
				arrobj.V = tObj.checked;
			else if (tObj.type == "radio" && tObj.checked)
				arrobj.V = tObj.value;
			else
				arrobj = null;
			if (arrobj)
				retval[count++] = arrobj;
		}
		var inputs = p.getElementsByTagName("select");
		for(var x=0; x < inputs.length; x++ )
		{
			var tObj = inputs[x];
			var arrobj = { };
			arrobj.K = tObj.name == null ? tObj.id : tObj.name;
			arrobj.V = get_menu_val(tObj);
			retval[count++] = arrobj;						
		}
	}
	return retval;
}


// parses supplied text into an XML document
function text2XMLDoc(t)
{
	var doc;
	if (window.ActiveXObject)
	{
	  doc=new ActiveXObject("Microsoft.XMLDOM");
	  doc.async="false";
	  doc.loadXML(t);
	}
	else
	{
	  var parser=new DOMParser();
	  doc=parser.parseFromString(t,"text/xml");
	}
	return doc;
}

function getstringreturn2(tx)
{
	try
	{
		var xmlobj = text2XMLDoc(tx);
		return xmlobj.documentElement.firstChild.nodeValue;
	}
	catch(err)
	{
		alert(err.description);
		return "(error)";
	}
}

function getstringreturn(tx)
{
	try
	{
		var start_point = tx.indexOf("<string");
		var end_point = tx.indexOf("</string>") - 1;
		if ( end_point > 0 )
		{
			start_point = tx.indexOf(">",start_point) + 1;
			return tx.substring(start_point,end_point+1);
		}
		else
			return ""; // in case it was something like <string />, i.e. empty string
	}
	catch(err)
	{
		return "(error)";
	}
}

// Add a trim method to all strings:
// i.e. " string surrounded with whitespace   ".trim() would return "string surrounded with whitespace";

String.prototype.trim = function(){
	var rx = new RegExp("(\\S+(\\s+\\S+)*)", "g");
	try
	{
		var rxo = rx.exec(this);
		return rxo[0];
	}
	catch(err) { return ""; }
};


// ---------------------------- cookie reading/writing/deleting ------------------000000000

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') 
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
			return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// ----------------------------- Keyboard filtering -----------------------------------
// Add: onFocus="document.onkeydown=numbersOnly;" onBlur="document.onkeydown=null

function numbersOnly(e)
{
	if (!e)
		e=window.event;
	var k = (window.event ?  e.keyCode : e.which);
	return (((k>47) && (k<58)) || k==8 || k==45 || k==189 || k==109 || k== 9 || ((k>95) && (k<106))); // 0-9, bksp, hyphen(s), tab
}

function amountsOnly(e)
{
	if (!e)
		e=window.event;
	var k = (window.event ?  e.keyCode : e.which);
	if (k==16) return true;
	return (((k>47) && (k<58)) || k==8 || k==9 || k==46 || k==110 || k==188 || k==190 || ((k>95) && (k<106)) ); // 0-9, bksp, tab, decimalpoint
}

// passed an HTML element as a parameter, returns an object 
// with 2 properties: absolute coordinates (x,y) of the element
function getxy(el) 
{
	var xy = {x:0,y:0};
	var element = ( typeof el == "object" ) ? el : document.getElementById(el);
	while (element) {
		try
		{
			xy.x += element.offsetLeft;
			xy.y += element.offsetTop;
		}
		catch(err) { }
		element = element.offsetParent;
	}
	return xy;
}

function getwindowsize()
{
	var xy = { x:0, y:0 };
	if (self.innerHeight) // all except Explorer
	{
		xy.x = self.innerWidth;
		xy.y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		xy.x = document.documentElement.clientWidth;
		xy.y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		xy.x = document.body.clientWidth;
		xy.y = document.body.clientHeight;
	}
	return xy;
}

function getscrolltop()
{
	var xy = { x:0, y:0 };
	if (self.pageYOffset) // all except Explorer
	{
		xy.x = self.pageXOffset;
		xy.y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
	{
		xy.x = document.documentElement.scrollLeft;
		xy.y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		xy.x = document.body.scrollLeft;
		xy.y = document.body.scrollTop;
	}
	return xy;
}

function getStyle(el, styleProp)
{
    var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

// --------------- validation --------------------

function email_validation(em)
{
	return /^((?:\w+[^\w\s@]?)+)@((?:[^\.@\s]+\.)+[a-z]{2,}|(?:\d{1,3}\.){3}\d{1,3})$/.test(em)
}


// ------------------------- mouse tracking -------------------------

function trackMouse(i)
{
	if (i=='start')
	{
		if (! document.all ) 
			document.captureEvents(Event.MOUSEMOVE)
		document.onmousemove = getMouseXY;	
	}
	else
	{
		if (! document.all ) 
			document.captureEvents(Event.NONE)
		document.onmousemove = null;	
	}
}


var mouseX = 0;
var mouseY = 0;

function getMouseXY(e) {
	if (document.all) 
	{
		mouseX = event.clientX + document.body.scrollLeft;
		mouseY = event.clientY + document.body.scrollTop;
	}
	else 
	{
		mouseX = e.pageX;
		mouseY = e.pageY;
	}  
	return true;
}


// --------------------------------

// returns an array of {K,V} objects
function getObjectChildrenInput(oParent)
{
	var retval = [];
	var count = 0;
	var p = ( typeof oParent == "object" ) ? oParent : document.getElementById(oParent);
	if (p)
	{
		var inputs = p.getElementsByTagName("input");
		for(var x=0; x < inputs.length; x++ )
		{
			var tObj = inputs[x];
			var arrobj = { };
			arrobj.K = tObj.name == null ? tObj.id : tObj.name;
			if (tObj.type == "text")
				arrobj.V = tObj.value;
			else if (tObj.type == "checkbox")
				arrobj.V = tObj.checked;
			else if (tObj.type == "radio" && tObj.checked)
				arrobj.V = tObj.value;
			else
				arrobj = null;
			if (arrobj)
				retval[count++] = arrobj;
		}
		
		inputs = p.getElementsByTagName("select");
		for(var x=0; x < inputs.length; x++ )
		{
			var tObj = inputs[x];
			var arrobj = { };
			arrobj.K = tObj.name == null ? tObj.id : tObj.name;
			arrobj.V = get_menu_val(tObj);
			retval[count++] = arrobj;						
		}
	}
	return retval;
}

// ------------------------------ veil ---------------------------------------

var veil_count = 0;

function show_veil()
{
	if ( veil_count == 0 )
	{
		try
		{
			var ww = getwindowsize();
			var st = getscrolltop();
			$('#veil').css( "top", "" + st.y + "px" );
			$("#veil").css( "width", "" + (ww.x - 1 ) + "px" );
			$("#veil").css( "height", "" + (ww.y - 1 ) + "px" );
			$('#veil').css("filter", "alpha(opacity=10)" );
			$('#veil').fadeIn('slow');
			try{
				veil_showing(); // may not exist;
			}
			catch(err) { }
			veil_visible = true;
		}
		catch(err) { alert(err.description?err.description:err); }
	}
	veil_count++;
}

function hide_veil()
{
	if ( veil_count == 1 )
	{
		if ( veil_visible )
		{
			$('#veil').fadeOut('slow');
			try{
				veil_hiding(); // may not exist;
			}
			catch(err) { }
			veil_visible = false;
		}
	}
	veil_count--;
}


// ------------------ animate ------------------------------


var animate =
{
	anisteps: 10,	//
	anicurstep: 0,
	anispeed: 25, // milliseconds
	anipos: null,
	anidispl: null,
	targinfo: { left:0, top:0, width:0, height:0 },
	anitarg: null,
	anicallback: null,
	border: "1px solid #999",
	backgroundColor: null,
	
	resetdefaults: function()
	{
		this.anisteps = 10;
		this.anispeed = 15;
		this.border = "1px solid #999";
		this.backgroundColor = null;
	},
	
	doOpen: function()
	{
		if (this.anicurstep <= this.anisteps )
		{
			this.anidispl.style.left = "" + Math.floor( this.anipos.x + ((this.targinfo.left - this.anipos.x) * (this.anicurstep/this.anisteps))) + "px";
			this.anidispl.style.top = "" + Math.floor( this.anipos.y + ((this.targinfo.top - this.anipos.y) * (this.anicurstep/this.anisteps))) + "px";
			this.anidispl.style.width = "" + Math.floor( this.targinfo.width * this.anicurstep / this.anisteps) + "px";
			this.anidispl.style.height = "" + Math.floor( this.targinfo.height * this.anicurstep / this.anisteps) + "px";
			try
			{
				this.anidispl.style.display = "inherit";
			}
			catch(err)
			{
				$('#' + this.anidispl.id ).show();
			}
			setTimeout("animate.doOpen()", this.anispeed);
		}
		else
		{
			try
			{
				this.anidispl.style.display="none";
			}
			catch(err)
			{
				$('#' + this.anidispl.id ).hide();
			}
			if (typeof(this.anicallback) == "function")
				this.anicallback();
		}
		this.anicurstep++;
	},
	
	doClose: function()
	{
		if (this.anicurstep > 0 )
		{
			this.anidispl.style.left = "" + Math.floor( this.anipos.x + ((this.targinfo.left - this.anipos.x) * (this.anicurstep/this.anisteps))) + "px";
			this.anidispl.style.top = "" + Math.floor( this.anipos.y + ((this.targinfo.top - this.anipos.y) * (this.anicurstep/this.anisteps))) + "px";
			this.anidispl.style.width = "" + Math.floor( this.targinfo.width * this.anicurstep / this.anisteps) + "px";
			this.anidispl.style.height = "" + Math.floor( this.targinfo.height * this.anicurstep / this.anisteps) + "px";
			try
			{
				this.anidispl.style.display = "inherit";
			}
			catch(err)
			{
				$('#' + this.anidispl.id).show();
			}
			setTimeout("animate.doClose()", this.anispeed);
		}
		else
		{
			try
			{
				this.anidispl.style.display="none";
			}
			catch(err)
			{
				$('#' + this.anidispl.id).hide();
			}
			if (typeof(this.anicallback) == "function")
				this.anicallback();
		}
		this.anicurstep--;
	},
	

	setup: function(targetdiv,callback,displaydiv,curpos,rect,steps,speed)
	{
		this.anisteps = steps ? steps : this.anisteps;
		this.anicurstep = 0;
		this.anispeed = speed ? speed : this.anispeed;
		this.anitarg = typeof(targetdiv) == "object" ? targetdiv : document.getElementById(targetdiv);
		this.anicallback = (typeof(callback)=="function") ? callback : null;
		if (curpos)
			this.anipos = curpos;
		else
		{
			var ws = getwindowsize();
			var st = getscrolltop();
			this.anipos = { x: Math.floor((ws.width + st.x)/2), y: Math.floor((ws.height + st.y)/2) }; 
		}
		if(typeof(displaydiv) == "object")
			this.anidispl = displaydiv;
		else if(typeof(displaydiv) == "string")
		{
			this.anidispl = document.getElementById(displaydiv);
		}
		if (this.anidispl == null)
		{
			this.anidispl = document.getElementById(this.anitarg.id + "_ani");
			if ( this.anidispl == null )
			{
				this.anidispl = document.createElement("div");
				this.anidispl.style.position = "absolute";
				this.anidispl.style.zIndex=10000000;
				this.anidispl.id = this.anitarg.id + "_ani";
				this.anidispl.style.display = "none";
				this.anidispl.style.border = this.border
				this.anidispl.style.backgroundColor = this.backgroundColor;
				document.body.appendChild(this.anidispl);
			}
		}
		if(rect)
			this.targinfo = rect;
		else
		{
			var xy = getxy(this.anitarg);
			this.targinfo.left = xy.x;
			this.targinfo.top = xy.y;
			this.targinfo.width = parseInt(this.anitarg.style.width);
			this.targinfo.height = parseInt(this.anitarg.style.height);
		}
	},
	
	open: function (targetdiv,callback,displaydiv,curpos,rect,steps,speed)
	{
		this.setup(targetdiv,callback,displaydiv,curpos,rect,steps,speed)
		this.doOpen();
	},

	close: function (targetdiv,callback,displaydiv,curpos,rect,steps,speed)
	{
		if(!curpos && typeof(this.anipos)=="object")
			curpos=this.anipos;
		this.setup(targetdiv,callback,displaydiv,curpos,rect,steps,speed)
		this.anicurstep = this.anisteps; // must reset this since we're going reverse
		this.doClose();
	}
	
}
