
function validateEmail(source, args)
{
  args.IsValid = (args.Value.indexOf(".") > 0 && args.Value.indexOf("@") > 0);
}
/*
 * rDropDown
 * Adds class of 'hover' to LI onmouseover. Removes class onmouseout. Adds iFrame fix for IE
 */
function rDropDown() {
	this.initialize();
}
rDropDown.prototype = {
	open: false,
	timeout: false,
	openLi: null,
	initialize: function() {
	    var userAgent = navigator.userAgent.toLowerCase()
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1)
            $("#mainNav > ul").addClass('macFF');
            
		var lis = $("#mainNav > ul > li");
		for (var i=0; i<lis.length; i++) {
			$(lis[i]).bind('mouseover', {parentThis: this, li:lis[i]}, function(params) {
				params.data.parentThis.show(params.data.li);
			});
			$(lis[i]).bind('mouseout', {parentThis: this, li:lis[i]}, function(params) {
				params.data2 = params.data;
				params.data.parentThis.timeout = setTimeout(function() {
					params.data = params.data2;
					params.data.parentThis.hide(params.data.li);
				}, 1);
			});
		}
	},
	show: function(li) {
		if (this.openLi && this.openLi != li) {
			this.hide(this.openLi);
		}
		if(this.timeout){
			clearTimeout(this.timeout);
			this.timeout = false;
		}
		if(this.open){
			return;
		}
		if ($(li).hasClass('hasSub')) {
			$(li).addClass('hoverSub');
		}
		else {
			$(li).addClass('hover');
		}
		this.openLi = li;
		this.open = true;
		this.iframeFix(li);
	},
	hide: function(li) {
		if(!this.open){
			return;
		}
		$(li).removeClass('hover');
		$(li).removeClass('hoverSub');
		this.open = false;
		if (this.iframe) {
			this.iframe.style.display = "none";
		}
	},
	iframeFix: function(li) {
		if(!document.all) {
			//return;
		}
		
		var subnav = $('div.subnav', li)[0];
		if (subnav) {
			if (!this.iframe) {
				this.iframe = document.createElement('iframe');
				this.iframe.style.position = 'absolute';
				this.iframe.frameBorder = 0;
				this.iframe.style.filter = 'alpha(opacity=0)';
				this.iframe.style.zIndex = -1;
				document.body.appendChild(this.iframe);
			}
			this.iframe.style.display = "block";
			this.iframe.style.top = $(subnav).offset().top + 'px';
			this.iframe.style.left = $(subnav).offset().left + 'px';
			this.iframe.style.width = $(subnav).width() + 'px';
			this.iframe.style.height = $(subnav).height() + 'px';
		}
	}
}
/*
* onLoad functions
* Initializes our functions on page load
*/
$(document).ready(function(){
 new rDropDown();
 clickTrack();
});

