var wthreec = (document.getElementById) ? true: false;
var ie5 = (wthreec && document.all) ? true : false;
var tmp_data = {};

var  parsed = false;
var curent_request = null;

function counted_array()
{
    this.len = 0;
    this.data = {};
    this.counters = {};
    this.addValue = function(vname,val)
    {
        if (this.data[vname] != null)
        {
            if (this.counters[vname] == null)
                this.counters[vname] = 1;
            if (this.counters[vname] < 2)
            {
                var tmp_value = this.data[vname];
                this.data[vname] = {};
                this.data[vname][0] = tmp_value;
            }
            this.data[vname][this.counters[vname]] = val;
            this.counters[vname]++;
        }
        else
        {
            this.data[vname] = val;
            this.len = this.len+1;
        }
    }
    this.getData = function ()
    {
        return this.data;
    }
}

function getAllNodes(obj)
{
    if (null == obj)
        return null;
    var result = new counted_array();

    for (var i = 0; i < obj.childNodes.length; i++)
    {
        var tagName = obj.childNodes.item(i).tagName;
        var nodeType = obj.childNodes[i].nodeType;
        var textCont =  obj.childNodes[i].data;
        if (nodeType == 1)
        {
            if (tagName != null)
                result.addValue([obj.childNodes.item(i).tagName],getAllNodes(obj.childNodes[i]));
        }
        else if (tagName != null)
        {

            result.addValue(tagName,textCont);
        }
        else if (nodeType == 3)
        {
            return textCont;
        }
    }

    if (result.len == 0)
        return obj.textContent;
    else
        return result.getData();
}

