/***************************************************************
* rAyJAX                                   Author: Ray Dollete *
*                                      Created: April 04, 2006 *
*                                  Last Modified: May 31, 2006 *
*                                                              *
* A supplementary Javascript library designed for implementing *
* Document-Object Manipulation and facilitating the use of     *
* AJAX architecture with maximum cross-browser compatibility,  *
* designed in conjunction with the MIGI proprietary software   *
* package for Digital Performance, Inc.                        *
****************************************************************
* SCRIPT REQUIREMENTS:                                         *
*    In order to properly use rAyJAX functions, you must have  *
*    areas on the HTML with id's designated as "status_bar"    *
*    and "debug".  All other area-updates are specified at the *
*    function call.                                            *
****************************************************************/



/****************************************
* Basic Javascript shortcut functions.  *
*****************************************/

function elementValue(element) {
	var v = document.getElementById(element).value;
	return v;
}

function goLink(url) {
	window.location = url;
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

function updateElement(element, contents) {
	document.getElementById(element).innerHTML = contents;
}

function updateElementSRC(element, newsrc) {
	document.getElementById(element).src = newsrc;
}

function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

function getBrowserSize() {          // Get browser size, return width/height in pixels
	var myWidth = 0, myHeight = 0;
	if(typeof(window.innerWidth) == 'number') {
	//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}else if(document.documentElement &&
	(document.documentElement.clientWidth || document.documentElement.clientHeight)) {
	//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
	//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [myWidth, myHeight];
}

function findPosX(obj) {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

function domValue(element) {
    var evalue = document.getElementById(element).value;
    return evalue;
}

/***********************************************************
* Primary AJAX function calls, which include random-number *
* generator to force GET updates in Internet Explorer.     *
************************************************************/


function rayjaxReturn(url, element)
{
	var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        document.getElementById("status_return").innerHTML = '<center>XMLHTTP error.</center>';
        return false;
    }
    http_request.onreadystatechange = function() {	elementReturn(http_request, element); };
	
	target = url+'&random=' + (Math.random() * Date.parse(new Date()));
	
    http_request.open('GET', target, true);
    http_request.send(null);


}

function elementReturn(http_request, element) {

    if (http_request.readyState == 4) {
        if (http_request.status == 200) {                

			var PHPresults = http_request.responseText;
			document.getElementById(element).innerHTML = PHPresults;
			
        } else {
            if(document.getElementById('status_bar'))
                document.getElementById("status_bar").innerHTML = 'There was a problem with the request.';
        }
    }
	
}

function rayjaxCustomReturn(url, func, opts)   // Usage: rayjaxCustomReturn(url, function() { commands; };, x);
{											   // the 'x' option indicates an XML response
                                               // the 'p' option invokes the POST method
	var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        document.getElementById("status_return").innerHTML = '<center>XMLHTTP error.</center>';
        return false;
    }
    http_request.onreadystatechange = function() {	
		if (http_request.readyState == 4) {
	      	if (http_request.status == 200) {                								
				
				func(http_request);
				
	        } else {
	            document.getElementById("status_bar").innerHTML = 'There was a problem with the request.';
	        }
	    }
	};
	
	target = url+'&random=' + (Math.random() * Date.parse(new Date()));

    if (opts == 'p') {
        url_array = target.split('?');
        target = url_array[0];
        params = url_array[1];
    
        http_request.open('POST', target, true);
        
    	//Send the proper header infomation along with the request
    	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	http_request.setRequestHeader("Content-length", params.length);
    	http_request.setRequestHeader("Connection", "close");
    
    	http_request.send(params);        
        
    } else {    	
        http_request.open('GET', target, true);

    	if (opts == 'x')
    		http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    	
        http_request.send(null);

	}
	

}

function rayjaxStatusReturn(url)
{
	var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        document.getElementById("status_return").innerHTML = '<center>XMLHTTP error.</center>';
        return false;
    }
    http_request.onreadystatechange = function() {	
	    if (http_request.readyState == 4) {
	        if (http_request.status == 200) {                
	
				var PHPresults = http_request.responseText;
				document.getElementById("status_bar").innerHTML = PHPresults;
				
	        } else {
	            document.getElementById("status_bar").innerHTML = 'There was a problem with the request.';
	        }
		}
	
	};
	
	target = url+'&random=' + (Math.random() * Date.parse(new Date()));
	
    http_request.open('GET', target, true);
    http_request.send(null);
	
}
	
