/*
habanero.js

original style sheet switcher script by: Paul Sowden
http://www.alistapart.com/stories/alternate/

author: Sing Chan, Mark Bice
version: 2.0
last modified: March 14, 2007
*/

function SetActiveStyleSheet(title) {
  var i, a, main;
  for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")!="default" && a.getAttribute("title")) {
      a.disabled = true;
      if (a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (title != "print_preview") {
		CreateCookie("tg-style", title, 365);
		styleTitle = title;
	}
}

function CallParentResize(iframeName, modalResize)
{
	try {
		if (iframeName == null || iframeName == "")
			iframeName = "htmlIFrame";
	  
		if (document.getElementById) {
			var iFrame = window.parent.document.getElementById(iframeName);
	   
			// If the specified (iframe) object is found, call the ResizeIFrame method.
			if (iFrame)
				window.top.ResizeIFrame(iFrame.name, document.body.scrollHeight, modalResize);
		}
	}
	catch (e)
	{ }
}

ResizeIFrame = function(iframeName, height, modalResize) {
	try 
	{
		if (document.getElementById)
		{
			var iframe = document.getElementById(iframeName);
			iframe.height = height + 20;  // add 20px to adjust for Mozilla/Netscape.
			if (modalResize) {
				var x;
				for (x in TGModal) {
					var modal = TGModal[x];
					if (modal != null)
						modal.resetScreenHeight();
				}
			}
		}
	}
	catch (e) 
	{	}
}

function GetActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function GetPreferredStyleSheet() {
  var i, a;
  for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("rel").indexOf("alt") == -1 && a.getAttribute("title")) {
			return a.getAttribute("title");
		}
  }
  return null;
}

function CreateCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else {
		expires = "";
	}
  document.cookie = name + "=" + value + expires + "; path=/";
}

function ReadCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

if (document.getElementsByTagName) {
	var cookie = ReadCookie("tg-style");
	var styleTitle = cookie ? (cookie != "null" ? cookie : "default") : GetPreferredStyleSheet();
	SetActiveStyleSheet(styleTitle);
}


/* this gets rid of the flashing background on rollover in IE6 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}



/* Region Select Controller */
var RegionSelect = new Class({

    initialize: function() {
        this.Prompt = $('tg-RegionSelect-Prompt');
        this.Panel = $('tg-RegionSelect-Panel');
        this.PanelInner = $('tg-RegionSelectInner-Panel');
        this.ToggleLink = $$('.toggle')[0];
        this.ToggleLinkAction = this.ToggleLink.onclick;
        
        this.preload();
    },
    preload: function() {
		//strange IE6 issue with b/g images disappearing...  have to explicitly set "src" attributes.
		
		if ($('tg-Region-SetButton')) {
			$('tg-Region-SetButton').src = $('tg-Region-SetButton').src;
			$('tg-Region-CloseIcon').src = $('tg-Region-CloseIcon').src;
		}
    },
    
    toggle: function() {
        if (this.Panel.style.display != 'block') {
            this.closePrompt();
    	    this.Panel.style.display = 'block';
			
			this.toggleLink();
            var regionSelectResize = new Fx.Styles(this.Panel, {duration:300, onComplete:function() { TGRegion.PanelInner.style.display='block'; TGRegion.toggleLink(); } });
            regionSelectResize.start({
                'width':[0,450],
                'height':[0,405]
            });
        }
        else {
			
			document.forms["RegionSelector"].reset();
			
            this.PanelInner.style.display = 'none';
            
            this.toggleLink();
            var regionSelectResize = new Fx.Styles(this.Panel, {duration:300, onComplete:function() { TGRegion.Panel.style.display='none'; TGRegion.toggleLink(); } });
            regionSelectResize.start({
                'width':[450,0],
                'height':[405,0]
            });
        }
    },
    
    togglePrompt: function() {
        
        if (ReadCookie("tg-RegionSelect-Prompt") == null) {    
            this.Prompt.style.display = 'block';
            var regionPromptFade = new Fx.Styles(this.Prompt, {duration:1500, onComplete:function() { CreateCookie("tg-RegionSelect-Prompt", "1", 30); setTimeout("TGRegion.togglePrompt()", 8000);  /*hide after a few seconds*/ } });
            regionPromptFade.start({
                'opacity':[0,1]
            });
        }
        else {
            if (this.Prompt.style.display == 'block') {  //only apply fadeout if already showing
                var regionPromptFade = new Fx.Styles(this.Prompt, {duration:1500});
                regionPromptFade.start({
                    'opacity':[1,0]
                });
            }
        }
    },
    
    toggleLink: function() {
		if (this.ToggleLink.onclick == "" || this.ToggleLink.onclick == null) {
			this.ToggleLink.onclick = this.ToggleLinkAction;
		}
		else {
			this.ToggleLink.onclick = null;
		}
    },
    
    closePrompt: function() {
        this.Prompt.style.display = 'none';
    }
    
});



