/*****************************************************************************
 * Author:          Nik Estep
 * Created:         August 31, 2009
 * Last Modified:   April 10, 2010
 * Purpose:         Contains the javascript functions that are necessary to
 *                  the Installer Raw Data page.
 *****************************************************************************/

var currDataDay = new Date ();
var currDisplayUnit = '.colBTU';


/**
 * This is an event function that will run once the document has completely
 * loaded. This lets us run some tasks on the document once it has loaded.
 */
jQuery(document).ready (function () {
	/* These are functions we need to call once the document is loaded */
	configureInputs ();
	loadLocations ('../..', 'roof');
	
	/* We are going to bind to a change event on our site selector so that we
	 * can make sure the minimum date is set correctly for the dat picker.
	 */
	jQuery('#selSite').change ( function () {
		for (var i = 0; i < locations.length; i++) {
			if (locations[i].idName == jQuery('#selSite').val ()) {
				dayPicker.TC0H = locations[i].startDate;
				break;
			}
		}
   });
});


/**
 * Reset the inputs on the page.
 */
function configureInputs () {
	jQuery('#btnView').attr ('disabled', false);
	jQuery('#inDate').val (formatDateForTigra (new Date ()));
	jQuery('#selUnit').val ('.colBTU');
}


/**
 * Load raw data from a location for a certain day.
 */
function loadRawData () {
    /* Verify input */
    if (jQuery('#selSite').val () == 'select') {
        alert ('Please Select a Location');
        return;
    }
    if (jQuery('#inDate').val () == '') {
        alert ('Please Select a Date');
        return;
    }
    
    /* Save the date */
    currDataDay = new Date (jQuery('#inDate').val ());
    
    /* Gray the data table */
    jQuery('#installerData').addClass ('transparent');
    jQuery('#btnView').attr ('disabled', true);
    
    /* Reset the unit drop down */
    currDisplayUnit = '.colBTU';
 	jQuery('#selUnit').val (currDisplayUnit);
    
    /* Call AJAX request to replace the data */
    /* By sending fail conditions to non-existent element we can hide the
       message returned. The onFailure event will show the user a message
       instead */
    jQuery('#installerData').load ('../../meter_monitor/data/getRawData.php',
    							   {
    									siteIdName: jQuery('#selSite').val (),
    									year: currDataDay.getFullYear (),
    									month: (currDataDay.getMonth () + 1),
    									day: currDataDay.getDate ()
    							   },
    							   function (response, status, xhr) {
    								    /* Set which buttons should be visible */
    		                            var today = new Date ();
    		                            var siteIndex = getSiteIndex (jQuery('#selSite').val ());
    		                            
    		                            if (doDatesMatch (currDataDay, today)) {
    		                            	jQuery('#installerNext').addClass ('hidden');
    		                            }
    		                            else {
    		                            	jQuery('#installerNext').removeClass ('hidden');
    		                            }
    		                            
    		                            if (doDatesMatch (currDataDay,
    		                                             locations[siteIndex].startDate)) {
    		                            	jQuery('#installerPrev').addClass ('hidden');
    		                            }
    		                            else {
    		                            	jQuery('#installerPrev').removeClass ('hidden');
    		                            }
    		                            
    		                            /* Show buttons */
    		                            jQuery('#installerButtons').removeClass ('hidden');
    		                            
    		                            /* Schedule the other methods */
    		                         	//setTimeout ("unitChange ();", 100);
    		                         	setTimeout ("resizeColumns ();", 100);
    		                         	
    		                         	/* Undo input deterant */
    		                         	jQuery('#installerData').removeClass ('transparent');
    		                            jQuery('#btnView').attr ('disabled', false);
    							   });
}


/**
 * Resize the columns of newly loaded data so that the table head and table
 * body column widths match.
 */
