/**
 * Helper javascript function which makes the AJAX call to clicktrack
 *
 */

var request = false;
var debug = false;


/**
 * tracks a user click.
 * clickTrackData - this is the clicktrackData returned from the clicktrack object
 */
function clicktrack(clickTrackData) {
	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			request = new XMLHttpRequest();
			if(debug) {
				alert("XmlHttpObject successfully created.");
			}
        } catch(e) {
			request = false;
        }
        
    } else if(window.ActiveXObject) {
       	try {
        	request = new ActiveXObject("Msxml2.XMLHTTP");
        	if(debug) {
				alert("IE XmlHttpObject v1 successfully created.");
			}
      	} catch(e) {
        	try {
          		request = new ActiveXObject("Microsoft.XMLHTTP");
          		if(debug) {
					alert("IE XmlHttpObject v2 successfully created.");
				}
        	} catch(e) {
          		request = false;
        	}
		}
    }
    
	if(request) {
		request.onreadystatechange = processRequestStateChange;
		request.open("POST", "/phplib/ajax/clicktrack/ajaxClicktrack.php", true);
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		request.setRequestHeader("Content-length", clickTrackData.length);
		request.send(clickTrackData);
	}
}

/**
 * Event handler for completion of ajax request
 */ 
function processRequestStateChange() {
    if(request.readyState == 4) {
        if(debug) {
			alert("Request returned with status completed.");	
		}
    	if(request.status == 200) {
            if(debug) {
            	alert('Clicktrack *successful*');
            }
        } else {
            if(debug) {
            	alert('Clicktrack *failed*: ' + request.status + " " + request.statusText);
            }
        }
    }
}


/**
 * A convenience function for clicks which open new links.
 *
 * redirectUrl - the destination of the link
 * clickTrackData - this is the clicktrackData returned from the clicktrack object
 */
function clicktrackAndRedirect(redirectUrl,clickTrackData) {
	clicktrack(clickTrackData);
	if(!debug) {
		location.href = redirectUrl;
	}
}

/**
 * A convenience function for clicks which open new links in a new window.
 *
 * redirectUrl - the destination of the link
 * clickTrackData - this is the clicktrackData returned from the clicktrack object
 * target - optionally pass in a value for the target attribute (same as what you would pass to window.open())
 *			default is "_blank"
 * specs - optional specs for how the new link will be opened (same as what you would pass to window.open())
 */
function clicktrackAndRedirectNewWindow(redirectUrl,clickTrackData,target,specs) {
	clicktrack(clickTrackData);

	if(!debug) {
		if(target == '') {
			target = '_blank';
		}
	
		if(specs != '') {
			window.open(redirectUrl,target,specs);
		} else {
			window.open(redirectUrl,target);
		}
	}
}


