/***
*
*	Notes:
*	------------------------------------------------------------
*	1. axXXX functions puts host name automatically, you should just 
*	   place urlpath and your script parameters.
* 
*	2. It is strongly recommended to use standard axXXX function to 
*	   detect response status (axCheckResponse) and to get response
*	   text (axResponse).   
*
*	3. This script can work in debug mode, for it set axDebugMode 
*	   variable in TRUE, and function will allert all inside errors.
*
*	4. For send requests in synchronous mode, set axSyncReq to TRUE
*	
*
****************************************************************/

/***
*
*	Global Definitions
*
****************************************************************/

var axSyncReq 		= true; 			// False - enable asynchronous mode
var axReq 			= false; 			// 
var axDebugMode		= false;			// Enable debug mode
var axLoadingImg	= '/public/images/lightbox/ajax-loading.gif';	// Loading image path
var axLoadingClass	= 'axLoading';

/***
*
*	Private Definitions
*
****************************************************************/

var _axPlaceId 	= '';					
var _axTabs		= new Array();

/***
*
*	Error Definitions
*
****************************************************************/

var Error = new Array();
	Error[0] = 'Success';
	Error[1] = 'Request initialization failed';
	Error[2] = 'Invalid argument';
	Error[3] = 'Element is not available';
	Error[4] = 'Reserved';

/***
*
*	Global Functions
*
****************************************************************/

// Return error code, in debug mode alert error message

function axResult(axErr) 
{
	if (axDebugMode) {
		alert(Error[axErr]);
		return axErr;
	} else {
		return axErr;
	}

}

// Initialize XMLHTTP Object

function axInitRequest() 
{
	axReq = false;
	try {
        axReq = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            axReq = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            if(window.XMLHttpRequest){
               axReq = new XMLHttpRequest();
            }
        }
    }
    return axReq;
}

// Send request to URL and return result to callback function

function axSend(url, action, callback) 
{
	axReq = axInitRequest();
	
	if (!axReq) { return axResult(1); }
	
	var host = window.location.protocol + '//' + window.location.host;
	var fullURL = '';
	
	if (url.search(host) == -1) {
		fullURL = host + url;
	} else {
		fullURL = url;
	}
	
	axReq.onreadystatechange = callback;
	if (action.toLowerCase() == 'post') {
		url = fullURL.split('?');
	    axReq.open(action, url[0], axSyncReq); 
		axReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		_axInitHeader();
		axReq.send(url[1]);
	} else if (action.toLowerCase() == 'get') {
	    axReq.open(action, fullURL + (fullURL.indexOf('?') == -1 ? '?' : '&') + 'unique=' + Math.random(), axSyncReq); 
		_axInitHeader();
	    axReq.send(null);	
	} else {
		axResult(2);
	}
}

// Return TRUE, when response is ready

function axCheckResponse()
{
	return (axReq.readyState == 4 && axReq.status == 200);
}

// Return response content

function axResponse()
{
	return axReq.responseText;
}

/*
*
*	animation {
*		0 - No Animation
*		1 - Full (With Image & Text)
*		2 - Image Only
*		3 - Text Only
*	}
*
*/

// Load content from URL to some HTML container

function axLoadContent(from, to, animation, callback)
{
	_axPlaceId = to;

	axPut(to, _axAnimationContent(animation));
	if (callback == 'undefined' || callback == null) {
		axSend(from, 'get', _axPlace);
	} else {
		axSend(from, 'get', callback);
	}	
}

// Put content to some HTML container

function axPut(id, content)
{
	try {
		document.getElementById(id).innerHTML = content;
	} catch(e) {
		return axResult(3);
	}
}

// Post form  to URL and result return to callback function

function axSubmitForm(fmName, callback, disable)
{
	axSend(_axGetFormURL(fmName), fmName.method, callback);
}

// Enable all form fields

function axEnableForm(fmName) {
	if (!document.forms[fmName]) { return axResult(3); }
	
	var elemsCount = document.forms[fmName].elements.length;
	for (i = 0; i < elemsCount; i++){
		document.forms[fmName].elements[i].disabled = false;
	}
}

// Initialize tabs

function axStartTabs(tabGroup, tabContent)
{
	var tbGroup = document.getElementById(tabGroup);
	var tbContent = document.getElementById(tabContent);
	
	if (!tbGroup || !tbContent) { return axResult(3); }
	
	var links = _axExtractLinks(tbGroup, tabContent);
	
	_axTabs[tabGroup] = links;
	
	for (i = 0; i < links.length; i++) {
		if (links[i].parentNode.className == 'selected') {
			axLoadContent(links[i].href, tabContent, 1);
		}
		links[i].onclick = _axTabClick;
	}
}

function axLoadContentExec(from, to, animation)
{
	_axPlaceId = to;
	axPut(to, _axAnimationContent(animation));
	axSend(from, 'get', _axExecContent);
}

