// myAjax object //
/**
* class myAjax - simple ajax class for dynamic content loading
*
* @author Szymon Kosydor aka BuBi
* @link http://szymon.kosydor.pl
* 
*/

function ajax( post, target, add ) {
	var ajax = new myAjax();
	ajax.post( post, target, add );
}

myAjax = function( classer ) {
	var obj = this.createObject();
	this.obj = obj;
	this.date = new Date();
	this.time = this.date.getTime()+(this.date.getMilliseconds()/1000);
	this.target = '';
	this.add = undefined;
	this.response = '';
	this.action = '';
	this.classer = ( classer != undefined ) ? classer : '';
	var ajax = this;
	this.ajax = ajax;
	obj.onreadystatechange = function() {
		ajax.onResponse();
	}
}

myAjax.prototype.updateTime = function() {
	var spanA = document.getElementById( 'ajax_time' );
	if( spanA != undefined ) {
		var time = (this.date.getTime()+(this.date.getMilliseconds()/1000))-this.time;
		time = Math.round( time * 1000 ) / 1000;
		spanA.style.display = 'block';
		spanA.innerHTML = 'Czas generacji MyAjax '+time.toString()+'s.';
	}
}
myAjax.prototype.onLoad = function( ) { }

myAjax.prototype.onResponse = function() {
	switch( this.obj.readyState ) {
	// 0 - uninitialized 
	// 1 - loading
	// 2 - loaded
	// 3 - interactive
	// 4 - complete
		case 4:
			var stat = 0;
			try{
				stat = this.obj.status;
			} catch ( e ){
				/*ignore*/
			}
			if( ( stat == 200 ) || ( stat == 0 ) ) {
				this.response = this.obj.responseText.toString();
				this.ajax.onLoad();
				this.ajax.updateTime();
				if( this.target != undefined ) {
					switch( typeof( this.target ) ) {
						case 'object':
							var u = this.target;
							break;
						case 'string':
							var u = document.getElementById( this.target );								
							break;
					}
					u.style.display = 'block';
					if( this.add == 'add' ) {
						u.innerHTML = u.innerHTML + this.response;
					} else if( u.innerHTML != this.response ) {	
						u.innerHTML = this.response;
					}
				}
			}		
			break;
		default:
			break;
	}
}

myAjax.prototype.post = function( post_data, target, add ) {
	this.time = this.date.getTime();	
	this.target = ( target != undefined ) ? target : null;
	this.add = ( add != undefined ) ? add : null;
	if( ( post_data.indexOf( 'action=' ) == -1 ) && ( this.action != '' ) ) {
		post_data = 'action=' + this.action + '&' + post_data;
	}
	if( ( post_data.indexOf( 'classer' ) == -1 ) && ( this.classer != '' ) ) {
		post_data = 'classer=' + this.classer + '&' + post_data;
	}
	if( this.uri == undefined ){ this.uri = '/ajax.php'; }
	try {
		this.obj.open( "POST", this.uri, true );
		this.obj.setRequestHeader( "Method", "POST " + this.uri + " HTTP/1.1");
		this.obj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded");	
		this.obj.send( post_data );
	} catch( e ) {
		this.onDebug( '.post( \''+ this.uri + '\' ) ', e );		
	}
	var p = post_data.indexOf( 'action' ) + 7;
	if( p != 6 ) {
		var pdata = post_data.substring( p );
		var pend = pdata.indexOf( '&' );
		this.action = ( pend == -1 ) ? this.action = pdata : pdata.substring( 0, pend );
	}
	
}

myAjax.prototype.get = function() {
	try {
		this.onDebug( '.get( \''+ this.uri + '\' ) ' );
		this.obj.open( "GET", this.uri, true );
		this.obj.send( null );
	} catch( e ) {
		this.onDebug( '.get( \''+ this.uri + '\' ) ', e );
	}
}

