// Sniffer based on http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html

var uagent    = navigator.userAgent.toLowerCase();
var is_safari = ( (uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var is_opera  = (uagent.indexOf('opera') != -1);
var is_webtv  = (uagent.indexOf('webtv') != -1);
var is_ie     = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv) );
var is_ie4    = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) );
var is_moz    = ( (navigator.product == 'Gecko')  && (!is_opera) && (!is_webtv) && (!is_safari) );
var is_ns     = ( (uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari) );
var is_ns4    = ( (is_ns) && (parseInt(navigator.appVersion) == 4) );
var is_kon    = (uagent.indexOf('konqueror') != -1);

var is_win    =  ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) );
var is_mac    = ( (uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc.") );

/*****************************
/* Global Object
/*****************************/
var ajax = null;

/*****************************
/*
/*****************************/
function ajaxRequest(url, feedback) {

	//var ajaxCursor = "http://design.svnets.lv/ads/skins/default/cursors/ajax.cur";
	//this.ajaxResult = "";
	//this.ajaxResultXML = null;
	this.showLoadingImage = false;
	this.xmlhttp = null;
	this.url = url ? url : "";
	this.postVars = new Array();
	this.feedback = feedback ? feedback : null;
	this.useIframe = false;
	this.responseText = "";

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.init = function() {

	if (window.XMLHttpRequest) {

		/*****************************
		/* Firefox, Opera
		/*****************************/

		this.xmlhttp = new XMLHttpRequest();

	} else if (window.ActiveXObject) {

		/*****************************
		/* IE
		/*****************************/

		try {

			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

		} catch (e) {

			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {

			}

		}

	}

	if (!this.xmlhttp) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	if (this.showLoadingImage) this.imageInit();
	if (this.useIframe) this.iframeInit();

	this.xmlhttp.onreadystatechange = this.onreadystatechange;

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.process = function( url, method, feedback ) {

	method = method == "POST" ? "POST" : "GET";

	this.init();
	if (typeof(feedback) == 'function') this.feedback = feedback;

	if (this.readyToProcess()) {

		if (this.showLoadingImage) this.showAjaxImage();

		url = url ? url : this.url;
		if (url.indexOf('?') > -1) url += "&ajax=1";
		else url += "?ajax=1";

		this.xmlhttp.open( method, url, true );
		this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  		//this.xmlhttp.setRequestHeader("Connection", "close");
  		if (is_ie) {
			this.xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
   			this.xmlhttp.setRequestHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT")
   			this.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
   			this.xmlhttp.setRequestHeader("Pragma", "no-cache");
  		}
		if (method == "GET") { //GET
			this.xmlhttp.send( null );
		} else { //POST
			var postString = this.getPostString();
			this.xmlhttp.setRequestHeader("Content-length", postString.length);
			this.xmlhttp.send( postString );
		}

		return false;

	}

	return false;

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.readyToProcess = function() {

	//if (!this.xmlhttp) return false;
	return !( this.xmlhttp.readyState && ( this.xmlhttp.readyState < 4 ) );

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.responseState = function() {

	//if (!this.xmlhttp) return false;
	return ( this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200 ) ? true : false;

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.onreadystatechange = function( ) {

	if (ajax.responseState()) {
		/*if (ajax.showLoadingImage) hide( 'ajaxImage' );
		if ( typeof( ajax.feedback ) == 'function' ) {
			ajax.feedback( ajax );
			ajax.feedback = null;
		} else {
			ajax.defaultFeedback();
		}*/
		ajax.done();
	}
	//ajax.postVars = new Array();

}

ajaxRequest.prototype.iframeOnLoad = function( content ) {

	ajax.responseText = content;
	ajax.done();

}

ajaxRequest.prototype.done = function( ) {
	
	if (this.showLoadingImage) hide( 'ajaxImage' );
	if ( typeof( this.feedback ) == 'function' ) {
		this.feedback( this );
		this.feedback = null;
	} else {
		this.defaultFeedback();
	}
	this.reset();
	
}

ajaxRequest.prototype.reset = function() {
	//this.postVars = new Array();
	this.xmlhttp = null;
	this.url = "";
	this.postVars = new Array();
	this.feedback = null;
	this.useIframe = false;
	this.responseText = "";
}

//referenced to global.js
//work only for JSON feedback
ajaxRequest.prototype.defaultFeedback = function() {
	var json = this.getJson();
	if (!json) return;
	if ( json.ajax_time && $('ajax-debug')) {
		$('ajax-debug').innerHTML = 'Ajax Response Time: '+json.ajax_time;
	}

	if (json.status == 0) {
		//json.message = json.message.replace(/\n+$/, '');
		showMessage( json.message.replace(/\n/g, '<br />') );
	} else {

		for (i in json) {

			//alert(json[i].type);

			if (typeof(json[i]) != 'object') continue;

			/* IE prints 'null' on page. Stupid! */
			if (json[i].content == null) { json[i].content = ''; }

			switch( json[i].type ) {

				case 'insert':
					$( json[i].object ).innerHTML += json[i].content;
					break;
				case 'replace':
					$( json[i].object ).innerHTML = json[i].content;
					break;
				case 'reset':
					document.forms[ json[i].object ].reset();
					break;
				case 'hide':
					hide( json[i].object );
					break;
				case 'message':
					showMessage( json[i].content );
					break;
				case 'redirect':
					_href( siteUrl+'?'+json[i].content  );
					break;
				case 'eval':
					eval( json[i].content );
			}

		}

		if ( typeof(json.messageStatus) != 'undefined' ) {

			allowCloseMessage = json.messageStatus;

		}

	}

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.getByXML = function( tagName, tagNum ) {

	if ( !tagName ) return;
	if ( !tagNum ) tagNum = 0;

	var node = this.xmlhttp.responseXML.getElementsByTagName( tagName )[ tagNum ];

	if (node)
		return node.firstChild.nodeValue;
	else return false;

}

ajaxRequest.prototype.getNodeByXML = function( tagName, tagNum ) {

	if ( !tagName ) return;
	if ( !tagNum ) tagNum = 0;

	return this.xmlhttp.responseXML.getElementsByTagName( tagName )[ tagNum ];

}

ajaxRequest.prototype.getText = function() {

	if (this.xmlhttp)
		return this.xmlhttp.responseText;
	else
		return this.responseText;

}

ajaxRequest.prototype.getJson = function() {

	var json = "";
	if (!this.getText()) return;
	try {
		json = eval( "(" + this.getText() + ")" );
		if (typeof(json) != 'object') {
			showMessage(this.getText());
		}
	} catch( e ) {

		var txt = this.getText();
		if (txt.length > 500) txt = txt.substr(0, 500) + "...";
		txt = txt.replace('<', '&lt;');
		txt = txt.replace('>', '&gt;');

		showMessage( txt );

	} finally {

		if (json != "") return json;
		//showMessage(this.getText());
		return false;

	}

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.get = function(url, feedback) {
	
	if (feedback) this.feedback = feedback;
	this.process( url, 'GET' );
	
}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.imageInit = function() {

	if ($('ajaxImage')) return;

	var objBody = document.getElementsByTagName("body").item(0);

	var objLoadingImage = document.createElement("div");
	objLoadingImage.setAttribute('id','ajaxImage');
	objLoadingImage.style.position = 'absolute';
	objLoadingImage.style.zIndex = '150';
	objLoadingImage.style.display = 'none';
	objBody.insertBefore(objLoadingImage, objBody.firstChild);

	return false;

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.iframeInit = function() {

	if ($('ajax-iframe')) return;

	var objBody = document.getElementsByTagName("body").item(0);

	if (is_ie) {
		var objIframe = document.createElement("<iframe name=\"ajax-iframe\" id=\"ajax-iframe\">");
	} else {
		var objIframe = document.createElement("iframe");
		objIframe.setAttribute('name','ajax-iframe');
		objIframe.setAttribute('id','ajax-iframe');
	}
	if (objIframe.addEventListener) { //FF, Opera...
		objIframe.addEventListener("load", function() {		
			var content = '';
			if (this.contentDocument) {
			  content = this.contentDocument.body.innerHTML; 
			} else if (this.contentWindow) {
			  content = this.contentWindow.document.body.innerHTML;
			} else if (this.document) {
			  content = this.document.body.innerHTML;
			}
			//c = c.replace(/\\n/g, '');
			//c = c.replace(/\\r/g, '');
			ajax.iframeOnLoad( content );
		}, false);
	} else if( objIframe.attachEvent ) {//IE
		objIframe.attachEvent("onreadystatechange", function() {
			if(objIframe.readyState === "loaded" || objIframe.readyState === "complete") {
				var iframe = $('ajax-iframe');
				var content = '';
				if (iframe.contentDocument) {
				  content = iframe.contentDocument.body.innerHTML; 
				} else if (iframe.contentWindow) {
				  content = iframe.contentWindow.document.body.innerHTML;
				} else if (iframe.document) {
				  content = iframe.document.body.innerHTML;
				}
				content = content.replace(/\\n/g, '');
				content = content.replace(/\\r/g, '');
				ajax.iframeOnLoad( content );
			}
		} );
	}
	objIframe.style.position = 'absolute';
	objIframe.style.top = '0';
	objIframe.style.visibility = 'hidden';
	objIframe.style.width = '0px';
	objIframe.style.height = '0px';
	//objBody.insertBefore(objIframe, objBody.firstChild);
	objBody.appendChild(objIframe);

	objIframe.name = 'ajax-iframe';

	return false;

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.showAjaxImage = function() {

	//obj = $('ajaxImage');
	show('ajaxImage');

}

/*****************************
/*
/*****************************/
ajaxRequest.prototype.parseForm = function( form ) {

	var oForm = form;
	if (!oForm) return false;

	for (var i = 0; i < oForm.elements.length; i++) {

		var el = oForm.elements[i];
		if (el.type == 'file') {
			this.useIframe = true;
			if (oForm.enctype != 'multipart/form-data') {
				alert('Form with file type input not have enctype="multipart/form-data"');
				prompt('enctype="multipart/form-data"');
			}
		}
		if (el.type == 'checkbox' || el.type == 'radio') {
			if (el.checked) {
				this.addPostVar( el.name, el.value );
			}
		} else {
			//if (el.value.length > 0)
				this.addPostVar( el.name, el.value );
		}
		//alert(oForm.elements[i].type+" : "+oForm.elements[i].value);

	}

	var url = oForm.action ? oForm.action : window.location.href;

	if (this.useIframe) {
		this.iframeInit();
		if (url.indexOf('?') > -1) {
			if (url.indexOf("ajax=") > -1) {
				url = url.replace(/ajax=(\d)/, "ajax=2");
			} else {
				url += "&ajax=2";
			}
		}
		else url += "?ajax=2";
	}

	return url;

}

ajaxRequest.prototype.page = function( element ) {

	var url = element.href;
	this.process( url, 'get' );
	return false;

}

ajaxRequest.prototype.addPostVar = function( name, value ) {

	if (!this.postVars[ name ]) {
		this.postVars[ name ] = value;
	} else if (typeof (this.postVars[ name ]) == "string") {
		var tmpValue = this.postVars[ name ];
		this.postVars[ name ] = new Array();
		this.postVars[ name ][ 0 ] = tmpValue;
		this.postVars[ name ][ 1 ] = value;
	} else {
		this.postVars[ name ][ this.postVars[ name ].length ] = value;
	}

}

ajaxRequest.prototype.getPostString = function() {

	var str = "";
	for ( var i in this.postVars ) {
		if (typeof (this.postVars[i]) == "object") {
			for (var j = 0; j < this.postVars[i].length; j++) {
				str += encodeURI(i)+"="+encodeURI( this.postVars[i][j] )+"&";
				//	^ no need here [] (array squares). it will be here by itself.
			}
		} else {
			str += encodeURI(i)+"="+encodeURI(this.postVars[i])+"&";
		}
	}

	str = str.replace(/&$/, "");

	return str;

}

ajax = new ajaxRequest();

/*### Simple Function ###*/

function ajaxForm( form, feedback, customUrl ) {

	//ajax = new ajaxRequest();
	if (feedback) {
		ajax.feedback = feedback;
	}
	url = ajax.parseForm( form );
	if (customUrl) url = customUrl;
	if (ajax.useIframe) {
		form.target = 'ajax-iframe';
		//form.target = '_blank';
		form.action = url;
		return true;
	}
	if (url != false) {
		ajax.process(url, "POST");
	}
	return false;

}