//::: SECTION SWITCHING FOR THE ISSUES PAGES :::
//::::::::::::::::::::::::::::::::::::::::::::::
var oSlidePicker = {
    sCurrSection:null,
    sImgPathBase:"/assets/images/",
    sSWFPathBase:"/assets/flash/",

    init:function(oParentUL,oContEl,oLGImg,oTitleEl/*,oDescripEl*/,sSWFContId) {
        var o=this;
        oParentUL.find('a').each(function(i) { 
            //Opacity
            if(i==0) {
                $(this).find('img').addClass('active');
            }
            else {
                $(this).find('img').css({opacity:.75});
            }

            $(this).bind("click",function() {o.ShowSlide(this,i);return false;}); 
            $(this).children('img').bind("mouseover",function() {o.ToggleOpacity(this,1);return false;}); 
            $(this).children('img').bind("mouseout",function() {o.ToggleOpacity(this,0);return false;}); 
        });

        this.oContEl = oContEl;
        this.oLGImg = oLGImg;
        this.sSWFContId = sSWFContId;
        this.oTitleEl = oTitleEl;
        this.oParentUL = oParentUL;
    },

    ToggleOpacity:function(oEl,sWhich) {
        if($(oEl).hasClass('active')) return;
        (sWhich)?$(oEl).css({opacity:1}):$(oEl).css({opacity:.75});
    },

    ShowSlide:function(oEl,iCount) {
        this.SetVisual(oEl,iCount);
        this.SetCopy(oEl,iCount);
    },

    SetVisual:function(oEl,i) {
        this.iCount = i;

        if(!$(oEl).find('img').hasClass('active')) {
            $(this.oParentUL).find('img.active').removeClass('active').css({opacity:.75});
            $(oEl).find('img').css({opacity:1}).addClass('active');
        }

        this.oLGImg.attr({src:this.sImgPathBase+oMedia[i].fullSizeImg[0], alt:oMedia[i].description}).width(oMedia[i].fullSizeImg[1]).height(oMedia[i].fullSizeImg[2]);
     
        //Custom callbacks?
        if(this.CustomCallbacks) this.CustomCallbacks();

        if(oMedia[i].SWF && !oMedia[i].FLV) {
            var fo = new SWFObject(this.sSWFPathBase+oMedia[i].SWF[0], "movie", oMedia[i].SWF[1].toString(), oMedia[i].SWF[2].toString(), "6");
            fo.addParam("wmode", "transparent");
            fo.write(this.sSWFContId);
        }
        if(oMedia[i].FLV) {
            var fo = new SWFObject(this.sSWFPathBase+oMedia[i].SWF[0], "movie", oMedia[i].SWF[1].toString(), oMedia[i].SWF[2].toString(), "6");
            fo.addParam("wmode", "transparent");
            fo.addVariable("flvURL",this.sSWFPathBase+oMedia[i].FLV[0]);
            fo.addVariable("hasInitialFrame","true");
            fo.addVariable("initFrameURL",this.sSWFPathBase+oMedia[i].FLV[1]);
            fo.write(this.sSWFContId);
        }
    },

    SetCopy:function(oEl,i) {
        if(oMedia[i].title){ 
            this.oTitleEl.html(oMedia[i].title)
        } else {
            this.oTitleEl.html("")
        }
        if(oMedia[i].descriptionId){ 
            $("#"+oMedia[i].descriptionId).parent().children().hide();
            $("#"+oMedia[i].descriptionId).show();
        }else{
            $('.synop > div').hide();
        }
    },

    ResetInitState:function(sTarget) {
            var o=this;

            //Reset opacity
            $(this.oParentUL).find('img.active').removeClass('active').css({opacity:.75});

            //Match LI add class...
            var oLIMatch = null;
            $('li.'+sTarget).find('a').each(function(i){
                if(i==0) { 
                    $(this).find('img').addClass('active').css({opacity:1}); 
                    oLIMatch = $(this).parent();
                }
            });

            //Set Visual
            $(this.oParentUL).children().each(function(i) { if(this == oLIMatch[0]) o.SetVisual($(this).find('a'),i); });
    }
}


var oStates = {

    init:function(oRootUL) {
        var o=this;
        $(oRootUL).children().each(function(i) {
            $(this).bind("click",function() {o.StateChange(this,i);return false;});
        });
        this.oRootUL = oRootUL;
    },

    StateChange:function(oEl,iCount) {
        this.iCount = iCount;

        if($(oEl).hasClass('current')) return;
        else {
            //Go Reset opacity and Visuals
            oSlidePicker.ResetInitState(aStatesSupplemental[0].States[iCount]);

            $(aStatesSupplemental[0].States).each(function(i) { $('li.'+this).hide(); });
            $('li.'+aStatesSupplemental[0].States[iCount]).show();

            $(this.oRootUL).find('li.current').removeClass('current');
            $(oEl).addClass('current');

            if(this.CustomCallbacks) this.CustomCallbacks();
        }
    }
}



// Call page functions