/****************************
* Functions for XML Parsing *
*****************************/

function getXML(req, tagname)  // Usage: var thing = getXML(req, 'thing');
{							   // Includes ActiveX workaround for IE to parse XML from a non-*.xml

	if(window.XMLHttpRequest)
		var doc = req.responseXML;
	
	else if (window.ActiveXObject)
	{
		var doc = new ActiveXObject("Microsoft.XMLDOM");
		doc.loadXML(req.responseText);
	}
	
	var output = doc.getElementsByTagName(tagname)[0].firstChild.nodeValue;	
	   
	return output;
}

/***********************************************************
* Note on Attribute XML Parsing:                           *
*                                                          *
* If you are not going to use the <tagname>value</tagname> *
* format of XML, you can use attributes instead, as in:    *
* <tagname attrib=value> but your parse syntax becomes:    *
*                                                          *
* var doc = new ActiveXObject("Microsoft.XMLDOM");         *
* doc.loadXML(req.responseText);                           *
* var things = doc.getElementsByTagName("tagname");        *
* var thing1 = parseFloat(things[0].getAttribute(attrib)); *    // things is an array depending on how many <tagname> instances
************************************************************    // you have */



/*****************************************************
* Functions for JavaScript-Converted Form Submission *
******************************************************/


function sub(f, url, subname, subvalue)     // usage: onClick="sub(this.form, url-to-receive-submission, name of old Submit button, value of old Submit button)"
{										    // -=OR=- if the 'button' is not a standard form element (as in a DIV onclick), use document.nameOfForm
	statusBar("Processing...");
	var str = serializeForm(f);   
	url = url + '?' + str + '&' + subname + '=' + subvalue;
	rayjaxStatusReturn(url);	   
}

function subReturn(f, url, subname, subvalue, element)   // same as sub() except will return to a specified element
{                                                        // and has no statusbar updates

	var str = serializeForm(f);   
	url = url + '?' + str + '&' + subname + '=' + subvalue;
    rayjaxReturn(url, element); 
}

function subCustom(f, url, subname, subvalue, func, opts)      // same as sub() except will perform func() 
{                                                              // using rayjaxCustomReturn()

	var str = serializeForm(f);   
	url = url + '?' + str + '&' + subname + '=' + subvalue; 
	rayjaxCustomReturn(url, func, opts);
}

function serializeForm(theform)     // Converts FORM-submission values into URL variables without a real SUBMIT
{
	var els = theform.elements;
	var len = els.length;
	var queryString = "";
	var arrayname = "";
	
	this.addField = 
		function(name,value) { 
			if (queryString.length>0) { 
				queryString += "&";
			}
			queryString += encodeURIComponent(name) + "=" + encodeURIComponent(value);
		};
		
	for (var i=0; i<len; i++) {
		var el = els[i];
		if (!el.disabled) {
			switch(el.type) {
				case 'text': case 'password': case 'hidden': case 'textarea': 
					this.addField(el.name,el.value);
					break;
				case 'select-one':
					if (el.selectedIndex>=0) {
						this.addField(el.name,el.options[el.selectedIndex].value);
					}
					break;
				case 'select-multiple':
					idx = 0;
					for (var j=0; j<el.options.length; j++) {
						if (el.options[j].selected) {
												
							str = el.name;
							str = str.replace('[]','');
							str = str +'['+idx+']';
							this.addField(str,el.options[j].value);
							idx++;
							
						}
					}
					break;
				case 'checkbox': case 'radio':
					if (el.checked) {
						this.addField(el.name,el.value);
					}
					break;
			}
		}
	}
	return queryString;
}


function disableEnterKey(e)  // Disable Form-Submit on Enter Key Completely
{                            // Usage: <input type=text onKeyPress="return disableEnterKey(event)">
    var key;

    if(window.event)
    	key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if(key == 13)
        return false;
    else
        return true;
}


/***************************************************
* Functions for inserting status and debug updates *
****************************************************/

function debug(debug_text) {
	document.getElementById("debug").innerHTML = debug_text;
}

function statusBar(status_text) {
	//document.getElementById("status_bar").innerHTML = status_text;
	top.headerpanel.document.getElementById('header_status').innerHTML = status_text;
}

/*********************************************
* Button Highlight and DeHighlight functions *
**********************************************/

function buttonHighlight(element, color) {
	document.getElementById(element).style.backgroundColor = color;
}

function buttonDeHighlight(element) {
	document.getElementById(element).style.backgroundColor = '';
}