myAjax.prototype.createObject = function() {
	if ( typeof XMLHttpRequest != "undefined" ) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		var ieVer = [ "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp","Microsoft.XMLHttp" ];
		for (var i = 0; i < ieVer.length; i++) {
			try {
				var XH = new ActiveXObject( ieVer[ i ] );
				return XH;
			} catch ( e ) {
				/* ignore */
			}
		}
		this.onDebug( "XMLHttp object not created" );
	}
}

myAjax.prototype.onDebug = function( str, e ) {
	var u = document.getElementById( 'myAjaxDebug' );
	u.style.display = 'block';
	u.innerHTML = "Debug :\n\n<br/><br/> "+str+"\n<br/>"+e;
}

function restoreFieldBorders( formId ) {
    if( document.formStyles == undefined ) {
	// zapamiętanie styli ramek elementów formularza
	document.formStyles = new Array();
	document.formStyles[ formId ] = new Array();
	var ar = document.formStyles[ formId ];
	$( '#'+formId+' input, #'+formId+' textarea, #'+formId+' select, #'+formId+' radio ' ).each(function(index, item) {ar[ item ] = $(item).css( 'border' ) });
    } else {
	// powrot do normalnego stylu
	var ar = document.formStyles[ formId ];
	$( '#'+formId+' input, #'+formId+' textarea, #'+formId+' select, #'+formId+' radio ' ).each(function(index, item) {$(item).css( 'border', ar[ item ] ) });
    }
}

/**
 * podświetlenie pól formularza - ramka czerwona dookoła
 */
function highlightFields( formId, fields ) {
    restoreFieldBorders( formId );
    for( i in fields ) {
	var field = fields[ i ];
	$( '#'+field ).css( 'border', '1px solid #900' );
    }
}

/**
 * zmienia css bloczka odpowiedzi na błąd
 */
function highlightErrorResponse( objId ) {
	$( '#'+objId ).css( 'color', '#933' );
	$( '#'+objId ).css( 'font-weight', 'bold' );
}

/**
 * zmienia css bloczka odpowiedzi na normalny
 */
function highlightOkResponse( objId ) {
	$( '#'+objId ).css( 'color', '#393' );
	$( '#'+objId ).css( 'font-weight', 'bold' );
}

/**
 * zczytanie odpowiedzi i statusu
 * @param string xmlResponse zwracany xml przez ajax
 * @return object obiekt z właściwościami
 *  hasError boolean czy jest błąd
 *  highlight array tablica z id podświetlanych pól
 *  text string treść odpowiedzi
 */
function handleResponse( xmlResponse, formId, responseId ) {
    var response = new Object();
    var parser = getDOMParser( xmlResponse );
    response.hasError = ( parser.firstChild.getAttribute( 'status' ) == 'error' ) ? true : false;
    response.highlightedFields = ( parser.firstChild.getAttribute( 'highlight' ).length > 0 ) ? parser.firstChild.getAttribute( 'highlight' ).split( '|' ) : false;
    response.text = parser.firstChild.firstChild.nodeValue;
    restoreFieldBorders( formId );
    if( response.hasError ) {
	highlightErrorResponse( responseId );
	$( '#'+responseId ).html( response.text );
	if( response.highlightedFields !== false ) {
	    highlightFields( formId, response.highlightedFields );
	}
    } else {
	highlightOkResponse( responseId );
	$( '#'+responseId ).html( response.text );
        $('#insurance').hide();
    }
    return response;
}

/**
 * zczytanie wszystkich pól formularza
 * @param string id formularza
 * @return string parametry do requestu
 */
function getFormFieldsValueString( formId ) {
    var str = '';
    $( '#'+formId+' input, #'+formId+' textarea, #'+formId+' select, #'+formId+' radio ' ).each(function(index, item) {str += '&'+$(item).attr('id')+'='+$(item).val() });
    str = str.substr( 1 );
    return str;
}

function getDOMParser( str ) {
    if (window.DOMParser)  {
      parser=new DOMParser();
      xmlDoc=parser.parseFromString(str,"text/xml");
    } else {// Internet Explorer
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async="false";
      xmlDoc.loadXML(str);
  }
  return xmlDoc;
}
