/* RDM site jquery features 2011 */

/* Custom form elements plugin ***************************************************************************************************************/
//jQuery.fn.customInput = function(){
//	$(this).each(function(i){
//		
//		// 29/10/10 need to add Check for dropdown list (And event handlers)
//		//if($(this).is('[type=dropdownlist]')){
//		//    var dropDownList = $(this);		    		
//		
//		//}
//		
//		if($(this).is('[type=checkbox],[type=radio]')){
//			var input = $(this);
//			
//			// get the associated label using the input's id
//			var label = $('label[for='+input.attr('ID')+']');  
//			
//			//get type, for classname suffix 
//			var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';						
//			
//            // wrap the input + label in a div			 
//            $('<div class="custom-checkbox"></div>').insertBefore(input).append(input, label);			
//        
//			// find all inputs in this set using the shared name attribute  /* myNote: this is for the radiobutton grouping */
//			var allInputs = $('input[name='+input.attr('name')+']');
//			
//			// necessary for browsers that don't support the :hover pseudo class on labels
//			label.hover(
//				function(){
//                    $(this).addClass('hover');                    
//                    if(inputType == 'checkbox' && input.is(':checked')){ 
//					    $(this).addClass('checkedHover');
//                    } 
//				},
//				function(){ $(this).removeClass('hover checkedHover'); }
//			);

//			
//			
//			//bind custom event, trigger it, bind click,focus,blur events
//			input.bind('updateState', function(){ 	
//				if (input.is(':checked')) {
//					if (input.is(':radio')) {				
//						allInputs.each(function(){
//							$('label[for='+$(this).attr('id')+']').removeClass('checked');
//						});		
//					};
//					label.addClass('checked');
//				}
//				else { label.removeClass('checked checkedHover checkedFocus'); }
//										
//			})
//			
//			.trigger('updateState')
//			
//			.click(function(){ 
//				$(this).trigger('updateState'); 
//			})
//			
//			.focus(function(){ 
//				label.addClass('focus'); 
//				if(inputType == 'checkbox' && input.is(':checked')){ 
//					$(this).addClass('checkedFocus'); 
//				} 
//			})
//			
//			.blur(function(){ label.removeClass('focus checkedFocus'); });
//		}
//	});
//};

/* End Custom form elements plugin ***********************************************************************************************************/



// Image cycling ****************************************************************************************************************************/
var imgCounter = 0;

function fadeHandler(link) {        
    // Grab imageGallery element
    var hrefArray = $("#imgGallery ul li a");   
        
    $("#imgGallery ul li a").each(function(i) { 
        // setInterval event (no parameter passed)
        if(link == null) {
            // Check for loop end
            if (imgCounter >= hrefArray.length){
                imgCounter = 0;
            }
            // assign image href and move to next element
            link = hrefArray[imgCounter];
            imgCounter++;     
        }                      
        
        // Click event 
        if(link == $(this).attr("href")){
            
            // cycle navigation button rollovers ( Note: "Contextualized selector" format is: $(expression, context)  )           
            $("#imgGalleryNavigation a", "#imgGallery").each(function(i) {              
                if(link == $(this).attr('href')){
                    // Button "selected" css
                    $(this).addClass('selected');                                                   
                }
                else {
                    $(this).removeClass('selected');
                }	        		                           
            });
   
            // Animate fade in
	        $(this).parent().stop().animate({opacity: 1.0}, 1000);
	        $(this).parent().css("z-index", 50);
        }
        else {
            // Animate fade out
            $(this).parent().stop().animate({opacity: 0.0}, 1000);
            $(this).parent().css("z-index", 1);                        
        }                
    });
};

// End Image cycling ********************************************************************************************************************/



// Element enclosing ********************************************************************************************************************/
function encloseElement(elementClass){
    var tabHeight;
    var panelHeight = 0;    
    
    // Loop through panels, identify current selection (using "attribute substring selector")
    $("div[class*='panel']").each(function(i) {
        if($(this).attr("class") == elementClass){
            // Set element height & display
            tabHeight = $("#panelTabs").height();
            panelHeight = $(this).height();
            $("#panels").height(panelHeight+tabHeight);
            $(this).show();
        }
        else {
            // Hide other panel(s)
            $(this).hide(); 
        }        
    });         
}
// End Element enclosing ********************************************************************************************************************/





