

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Copyright (c) 2006-2010 Skeletal Software Ltd, England.              //
// All rights reserved.                                                 //
//                                                                      //
// Redistribution or modification of the source is prohibited without	//
// the written consent of Skeletal Software Ltd.                        //
//                                                                      //
// This software is provided by Skeletal Software Ltd 'as is' and any	//
// express 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 Skeletal Software Ltd. 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.         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////
//	Ajax responces
////////////////////////////////////////////////////////////////////////////////////

function ajax_make_request(url,handler,type,fail_data,retry)
{
	var httpRequest;
	if (!retry)         retry=0;
	if (window.XMLHttpRequest) // Mozilla etc
	{
		httpRequest=new XMLHttpRequest();
		if (httpRequest.overrideMimeType)
		{
			httpRequest.overrideMimeType('text/'+type);
		}
	}
	else if (window.ActiveXObject) //IE
	{
		try
		{
			httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				// try different
				httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				// failed
			}
		}
	}

	// Failed to get instance
	if (!httpRequest)
	{
		alert('Failed to create XMLHTTP instance');
		return false;
	}

	httpRequest.onreadystatechange=function() { ajax_receive_contents(httpRequest,handler,type,url,fail_data,retry); };
	httpRequest.open('GET',url,true);
	httpRequest.send('');

}

////////////////////////////////////////////////////////////////////////////////////

function ajax_receive_contents(httpRequest,handler,type,url,fail_data,retry)
{
	try
	{
		// ready state 4 is done
		if (httpRequest.readyState==4)
		{
			if (httpRequest.status==200)
			{
				// we got something back
				if (httpRequest.responseText && type=='plain')
					handler(httpRequest.responseText);
				else if (httpRequest.responseXML && type=='xml')
					handler(httpRequest.responseXML);
			}
			else if (httpRequest.status==404)
			{
			    if (fail_data)
			        handler(fail_data);
			    else 
				    alert('Failed to get file from server');
			}
			else
			{
                if (retry<3)
                {
                    ajax_make_request(url,handler,type,fail_data,retry+1);
                }
                else
                {
                    if (fail_data)
                        handler(fail_data);
                    else 
                        alert('Failed to get response from server: '+httpRequest.status);
                }
			}
		}
	}
	catch (e)
	{
		// kill problems in the XML responce code
	}
}

///////////////////////////////////////////////////////////////////////////////////////
// extract html from XML list
///////////////////////////////////////////////////////////////////////////////////////

function ss_extract_html_from_xml_list(node)
{
    var html='';
	var children=node.childNodes
	for (var i=0;i<children.length;i++)
		if (children[i].nodeValue)
			html+=children[i].nodeValue;
		else
			html+="<" + children[i].nodeName + "/>";
	return html;
}

///////////////////////////////////////////////////////////////////////////////////////
// Database update of a field via ajax
///////////////////////////////////////////////////////////////////////////////////////
// ss_ajax_update_db_element(params,id)
// ss_ajax_read_db_element(xml_list,element_name)
// ss_ajax_set_db_element_controls(data)
///////////////////////////////////////////////////////////////////////////////////////
// Update creats partial url to transmit update
///////////////////////////////////////////////////////////////////////////////////////
// if id is present it tags _<id> after each param
// for most prarams it encodes value but for check box it sends on/off 
function ss_ajax_update_db_element(params,id)
{
    var partial_url='';
    for (var i in params) 
    {
        var end=(id ? '_'+id : '')
        var obj=ss_get_object(params[i]+end);
        if (obj)  
        {
            partial_url+='&' + params[i] + '=';
            if (obj.tagName=='INPUT' && obj.type=='checkbox')
               partial_url+=(obj.checked ? 'on' : 'off')
            else   
                partial_url+=encodeURIComponent(obj.value);
        }
	}
	return partial_url;
}

///////////////////////////////////////////////////////////////////////////////////////
///  ss_ajax_read_db_element
///////////////////////////////////////////////////////////////////////////////////////

function ss_ajax_read_db_element(xml_list,element_name)
{
	// decode xml
	var list=new Array();
	// grab elements 
	var element_list=xml_list.getElementsByTagName(element_name);
	for (var i=0;i<element_list.length;i++)
	{
		var element=element_list[i];
		list[i]=new Array();
		var field_list=element.getElementsByTagName('field');
		// write fields into an aray
		for (var j=0;j<field_list.length;j++)
        {
            var name=field_list[j].getAttribute('name');
            var value=field_list[j].getAttribute('value');
            if (value==null && field_list[j].firstChild)
            {
                // option 1 there is data and its a straight conversion
                if (field_list[j].firstChild.data)
				{
				    // there is data and its a straight conversion
				    value=field_list[j].firstChild.data;
			    }
			    else
			    {
			        // its a set of data - due to 4096 limit of string
			        var section_list=field_list[j].getElementsByTagName('section');
		            value='';
		            for (var k=0;k<section_list.length;k++)
		                if (section_list[k].firstChild && section_list[k].firstChild.data)
                            value+=section_list[k].firstChild.data;
			    }
			    
			}
            list[i][name]=value;
        }
	}
	return list;
}

///////////////////////////////////////////////////////////////////////////////////////
// set field controls with <field_name>_<id> format
function ss_ajax_set_db_element_controls(data,no_id)
{
    if (data && data.length && data[0])
    {
        var id=0;
        // grab ID from database field
    	for (var name in data[0])  
    	if (name=='id')  
    	{
    	      id=data[0][name];
    	}
    	// if we find the id - reintroduce data back into 
    	if (id>0)
    	{
    	    for (var name in data[0]) 
    	        if (name!='id')  
    	        {
    	            var obj= ss_get_object(name+(no_id==true ? '' : '_' +id))
    	            if (obj)
    	            {
    	                if (obj.value)
    	                     obj.value=data[0][name];
    	                else if (obj.innerHTML)
    	                    obj.innerHTML=data[0][name];
    	            }
    	        }
    	}
    	return id;
	}
	return 0;
}

///////////////////////////////////////////////////////////////////////////////////////
// only works when panel is included
function ss_ajax_display_error(title,xml_list)
{
    var error=xml_list.getElementsByTagName('error');
	if (error && error.length>0 && error[0].firstChild && error[0].firstChild.data)
	{
		var html="<table width='400px' height='100px'>";
		html+="<tr><td align='center' valign='center'>"+error[0].firstChild.data+"</td></tr></table>";
		if (ss_panel_create)
		    return ss_panel_create(-1,-1,400,html,title);
	}
	return null;
}

///////////////////////////////////////////////////////////////////////////////////////

function ss_ajax_reconstruct_section_data(xml_list,section_marker)
{
	var value='';
	var element_list=xml_list.getElementsByTagName(section_marker);
	for (var i=0;i<element_list.length;i++)
	{
		var element=element_list[i];
        if (element.firstChild)	
		{
			var section_list=element.getElementsByTagName('section');
			if (section_list.length>0)
			{
				for (var j=0;j<section_list.length;j++)
					if (section_list[j].firstChild && section_list[j].firstChild.data)
						value+=section_list[j].firstChild.data;	
			}
			else
			{
				value+=element.firstChild.data;
			}
		}
	}
	return value;
}
