// -------------------------------------------------------------------------------------------------
$(document).ready(function() {
	
	
  // bind text size events
  textSize();
  checkTextSizeCookie();		

  // set up form show-hides
  fnSwitchDisabled();
	
  // Preload all images with 'roll' class
  $('.roll').each(function() {
    $(this).preloadImg();
  });
  
  // Apply hover to image with class 'roll' via their parent anchor.
  $('a').each(function() {
    oFirstChild = $(this).children(':first');
    if (oFirstChild.is('img')) {
      if (oFirstChild.attr('class') == 'roll') {
        $(this).hover(
          function () {
            $(this).children(':first').swapImg();
          }, 
          function () {
            $(this).children(':first').swapImg();
          }
        );
      }
    }
  });
  
  //Apply hover to image without wrapping anchors (e.g. form input image)
  $('input.roll').hover(
    function () {
      $(this).swapImg();
    }, 
    function () {
      $(this).swapImg();
    }
  );  
  
  // FAQ show-hide questions
  if($('.faq').length>0){
  	faqShowHide();
  }
  
  fnRecuringDates()
  
  /*functions to hide some markup generated by worldpay*/
  //fnHideUserPass(); // hide some markup on worldpay returned page  
  //fnHideCheckoutLogin(); // hide login info on first screen of checkout
  fnDisableHoursRads(); //lesson booking radio buttons
  
});
  
// -------------------------------------------------------------------------------------------------
// Extend the jQuery core hover function.

$.fn.extend({
  hover: function(fnOver, fnOut) {
    return this.bind('mouseover focus', fnOver).bind('mouseout blur', fnOut);
  }
});
  
// -------------------------------------------------------------------------------------------------
// Preload image function

$.fn.preloadImg = function() {
  var sExt = '.'+getExt($(this).attr('src'));
  var sCurSrc = $(this).attr('src');
  var img = new Image();
  img.src = sCurSrc.replace(sExt,'_hover'+sExt);
}

// -------------------------------------------------------------------------------------------------
// Swap image src attributes to add or remove '_hover'.

$.fn.swapImg = function() {
  var sExt = '.'+getExt($(this).attr('src'));
  var sCurSrc = $(this).attr('src');
  var sNewSrc
  if (sCurSrc.indexOf('_hover'+sExt) != -1) {
    sNewSrc = sCurSrc.replace('_hover'+sExt,sExt);
  } else {
    sNewSrc = sCurSrc.replace(sExt,'_hover'+sExt);
  }
  $(this).attr('src',sNewSrc);
}

// -------------------------------------------------------------------------------------------------
// Find the extension of the supplied filename.

function getExt(f) {
  var ext;
  var aF = f.split('.');  // Split the filename.
  if (aF.length > 1) { // If the array is longer than 1 return the last element (the extension).
    ext = aF[aF.length-1]; 
  }
  return ext;
}

// -------------------------------------------------------------------------------------------------
// FAQ show-hide functionality

function faqShowHide() {
  
	$('div.faq div.cont:gt(0)').hide();//hide all questions after the first	
	
	$('div.faq_no a') // setup click event for faq list
		.click(function() {
			
			$('div.faq_no li').removeClass("selected");
			$(this).parents("li:first").addClass('selected')
			$('div.faq div.cont').hide()
			$($(this)[0].hash).show();			
			return false
		});
	
}

// -------------------------------------------------------------------------------------------------

// text size functionality

function textSize() {  
	
	var options = { path: '/', expires: 0 };
	
	$('#text_size_sml') .click(function() {
			$('body').attr("id","small");
			$.cookie('__bsmTextSize__', 'small', options);
			return false;
		});
	$('#text_size_med') .click(function() {	
		$('body').attr("id","medium");
		$.cookie('__bsmTextSize__', 'medium', options);		
		return false;
	});
	$('#text_size_lrg') .click(function() {	
		$('body').attr("id","large"); 
		$.cookie('__bsmTextSize__', 'large', options);
		return false;
	});			
}

// -------------------------------------------------------------------------------------------------

// text size functionality

function checkTextSizeCookie() {
	if($.cookie('__bsmTextSize__') != null) {
		$('body').attr("id",$.cookie('__bsmTextSize__')).toString();
	}	
}

// -------------------------------------------------------------------------------------------------

