

var onloadEvents = new Array();

var baseUrl = '/';

function addToOnload(event){
	onloadEvents.push(event);
	window.onload = function() { 
		for (var x = 0; x < onloadEvents.length; x ++) {
			eval(onloadEvents[x]);
		}
	}
}

var FormSubmitActive = false;

/**
 * Form Submission
 */
var FormSubmit = function(f){
	
	//Check the filename is valid
	var filePath = f.elements['userfile'].value; var bits = filePath.split(/[\/|\\]/);
	//Get the last bit which is the filename
	var filename = bits[bits.length -1];
	//Get the extension
	var ext = filename.split('.'); ext = ext[ext.length -1].toLowerCase();
	if (ext != 'gz' && ext != 'zip' && ext != 'bz2' && ext !='tar'){
		alert('Files of type zip, gz, tar, and bzip2 only');
		return false;
	}
	
	if (FormSubmitActive) return false;
	
	//Display a wait message
	var sbutton = f.elements['submitForm'];
	//Please Wait text
	var e = document.createElement('span');
	e.innerHTML = 'Please Wait';
	e.className ='blueText';
	sbutton.parentNode.appendChild(e);
	
	
	//Safari Detection
	if (navigator.vendor){
		var uA = navigator.userAgent;
		if (uA.search(/Safari/) != -1){
			return true;
		}
	}
	
	FormSubmitActive = true;
		
	//Change the target of the form
	f.target = 'formIframe';	
	
	//Get the upload identifier	
	var uploadId = f.elements['UPLOAD_IDENTIFIER'].value;	
	var myFunc = FormSubmitFunc(f);
	
	//Run a periodical Ajax call to update the progress bar
	var intervalId = ProgressBar.run(uploadId);
	
	//Change the action of the form. 
	f.action = f.action+ '?uploadMonitor=true&AjaxRequest=true&ProgressInterval='+intervalId+'&UploadId='+uploadId;	
	
	FormSubmitInterval = window.setInterval(myFunc,2000);
	
	return false;
}

var FormSubmitFunc = function(f){
	return (function(){clearInterval(FormSubmitInterval);f.submit();});
}

var ProgressBar = {
	run : function (uploadId){
		var ajaxOptions = {method: 'get', period: 1500};		
		ajaxOptions.url = baseUrl+"uploadProgress.php?id="+uploadId;
		ajaxOptions.updateElement = 'uploadProgress'+uploadId;
		var AjaxObj = new Ajax(ajaxOptions);
		return AjaxObj.intervalId;
	},
	
	update : function(progressInfo){
		//state, speedAverage, bytesTotal, bytesUploaded, percentComplete, uploadId, jsIntervalId
		
		
		var percentComplete = (progressInfo.state =='Initiating') ? '2' : progressInfo.percentComplete;
		if (percentComplete == '100' || progressInfo.state == 'Complete' || progressInfo.state == 'Cancelled'){
			clearInterval(progressInfo.jsIntervalId);
		}
		
		var updateElement = document.getElementById('uploadProgress'+progressInfo.uploadId);
		if (updateElement){
			updateElement.className = 'progressContainer';			
			//need to create the animation bar and info bar if it doesnt exist already
			var progressBar = document.getElementById('progressBar'+progressInfo.uploadId);	
			
			if (!progressBar){
				//Hide the form field
				var formField = document.getElementById('fileFormField'+progressInfo.uploadId);	
				formField.style.display = 'none';
				
				//Create animation bar container 
				var aniContainer = document.createElement('div');
				aniContainer.id = 'animationContainer';
				aniContainer.className = 'animationContainer';
				updateElement.appendChild(aniContainer);
				
				//Create the animation bar
				var newE = document.createElement('div');
				newE.id = 'progressBar'+progressInfo.uploadId;
				newE.className = progressInfo.state != 'Complete' ? 'progressAnimation' :'progressAnimationComplete';
				newE.style.width = '0';
				aniContainer.appendChild(newE);
				
				//Now create the text bar
				var newE = document.createElement('div');
				newE.id = 'progressText'+progressInfo.uploadId;
				newE.className = 'progressText';
				updateElement.appendChild(newE);
			}
			
			var progressBar = document.getElementById('progressBar'+progressInfo.uploadId);
			var progressText = document.getElementById('progressText'+progressInfo.uploadId);
			
			
			progressBar.style.width = percentComplete+'%';
			
			var uploadText = progressInfo.bytesUploaded ? progressInfo.bytesUploaded : '0 Bytes';
			if (progressInfo.state == 'Complete'){				
				progressBar.className = 'progressAnimationComplete';				
				progressText.innerHTML = 'Upload Complete. <br/>Processing Your Log File Please Wait.';
				//Ajax Load the page that starts the log file process.
				var ajaxOptions = {method: 'GET', feedbackFunction: 'AjaxLoader.feedbackAnimation'};
				ajaxOptions.updateElement =  'progressBar'+progressInfo.uploadId;
				ajaxOptions.feedbackElement =  'contentWrapper';
				
				ajaxOptions.url =  "?processUpload=true&AjaxRequest=true";
				FormSubmitActive = false;
				new Ajax(ajaxOptions);
			} else {
				if (progressInfo.state == 'Initiating'){
					progressText.innerHTML = 'Initiating Connection';
				} else if (progressInfo.state == 'Cancelled'){
					progressText.innerHTML = 'Upload Cancelled';
				} else {
					progressText.innerHTML = uploadText+' uploaded, '+percentComplete+'% complete.';	
				}
 			}
		}
	},	
	/**
	 * Display an error message 
	 */
	errorMessage : function(progressInfo){
		var progressBar = document.getElementById('progressBar'+progressInfo.uploadId);
		var progressText = document.getElementById('progressText'+progressInfo.uploadId);	
		progressBar.style.visibility = 'hidden';
		progressText.innerHTML = 'Error with file or nothing uploaded. <br/> <a href="'+baseUrl+'">Click here to try again</a>';
	}
}

