/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2003 Institute of Information Science, 
 * Academia Sinica, Taiwan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:  
 *       "This product includes software developed by Jenghan Hsieh,
 *        Bike Hsu. (http://axeframework.sourceforge.net/) during
 *        2002-04/12 and by Jenghan Hsieh at Academia Sinica, Taiwan
 *        during 2003-01/07."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "AXEFramework", and "Academia Sinica, Taiwan" must not 
 *    be used to endorse or promote products derived from this software
 *    without prior written permission. For written  permission, please
 *    contact jenghan@iis.sinica.edu.tw.
 *
 * 5. Products derived from this software may not be called "AXEFramework"
 *    nor may "AXEFramework" appear in their names without prior written
 *    permission of the author (jenghan@iis.sinica.edu.tw) .
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals.  For more information on the Architectural XML Editing
 * Framework, please see
 * <http://axeframework.sourceforge.net/>.
 *
 * ====================================================================
 
	[2003-10-20 bear] The SubmitXML( ) is now functional for IE and Mozilla
	
	[2003-10-20 bear] [TBD] Error handling of GetXML() and SubmitXML() need further refinements.

 */

// =========================================
//  GetXML ( [optional] cResourceURL [optional] cNSDeclaration )
// --------------------------------------------------------------------------
//
//  1. if cResourceURL is not presented, this function is a wrapper of _interop_GetDocument()
//  2. if cResourceURL is presented, the resource located at cResourceURL is retrieved synchronously and return as an XML document object.
//  3. if cNSDeclaration is presented, the user defined namespace declarations are configured in the XML document object. 
//
//  [2003-10-20 bear] how to make the cNSDeclaration function on both Mozilla and IE is [TBD]
//
// =========================================

var _agt=navigator.userAgent.toLowerCase();
var is_ie = ((_agt.indexOf("msie") != -1) && (_agt.indexOf("opera") == -1));


function GetXML( cResourceURL, cNSDeclaration )
{
	var oXML, oXMLHttp;
	
	if( ! cNSDeclaration )
	{
		cNSDelaration = "xmlns:a='urn::DXAF-architecture'"
	}

	if( cResourceURL )
	{
		try {
			oXMLHttp = new XMLHttpRequest();
		} catch (e) {
		  	oXMLHttp = new ActiveXObject("Msxml2.XMLHttp");
		}
		try {
			oXMLHttp.open("GET", cResourceURL ,false);
			oXMLHttp.send(null);
		} catch (e) {
		  	return("<error>Network Down!</error>");
		}/*
		oXMLHttp.open("GET", cResourceURL ,false);
		oXMLHttp.send(null);
`		*/
		oXML = oXMLHttp.responseXML;
	
		if( is_ie )
		{
			oXML.setProperty("SelectionLanguage", "XPath");
			oXML.setProperty("SelectionNamespaces", cNSDeclaration );
		}
		
	}
	else
	{
		oXML = _interop_GetDocument();
	}

	return( oXML );
}

// =========================================
//   Submitting Object : SubmitXML ( cListenerURL, oMessage )
// --------------------------------------------------------------------------
//
//  Submit the [IXMLDOMElement] oMessage to the listener indicated by [String] cListenerURL.
//
//  [2003-10-20 bear] how to make the cNSDeclaration function on both Mozilla and IE is [TBD]
//
// =========================================

// 實際上送出 XML 並要求伺服器儲存
function SubmitXML( cListenerURL, oMessage ){
	
	var tmpAttrName;
	//var strMessage;
	//strMessage = _interop_SerializeXMLElement( oMessage );
	//alert(strMessage);
	var cMessage = _interop_SerializeXMLElement( oMessage );
	
	try {
	  oXMLHttp = new XMLHttpRequest();
	} catch (e) {
	  oXMLHttp = new ActiveXObject("Msxml2.XMLHttp");
	}
	try {
		oXMLHttp.open( "POST", cListenerURL, false );
    		oXMLHttp.setRequestHeader( "Content-type", "text/xml" );
    		oXMLHttp.setRequestHeader( "Content-length", cMessage.length );
		oXMLHttp.send( cMessage );
	} catch (e) {
		  return("<error>Network Down!</error>");
	}
	/*
	oXMLHttp.open( "POST", cListenerURL, false );

    	oXMLHttp.setRequestHeader( "Content-type", "text/xml" );
    	oXMLHttp.setRequestHeader( "Content-length", cMessage.length );
	oXMLHttp.send( cMessage );
	*/
	// simple error handling. to be improved.	
	switch( oXMLHttp.status )
	{
		case 200 : // OK
			xmlResult = oXMLHttp.responseXML;
			//alert( "Server Success (state:200) "+xmlResult );
			
			if(xmlResult == null)
				xmlResult = ""; // No response.			
			else
				var cResultString = _interop_SerializeXMLElement( xmlResult );
		break;
		default:
		case 500 : // Server Error
			alert( "Server Error (state:500) : \n " + oXMLHttp.responseTEXT );
			try{ divErrorMessage.innerHTML = oXMLHttp.responseTEXT } catch (e) {};
			xmlResult = null;
		break;
	}

	return( xmlResult );
}

// =========================================
//  QueryString Construction : Q( ... )
// --------------------------------------------------------------------------
//
//  Serialize the user query in standard QueryString format.
//  Developers can append the resulting string to the "cQueryBrokerURL",
//  in order to perform specific query on the query broker.
//
// --------------------------------------------------------------------------
//  examples :
//
//    cURLQuery = Q( "Author", "=", "Jenghan",
//							   "PuhlishDate", ">", "2002" );
//
//    cURLQuery = Q( "Author", "=", "*",
//							   "PuhlishDate", "!=", "2002*" );
//
// =========================================

function Q(){

	_checkArguments( arguments );
		
		var arg = "";
		var ope = "";
		var val = "";
		for(var i = 0; i < ((arguments.length / 3) - 1); i ++){
			arg = arg + arguments[i * 3] + ",";
			val = val + arguments[i * 3 + 2] + ",";
			switch (arguments[i * 3 + 1]){
			case ">":
				ope = ope + "G,";
			break;
			case "=":
				ope = ope + "E,";
			break;
			case "<":
				ope = ope + "L,";
			break;
			case ">=":
			case "=>":
				ope = ope + "GE,";
			break;
			case "<=":
				ope = ope + "LE,";
			break;
			case "!=":
				ope = ope + "GL,";
			break;
			default:
				throw "wrong operator";
			}
		}
		
		arg = arg + arguments[i * 3];
		val = val + arguments[i * 3 + 2];

		switch (arguments[i * 3 + 1]){
		case ">":
			ope = ope + "G";
		break;
		case "=":
			ope = ope + "E";
		break;
		case "<":
			ope = ope + "L";
		break;
		case ">=":
		case "=>":
			ope = ope + "GE";
		break;
		case "<=":
			ope = ope + "LE";
		break;
		case "!=":
			ope = ope + "GL";
		break;
		default:
			throw "wrong operator";
		}
	
		return("Index=" + arg + "&relation=" + ope + "&Value=" + val);
    }

function _checkArguments( oArguments )
{
	if ( (oArguments.length % 3) != 0)
	{
		throw "wrong number of arguments";
	}
	
	if( (oArguments.length / 3) == 0){
		throw "no arguments";
	}
}