// form section show-hide functionality
function fnSwitchDisabled(){
	// console.log('dsds');
    $('.trig').each(
        function(i){
        	//disable elements in this section that are targets
        	fnDisable($(this));
                
                var obj = $(this);
                
                if(obj.is(':radio')){
                //find the rest of the radiobuttons in this group as we have to trigger the event on all of the radiobuttons not just the trigger.
                var name = $(this).attr('name');
                $(":radio[name='"+ name +"']").click(
                    function(){
                        if($(this).hasClass('trig')){
                        	//if it is the trigger then enable the field(s)
                            fnEnable($(this));
                        }else{
                            fnDisable($(this));
                        }
                    }
                );
            }
            if(obj.is(':checkbox')){
                $(this).click(function(){
                	 if($(this).is(':checked')){
                	 		//if the trigger is checked then enable the field(s)
                            fnEnable($(this));
                        }else{
                            fnDisable($(this));
                        }
                });
            }
             if(obj.is('select')){   
                $(this).change(function(){
                	fnCheckSelects($(this));
                	
	                });
            }

        }
    );
    fnInit();
}

function fnDisable(x){
    x.parents('.sect').find('.targ').attr('disabled','disabled').addClass("inputDisabled")/*.val("").removeAttr('checked')*/;
}

function fnEnable(x){
    x.parents('.sect').find('.targ').attr('disabled','').removeClass("inputDisabled");
}

function fnCheckSelects(x){
	val = x.val().toLowerCase(); 
	
	// AJL added substring(4) as form builder adds 4 numbers to start of value.
	if(val == 'other' || val == 'sometimes' || val =='in some cases' || val.substring(4) == 'other' || val.substring(4) == 'sometimes' || val.substring(4) == 'in some cases'){
		//if the value of the selected item is other OR sometimes then enable the field
		 fnEnable(x);
	}else{
		fnDisable(x);
	}
}


function fnInit(){
	/* Check for all prepopulated cases */
    /* Radio buttons /checkboxes */
    $('.trig:checked').each(
        function(){
            fnEnable($(this));
        }
    );
    $('select.trig').each(function(){
    	fnCheckSelects($(this));
    });
}
// -------------------------------------------------------------------------------------------------

// selected date reccuring weekly, taken from lessons site and modified.

function fnRecuringDates(){
	if($('#edit-lesson1check').length >0){
	
		$('#edit-lesson1check').click(function(){
				fnChangeDates();
			});
		$('#edit-lesson1-day, #edit-lesson1-month, #edit-lesson1-year, #edit-lesson1slot').change(function(){
			fnChangeDates();
		});
	}
}

function fnChangeDates(){
	if($('#edit-lesson1check').is(':checked')){
		
		var newtime = new Date();
        		
		newtime.setDate($('#edit-lesson1-day')[0].value);
		newtime.setMonth($('#edit-lesson1-month')[0].selectedIndex);
		newtime.setFullYear($('#edit-lesson1-year')[0].value);
		
		for (var i = 2; i<=5; i++){
		// Change it to 1 week in advance
		newtime = new Date(newtime.getTime() + 24 * 60 * 60 * 1000 * 7);

		$('#edit-lesson'+i+'-day')[0].value = newtime.getDate();
		$('#edit-lesson'+i+'-month')[0].selectedIndex = newtime.getMonth();
		$('#edit-lesson'+i+'-year')[0].value = newtime.getFullYear();
		
		$('#edit-lesson'+i+'slot')[0].selectedIndex = $('#edit-lesson1slot')[0].selectedIndex;
		}
	}
}

// -------------------------------------------------------------------------------------------------



// -------------------------------------------------------------------------------------------------

function fnHideUserPass() {
	
	// on order confirmation page - after payment through worldpay
	$('p strong:contains("Username")').parent().remove();
	$('p:contains("to your new account using the following information:")').remove();
	
}
// -------------------------------------------------------------------------------------------------

function fnHideCheckoutLogin() {
	
	// on checkout 1st page - hide reference to logging in
	var find = $('#customer-pane');
	if(find.length > 0){		
		$("div.description",find).hide();
	}
	
}
// -------------------------------------------------------------------------------------------------

function fnDisableHoursRads() {
	
	// Disabled hour radio buttons if user selects a number of hours from the dropdown list
	var sel = $('#edit-hours-dropdown');
	var rads = $('input[name=hours].form-radio');
	
	if(sel.length > 0){
		sel.change(function() {
			if($(this).val() != '0'){
				rads.attr('disabled','disabled');
			}
			else{
				rads.attr('disabled','');
			}
		});
	}
	
	
}
// -------------------------------------------------------------------------------------------------