function AJAX()
{
    this.http_request = false;
    this.xmldoc = null;
    this.xmlarray = null;
    this.textdoc = null;
    this.errorText = null;
    this.timer = null;
    this.onReady = null;
    this.onError = null;
    var test = 'Testing..';
    this.onTimer = function ()
    {
        curent_request.http_request.abrot();
        curent_request.onTimer.OnTimer = null;
    }


    if (window.XMLHttpRequest) { // Mozilla, Safari,...
         this.http_request = new XMLHttpRequest();
         if (this.http_request.overrideMimeType) {
            this.http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            this.http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
         //this.http_request.overrideMimeType('text/xml');
      }
      if (!this.http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
    this.processReqChange = function (test)
    {
    	if ((!document.all && curent_request.http_request.readyState == 4) ||
    	       (document.all && !parsed && curent_request.http_request.readyState == 4))
    	{
    		clearTimeout(curent_request.timer);
    		curent_request.onTimer = null;
    	    if (curent_request.http_request.status == 200)
    		{
				 _alert('Respond recieved','AJAX() instance');
    		     curent_request.xmldoc = curent_request.http_request.responseXML ;
    		     if (curent_request.xmldoc != null) {
                    //curent_request.xmlarray = getAllNodes(curent_request.http_request.responseXML);
                    _alert('XML Found','AJAX() instance');
    		     }
                 curent_request.textdoc = curent_request.http_request.responseText;
              	 curent_request.responce_array = null;
              	 try {
              	 	eval('curent_request.responce_array = ' + curent_request.textdoc);
              	 }
              	 catch (e) {
              	 }
              	 if (curent_request.responce_array != null) {
              	 	_alert('Found arrayed data','AJAX() instance');
              	 	debug(curent_request.responce_array,'curent_request.responce_array');
              	 }
                 if (null != curent_request.onReady)
                     curent_request.onReady(curent_request);
                 __global_wait_timer = setTimeout('__global_ajax_handler.freeRequest()',500);
    		}
    		else
    		{
    		  curent_request.errorText = curent_request.http_request.status + ': ';
    		  if (null != curent_request.onError)
    		      curent_request.onError(curent_request);
    		}
    	}
    }

    this.http_request.onreadystatechange = this.processReqChange;
	if (!document.all)
    	this.http_request.parentObj = this;
    this.sendForm = function (id,uri)
	{

		var working_form = 'object' == typeof(id)? id : $(id);
		if (null == working_form)
			return false;
		var method = working_form.method.toUpperCase();
		var data = new Array();
		for (cnum in working_form.elements)
		{
		    var __currentElement = working_form.elements[cnum];
		    if (__currentElement && __currentElement.name)
			 data[__currentElement.name] = __currentElement.value;
		}
		data['confirm_sending_form'] = '1';
        this.sendRequest(uri,data,method);
        this.timer = setTimeout('curent_request.onTimer();',15000);
	}
    this.sendRequest = function (url,data,method)
    {
        curent_request = this;
		// setting default method
		if (null == method)
			method = 'GET';

		// endoding data
		var encoded_data = '';
		for(v in data)
      		encoded_data += v + "=" + encodeURIComponent(data[v]) + "&";

		// sending data
		if ('GET' == method )
		{
			url +='?'+encoded_data;
			post_data = null;
			this.http_request.open('GET',url,true);
		}
		else
		{
			post_data = encoded_data;
			this.http_request.open('POST',url,true);
			this.http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			this.http_request.setRequestHeader("Content-Length", post_data.length);
		}
		parsed = false;
		this.http_request.send(post_data);
    }
}

var curent_reques = null;

function AJAXHolder()
{
	_alert('Start initialization','AJAXHolder()');
	__global_ajax_handler = this;
	__global_wait_timer = null;
	this.__sent_id = -1;
	this.request = Array();
	this.queed_data = Array();
	this.callBacks = Array();
	this.requestTypes = Array();
	_alert('Initialized variables','AJAXHolder()');
	this.sendRequest = function (url,data,method,__callBack)
	{
		var __id = this.request.length;
		this.request[__id] = new AJAX();
		this.queed_data[__id] = {'url':url,'data':data,'method':method};
		if (__callBack != undefined)
			this.callBacks[__id] = __callBack;
		this.requestTypes[__id] = 1;
		_alert('AJAX instance created. Request queued in sendRequest()','AJAXHolder()');
		if (this.__sent_id < 0)
		{
			this.__sent_id = __id;
			__global_wait_timer = setTimeout('__global_ajax_handler.__sendRequest('+__id+')',500);
		}
	}
	this.__sendRequest = function (__id)
	{
		clearTimeout(__global_wait_timer);
		__global_wait_timer = null;
		__global_request_callback = this.callBacks[__id];
		curent_request = this.request[__id];
		curent_request.onReady = this.callBacks[__id];
		var __item = this.queed_data[__id];
		_alert('Sending request...','AJAXHolder()');
		curent_request.sendRequest(__item.url,__item.data,__item.method);
	}
	this.sendForm = function (id,url,__callBack)
	{
		var __id = this.request.length;
		this.request[__id] = new AJAX();
		this.queed_data[__id] = {'url':url,'id':id};
		if (__callBack != undefined)
			this.callBacks[__id] = __callBack;
		this.requestTypes[__id] = 2;
		_alert('AJAX instance created. Request queued in sendForm()','AJAXHolder()');
		if (this.__sent_id < 0)
		{
			this.__sent_id = __id;
			__global_wait_timer = setTimeout('__global_ajax_handler.__sendForm('+__id+')',500);
		}
	}
	this.__sendForm = function (__id)
	{
		clearTimeout(__global_wait_timer);
		__global_wait_timer = null;
		curent_request = this.request[__id];
		curent_request.onReady = this.callBacks[__id];
		var __item = this.queed_data[__id];
		_alert('Sending request...','AJAXHolder()');
		curent_request.sendForm(__item.id,__item.url);
	}
	_alert('Initilized send functions.','AJAXHolder()');
	this.freeRequest = function ()
	{
		clearTimeout(__global_wait_timer);
		__global_wait_timer = null;
		var __id = this.__sent_id;
		if (__id+1 < this.request.length)
		{
			__id++;
			this.__sent_id = __id;
			if (this.requestTypes[__id] == 1)
				__global_wait_timer = setTimeout('__global_ajax_handler.__sendRequest('+__id+')',500);
			else
				__global_wait_timer = setTimeout('__global_ajax_handler.__sendForm('+__id+')',500);
			_alert('Free request & run new from queue','AJAXHolder()');
		}
		else
		{
			this.__sent_id = -1;
			this.cleanUp();
		}
	}
	this.cleanUp = function ()
	{
		for (var __counter = 0; __counter < this.request.length; __counter++)
		{
			this.request[__counter] = null;
			this.queed_data[__counter] = null;
			this.callBacks[__counter] = null;
			this.requestTypes[__counter] = null;
		}
		__global_wait_timer = null;
		this.__sent_id = -1;
		this.requests = Array();
		this.queed_data = Array();
		this.callBacks = Array();
		this.requestTypes = Array();
		_alert('Request queue was cleaned up.','AJAXHolder()');
	}
	this.callBack = function()
	{
		this.callBacks[this.__sent_id](this.request[this.__sent_id]);
	}
	_alert('AJAXHolder successfuly initialized.');
	_alert(__skip_line);
	//this.__sendForm()
}

function urlEncodeData(data)
{
	var query = [];
	if (data instanceof Object)
	{
		for (var k in data)
		{
			query.push(encodeURIComponent(k) + (data[k] != ''?"=" + encodeURIComponent(data[k]):''));
		}
		return query.join('&');
	}
	else
	{
		return encodeURIComponent(data);
	}
}

function HTMLDecode(str) {
    var result = str;
    result = result.replace(/&gt;/gi, ">");
    result = result.replace(/&lt;/gi, "<");
    result = result.replace(/&amp;/gi, "&");
    return result;
}


function change_projects_page(my_sender)
{
	debug(my_sender.textdoc);
	_alert('Catched request!');
	$('wb_container').innerHTML = '';
	_alert('Cleared container');
	for (k in my_sender.responce_array.projects)
	{
		var pr_obj = my_sender.responce_array.projects[k];
		var project_cont = document.createElement('DIV');
		project_cont.className = 'project_container' + pr_obj.className;

		var link1 = document.createElement('A');
		var link2 = document.createElement('A');
		link1.href =  pr_obj.link;
		link2.href =  pr_obj.link;
		link2.innerHTML  = pr_obj.project_name + '&nbsp;<b>&gt;</b>';

		var pr_image = document.createElement('IMG');
		pr_image.src = pr_obj.img;
		pr_image.alt = pr_obj.project_name;
		pr_image.title = pr_obj.project_name;

		link1.appendChild(pr_image);
		project_cont.appendChild(link1);
		project_cont.appendChild(link2);
		$('wb_container').appendChild(project_cont);
		_alert('Project ' + pr_obj.project_name + 'added.');

	}
	__next_page = my_sender.responce_array.next_page_num;
	$('project-content').style.height = '';
	$('project-content').style.height = $('project-content').offsetHeight + 'px';
	$('project-content').maxh = $('project-content').offsetHeight;
}
