AttachEvent(window, 'load', aj_Init, false);

// the current url thati s in the browser address bar:
var ajCurrentHash;

// processing an ajax page / in the middle of loading. true or false
var aj_Busy = false;

// delay in miliseconds of the rate of checking if there is a new url
var ajDelay = 10;

/*
	Init first page, check if this has anchor, if so, redirect to real page:
*/

var cLoc = location.pathname;
var wLoc = retrieveAncor();

//var aj_Optional = {};


// if both the manual location is empty (/) AND the hash portion (#/...) is empty, redirect to home page:

if((!cLoc || cLoc == WSD_WEBROOT) && (!wLoc || wLoc == WSD_WEBROOT) && WSD_AJAX)
{
	var url_allready_in_bar = true;

	location.href = WSD_WEBROOT+'#';
}


// if there is some data in the manual location, convert this to anchor mode (#..)

else if(cLoc && cLoc != WSD_WEBROOT && WSD_AJAX)
{
	var url_allready_in_bar = true;

	var re = eval("/^("+WSD_WEBROOT.replace(/\//gi, "\\/")+")(.*?)/gi");

	location.href = WSD_WEBROOT+'#'+cLoc.replace(re, "$2");
}



/*
	Initialize, check for any new anchor (#), and load that page..
*/

function aj_Init(e)
{
	ajTimer = setTimeout(aj_UpdatePage, ajDelay);
}


/*
	Refresf the timer
*/

function aj_UpdatePage(e)
{
	// get the value after #
	var wLoc = retrieveAncor();

	// first see if anchor value starts with #, then see if the page you're switching to is different as the one you are on now,
	if(ajCurrentHash != WSD_WEBROOT+wLoc && !aj_Busy)
	{
		if(url_allready_in_bar)
		{
			url_allready_in_bar = false;

			request(WSD_WEBROOT+wLoc, {'manual_redir' : true});
		}
		else
		{
			request(WSD_WEBROOT+wLoc, {'manual_redir' : false});
		}

		aj_Busy = true;
	}

	ajTimer = setTimeout(aj_UpdatePage, ajDelay);
}

function request(rawUrl, optional)
{
	if(!WSD_AJAX) return true;

	E('ajLoading').style.display = 'block';

	if(rawUrl.match(/\?/gi))
	{
		urlLoc = rawUrl+'&fromAjax=yes';
	}
	else
	{
		urlLoc = rawUrl+'?fromAjax=yes';
	}

	createXMLHttpRequest();
	xmlHttp.onreadystatechange = function(){updateMenuRequest(false, false, false, false, rawUrl, optional);};
	xmlHttp.open("GET", urlLoc, true);
	xmlHttp.send(null);

	return false;
}

function abort()
{
	if(!xmlHttp) return false;
	else
	{
		xmlHttp.abort();
		xmlHttp = null;

		aj_Busy = false;

		E('ajLoading').style.display = 'none';
		
		// optional redir
		var re = eval("/^("+WSD_WEBROOT.replace(/\//gi, "\\/")+")(.*?)/gi");
		location.href = WSD_WEBROOT+'#'+urlVar.replace(re, "$2");
	}
}

function updateMenuRequest(itemCode, menuType, menuID, subID, urlVar, optional)
{
	if(!optional) var optional = {};

    if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 404)
		{
			//alert("Page was not found ! You are now being redirected to our frontpage.");

			// done loading page, busy = false. the 'true' state prevents other ajax request from happening
			aj_Busy = false;

			// loading bar:
			E('ajLoading').style.display = 'none';

			// set current page in variable
			ajCurrentHash = urlVar;

			//location.href = '/#'+REDIR_ROOT+'home.html';

			dn_MenuItemByURL(REDIR_ROOT+'404.html');
		}
		else if(xmlHttp.status == 200)
		{
			var responseStatus = xmlHttp.responseText;

			/*
				first detect a redir:
			*/
			if(responseStatus.match(/redir: /gi))
			{
				eval(responseStatus.replace(/redir: (.*)/gi, "$1"));
				return false;
			}

			var dnContent = E('dnContent');
			var menuContent = responseStatus;	// Content

			// check for custom target elements (put retrieved ajax content in specific element instead of replacing the whole page)
			if(optional['target_id'] && E(optional['target_id']))
			{
				E(optional['target_id']).innerHTML = menuContent;
			}
			else
			{
				dnContent.innerHTML = menuContent;
			}

			// excecute the <script> tags in ajax content
			parseScript(menuContent)

			// loading bar:
			E('ajLoading').style.display = 'none';

			// set current page in variable, but NOT if a custom in-page element is specified as the target for the ajax content
			if(!optional['target_id'])
			{
				ajCurrentHash = urlVar;
			}

			// Location.href needs to excute BEFORE the external scripts(eval) below
			if(!optional['manual_redir'] && !optional['target_id'])
			{
				var re = eval("/^("+WSD_WEBROOT.replace(/\//gi, "\\/")+")(.*?)/gi");
				location.href = WSD_WEBROOT+'#'+urlVar.replace(re, "$2");
			}

			// title
			if(E('aj_HeaderInfo'))
			{
				document.title = E('aj_HeaderInfo').getAttribute('alt');
			}
			
			// optional scroll to specific portion of the page
			if(optional['scroll'])
			{
				scroll(optional['scroll'][0], optional['scroll'][1]);
			}

			// done loading page, busy = false. the 'true' state prevents other ajax request from happening
			aj_Busy = false;
		}
	}
}

/*
	Submitting Forms
*/

function dn_SubmitForm(formName, formTarget, page_type)
{
	if(!WSD_AJAX) return true;

	E('ajLoading').style.display = 'block';

	var elList = document.forms[formName].elements;

	var formOutput = "";

	for(i = 0; i < elList.length; i++)
	{
		var elAdded = false;
		var elType = elList[i].type;
		var elName = elList[i].name;
		var elValue = elList[i].value;

		if(elType == "checkbox" || elType == "radio")
		{
			if(elList[i].checked)
			{
				formOutput += elName+"="+encodeURIComponent(elValue);
				elAdded = true;
			}
		}
		else if(elType == 'hidden' && elList[i].getAttribute('file_status') == 'waiting')
		{
			alert('please wait for all file uploads to finish.');
			
			// loading bar:
			E('ajLoading').style.display = 'none';

			return false;
		}
		else
		{
			if(elValue.trim())
			{
				formOutput += elName+"="+encodeURIComponent(elValue);
				elAdded = true;
			}
		}

		if(elAdded)
		{
			formOutput += "&";
		}
	}

	if(!formOutput.trim())
	{
		return false;
	}

	formOutput += "submit_form_ajax=yes";
	formOutput += "&submit_page_type="+page_type;

	createXMLHttpRequest();
	xmlHttp.onreadystatechange = function(){updateFormRequest(formName);};
	xmlHttp.open('POST', formTarget, true);
	xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(formOutput);

	return false;
}

function updateFormRequest(formName)
{
    if(xmlHttp.readyState == 4)
	{
		//alert(xmlHttp.status);
		if(xmlHttp.status == 200)
		{
			var responseStatus = xmlHttp.responseText.trim();

			// loading bar:
			E('ajLoading').style.display = 'none';
			
			if(responseStatus.match(/^redir: /gi))
			{
				eval(responseStatus.replace(/^redir: (.*)/gi, "$1"));
				return false;
			}
			else if(responseStatus.match(/^error: /gi))
			{
				alert(responseStatus.replace(/^error: (.*)/gi, "$1"));
			}
			else if(responseStatus.match(/^display: /gi))
			{
				scroll(0,0);

				document.forms[formName].style.display = 'none';

				E('form_success').style.display = 'block';
				E('form_display').innerHTML = responseStatus.replace(/display: (.*)/gi, "$1");
			}
			else
			{
				alert("UNKOWN: "+responseStatus);
			}
		}
	}
}

var xmlHttp;

function createXMLHttpRequest()
{
    if (window.ActiveXObject) {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
       xmlHttp = new XMLHttpRequest();
    }

	return xmlHttp;
}

function generalAJAXStatus(xmlHttp, whatTodoNext)
{
    if(xmlHttp.readyState == 4)
	{
        if(xmlHttp.status == 200)
		{
			var responseStatus = xmlHttp.responseText;

			if(responseStatus != 'good')
			{
				alert(xmlHttp.responseText);
			}
			else
			{
				switch(whatTodoNext)
				{
				}
			}
		}
	}
}