// Font scaling *****************************************************************************************************************************/
var min=12;
var max=20;

function increaseFontSize() {  // need to add jquery "onclick" handler - refactor these into one method with parameter
    var box = $('.box');
    
    // Set font size on all elements with ".box" class
    for(i=0;i<box.length;i++) {
        if(box[i].style.fontSize) { // check the element has the "fontSize" property
            var s = parseInt(box[i].style.fontSize.replace("px","")); //grab it's fontSize value
        } 
        else {
            var s = 12;
        }
        if(s!=max) {  // check range
            s += 1;   // increment fontSize
        }
        box[i].style.fontSize = s+"px";           
    }
     
    //Check page for "panels"
    if($('#panelBody') != null){
        var visiblePanel
        
        // Determine visible panel
        $("div[class*='panel']").each(function(i) {
        if($(this).is(':visible')) {
            visiblePanel = $(this).attr("class"); 
            }
        });                         
        
        // Invoke panel resizing function
        encloseElement(visiblePanel);            
    }
}
function decreaseFontSize() {    
    var box = $('.box');    
        
    for(i=0;i<box.length;i++) { // loop through all p elements
        if(box[i].style.fontSize) { // check the element has the "fontSize" property
            var s = parseInt(box[i].style.fontSize.replace("px","")); //grab it's fontSize value
        } 
        else {
            var s = 12;
        }
        if(s!=min) {  // check range
            s -= 1;   // increment fontSize 
        }
        box[i].style.fontSize = s+"px";
    }
    
    //Check page for "panels"
    if($('#panelBody') != null){
        var visiblePanel;

        // Determine visible panel
        $("div[class*='panel']").each(function(i) {
        if($(this).is(':visible')) {
            visiblePanel = $(this).attr("class");
            }
        });                         
 
        // Invoke panel resizing function
        encloseElement(visiblePanel);
    }
}
// End Font scaling ************************************************************************************************************************/




/* Navigation area rollovers **************************************************************************************************************/
//function attachNavEvents(parent, navClass) {
//    $(parent).mouseover(function() {        
//        //console.info("Value of navClass is: " + navClass);
//        if(navClass.indexOf("-over") == -1){                
//            $(this).removeClass(navClass);
//            $(this).addClass(navClass + "-over");
//        }        
//    }).mouseout(function() {               
//        $(parent).removeClass(navClass + "-over");
//        $(parent).addClass(navClass);
//    });        
//}
/*****************************************************************************************************************************************************************/



/* jquery "page scroll" function   20/11/10 *********************************************************************************************************************/
$('.scrollPage').click(function() {
   var elementClicked = $(this).attr("href");
   var destination = $(elementClicked).offset().top;
   $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-20}, 500 );
   return false;
});


/* jquery "random string" generator method (implemented as workaround to browser "caching issues", to ensure re-request of resources) ***************************/
 $.extend({ 
  password: function (length, special) {
    var iteration = 0;
    var password = "";
    var randomNumber;
    if(special == undefined){
        var special = false;
    }
    while(iteration < length){
        randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
        if(!special){
            if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
            if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
            if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
            if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
        }
        iteration++;
        password += String.fromCharCode(randomNumber);
    }
    return password;
  }
});
/*****************************************************************************************************************************************************************/