/* Nav Menu Class */
var NavMenu = new Class({

    initialize: function()
    {
        this.PrimaryNavItems = new Array();
        this.SecondaryNavItems = new Array();
        this.HideDelay, this.ShowDelay;
        this.LastSectionVisited;
        
        var navRoot = $('tg-NavPrimary');
        var navSecondary = $('tg-NavSecondaryContainer');
        var nodeCount = 0;
        
        if (navRoot && navSecondary) {
        
			this.SelectedID = 0;
			this.HighlightedID = 0;
			this.NextHighlightedID = 0;
        
			for (i=0;i<navRoot.childNodes.length;i++) {
			    node = navRoot.childNodes[i];
			    
			    if (node.nodeName == "LI") {
			        this.PrimaryNavItems[nodeCount] = node.childNodes[0];  //link contained within
			        node.ID = nodeCount;
			        node.onmouseover = function() { TGMenu.preshow(this.ID); };
			        node.onmouseout = function() { TGMenu.prehide(); };
			        			        
			        if (node.className.indexOf("selected") >= 0) {
			            this.SelectedID = nodeCount;
			        }
			        if (node.className.indexOf("tg-LastSectionVisited") >= 0) {
						this.LastSectionVisited = nodeCount;
			        }
			        
			        nodeCount++;
			    }
			}
        
			nodeCount = 0;
        
			for (i=0;i<navSecondary.childNodes.length;i++) {
			    node = navSecondary.childNodes[i];
			    
			    if (node.nodeName == "DIV") {
			        node.ID = nodeCount;
			        this.SecondaryNavItems[nodeCount] = node;
			        node.onmouseover = function() { TGMenu.preshow(this.ID); }
			        node.onmouseout = function() { TGMenu.prehide(); }
			        nodeCount++;
			    }
			}
		}
    },
    
    preshow: function(id)
    {
        clearTimeout(TGMenu.HideDelay);
        TGMenu.NextHighlightedID = id;
        TGMenu.ShowDelay = setTimeout("TGMenu.show()", 500);
    },
    
    show: function()
    {
        this.hide();
        this.HighlightedID = this.NextHighlightedID;
        
        this.PrimaryNavItems[this.SelectedID].style.backgroundPosition = "0px 0px";
        this.PrimaryNavItems[this.HighlightedID].style.backgroundPosition = "0px -25px";
        
        this.SecondaryNavItems[this.SelectedID].style.display = 'none';
        this.SecondaryNavItems[this.HighlightedID].style.display = 'block';
        
        this.SecondaryNavItems[this.HighlightedID].className = 'tg-NavSecondary';
    },
    
    prehide: function()
    {
        clearTimeout(TGMenu.ShowDelay);
        TGMenu.HideDelay = setTimeout("TGMenu.hide()", 1250);
    },
    
    hide: function()
    {
        this.PrimaryNavItems[this.HighlightedID].style.backgroundPosition = "0px 0px";
        this.SecondaryNavItems[this.HighlightedID].style.display = 'none';
        
        if (this.LastSectionVisited >= 0) {
			this.PrimaryNavItems[this.SelectedID].style.backgroundPosition = "0px -50px";
			this.SecondaryNavItems[this.SelectedID].className = 'tg-NavSecondary tg-LastSectionVisited';
		}
		else {
			this.PrimaryNavItems[this.SelectedID].style.backgroundPosition = "0px -25px";
		}
        
        this.SecondaryNavItems[this.SelectedID].style.display = 'block';
    }
    
});


RePositionSpanningImage = function() {
	//check for primary content and an <img> as first element... will then position absolute
    //and push next element in container down by the image's vertical dimension.  This is to fix a
    //quirk with IE 5/6 where an image too large for its container actually pushes the bounds of the container
    //interfering with they layout (in all other browsers the image just extends above the container).
    
    if (window.ie6) {
    
		var ContentPrimary = $$('.tg-ContentPrimary')[0];
        
		if (ContentPrimary) {
			var first = ContentPrimary.getFirst();
			var next = first.getNext();
			
			if (first.className == 'tg-SplashImage') {  //sometimes image wrapped in "splash image" div
			    first = first.getElements("img")[0];  //gets first image it finds
		    }
		    
		    if (first) {
			    if (first.tagName == 'IMG') {  //first element is an image
			        var increment = parseInt(first.getSize().size.y) + parseInt(next.getStyle('margin-top').replace('px', ''));
					
			        if (parseInt(next.getStyle('margin-top').replace('px', '')) < first.getSize().size.y) {
						first.setStyle('position', 'absolute');
						next.setStyle('margin-top', increment + 'px');
				    }
			    }
			}
		}
		
	}
}

