/*****************************************************************************
 * Author:          Nik Estep
 * Created:         August 11, 2009
 * Last Modified:   April 11, 2010
 * Purpose:         Contains all of the javascript necessary for the operation
 *                  of the meter charts.
 *****************************************************************************/

var currChartSiteId = '';
var currChartSiteStartDate = new Date ();
var currChartDay = new Date ();
var currChartUnits = '';
var currChartIndex = 0;
var currBigChart = '';
var firstLoad = 1;
var imageOne = '';
var imageTwo = '';
var initialLoadComplete = false;


/**
 * This is an event function that will get called once the whole page has been
 * loaded. We need to wait until this point before we set up the page.
 */
jQuery(document).ready (function () {
	/* These are functions we need to call once the document is loaded */
	configureInputs ();
	loadLocations ('../..', 'roof');
	loadLocationView ('../..', 'roof', 'BTU');
	
	/**
	 * 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 () {
		if (initialLoadComplete) {
			return;
		}
		
		for (var i = 0; i < locations.length; i++) {
			if (locations[i].idName == currChartSiteId) {
				currChartSiteStartDate = locations[i].startDate;
				dayPicker.TC0H = currChartSiteStartDate;
				break;
			}
		}
		
		initialLoadComplete = true;
   });
});


/**
 * Configure the input fields on the page.
 */
function configureInputs () {
    jQuery('#selSite').attr ('disabled', false);
    jQuery('#selUnit').attr ('disabled', false);
    jQuery('#selUnit').val ('select');
}


/**
 * Switch the page view to a new location.
 * 
 * @param prefix {string}	Path prefix from this page to meter_monitor folder
 */
function switchLocationView (prefix) {
	loadLocationView (prefix,
					  jQuery('#selSite').val (),
					  jQuery('#selUnit').val ());
}


/**
 * Load the charts for the given location in the given unit.
 * 
 * @param prefix {string}	Path prefix from this page to meter_monitor folder
 * @param site {string}		Site ID to load
 * @param unit {string}		Unit to load charts for
 */
function loadLocationView (prefix, site, unit) {
	/* If the site has changed, save the new site, load the thumbnails, and
	 * load a new GHG chart */
    if (site != currChartSiteId) {
    	currChartSiteId = site;
		loadThumbnails ();
		
		/* Find the location and save the start date */
		for (var i = 0; i < locations.length; i++) {
			if (locations[i].idName == currChartSiteId) {
				/* Store the start date */
				currChartSiteStartDate = locations[i].startDate;
				
				/* Set the min, max, current, and today date */
				dayPicker.TC0H = currChartSiteStartDate;
				dayPicker.TC0F = new Date ();
				dayPicker.TC0L = new Date ();
				dayPicker.TC0O = new Date ();
				
				/* Stop searching */
				break;
			}
		}
		
		/* Load the GHG Chart */
		loadChart (prefix,
				   'ghgChart',
				   'swfGHGChart',
				   'Bar2D',
				   '420',
				   '225',
				   currChartSiteId,
				   'GHG',
				   currChartUnits,
				   formatDateForServer (currChartDay),
				   0);
	}
    
    currChartDay = new Date ();
	
    jQuery('#selSite').val (site);
    jQuery('#selUnit').val (unit);
	
	/* Save the unit parameter */
    currChartUnits = unit;
    
	/* Load the totals */
	loadTotals (prefix);
	
	/* Load the Daily Chart */
	loadChart (prefix,
			   'dailyChart',
			   'swfDailyChart',
			   'MSLine',
			   '420',
			   '225',
			   currChartSiteId,
			   'DAILY',
			   currChartUnits,
			   formatDateForServer (currChartDay),
			   0);
	
	/* Load the Weekly Chart */
	loadChart (prefix,
			   'weeklyChart',
			   'swfWeeklyChart',
			   'MSLine',
			   '420',
			   '225',
			   currChartSiteId,
			   'WEEKLY',
			   currChartUnits,
			   formatDateForServer (currChartDay),
			   0);
	
	/* Load the Yearly Chart */
	loadChart (prefix,
			   'yearlyChart',
			   'swfYearlyChart',
			   'MSLine',
			   '420',
			   '225',
			   currChartSiteId,
			   'YEARLY',
			   currChartUnits,
			   formatDateForServer (currChartDay),
			   0);
}


/**
 * Try to load the thumbnails for a particular site.
 */
function loadThumbnails () {
    for (var i = 0; i < locations.length; i++) {
        if (locations[i].idName == currChartSiteId) {
            if (locations[i].image1 != '') {
                /* Create the new image and size it to a thumbnail */
                imageOne = new Image ();
                imageOne.src = 'http://www.qisol.com/meter_monitor/data' +
                               '/images/' +
                               locations[i].image1;
                
                /* Launch loader */
                imageOneLoader ();
            }
            else {
                $('aThumbLeft').remove ();
                imageOne = '';
            }
            if (locations[i].image2 != '') {
                /* Create the new image and size it to a thumbnail */
                imageTwo = new Image ();
                imageTwo.src = 'http://www.qisol.com/meter_monitor/data' +
                               '/images/' +
                               locations[i].image2;
                
                /* Launch loader */
                imageTwoLoader ();
            }
            else {
                $('aThumbRight').remove ();
                imageTwo = '';
            }
        }
    }
}


/**
 * Function to handle the loading of the first thumnail image. If the image is
 * not fully loaded yet, we set up to re-run this function in 1/2 second.
 */
function imageOneLoader () {
    if (!imageOne.complete) {
        setTimeout ("imageOneLoader ()", 500);
        return;
    }
    
    var width = imageOne.width;
    var height = imageOne.height;
    
    if (width == undefined || height == undefined) {
        width = imageTwo.offsetWidth;
        height = imageTwo.offsetHeight;
    }
    
   // alert (width + ', ' + height);
    
    while (width > 65) {
        width *= .8;
        height *= .8;
    }
    
    /* Calculate margin */
    var marginLeft = ((65 - width) / 2);
    
    /* Create the elements to add it to the page */
    var linkElem = "<a id='aThumbLeft' href='javascript:bigThumbnail (1);' onclick='bigThumbnail (1);' target='_self'>";
    var imageElem = "<img id='imgThumbLeft' src='" + imageOne.src + "' width='" + width + "' height='" + height + "' />";
    jQuery('#thumbLeft').empty ();
    jQuery('#thumbLeft').append (linkElem + imageElem + "</a>");
}


/**
 * Function to handle the loading of the second thumnail image. If the image is
 * not fully loaded yet, we set up to re-run this function in 1/2 second.
 */
function imageTwoLoader () {
    if (!imageTwo.complete) {
        setTimeout ("imageTwoLoader ()", 500);
        return;
    }
    
    var width = imageTwo.width;
    var height = imageTwo.height;
    
    if (width == 0 || height == 0) {
        width = imageTwo.offsetWidth;
        height = imageTwo.offsetHeight;
    }
    
    while (width > 65) {
        width *= .8;
        height *= .8;
    }
    
    /* Calculate margin */
    var marginLeft = ((65 - width) / 2);
    
    /* Create the elements to add it to the page */
    var linkElem = "<a id='aThumbRight' href='javascript:bigThumbnail (2);' onclick='bigThumbnail (2);' target='_self'>";
    var imageElem = "<img id='imgThumbRight' src='" + imageTwo.src + "' width='" + width + "' height='" + height + "' />";
    jQuery ('#thumbRight').empty ();
    jQuery('#thumbRight').append (linkElem + imageElem + "</a>");
}


/**
 * Load the chart object for the first time. This will create the chart object,
 * set our starting parameters, and have the chart data loaded.
 *
 * @param prefix {string}       The path prefix to the 'meter_monitor' folder
 *                              from the calling page
 * @param divName {string}      Name of the div tag to render the chart object
 *                              into
 * @param chartName {string}    Name to assign to the chart object
 * @param swfFile {string}		Name of SWF chart file
 * @param width {string}        Width of the chart object
 * @param height {string}       Height of the chart object
 * @param site {string}         Installation location to load data from
 * @param type {string}         Type of chart to retrieve data for
 * @param unit {string}         Measurement unit to load data in
 * @param day  {string}         Day to get data from
 * @param index {int}			Weekly or Yearly chart index
 * @param bigChart {boolean}	If this is for a big chart. It will default to
 * 							   	false if not provided.
 */
function loadChart
(
    prefix,
    divName,
    chartName,
    swfFile,
    width,
    height,
    site,
    type,
    unit,
    day,
    index,
    bigChart
) {
	if (bigChart == null) {
		bigChart = false;
	}
	
    /* Create the Chart */
    var myChart = new FusionCharts (prefix +
                                    "/meter_monitor/FusionCharts/Charts/" +
                                    swfFile +
                                    ".swf?registerWithJS=1",
                                    chartName,
                                    width,
                                    height);
                                    
    /* Set the data URL */
    myChart.setDataURL (escape (prefix +
                                "/meter_monitor/data/getChartData.php" +
                                "?siteIdName=" + site +
                                "%26chartType=" + type +
                                "%26chartUnit=" + unit +
                                "%26chartDay=" + day +
                                "%26chartIndex=" + index +
                                "%26bigChart=" + (bigChart ? 1 : 0)));
    
    /* Set some parameters */
    //myChart.addParam ("onclick", "bigChart ('" + type + "');");
    //myChart.addParam ("href", "javascript:bigChart ('" + type + "');");
    myChart.addParam ("WMODE", "transparent");
    myChart.setAttribute ("baseFontSize", "9");
    
    /* Render the chart */
    myChart.render (divName);
}


/**
 * Load the totals for the current location.
 *
 * @param prefix	{string}    The path prefix to the 'meter_monitor' folder
 *                  			from the calling page
 */
function loadTotals
(
    prefix
) {
	jQuery.getJSON (prefix + "/meter_monitor/data/getTotals2.php",
				{
					siteIdName: currChartSiteId,
					Unit: currChartUnits
				},
				function (json) {
					if (json.valid == 1) {
                    	/* Find Location */
                    	var index = 0;
                    	var yearDate = '';
                    	while (index < locations.length) {
                    		if (locations[index].idName == currChartSiteId) {
                    			yearDate = locations[index].yearStartDate;
                    			break;
                    		}
                    		
                    		index++;
                    	}
                    	
                        jQuery('#pDayTotal').text (json.dailyTotal +
                                               " " +
                                               currChartUnits +
                                               "s Today");
                        jQuery('#pWeekTotal').text (json.weeklyTotal +
                                                " " +
                                                currChartUnits +
                                                "s This Week");
                        
                        if (yearDate == '') {
                        	jQuery('#pYearTotal').text (json.yearlyTotal +
													" " +
													currChartUnits +
													"s This Year");
							
                        	jQuery('#pGHGTotal').text (json.ghgTotal +
												   " Pounds CO2 Saved " +
												   "This Year");
						}
						else {
							jQuery('#pYearTotal').text (json.yearlyTotal +
													" " +
													currChartUnits +
													"s Since " +
													yearDate);
							
							jQuery('#pGHGTotal').text (json.ghgTotal +
												   " Pounds CO2 Saved " +
												   "Since " +
												   yearDate);
						}
				}
			});
    
    /* Set to re-run */
    timeoutHandle = setTimeout ('loadTotals ("' +
                                prefix +
                                '")',
                                300000);
}


/**
 * Display the big chart.
 * 
 * @param type Chart type to load in the big chart.
 */
function bigChart (type) {
	/* Save big chart type */
	currBigChart = type;
	
	/* Set stored stuff */
	currChartIndex = 0;
	currChartDay = new Date ();
	dayPicker.TC0L = currChartDay;
	dayPicker.TC2D ();
	jQuery('#inDate').val (formatDateForTigra (currChartDay));
	
	/* Decide the chart type */
	var swf = 'MSLine';
	
	if (type == 'GHG') {
		swf = 'Bar2D';
	}
	
	/* Load the big chart */
	loadChart ('../..', 
			   'dvBigChart', 
			   'bigChart', 
			   swf,
			   840, 
			   440, 
			   currChartSiteId, 
			   type, 
			   currChartUnits, 
			   formatDateForServer (currChartDay), 
			   0,
			   true);
	
	/* Set button states */
	jQuery('#btnPrevious').attr ('disabled', false);
	jQuery('#btnNext').attr ('disabled', true);
	
	/* Set button text */
	if (currBigChart == 'DAILY') {
		jQuery('#btnPrevious').val ('Previous Day');
		jQuery('#btnNext').val ('Next Day');
		jQuery('#tdDatePicker').removeClass ('hidden');
	}
	else if (currBigChart == 'WEEKLY' || currBigChart == 'GHG') {
		jQuery('#btnPrevious').val ('Previous Week');
		jQuery('#btnNext').val ('Next Week');
		jQuery('#tdDatePicker').addClass ('hidden');
	}
	else if (currBigChart == 'YEARLY') {
		jQuery('#btnPrevious').val ('Previous Year');
		jQuery('#btnNext').val ('Next Year');
		jQuery('#tdDatePicker').addClass ('hidden');
	}
	
	/* Unhide the overlay div */
	jQuery('#ourBigChart').removeClass ('hidden');
}


/**
 * Show the fullsize image of a thumbnail.
 * 
 * @param thumbID Thumbnail number to show full size image of
 */
function bigThumbnail (thumbID) {
	/* Some variables */
	var posTop = 0;
	var posLeft = 0;
	var width = 0;
	var height = 0;
	var source = '';
	
	if (thumbID == 1) {
		/* Resize image to be less than 845 px wide and 10 px smaller than viewport height */
		width = imageOne.width;
		height = imageOne.height;
		
		while (width > 845 || height > 600) {
			width *= .8;
			height *= .8;
		}
		
		/* Store source */
		source = imageOne.src;
	}
	else if (thumbID == 2) {
		/* Resize image to be less than 845 px wide and 10 px smaller than viewport height */
		width = imageOne.width;
		height = imageOne.height;
		
		while (width > 845 || height > 600) {
			width *= .8;
			height *= .8;
		}
		
		/* Store Source */
		source = imageTwo.src;
	}
	
	/* Calculate the div position */
	posTop = ((600 - height) / 2);
	posLeft = ((845 - (width + 24)) / 2);
	
	/* Set div position (JSON notation) */
	jQuery('#ourBigImage').css ('left', posLeft + 'px');
	jQuery('#ourBigImage').css ('top', posTop + 'px');
	
	/* Set image */
	jQuery('#imgBig').attr ('src', source);
	jQuery('#imgBig').attr ('height', height);
	jQuery('#imgBig').attr ('width', width);
	
	/* Unhide the overlay div */
	jQuery('#ourBigImage').removeClass ('hidden');
}


/**
 * Go to previous day or chart index in the big chart view.
 */
function prevButton () {
	/* Increment chart index or day */
	if (currBigChart == 'DAILY') {
		currChartDay.setDate (currChartDay.getDate () - 1);
	}
	else {
		currChartIndex += 1;
	}
	
	/* Decide the chart type */
	var swf = 'MSLine';
	
	if (currBigChart == 'GHG') {
		swf = 'Bar2D';
	}
	
	/* Load the big chart */
	loadChart ('../..', 
			   'dvBigChart', 
			   'bigChart',
			   swf,
			   840, 
			   440, 
			   currChartSiteId, 
			   currBigChart, 
			   currChartUnits, 
			   formatDateForServer (currChartDay), 
			   currChartIndex,
			   true);
			   
	/* Decide if we should disable the button */
	jQuery('#btnNext').attr ('disabled', false);
	if (currBigChart == 'DAILY') {
		if (doDatesMatch (currChartSiteStartDate, currChartDay)) {
			jQuery('#btnPrevious').attr ('disabled', true);
		}
		
		dayPicker.TC0L = currChartDay;
	}
	else {
		if (currChartIndex == 5) {
			jQuery('#btnPrevious').attr ('disabled', true);
		}
	}
	
	/* Update the selector box */
	jQuery('#inDate').val (formatDateForTigra (currChartDay));
}


/**
 * Go to next day or chart index in the big chart view.
 */
function nextButton () {
	/* Decrement chart index or day */
	if (currBigChart == 'DAILY') {
		currChartDay.setDate (currChartDay.getDate () + 1);
	}
	else {
		currChartIndex -= 1;
	}
	
	/* Decide the chart type */
	var swf = 'MSLine';
	
	if (currBigChart == 'GHG') {
		swf = 'Bar2D';
	}
	
	/* Load the big chart */
	loadChart ('../..', 
			   'dvBigChart', 
			   'bigChart', 
			   swf,
			   840, 
			   440, 
			   currChartSiteId, 
			   currBigChart, 
			   currChartUnits, 
			   formatDateForServer (currChartDay), 
			   currChartIndex,
			   true);
	
	/* Decide if we should disable the button */
	jQuery('#btnPrevious').attr ('disabled', false);
	if (currBigChart == 'DAILY') {
		if (doDatesMatch (new Date (), currChartDay)) {
			jQuery('#btnNext').attr ('disabled', true);
		}
		
		dayPicker.TC0L = currChartDay;
	}
	else {
		if (currChartIndex == 0) {
			jQuery('#btnNext').attr ('disabled', true);
		}
	}
	
	/* Update the selector box */
	jQuery('#inDate').val (formatDateForTigra (currChartDay));
}


/**
 * This method gets called when a date is selected in the date picker in the
 * big chart view.
 */
function dayPickerSelection () {
	/* Store the selected day */
	currChartDay = dayPicker.TC0L;
	
	/* Load the big chart */
	loadChart ('../..', 
			   'dvBigChart', 
			   'bigChart', 
			   'MSLine',
			   840, 
			   440, 
			   currChartSiteId, 
			   currBigChart, 
			   currChartUnits, 
			   formatDateForServer (currChartDay), 
			   currChartIndex,
			   true);
	
	/* Decide which buttons should be enabled */
	if (doDatesMatch (new Date (), currChartDay)) {
		jQuery('#btnNext').attr ('disabled', true);
	}
	else {
		jQuery('#btnNext').attr ('disabled', false);
	}
	
	if (doDatesMatch (currChartSiteStartDate, currChartDay)) {
		jQuery('#btnPrevious').attr ('disabled', true);
	}
	else {
		jQuery('#btnPrevious').attr ('disabled', false);
	}
}


/**
 * Format a date object into the string format the the server is expecting.
 * 
 * @param date {Date}	Date object to format
 * @return {string}		String of formatted date 
 */
function formatDateForServer (date) {
	return date.getFullYear () +
		   "-" +
		   (date.getMonth () + 1) +
		   "-" +
		   date.getDate ();
}