function axIsBrowserType(type)
{
	var version = window.navigator.appVersion; 
	var browser = window.navigator.appName;
	
	if(window.navigator.appName == "Microsoft Internet Explorer" && type.toLowerCase() == 'explorer') {
		return true;
	} else if(window.navigator.appName == "Opera" && type.toLowerCase() == 'opera'){
		return true; 
	} else if(version.indexOf("Safari") > 0 && type.toLowerCase() == 'safari') {
		return true;
	} else if(window.navigator.appName == 'Netscape' && type.toLowerCase() == 'mozilla') {
		return true;
	} else {
		return false;
	}
}

/***
*
*	Private Functions
*
****************************************************************/

function _axExecContent()
{
	if (!axCheckResponse()) { return; }
	
	var reg = new RegExp("<script[^>]*?>([\n*\r*]*?.*?[\n*\r*]*?)</script>", "gi");
	var result;
	axPut(_axPlaceId, axResponse());

	var str = new String(axResponse());
	str = str.replace(/([\r\n])([\s]+)/gi, '');
	str = str.replace(/(\/\/.*?)/gi, '');
	if (!axIsBrowserType('explorer')) {
		while ((result = reg.exec(str)) != null) {
			try{
				eval(result[1]);
			} catch(e){}
		}
	} else {
		var str_old = '';
		var cnt = 0;
		
		while(str_old != (str = str.replace('<script', ''))){
			str_old = str;
			cnt++;
		}
		
		str = axResponse();
		str = str.replace(/([\r\n])([\s]+)/gi, '');
		str = str.replace(/(\/\/.*?)/gi, '');
		
		for (i = 0; i < cnt; i++) {
			arr = reg.exec(str);
			str = str.replace(reg.toString(), '');
			try {
				eval(arr[1]);
			} catch(e){}
		}
	}
}

function _axPlace()
{
	if (axCheckResponse()){
		axPut(_axPlaceId, axResponse());
	}
}

function _axExtractLinks(obj, rel) 
{
	var res = new Array();
	var childs = obj.childNodes;
	var idx = 0;	
	
	for (i = 0; i < childs.length; i++) {
		if (typeof(childs[i].childNodes[0]) == 'object' && childs[i].childNodes[0].rel == rel) {
			res[idx] = childs[i].childNodes[0];
			idx++;
		}
	}
		
	return res;
}

function _axTabClick() 
{
	if (this.rev.toLowerCase() == 'exec') {
		axLoadContentExec(this.href, this.rel, 1);
	} else {
		axLoadContent(this.href, this.rel, 1);
	}
	var rel = this.parentNode.parentNode.id;
	for (i = 0; i < _axTabs[rel].length; i++){
		_axTabs[rel][i].parentNode.className = '';
	}
	this.parentNode.className = 'selected';
	return false;
}

function _axAnimationContent(num) {
	var animationContent = new String("");
	switch (num) {
		case 0:
			animationContent = '<span class="' + axLoadingClass + '"></span>';		
			break;
		case 1:
			animationContent = '<span class="' + axLoadingClass + '"><img src="' + axLoadingImg + '" alt="Loading" /><span>Adding to favorites. Please wait...</span></span>';		
			break;
		case 2:
			animationContent = '<span class="' + axLoadingClass + '"><img src="' + axLoadingImg + '" alt="Loading" /></span>';		
			break;
		case 3:
			animationContent = '<span class="' + axLoadingClass + '">Adding to favorites. Please wait...</span>';		
			break;
		default:
			break;
	}
	return animationContent;
}

function _axGetFormURL(fmName)
{
	if (!fmName) { return axResult(3); }
	
	var elemsCount = fmName.elements.length;
	var params = new String(""); 
	for (i = 0; i < elemsCount; i++){
		if (fmName.elements[i].name != '') {
			
			if(fmName.elements[i].type.toLowerCase() == 'checkbox')
			{
				if(fmName.elements[i].checked)
				{
					params += (fmName.elements[i].name + '=' + fmName.elements[i].value);
				}
			}
			else
			{
				params += (fmName.elements[i].name + '=' + fmName.elements[i].value);
			}
		}
		if ((i + 1) < elemsCount && fmName.elements[(i + 1)].name != '') {
			params += '&';
		}
		if(typeof(disable) == 'string' && disable.toLowerCase() == 'all'){
			fmName.elements[i].disabled = true;
		} else if (typeof(disable) == 'object') {
			disable.disabled = true;
		}	
	}
	
	return fmName.action + (fmName.action.search("\\?") > 0 ? '&' : '?') + params;
}

function _axInitHeader() 
{
	axReq.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
	axReq.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0');
	axReq.setRequestHeader('Pragma', 'no-cache');	
}