TableStripe = function() {
    var tables = document.getElementsBySelector('table.tg-TableStriped');
    var rows, classNames;
    
    tables.each( function(tbl) {
    
        rows = tbl.getElements('tbody tr');
        rows.each( function(row) {
            
            classNames = (row.rowIndex == rows.length) ? 'tg-LastTableRow ' : '';  //last row
            classNames += (row.rowIndex % 2 == 0) ? 'tg-alt' : '';  //even row?
            
            if (classNames != '') {
                
                row.getElements('td').each( function(cell) {  //cycle through cells
                    cell.addClass(classNames);
                });
                
            }
                     
        });
        
    });
}

InitToolTips = function() {
	var as = [];
	var offsetX = 0;
	
	$$('.tg-Tooltip').each(function(a){
	    if (a.getAttribute('title')) as.push(a);
    });
    
    var Tips2 = new Tips(as, {
		initialize:function(){
			this.fx = new Fx.Style(this.toolTip, 'margin-top', {duration: 300, wait: false, transition: Fx.Transitions.Quad.easeOut }).set(0);
			offsetX = ((this.toolTip.getSize().size.x / 2).round()) * -1;
			//this.fx2 = new Fx.Style(this.toolTip, 'opacity', {duration: 400, wait: false}).set(0);
		},
		onShow: function(tip) {
			marginTop = tip.getSize().size.y + 15;
			tip.setStyle('top', tip.getTop() - marginTop);
			
			this.fx.start(-7);
			//this.fx2.start(1);
			
			tip.setStyle('visibility', 'visible');
			
			// Offset x based on width of tooltip
			tip.setStyle('margin-left', offsetX);
		},
		onHide: function(tip) {
			this.fx.start(0);
			//this.fx2.start(0);
			tip.setStyle('visibility', 'hidden');
		},
		
		maxOpacity: 1, fixed: true, showDelay: 10, hideDelay: 0
		//maxOpacity: 1, fixed: true, showDelay: 10, hideDelay: 0, offsets: {'x': 0}
	});

}


/* modal */var Modal = new Class({
    initialize: function(cssClass, obj){
		var type = typeof obj;
		var d = new Date();
		
		this.id = 'tg-Modal' + d.getTime();
		this.closeButton = "<a href=\"javascript: TGModal['" + cssClass + "'].toggle();\" class=\"tg-Modal-Close\">close</a>";
		
		if (obj == 'undefined')
			this.html = '';
		else if (type == 'object')
			this.html = 'content!';
		else if (type == 'string')
			if (obj.substr(obj.length-4) == 'html' || obj.substr(obj.length-3) == 'htm')
				this.html = "<iframe id='htmlIFrame' allowtransparency='true' name='htmlIFrame' src='" + obj + "' frameborder='0' scrolling='no' width='100%' height='99%' marginwidth='0' marginheight='0' />";
			else
				this.html = obj;
		else
			this.html = "<iframe id='htmlIFrame' allowtransparency='true' name='htmlIFrame' src='" + obj + "' frameborder='0' scrolling='no' width='100%' height='99%' marginwidth='0' marginheight='0' />";
			
		this.initModal(cssClass);
    },
    
    initModal: function(cssClass) {
		var d = new Date();
    		this.modal = new Element('div', {			'class': 'tg-Modal',			'id': this.id		});
		this.modalHeader = new Element('div', {			'class': 'tg-Modal-Header'		});		this.modalBody = new Element('div', {			'class': 'tg-Modal-Body'		});
		this.modalFooter = new Element('div', {			'class': 'tg-Modal-Footer'		});
		this.screen = new Element('div', {			'class': 'tg-ModalScreen',			'id': 'tg-ModalScreen' + d.getTime()
		});
				this.modal.addClass(cssClass);		this.modal.appendChild(this.modalHeader);		this.modal.appendChild(this.modalBody);
		this.modal.appendChild(this.modalFooter);
		
		this.modalHeader.innerHTML = this.closeButton;
				document.getElementsByTagName('body')[0].appendChild(this.modal);
		document.getElementsByTagName('body')[0].appendChild(this.screen);	},
	setHTML: function(html) {		if (html != null)			this.html = html;
		
		this.modalBody.innerHTML = this.html;	},
		toggle: function(show) {		var visible = (show) ? 'visible' : 'hidden';		
		this.toggleFlash(show);		
		if (show) {
			this.setHTML();		}
				this.modal.setStyles({top: document.documentElement.scrollTop + 350 + 'px', visibility: visible});
		this.screen.setStyles({height: window.getScrollHeight() + 'px', visibility: visible});
	},
	
	toggleFlash: function(show) {
		$$('embed, object').each(function(a){
			if (show)
				a.style.visibility = 'hidden';
			else
				a.style.visibility = 'visible';
				
		});
	},
	
	resetScreenHeight: function() {
		for (x in TGModal) {
			var modal = TGModal[x];
			if (modal != null && modal.screen.style.visibility == 'visible') {
				modal.screen.setStyles({height: window.getScrollHeight() + 'px', width: window.getScrollWidth() + 'px', visibility: 'visible'});
			}
		}
	}
});