$(document).ready(function()
{
    //controls selected state for analysis sub nav
        navAnalysis();
    //accordion for contact page and similar
        headAccordion();
        listExpand();
        
    //replace input in actionlinks for styling
        inputToAnchor();

    //switches selected class on tabs.
        activateNav();
         
    //swaps out the over class for submit buttons for IE6 over states
         hoverSwap('.submitContact input');
         hoverSwap('.submitLogin input');
         hoverSwap('.submitReg input'); 
         hoverSwap('.submitLogin');
         hoverSwap('.submitForgot input');
         hoverSwap('ul.comments p.links'); 
         hoverSwap('.submitEdit input'); 
         hoverSwap('.submitPreview input'); 
         hoverSwap('.submitClose input');
         hoverSwap('.SendToFriendSuccess');
         hoverSwap('a.respondComment');
         hoverSwap('a.viewReplies');
         hoverSwap('a.recommendComment');         
         hoverSwap('ul.topicsPrevious div.textLeft a.actionLinkPng');                  
         hoverSwap('#SubmitPagination input');
         hoverSwap('.submitSearch input');
         hoverSwap('div.pagingWrapper input.go');
         hoverSwap('div.searchTips h4 a');
         hoverSwap('div.pagingWrapper ul li.NextPageLi a');
         hoverSwap('.mediaContain .leftArrow a');
         hoverSwap('.mediaContain .rightArrow a');
        
    //swaps out images for form inputs           
         imageSwap('#SendEcardSubmit', 'ecardFormSend.gif', 'ecardFormSendOver.gif');   
         imageSwap('#SubmitFriend', 'btn_submit.gif', 'btn_submitOver.gif');
         imageSwap('#SubmitEmailNotify', 'btn_submit.gif', 'btn_submitOver.gif');   
         imageSwap('#SendFriendSubmit', 'sendFriendSubmit.gif', 'SendFriendSubmitOver.gif');
         imageSwap('#SubmitEmailShare', 'btn_submit.gif', 'btn_submitOver.gif');
         imageSwap('#Previous', 'previous.gif', 'previousOn.gif');
         imageSwap('#Next', 'next.gif', 'nextOn.gif');

                      
    // 
         clearValue();
});

function imageSwap(formCSS, img1, img2)
{
    $(formCSS + ' input').hover(
        function(){
        $(this).attr('src','/assets/images/' + img2);
        },
        function(){
        $(this).attr('src','/assets/images/' + img1);
        }
    );
};

function hoverSwap(formCSS)
{
    $(formCSS).hover(
        function(){
        $(this).addClass('over');
        },
        function(){
        $(this).removeClass('over');
        }
    );
};

function sectionHrefCaller(section)
{
    $('ul.nav_tab li.nav' + section + ' a').addClass('selected');
    $('ul.nav_tab li.nav1 a').removeClass('selected');
    $('#section'+ section).removeClass('hide');
    $('#section1' ).addClass('hide');
    $('#section'+ section).addClass('show');
}

function activateNav()
{

$('ul.nav_tab a').click(function()
    {   
       $('ul.nav_tab a').removeClass('selected'); 
       $(this).addClass('selected');
       
       //Assign value of div to show from link's href
        var showThis = $(this).attr('href');
        
        //show showThis and hide other divs
        $("#issues div.issuesContent").removeClass('show').addClass('hide');
        $(showThis).removeClass('hide').addClass('show');
        this.blur();
        return false;
       
    });
    $('div#issues a.next, div#issues a.prev').click(function()
    {
        //Assign value of div to show from link's href
        var showThis = $(this).attr('href');
        if ($(this).hasClass('prev'))
        {  
            var x = showThis.replace('#section','') *1;
            var y = x + 1;   
        } 
        else
        {
            var x = showThis.replace('#section','') *1;
            var y = x-1;
        }

        //show showThis and hide other divs and nav      
        $('ul.nav_tab li.nav' + y + ' a').removeClass('selected'); 
        $('ul.nav_tab li.nav' + x + ' a').addClass('selected');        
        $("#issues div.issuesContent").removeClass('show').addClass('hide');
        $(showThis).removeClass('hide').addClass('show');
        this.blur();
        return false;        
    });
}
 
 
/**
 * JS for flash Game
 */