function resizeColumns () {
	/* Get the table header and body */
	var tableHead = jQuery('#installerData')[0].children[0].children[0];
	var tableBody = jQuery('#installerData')[0].children[0].children[1];
	
	if (navigator.userAgent.indexOf ('Safari') > 1) {
		tableBody.css ('top', '87px');
	}
	
	/* Get the header row to resize and a body row to resize */
	var headerResizeRow = tableHead.children[2];
	var bodyResizeRow = tableBody.children[0];
	
	/* Delcare an index to keep track of the current cell index */
	var cellIndex = 0;
	var headerWidth = 0;
	var bodyWidth = 0;
	var padding = 22;
	
	while (cellIndex < bodyResizeRow.childElementCount) {
		/* Check to see if this is a hidden energy column */
		if (cellIndex > (bodyResizeRow.childElementCount - 4)) {
			/* Make the column visible */
			jQuery(headerResizeRow.children[cellIndex]).removeClass ('notVisible');
			jQuery(bodyResizeRow.children[cellIndex]).removeClass ('notVisible');
		}
		
		/* Do this column */
		headerWidth = headerResizeRow.children[cellIndex].width;
		bodyWidth = bodyResizeRow.children[1].width;
		
		if (headerWidth == "" || headerWidth == 0) {
			headerWidth = headerResizeRow.children[cellIndex].offsetWidth - padding;
		}
		if (bodyWidth == "" || bodyWidth == 0) {
			bodyWidth = bodyResizeRow.children[cellIndex].offsetWidth - padding;
		}
		
		if (headerWidth >= bodyWidth) {
			jQuery(bodyResizeRow.children[cellIndex]).css ('width',  
												   		   headerWidth + 'px');
		}
		else {
			jQuery(headerResizeRow.children[cellIndex]).css ('width', 
												     		 bodyWidth + 'px');
		}
		
		/* Check to see if this is a hidden energy column */
		if (cellIndex > (bodyResizeRow.childElementCount - 4)) {
			/* Make the column visible */
			jQuery(headerResizeRow.children[cellIndex]).addClass ('notVisible');
			jQuery(bodyResizeRow.children[cellIndex]).addClass ('notVisible');
		}
		
		cellIndex++;
		
		if (navigator.userAgent.indexOf ('Firefox') > 1) {
			if (cellIndex == 2) {
				padding--;
			}
			else if (cellIndex == 5) {
				padding--;
			}
			else if (cellIndex == 6) {
				padding++;
			}
		}
		else if (navigator.userAgent.indexOf ('Safari') > 1) {
			padding -= 2;
		}
	}
	
	/* If this is Internet Explorer, we have to change the height of the
	 * data rows
	 */
	if (navigator.userAgent.indexOf ('Explorer') > 1) {
		var btus = jQuery('.colBTU');
		
		for (i = 0; i < btus.length; i++) {
			try {
				btus[i].css ('height', '14px');
			}
			catch (e) { }
		}
	}
	
	/* Resize the BTU column */
	jQuery ('#thEnergy').css ('width', '150px');
 	jQuery ('.colBTU').css ('width', '150px');
}


/**
 * The unit of produced power has been changed, so change it.
 */
function unitChange () {
	if (jQuery('#selUnit').val () == currDisplayUnit) {
		return;
	}
	
	/* Hide the currently visible unit */
	var currVisible = jQuery(currDisplayUnit);
	
	for (i = 0; i < currVisible.length; i++) {
		try {
			jQuery (currVisible[i]).addClass ('notVisible');
		}
		catch (e) { }
	}
	
	/* Show the new unit */
	var newVisible = jQuery(jQuery('#selUnit').val ());
	
	for (i = 0; i < newVisible.length; i++) {
		try {
			jQuery (newVisible[i]).removeClass ('notVisible');
		}
		catch (e) { }
	}
	
	jQuery(jQuery('#selUnit').val ()).css ('width', '150px');
	
	var width = 0;
	try {
		width = newVisible[0].offsetWidth;
	}
	catch (e) { }
	
	/* Store new unit */
	currDisplayUnit = jQuery('#selUnit').val ();
	
	/* Update energy tag */
	jQuery('#thEnergy').empty ();
	jQuery('#thEnergy').attr ('width', '150px');
	if (currDisplayUnit == '.colBTU') {
		jQuery('#thEnergy').html ('British Thermal Units');
	}
	else if (currDisplayUnit == '.colkWH') {
		jQuery('#thEnergy').html ('Kilowatt Hours');
	}
	else if (currDisplayUnit == '.colTherm') {
		jQuery('#thEnergy').html ('Therms');
	}
	else if (currDisplayUnit == '.colCCF') {
		jQuery('#thEnergy').html ('100 Cubic Feet');
	}
}


/**
 * Change the day that data is being displayed for.
 *
 * @param {bool}    If we are changing the day forward (next day)
 */
function changeDayButton (goForward) {
    /* Change the date */
    if (goForward) {
        currDataDay.setDate (currDataDay.getDate () + 1);
    }
    else {
        currDataDay.setDate (currDataDay.getDate () - 1);
    }
    
    /* Update the date in the text field */
    jQuery('#inDate').val (formatDateForTigra (currDataDay));
    
    /* Load the new raw data */
    loadRawData ();
}