InitAskExpertModal = function() {
	TGModal['tg-Modal-AskExpert'] = new Modal('tg-Modal-AskExpert', '/AskAnExpert.htm');
	
	$$('.tg-AskExpert-Link').each(function(a){
	    a.setAttribute('href', 'javascript: TGModal[\'tg-Modal-AskExpert\'].toggle(1);');
    });
}

InitRateModals = function() {
	if ($$('.tg-FixedRates td.tg-Value a').length > 0)
	{
		TGModal['tg-Modal-Rates'] = new Modal('tg-Modal-Rates');  //pass in

		$$('.tg-FixedRates td.tg-Value a').addEvent('click', function() {
			TGModal['tg-Modal-Rates'].setHTML($(this).getParent().getElement('.tg-ModalContent').innerHTML);
			TGModal['tg-Modal-Rates'].toggle(1);
		});
	}
}

InitCalcModal = function() {
	var content = '<img src="/Gas/assets/images/templates/energycostscalculator/wheredoIfind.jpg" alt="wheredoIfind" style="display:block;margin:0 auto" />';
	
	TGModal['tg-Modal-Rates tg-Modal-Calc'] = new Modal('tg-Modal-Rates tg-Modal-Calc', content);  //pass in
}


InitContentSwitcher = function() {
	var tabs = $$('.tg-ContentSwitcher li')
    tabs.each(function(a) {
        a.addEvent('click', ContentSwitcherClick);
        a.addEvent('mouseenter', ContentSwitcherHover);
    });

	if (tabs.length > 0) {
		ContentSwitcherClickInterval();
		contentSwitchInterval = setInterval(ContentSwitcherClickInterval, 8000);
	}
}
ContentSwitcherToggle = function() {
    this.toggleClass('hover');
}
ContentSwitcherHover = function() {
    clearInterval(contentSwitchInterval);
    IncrementContentSwitcher(this);
}
ContentSwitcherClick = function() {
	var el = $(this);
	var link = el.getElement('a');
	
	if (link)
		document.location.href = link.getProperty('href');
}
ContentSwitcherClickInterval = function() {
    var tabs = $$('.tg-ContentSwitcher li');
    contentSwitchCounter = (tabs.length == (contentSwitchCounter + 1)) ? 0 : contentSwitchCounter + 1;
    IncrementContentSwitcher(tabs[contentSwitchCounter]);
}
IncrementContentSwitcher = function(el) {
	var img = el.getElement('img');
	var href, src;
	
	if (img) {
		src = img.getProperty('src');
		$$('.tg-ContentSwitcher .tg-ImagePlaceholder').setHTML(img.getHTML());
	}
	else {
		$$('.tg-ContentSwitcher .tg-ImagePlaceholder').setHTML('');
	}
    
    $$('.tg-ContentSwitcher li.selected').removeClass('selected');
    el.addClass('selected');
}




Element.extend ({
	getHTML: function(){
		return new Element('div').adopt(this.cloneNode(true)).innerHTML.clean();
	}
});


var TGMenu, TGRegion;
var TGModal = new Object();
var contentSwitchInterval, contentSwitchCounter = -1;
var isEditMode = false;

window.onload = function() {
	isEditMode = $$('.tg-EditMode').length > 0;

    TGMenu = new NavMenu();
    InitAskExpertModal();
	InitRateModals();
	InitCalcModal();
	
    /*if ($('tg-RegionSelect-Panel')) {
        TGRegion = new RegionSelect();

        if (ReadCookie("tg-RegionSelect-Prompt") == null) {
            TGRegion.togglePrompt();
        }
    }*/
    if (!isEditMode)
		InitContentSwitcher();
		
	RePositionSpanningImage()  //IE 6 - make sure re-position worked
	TableStripe();  //scan and stripe marked tables
	InitToolTips();
}