function openFullScreenWindow(url) {
    var URL = url;
    var windowName = "Energyville";
    var browserName = navigator.appName;
    var operatingSystem = navigator.platform;
    var version = parseFloat(navigator.appVersion);
      
    if (browserName.indexOf("Netscape")!=-1 && version>=4.0 && operatingSystem.indexOf("Mac")!=-1) { // Netscape check version 4.0+ on Mac
        window.open(URL,windowName,'titlebar=no,top=0,left=0,width=' + window.screen.availWidth+',height='+window.screen.availWidth+',screenX=0,screenY=0,top=0,left=0');
    }
    else if (browserName.indexOf("Microsoft Internet Explorer")!=-1 && operatingSystem.indexOf("Mac")!=-1) { // MSIE Mac check
        window.open(URL,windowName,'titlebar=no,top=0,left=0,width=' + window.screen.availWidth+',height='+window.screen.availWidth+',screenX=0,screenY=0,top=0,left=0');
    }
    else if (browserName.indexOf("Netscape")!=-1 && operatingSystem.indexOf("Mac")!=-1) { // Netscape Mac check
        window.open(URL,windowName,'width='+screen.width+',height='+screen.height+',top=0,left=0');
    }
    else if (browserName.indexOf("Microsoft Internet Explorer")!=-1 && operatingSystem.indexOf("Win")!=-1) { // MSIE Windows
        window.open(URL,windowName,'titlebar=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,top=0,left=0,width=' + window.screen.availWidth+',height='+window.screen.availHeight+',screenX=0,screenY=0,top=0,left=0');
    }
    else if (browserName.indexOf("Netscape")!=-1 && operatingSystem.indexOf("Win")!=-1) { // Netscape Windows
        window.open(URL,windowName,'width='+screen.width+',height='+screen.height+',top=0,left=0');
    }
    else { window.open(URL,windowName); }

    return false;
}

/*
 * Sets barrel logic cookie
 */
var oBarrelsLogic = {
    iDiff:0,
    doit:function() {
        if(this.checkit()) {
            var sTimestamp = Date.parse(new Date());
            this.iDiff = sTimestamp - $.cookie('timestamp');
        }
        return this.iDiff;
    },

    checkit:function() {
        if(!$.cookie('timestamp')) {
            $.cookie('timestamp',Date.parse(new Date()),{path:'/'});
            return false;
        } else
            return true;
    }
}

/**
 * clearText MODULE
 */
function clearValue() 
{
    //this is to clear/restore the search input.
    $('input:text').focus(function(){
       // check to see if value is defined      

       //test for default value being set and if not, set class of noVal on input
       if($(this).attr('value') == undefined)
       {
       $(this).addClass('noVal');
       };
       
       // note added condition to not allow if a parent div has class formManage
       if(!$(this).hasClass('noVal') && !$(this).parents('div').hasClass('formManage') && !$(this).parents('div').hasClass('noClear') && !$(this).parents('fieldset').hasClass('loginPanel'))
       { 
        if ($(this).attr('title') == undefined){          
            //create var called value, and give it the value of the field
            var value = $(this).attr('value');            
            //create attribute title, and title = value
            $(this).attr('title', value);              
            var title = $(this).attr('title');
                        
            if ($(this).val() == title )
            {                                               
                $(this).val('');                                 
            };             
        };    
        if($(this).attr('value') == $(this).attr('title'))
        {
            $(this).val('');
        }
       }
     });// end focus 
     $('input:text').blur(function()       
     {
        if ($(this).attr('title') != undefined){ 
            var title = $(this).attr('title');                               
            if ($(this).val()=='' || $(this).val()==title){           
            $(this).val(title); 
            }; 
        }             
    }); //end blur   
}; //end function
 
function clickTrack(){
$('.ATPreview').click(function(){
$('#ATPreviewSub').attr('src', 'http://switch.atdmt.com/iaction/deichv_JoinDiscussionSubmitButton_1');
});
$('.ATSubmitPreview').click(function(){
$('#ATSubPre').attr('src', 'http://switch.atdmt.com/iaction/deichv_postoverviewpage_1');

});
}

// Function to select query variable

function getQueryVariable(variable) 
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) 
  {
      var pair = vars[i].split("=");
      if (pair[0] == variable) 
      {
        return pair[1];
      }
  }
}

