jQuery(document).ready( function() {
	var now = new Date();
    document.cumulativeBaseDate = new Date(2000, 0, 1);
	document.annualBaseDate = new Date(now.getFullYear(), 0, 1);
	document.dailyBaseDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
	
	document.breaksPerDay = 850;
	document.costPerBreak = 10000; // USD
	// document.costPerBreak = document.costPerBreak * document.cadToUsd;
	document.corrosionCostPerSec = 1279.16313088273; // very old average
	// document.corrosionCostPerSec = 1607.68645357686; // curr average
	// document.corrosionCostPerSec = document.corrosionCostPerSec * document.cadToUsd;
	document.secsPerDay = 60 * 60 * 24;
	document.breaksPerSec = document.breaksPerDay / document.secsPerDay;
    
	// makeScrollable('#rotator_list', '#rotator_list_interior');
	jQuery('#rotator_holder').cycle({ 
		fx: 'scrollLeft',
		pause: true,
		speed: 1000,
		timeout: 9000,
		cleartypeNoBg: true
	 });
	
	document.email_field_reset = true;
	jQuery('#email_field').bind('focus',function() {
		if(document.email_field_reset) {
			jQuery('#email_field').val('');
		}
		document.email_field_reset = false;
	});
	jQuery('#email_button').click(function() {
		jQuery('#10653705190').submit();
	});
});

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function getSeconds(type) {
	
	var now = new Date();
	if (type=='daily') {
		var numSecs = (now.getTime() - document.dailyBaseDate.getTime()) / 1000;
	} else if(type=='annual') {
		var numSecs = (now.getTime() - document.annualBaseDate.getTime()) / 1000;
	} else { // cumulative
		var numSecs = (now.getTime() - document.cumulativeBaseDate.getTime()) / 1000;
		var numSecsDay = (now.getTime() - document.dailyBaseDate.getTime()) / 1000;
	}
	
	var currBreaks = document.breaksPerSec * numSecs;
	var currBreaksDay = document.breaksPerSec * numSecsDay;
	var currCost = currBreaks * document.costPerBreak;
	var currCorrosionCost = document.corrosionCostPerSec * numSecs;
	
	jQuery('#costHolder').html('$' + addCommas(Math.round(currCost)));
	jQuery('#corrosionCostHolder').html('$' + addCommas(Math.round(currCorrosionCost)));
	jQuery('#breakHolder').html(addCommas(Math.round(currBreaks)));
	jQuery('#breakDayHolder').html(addCommas(Math.round(currBreaksDay)));
	
	setTimeout("getSeconds('"+type+"')",100);

}


// This code generates a "Raw Searcher" to handle search queries. The Raw
// Searcher requires you to handle and draw the search results manually.
google.load('search', '1');

var newsSearch;

function searchComplete() {

	// Check that we got results
	document.getElementById('news_holder').innerHTML = '';
	
	if (newsSearch.results && newsSearch.results.length > 0) {
		for (var i = 0; i < newsSearch.results.length; i++) {
		
			// Create HTML elements for search results
			var text = document.createElement('p');
			var title = document.createElement('a');
			var publisher = document.createElement('p');
			var thumb = document.createElement('img');
			
			title.href = newsSearch.results[i].url;
			title.innerHTML = newsSearch.results[i].titleNoFormatting;
			title.setAttribute('class', 'news_title');
			text.innerHTML = newsSearch.results[i].content;
			text.setAttribute('class', 'news_text');
			publisher.innerHTML = newsSearch.results[i].publisher;
			publisher.setAttribute('class', 'news_publisher');
			
			/*
			console.log(newsSearch.results[i].titleNoFormatting);
			console.log(newsSearch.results[i].image);
			*/
			/*
			if( typeof(newsSearch.results[i].image) != undefined) {
				thumb.src = newsSearch.results[i].image.tbUrl;
				thumb.width = newsSearch.results[i].image.tbWidth;
				thumb.height = newsSearch.results[i].image.tbHeight;
				thumb.setAttribute('class', 'news_thumb');
			}
			*/
			// Append search results to the HTML nodes
			/*
			jQuery("#news_holder").append(title);
			jQuery("#news_holder").append(publisher);
			jQuery("#news_holder").append(thumb);
			jQuery("#news_holder").append(text);
			*/
			jQuery("#news_holder").append(newsSearch.results[i].html);
		}
	}
}