/* Energy meter methods ******************************************************************************************************************************************/     
function energyMeter(){        
    // Generate random string to append to file, to force re-request (see "random string generator" above)
    $.password(8);

    var randomString = $.password(4);
    var fileWithRandom =  'wind.xml?' + randomString;
    
    $.get(fileWithRandom, function(d){
        $(d).find('item').each(function(){
            var $item = $(this);
            var itemName = $item.attr("name");
            var itemValue = $item.attr("value");                
            var itemUnits = $item.attr("units");
            var co2Units;                               
            
            if(itemName == "Energy")
            {
                //  Generate "energy" display (in kWhr)
                if($('#energyDisplay')) 
                {
                    // If updating, remove previous elements
                    $('#energyDisplay').remove();                                                
                }                  
                // Format value
                itemValue = Math.round($item.attr("value"));                                            
                var html = '<div ID="energyDisplay" class="lfloat" style="width: 160px;"" title="This value is a measure of the total electrical energy, in Kilowatts per hour, generated to date by the wind turbines installed at the RDM headquarters.">'+generateCounterCss(itemValue)+'</div>';
                $('#energyReadout').append($(html));  
                                  
                // Generate "carbon saved" display (in kgCO2e)                                        
                if($('#carbonDisplay')) 
                {
                    $('#carbonDisplay').remove();
                }                 
                // Calculate CO2 savings (kW·h x conversion factor) & format
                co2Units = Math.round(itemValue * 0.54522);                                       
                var html = '<div ID="carbonDisplay" class="lfloat" style="width: 167px;" title="This value is a measure of the total carbon emissions, in Kilogrammes of C02 equivalent, reduced through our adoption of wind turbine energy generation.">'+generateCounterCss(co2Units)+'</div>';
                $('#energyReadout').append($(html));                                                      
            }                
            if(itemName == "Power")
            {                     
                // Generate "power generating" display (in kW)
                if($('#powerDisplay')) 
                {
                    $('#powerDisplay').remove();                                                
                }                    
                var html = '<div ID="powerDisplay" class="lfloat" title="This value is a measure of the current energy, in Kilowatts, being generated by the wind turbines at the RDM headquarters.">'+generateCounterCss(itemValue)+'</div>';
                $('#energyReadout').append($(html));          
            }                                                                         
        });                                                                   
    });   
};
    
function generateCounterCss(itemValue)
{
    var html = "";
    itemValue = itemValue.toString()
    
    for (i = 0; i <= itemValue.length-1; i++)
    {
        // Parse string
        var itemValueChar = itemValue.charAt(i)        
        
        // Generate itemValue characters + css
        html += '<span class="energyCounter" ID="energyUnit'+i+'">'+itemValueChar+'</span>';          
    }
    return html;      
}
/* end Energy meter methods**************************************************************************************************************************************/     