//Function to select active analysis page nav based on url
function navAnalysis(){
    if($('ul.navAnalysis li a').length != 0){
    
        if(getQueryVariable('s') != undefined){
        $('ul.navAnalysis li a.analysisNav' + getQueryVariable('s')).addClass('selected'); 
        $('div.analysisNext a.analysisNav' + getQueryVariable('s')).addClass('selected');   
        }
        else
        {           
            $('ul.navAnalysis li a.analysisNav1').addClass('selected');
            $('div.analysisNext a.analysisNav1').addClass('selected');
        };
    };
};

/**
 * ACCORDION MODULE
 */
//slides the element with class "p.accordionText" when h4 with class "head" is clicked 
function headAccordion(){
    $(".accordion .head a").click(function()
    {
        if($(this).parent().hasClass('open'))
        {
            $(this).parent().next(".accordionText").slideUp("slow", function(){		        	    
	            $(this).prev().removeClass('open'); 
	        });           
        }
        else
        {
            $(this).parent().addClass('open').next(".accordionText").slideDown(300).siblings(".accordionText").slideUp("slow", function(){
		      		    
	            $(this).prev().removeClass('open');
	            });
        }
   	    this.blur();
        return false;
    });	

    if(document.location.href.indexOf('#section') != -1)
	    sectionHrefCaller(document.location.href.substring(document.location.href.length - 1));
};

function listExpand(){  
    //slides the element with class assigned from href when .list_expand a is clicked 
    $(".list_expand a").click(function()
    {
        //Initialize: close all open accordion forms on page and removes open class
	    $('.formReply').slideUp("slow");
	    $('.respondComment').removeClass('open');

        //test if comments is open or closed
	    if(!$('ul.dashboardComments').hasClass('open'))
	    {
	        $('ul.dashboardComments').addClass('arb');
	        $('ul.dashboardComments').addClass('open');
	    }
	    else    
	        $('ul.dashboardComments').removeClass('arb');
	    //toggle the div containing the form
	    if($('ul.dashboardComments').hasClass('arb'))
	    {
	        $('div.formComments').slideDown(300);
	    }	
        else
	    {		
	        $('div.formComments').slideUp(300, function()
	        {
	            $('ul.dashboardComments').removeClass('open');
	        })
    	   
	    };
   	    this.blur();
        return false;
    });
    
    
    //opens closes respond to comment	
    $("p.links a.respondComment").click(function()
    {   
        if($(this).siblings().hasClass('open')){
            $(this).parent().nextAll('ul.reply').slideUp("slow");
            $(this).siblings().removeClass('open');	            
        };
	 
        if($(this).hasClass('open'))
        {	        
            $('.formReply').slideUp("slow", function(){	             
                $(this).prevAll('p.links').children('a.respondComment').removeClass('open');
            });	        
        }
        else 
        {
            $('.formComments').slideUp("slow");
            if($('ul.dashboardComments').hasClass('arb'))
	        {
	            $('div.formComments').slideUp(300, function()
	            {
	                $('ul.dashboardComments').removeClass('open');
	            })
	        };	        
            $('.formReply').slideUp("slow");
            $('.respondComment').removeClass('open')
            $(this).addClass('open').parent().next('.formReply').slideDown(300);  
        };	   
        this.blur();
        return false;       
    });
    
    //opens closes view replies
    $("p.links a.viewReplies").click(function()
	    {   
    	
	        // check if a sibling is open, and if so, close it, but only the sibling. 
	        if($(this).siblings().hasClass('open')){
	            $(this).parent().nextAll('div.formReply').slideUp("slow");
	            $(this).siblings().removeClass('open');	            
	        };    	    
	        if($(this).hasClass('open'))
	        {
	            /*$('ul.reply').slideUp("slow", function(){
	                $(this).prevAll('p.links').children('a.viewReplies').removeClass('open');
	            });*/
    	        
	            $(this).parent().nextAll('ul.reply').slideUp("slow", function(){
	                $(this).prevAll('p.links').children('a.viewReplies').removeClass('open');
	            });	        
	        }
	        else 
	        {
	            // uncomment this to allow only one reply section to be viewed
	            /*$('ul.reply').slideUp("slow", function(){
	                $(this).prevAll('p.links').children('a.viewReplies').removeClass('open');
	            });*/    	       
                $(this).addClass('open').parent().nextAll('ul.reply').slideDown(300);  
	        };
            this.blur();
            return false;           
	    });
};