function onGoogleLoad() {

  
  // Create a News Search instance.
  newsSearch = new google.search.NewsSearch();
  
  // Set searchComplete as the callback function when a search is
  // complete.  The newsSearch object will have results in it.
  newsSearch.setSearchCompleteCallback(this, searchComplete, null);
  newsSearch.setResultSetSize(5);
  // Specify search quer(ies)
  newsSearch.execute('water main break');
	
  // Include the required Google branding
  google.search.Search.getBranding('branding');
}

// Set a callback to call your code when the page loads
google.setOnLoadCallback(onGoogleLoad);



/// FRONT PAGE SCROLL
function makeScrollable(wrapper, scrollable){
	// Get jQuery elements
	var wrapper = jQuery(wrapper), scrollable = jQuery(scrollable);
	
	// Hide images until they are not loaded
	scrollable.hide();
	var loading = jQuery('<div class="loading">Loading...</div>').appendTo(wrapper);
	
	// Set function that will check if all images are loaded
	var interval = setInterval(function(){
		var images = scrollable.find('img');
		var completed = 0;
		
		// Counts number of images that are succesfully loaded
		images.each(function(){
			if (this.complete) completed++;	
		});
		
		if (completed == images.length){
			clearInterval(interval);
			// Timeout added to fix problem with Chrome
			setTimeout(function(){
				
				loading.hide();
				// Remove scrollbars	
				wrapper.css({overflow: 'hidden'});						
				
				scrollable.slideDown('slow', function(){
					enable();	
				});					
			}, 1000);	
		}
	}, 100);
	
	function enable(){
		// height of area at the top at bottom, that don't respond to mousemove
		var inactiveMargin = 99;					
		// Cache for performance
		var wrapperWidth = wrapper.width();
		var wrapperHeight = wrapper.height();
		// Using outer height to include padding too
		var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
		// Do not cache wrapperOffset, because it can change when user resizes window
		// We could use onresize event, but it's just not worth doing that 
		// var wrapperOffset = wrapper.offset();
		
		// Create a invisible tooltip
		var tooltip = jQuery('<div class="sc_menu_tooltip"></div>')
			.css('opacity', 0)
			.appendTo(wrapper);
	
		// Save menu titles
		scrollable.find('a').each(function(){				
			jQuery(this).data('tooltipText', this.title);				
		});
		
		// Remove default tooltip
		scrollable.find('a').removeAttr('title');		
		// Remove default tooltip in IE
		scrollable.find('img').removeAttr('alt');	
		
		var lastTarget;
		//When user move mouse over menu			
		wrapper.mousemove(function(e){
			// Save target
			lastTarget = e.target;
 
			var wrapperOffset = wrapper.offset();
		
			var tooltipLeft = e.pageX - wrapperOffset.left;
			// Do not let tooltip to move out of menu.
			// Because overflow is set to hidden, we will not be able too see it 
			tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75); //tooltip.outerWidth());
			
			var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
			// Move tooltip under the mouse when we are in the higher part of the menu
			if (e.pageY - wrapperOffset.top < wrapperHeight/2){
				tooltipTop += 80;
			}				
			tooltip.css({top: tooltipTop, left: tooltipLeft});				
			
			// Scroll menu
			var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
			if (top < 0){
				top = 0;
			}			
			wrapper.scrollTop(top);
		});
		
		// Setting interval helps solving perfomance problems in IE
		var interval = setInterval(function(){
			if (!lastTarget) return;	
										
			var currentText = tooltip.text();
			
			if (lastTarget.nodeName == 'IMG'){					
				// We've attached data to a link, not image
				var newText = jQuery(lastTarget).parent().data('tooltipText');
 
				// Show tooltip with the new text
				if (currentText != newText) {
					tooltip
						.stop(true)
						.css('opacity', 0)	
						.text(newText)
						.animate({opacity: 1}, 1000);
				}					
			}
		}, 200);
		
		// Hide tooltip when leaving menu
		wrapper.mouseleave(function(){
			lastTarget = false;
			tooltip.stop(true).css('opacity', 0).text('');
		});			
				
	}
}