// Jquery "ready()" (function shorthand)
//$(function() {                
$(document).ready(function(){
    
    // Initialize "falling snow" plugin (Christmas 2012)
    //$("#container").jSnow();  
    
    
    /* Image slider code 8/11/11 *********************************************************************************************************************************************/
    var totWidth = 0;
	var positions = new Array();

	$('#slides .slide').each(function(i){
		/* Loop through all the slides and store their accumulative widths in totWidth */
		positions[i]= totWidth;
		totWidth += $(this).width();

		/* The positions array contains each slide's commulutative offset from the left part of the container */
		if(!$(this).width())
		{
			alert("Please, fill in width & height for all your images!");
			return false;
		}
	});

	$('#slides').width(totWidth);       // Set containing element width as total of child widths

	/* Change the cotnainer div's width to the exact width of all the slides combined */
	$('#menu ul li a').click(function(e){

		/* On a thumbnail click */
		$('li.menuItem').removeClass('act').addClass('inact');
		$(this).parent().addClass('act');

		var pos = $(this).parent().prevAll('.menuItem').length;

		$('#slides').stop().animate({marginLeft:-positions[pos]+'px'},450);
		/* Start the sliding animation */

		e.preventDefault();
		/* Prevent the default action of the link */
	});

	$('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact');
	/* On page load, mark the first thumbnail as active */
   /* end imageSlider ****************************************************************************************************************************************/
   
   
    
    
    
    // Configure carousel 
    jQuery('#carousel').jcarousel({
        // Configuration goes here
        wrap: 'circular'
    });
    
    
    // Initialize XML energy display 
    energyMeter();        
    
    // Update energy display
    window.setInterval(energyMeter, 15000);              
    
    
            
    /* Megamenu *********************************************************************************************************************************************/
                            
    //On Hover Over
    function megaHoverOver(){    //ul#topnav li     is "this"        
        $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
        (function($) {
            //Function to calculate total width of all ul's
            jQuery.fn.calcSubWidth = function() {
                rowWidth = 0;
                //Calculate row
                $(this).find("ul").each(function() { //for each ul...
                    rowWidth += $(this).width(); //Add each ul's width together                                        
                    rowWidth += parseInt($(this).css('margin-right'));  // Add element margins to total .sub container width (accommodate margin settings)
                    // TO DO: Modify width calculation. Need to add .sub ul width, margin and padding
                });
            };                        
        })(jQuery); 
                                        
        if ( $(this).find(".row").length > 0 ) { //If row exists...
            var biggestRow = 0;	

            $(this).find(".row").each(function() {	//for each row...
                $(this).calcSubWidth(); //Call function to calculate width of all ul's
                //Find biggest row
                if(rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });

            $(this).find(".sub").css({'width' :biggestRow}); //Set width
            $(this).find(".row:last").css({'margin':'0'});  //zero last row's margin

        } else { //If row does not exist...

            $(this).calcSubWidth();  //Call function to calculate width of all ul's
            $(this).find(".sub").css({'width' : rowWidth}); //Set Width            
        }
    }
    //On Hover Out
    function megaHoverOut(){
       // Commented out 7/3/11 for testing of login panel
        $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
            $(this).hide();  //after fading, hide it
        });                     
    }

    //Set custom configurations
    var config = {
         sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
         interval: 100, // number = milliseconds for onMouseOver polling interval
         over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
         timeout: 100, // number = milliseconds delay before onMouseOut
         out: megaHoverOut // function = onMouseOut callback (REQUIRED)
         //out: megaHoverOver // function = onMouseOut callback (REQUIRED)
    };

    $("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
    $("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations
    
    /* end Megamenu *********************************************************************************************************************************************/
    
    
        
     /* Login panel animation ************************************************************************************************************************************/
    $("#login-link").click(function(){        
        // Take account of people using outdated, decrepit browser (I.E 6)
        if($.browser.msie)
        {
            if ($.browser.version == "6.0")
            {                            
                // Browser is internet explorer version 6, redirect
                window.location.href = "/login.aspx";
            }
        }                        
        $("#login-panel").slideToggle(200);
    });
    // Login panel hide on keypress
    $(document).keydown(function(e) {
        if (e.keyCode == 27) {
            $("#login-panel").hide(0);            
        }
    });      
    /* end Login panel animation *********************************************************************************************************************************/
        
        

    /* Print page ***************************************************************************************************************************************/         
    $('#textControls .printControlsIcon').click(function() {
        window.print();
        return false;
     });                       
    /* end Print page ***************************************************************************************************************************************/ 




    // Add custom styles to input element(s)  ************************************************************************************************************************/     
    //$('#ctl00_MainContent_DetailsView1_Documentation').customInput();
    //$('input').customInput();  //  NOTE: this is applying to ALL input elements site - wide. Need to call this ONLY on the required pages?     NOTE: COMMENTED OUT 24/02/12 TESTING
    /* end Custom styles ********************************************************************************************************************************************/ 

     
             
    /* "Font scaling" Button events  *****************************************************************************************************************************/
    $(".smallerTxt").click(function(event){              
        decreaseFontSize();
    });    
    $(".largerTxt").click(function(event){              
        increaseFontSize();
    });
    /* "Font scaling" Button events end *****************************************************************************************************************************/
    
     
                               
    /* Attach navigation tab events  *****************************************************************************************************************************/
    //$("#navigation ul li a").each(function(i) {
      //  attachNavEvents($(this), $(this).attr("class"));   	        		                           
    //}); */  /* commented out 20/12/10 */
    /******************************************************************************************************************************/ 
        
        
        
    // intialise gallery resources 
	/*$('div#imgGallery ul li').css({opacity: 0.0});
	$('div#imgGallery ul li:first').css({opacity: 1.0});
	$('div#imgGallery .navigation a:first').addClass('selected');  block commented out 8/11/11 during refactor   */
	
    // Initialize imageGallery  - block commented out 9/11/11
    //fadeHandler();
    //var timer = window.setInterval("fadeHandler()", 15000);        					

    /* Gallery button events 
    $(".galleryBtn").hover(
        function () {
            $(this).addClass('galleryBtnR');
        }, 
        function () {
            $(this).removeClass('galleryBtnR');
        }
    );
       	
	$(".galleryBtn").click(function(event){        
        event.preventDefault();
        
        $("#imgGallery #imgGalleryNavigation a").each(function(i) {
            if(event.target.href == $(this).attr('href')){
                // Button "selected" css
                $(this).addClass('galleryBtnR');
                
                // Interrupt image cycling
                window.clearInterval(timer);
                
                // invoke image Cycle
                fadeHandler(this.href);                             
            }
            else {
                $(this).removeClass('galleryBtnR');                                                                                    
            }	        		                           
        });             
    });   -- end commented out block   */
    
    
    
    // "Element enclosing" Button event
    $("#panelTabs a").click(function(event){              
        encloseElement($(this).attr("class"));
        event.preventDefault();
    });
          
    
/* END */
}); 