// Replace the input type=image with a link 	
function inputToAnchor(){
    $('ul.comments p.links input').each(function(i){

        $(this).css('display','none');
        $(this).after('<a class="recommendComment" href="#" onclick="javascript:$(\'#'+$(this).attr('id')+'\').trigger(\'click\');return false;" ><span>Recommend This Comment</span></a>');	
    });
};

function hideViewReplies(){
// View Replies Section
	/*
	//This routine should be removed when addressed on the back end. this is to remove the link if there are no replies to view.
	var x = $("p.links a.viewReplies");
	for (i=0; i < x.length; i ++){
	   
	    jObj = $(x[i]);
  
	    if(!(jObj.parent().nextAll('ul.reply').attr('id')))
	    {	       
	        jObj.css({display:"none"});    
	    }	    
	}
	//end routine to hide unused view replies links
	*/
};

/*
function GetAnchors() {

$('a').each(function(i){
    if($(this).attr('href') != undefined)
    {
        if($(this).attr('href').indexOf('.pdf') != -1)
        {
            $(this).addClass('pdf');
            $(this).attr('title','PDF file');
        }
    }
});
}
*/
//addLoadEvent(GetAnchors);

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}



function emailSubjectNameApplier(){

    if ($('.sendFtr').hasClass('subjectUpdateEnabler')) {
        if ($('div.shareFriendForm input:first').attr('value') != undefined) {
            $($('div.shareFriendForm input')[2]).attr('value', $('div.shareFriendForm input:first').attr('value') + ' ' + $('input#subjectText').attr('value'));
        }
        $('div.shareFriendForm input:first').blur(function() {

            if ($('div.shareFriendForm input:first').attr('value') != undefined)
                $($('div.shareFriendForm input')[2]).attr('value', $('div.shareFriendForm input:first').attr('value') + ' ' + $('input#subjectText').attr('value'));
        });
        $($('div.shareFriendForm input')[2]).keyup(function(event) {
            if (event.keyCode != 9) {
                $('div.shareFriendForm input:first').unbind();
            }
        });
    }
}
$(document).ready(function(){

jGetAnchors();
emailSubjectNameApplier();
});

$(document).ready(function(){
  $('ul li.pagination ul li input').each(function(){
     if($(this).attr('name') == 'page_no') {
       $(this).keypress(function(e) {
          if(e.which || e.keyCode) {
            if ((e.which == 13) || (e.keyCode == 13)) { 
              $('ul li.go input').click();
              return false;
            }
          }  
          else {
            return true
          }; 
       });
     }
  });
});

function validateCharacters(source, args) {
  args.IsValid = false;
  if(args.Value.indexOf('<') + args.Value.indexOf('>') < 0)
  {
    args.IsValid = true;
  }
}

function validateMaxLength(source, args) {
   args.IsValid = args.Value.length <= 2500;
}

function openPopupWin(url) {
    var URL = url;
    var windowName = "GlobalFood";
	
	window.open(URL,windowName,'titlebar=no,scrollbars=0,resizable=0,status=0,toolbar=0,top=0,left=0,width=395,height=290,screenX=0,screenY=0');
	
	return false;
}

function openBookmarkWin(url) {
    var URL = url;
    var windowName = "StumbleUpon";
	
	window.open(URL,windowName,'titlebar=no,scrollbars=1,resizable=0,status=0,toolbar=0,top=0,left=0,width=1050,height=750,screenX=0,screenY=0');
	
	return false;
}