var SiteRake = {
	
	//Attach onclick functions to all elements with class "ajaxPage" and "graphIcon"
	init : function(){
		var alist = document.getElementsByTagName("a");
		for (var i=0; i< alist.length; i++){
			try {
				if (alist[i].className == 'ajaxPage'){	
					myOnclickfunc = SiteRake.getFunc(alist[i].href);
					alist[i]['onclick'] = myOnclickfunc;
				} else if (alist[i].className == 'graphIcon'){
					myOnclickfunc = SiteRake.getGraphFunc(alist[i]);
					alist[i]['onclick'] = myOnclickfunc;
				}
			} catch (e){
				continue;
			}
		}
	},
	/**
	 * Displays the graph for the search phrases
	 * @param {Object} ancObj
	 */
	displayGraph : function(ancObj){
		var offsetYTable = ancObj.parentNode.offsetTop;
		var phraseTable = document.getElementById('spOverview');
		var containerWidth = phraseTable.offsetWidth - 2;
		var containerHeight = phraseTable.offsetHeight;
		var ieOffset = 16;
		if (document.all && !window.opera){
			offsetYTable += ieOffset;
		}
		
		//Create Block for the Graph if it doesnt Exist
		var graph = document.getElementById('graphBlock');
		
		if (!graph){
			var graphContainer = document.createElement('div');
			graphContainer.id = 'graphContainerSmall';
			graphContainer.className = "graphContainerSmall";	
			graphContainer.style.width = containerWidth+"px";
			
			var graph = document.createElement('div');
			graph.id = "graphBlock";
			graph.className = "graphBlock";
			graph.style.marginLeft = '2px';
			var pnode = phraseTable.parentNode;		
			pnode.insertBefore(graphContainer, phraseTable);
			
			//Get the graph container and append the graph to it
			var graphContainer = document.getElementById('graphContainerSmall');
			graphContainer.appendChild(graph);
		}
		var graphBoxHeight = 380;
		
		graph.style.height = graphBoxHeight + "px";
		graph.innerHTML = '<a href="javascript:SiteRake.closeGraphBox()" class="closeButton"></a>';
		var graphX = containerWidth - 2;
		var graphMarginTop = graphBoxHeight + 30 + offsetYTable > containerHeight ? containerHeight - graphBoxHeight - 10 + ieOffset: offsetYTable;
		graph.style.width = graphX+'px';
		graph.style.marginTop = graphMarginTop+'px';
		
		//Now get the report and add it in the html of the graph div
		var ajaxOptions = {method: 'GET', updateElement: 'graphBlock', feedbackElement: 'graphBlock' ,feedbackFunction: 'AjaxLoader.feedbackAnimation'};
		ajaxOptions.url =  ancObj.href+"&AjaxRequest=report";
		new Ajax(ajaxOptions);
	},
	/**
	 * Closes the graph info box
	 */
	closeGraphBox: function (){
		var graphContainer = document.getElementById('graphContainerSmall');	
		var graph = document.getElementById('graphBlock');
		
		while (graph.firstChild) {
  			graph.removeChild(graph.firstChild);			
		}
		
		graph.parentNode.removeChild(graph);
		graphContainer.parentNode.removeChild(graphContainer);
	},
	
	getFunc : function(myHref){
		var ajaxOptions = {method: 'GET', updateElement: 'searchPhraseContainer', feedbackElement: 'searchPhraseContainer' ,feedbackFunction: 'AjaxLoader.feedbackAnimation'};
		var hrefBits = myHref.split('?');
		ajaxOptions.url =  baseUrl+"report/?"+hrefBits[1]+"&AjaxRequest=report";
		return(function() { new Ajax(ajaxOptions); return false;});
	},
	
	getGraphFunc : function(ancObj){
		return( function(){ SiteRake.displayGraph(ancObj); return false; } ); 
	}
}