//Extension detection, icon placement, and new window control 
function jGetAnchors() {
    jQuery('a,area').each(function(){
        jQuery(this).filter('.newWindow').bind("keypress, click", function(e){
            window.open(this.href)
            jQuery(this).attr('title', "New Window");
            return false;
        });
        jQuery(this).filter('.external').bind("keypress, click", function(e){
            window.open(this.href)
            jQuery(this).attr('title', "Link to External Site");
            return false;
        });
        jQuery(this).filter('.rss').bind("keypress, click", function(e){
            window.open(this.href)
            jQuery(this).attr('title', "RSS Feed");
            return false;
        });
        jQuery(this).filter('.catchCode').bind("keypress, click", function(e){
            gaCatchCode(this);
            jQuery(this).attr('title', "RSS Feed");
            return false;
        });

        if (this.href != null && this.href  != '') {
            var types = new Array("pdf", "doc", "xls", "ppt");
            fileExt = this.href.substr(this.href.lastIndexOf(".")+1).toLowerCase();
            if(jQuery.inArray(fileExt, types) != -1){
                jQuery(this).addClass(fileExt);
                jQuery(this).click(function(){
                    window.open(this.href);
                    return false;
                });
                switch(fileExt) {
                    case "doc":
                        jQuery(this).attr("title", "Word document");
                        break 
                    case "ppt":
                        jQuery(this).attr("title", "PowerPoint File");
                        break            
                    case "xls":
                        jQuery(this).attr("title", "Excel File");
                        break 
                    default:
                        jQuery(this).attr("title", fileExt.toUpperCase()+" file");
                }
            }
        }
    });
}

function getFeatures(obj) {
  var features = "";
  if (obj.className.indexOf(" scroll") != -1) {
    features += "scrollbars=yes,";
  }
  return features;
}

function gaCatchCode()
{
  var fileTypes = ['doc','xls','xml','pdf','mp3'];
  if(typeof(pageTracker) != 'undefined') 
  {
      if ($('.secondaryNav li a.selected').attr('href') == '/usingEnergyWisely/energyGenerator/') {
          pageTracker._trackPageview('/catchcode/energyGenerator/sendtoafriend');
      }
      else if ($('.secondaryNav li a.selected').attr('href') == '/usingEnergyWisely/mpgOptimizer/') {
          pageTracker._trackPageview('/catchcode/mpgOptimizer/sendtoafriend');
      }
  }
}


function trackSocialNetworkLinkEvent(source, networkName) {
  trackGoogleAnalyticsEvent('socialNetworking', source, networkName, null);
}

function trackEmailEvent(source) {
  trackGoogleAnalyticsEvent('sendToAFriend', source, 'sendEmail', null);
}

function trackGoogleAnalyticsEvent(category, action, label, value) {
  if(typeof(pageTracker) != 'undefined') {
    pageTracker._trackEvent(category, action, label, value);
  }
}

function GnewsPager ($divs, $prevButton, $nextButton) {
    this.$divs = $divs;
    this.$prevButton = $prevButton;
    this.$nextButton = $nextButton;
    this.showIndex(0);
    var engine = this;
    $prevButton.click(function(e) {
        engine.offsetIndexBy(-1);
        e.stopPropagation();
        e.preventDefault();
    });
    $nextButton.click(function(e) {
        engine.offsetIndexBy(1);
        e.stopPropagation();
        e.preventDefault();
    });
}

GnewsPager.prototype = {
    currentIndex: -1,
    offsetIndexBy: function (offset) {
        var newIndex = this.currentIndex + offset;
        while (newIndex < 0) {
           newIndex += this.$divs.length;
        }
        newIndex %= this.$divs.length;
        this.showIndex(newIndex);
    },
    showIndex: function (newIndex) {
        for (var i=0; i<this.$divs.length; i++) {
            if (i == newIndex) {
                this.$divs.eq(i).addClass("gnewsHeadlineSelected");
            } else {
                this.$divs.eq(i).removeClass("gnewsHeadlineSelected");
            }
        }
        this.currentIndex = newIndex;
        if (newIndex > 0) {
            this.$prevButton.removeClass("disabled");
        } else {
            this.$prevButton.addClass("disabled");
        }
        
        if (newIndex < this.$divs.length-1) {
            this.$nextButton.removeClass("disabled");
        } else {
            this.$nextButton.addClass("disabled");
        }
    }
}

$(document).ready(function($) {
    var $gnewsDivs = $(".toolsResourcesModuleLeft .gnewsHeadline");
    if ($gnewsDivs.length > 0) {
        window.gnews = new GnewsPager($gnewsDivs, $(".toolsResourcesModuleLeft a.prev"), $(".toolsResourcesModuleLeft a.next"));
    }
    
});