// some required vars
var news_slide_show_index = 0;
var news_int_slide_show_index = 0;
var news_slide_show_timeout = 5000;


function clearValue(clearInput, defaultValue)
{
    if (clearInput.value == defaultValue) clearInput.value = '';
}
function setElementAsScrollable(element) {

  var nav_sub = $(element);

  if (nav_sub.length) {

    var nav_sub_pos = nav_sub.position();

    var holder = $('<div>&nbsp;</div>');

    // the 'holder' element is used to occupy the same space used by 'nav-sub' once the 'nav-sub' is set as absolute
    // so that other nearby elements dont get affected in tems of positioning
    holder.css({
      'width': nav_sub.width(),
      'height': nav_sub.height(),
      'display': nav_sub.css('display'),
      'float': nav_sub.css('float'),
      'margin-left': nav_sub.css('margin-left'),
      'margin-top': nav_sub.css('margin-top'),
      'padding-top': nav_sub.css('padding-top'),
      'padding-right': nav_sub.css('padding-right'),
      'padding-bottom': nav_sub.css('padding-bottom'),
      'padding-left': nav_sub.css('padding-left'),
      'clear': 'left'
    });

    nav_sub.after(holder);

    // when this nav-sub is set as absolute (see below) the holder element which is added right after nav-sub moves up
    // and takes up the space prevlousy held by nav-sub which ensure positioning of nearby elements are not affected.
    nav_sub.css({
      'position': 'absolute',
      'top': nav_sub_pos.top,
      'left': nav_sub_pos.left
    });

    $(window).scroll(function () {
      $(element).stop().animate({
        top: Math.max(nav_sub_pos.top, $(window).scrollTop())
      });
    });

    $(window).resize(function () {
      $(element).css({
        'left': holder.position().left
      });
    });
  }
}


$(document).ready(function() {
  setElementAsScrollable('div.scrollablepdflink');
//  setElementAsScrollable('div.call-to-action.whiteallround');
});

$(document).ready(function()
{
  $('a[href="/d/50/request-a-quote.html"], a[href="../../d/50/request-a-quote.html"]').fancybox({
    'zoomOpacity'			: true,
    'overlayShow'			: true,
    'width'           : 700,
    'height'          : 575,
    'zoomSpeedIn'			: 500,
    'zoomSpeedOut'		: 500,
    'easingIn'				: 'easeOutBack',
    'easingOut'				: 'easeInBack',
    'transitionIn'    : 'elastic',
    'transitionOut'   : 'elastic',
    'centerOnScroll'  : 'true',
    'type'            : 'iframe'
  });

  $('.fancy').fancybox({
    'zoomOpacity'			: true,
    'overlayShow'			: true,
    'width'           : 500,
    'height'          : 450,
    'zoomSpeedIn'			: 500,
    'zoomSpeedOut'		: 500,
    'easingIn'				: 'easeOutBack',
    'easingOut'				: 'easeInBack',
    'transitionIn'    : 'elastic',
    'transitionOut'   : 'elastic',
    'centerOnScroll'  : 'true',
    'type'            : 'iframe',
    'scrolling'          : 'no'
  });

  // for client use via cms
  $('.fancybox').fancybox({
    'zoomOpacity'			: true,
    'overlayShow'			: true,
    'width'           : 800,
    'height'          : 500,
    'zoomSpeedIn'			: 500,
    'zoomSpeedOut'		: 500,
    'easingIn'				: 'easeOutBack',
    'easingOut'				: 'easeInBack',
    'transitionIn'    : 'elastic',
    'transitionOut'   : 'elastic',
    'centerOnScroll'  : 'true',
    'type'            : 'iframe'
  });

	// hide boxes with no content - user populated
  $('.box').each(function(i){
          var inner_html = $(this).html();
          var inner_html_trimmed = inner_html.replace(/^\s+|\s+$/g, '');
                  if (inner_html_trimmed == ''){
                          $(this).hide();
                  }
  });

  // hide boxes with no content - user populated
  $('.bluebox').each(function(i){
          var inner_html = $(this).html();
          var inner_html_trimmed = inner_html.replace(/^\s+|\s+$/g, '');
                  if (inner_html_trimmed == ''){
                          $(this).hide();
                  }
  });

  // hide boxes with no content - user populated
  $('.brownbox').each(function(i){
          var inner_html = $(this).html();
          var inner_html_trimmed = inner_html.replace(/^\s+|\s+$/g, '');
                  if (inner_html_trimmed == ''){
                          $(this).hide();
                  }
  });

  //hide toolbox if no other content
  $('#toolbox').each(function(i){

          var inner_html = $(this).html();
          var inner_html_trimmed = inner_html.replace(/^\s+|\s+$/g, '');
          if (inner_html_trimmed == '<h4>Toolbox</h4>' || inner_html_trimmed=="<H4>Toolbox</H4>"){
                  $(this).hide();
          }

  });

	$('.hide_empty').each(function(i){
		var inner_html = $(this).html();
		var inner_html_trimmed = inner_html.replace(/^\s+|\s+$/g, '');
			if (inner_html_trimmed != ''){
				$(this).show();
			}
	});

  // Reset Font Size
    var originalFontSize = $('html').css('font-size');
      $(".resetFont").click(function(){
      $('html').css('font-size', originalFontSize);
    });
    // Increase Font Size
    $(".increaseFont").click(function(){
      var currentFontSize = $('html').css('font-size');
      var currentFontSizeNum = parseFloat(currentFontSize, 10);
      var newFontSize = currentFontSizeNum*1.2;
      $('html').css('font-size', newFontSize);
      return false;
    });
    // Decrease Font Size
    $(".decreaseFont").click(function(){
      var currentFontSize = $('html').css('font-size');
      var currentFontSizeNum = parseFloat(currentFontSize, 10);
      var newFontSize = currentFontSizeNum*0.8;
      $('html').css('font-size', newFontSize);
      return false;
    });



	/* Only showing those sidebar block elements that contain content */
	$('.block').each(function(i){

		$(this).children('.inner').each(function(i){
			var inner_html         = $(this).html();
			var inner_html_trimmed = inner_html.replace(/^\s+|\s+$/g, '');
			if (inner_html_trimmed != '')
			{
				$(this).parent().show();
			}
		});

	});

	/* attaching rollover to nav elements */
	$('.nav_roll').hover(
	    function() {
	        //over
	        var newImage = $(this).find('img').attr('src').replace(/^(.*?)(\.(?:gif|jpg|png))$/, "$1.on$2");
	        if (newImage.indexOf('.on.on') == -1)
	        {
	           $(this).find('img').attr('src', newImage);
	        }
	    },
	    function() {
	        //out
	        var newImage = $(this).find('img').attr('src').replace('.on', '');
	        $(this).find('img').attr('src', newImage);
	    }
	);

	/* attaching rollover to branch map */
    if (isDefined('window','branchIds'))
	{
        $('area').click(
            function() {
                // over

                // find the branch code
                var branch_code = $(this).attr('href');
                if (branch_code.indexOf('#') == 0)
                {
                   branch_code = branch_code.substr(1,5);
                }

                // grab the branch id from the codes array
                if (branchIds[branch_code])
                {
                   // populate div with branch information
                   $('#branch_details').html(branchDetails[branch_code]);

                   // change links to correspond to correct branches
                   $('#branch_link_contact').attr('href',$('#branch_link_tmp_contact').attr('value')+branchIds[branch_code]);
                   $('#branch_link_gmaps').attr('href',$('#branch_link_tmp_gmaps_a').attr('value')+branchPostCodes[branch_code]+$('#branch_link_tmp_gmaps_b').attr('value'));
                   $('#branch_link_gmaps').attr('target','_blank');
                }
            },
            function() {
               // out
            }
        );

        /* attaching region zoom to branch map click */
        $('area').click(
            function() {

                // find the region
                var branch_region = $(this).attr('href');
                if (branch_region.indexOf('region') != -1)
                {
                   branch_region = branch_region.substr(7,20);
                   $(this).attr('href',$('#branch_link_tmp_region').attr('value')+branch_region);
                }
            }
        );
    }

	/* starting the electrical news slideshow */
	if (isDefined('window','newsItems') || isDefined('window','newsIntItems'))
	{
	   setTimeout ("slideNews()", news_slide_show_timeout);
	}

  //Size Specifier Flat/Pitch Search Determiner
  //This one is for when the option in the select box is changed
  $("#roof_select").change(function () {
    if ($("#roof_select option:selected").val()=="Flat") {
      $('#pitch_size_search').fadeOut(250);
      $('#flat_size_search').delay(250).fadeIn(250);
      $('input[name="viewable-width"]').val("Viewable Width (mm)");
      $('input[name="viewable-length"]').val("Viewable Length (mm)");
      $('input[name="structural-width"]').val("Structural Width (mm)");
      $('input[name="structural-length"]').val("Structural Length (mm)");
    } else if ($("#roof_select option:selected").val()=="Pitch") {
      $('#flat_size_search').fadeOut(250);
      $('#pitch_size_search').delay(250).fadeIn(250);
      $('input[name="kerb-width"]').val("Kerb Width (mm)");
      $('input[name="kerb-length"]').val("Kerb Length (mm)");
    }
  });

  //This one is for when the results page loads
  if ($("#roof_select option:selected").val()=="Flat") {
      $('#pitch_size_search').fadeOut(250);
      $('#flat_size_search').delay(250).fadeIn(250);
    } else if ($("#roof_select option:selected").val()=="Pitch") {
      $('#flat_size_search').fadeOut(250);
      $('#pitch_size_search').delay(250).fadeIn(250);
    }

  $('.sizespec-hover').tooltip({ delay: 0, showURL: false, fade: 250, extraClass: "sizespec-hover-text" });
});

function showHide (showOrHide, elementToChange) {
    if (showOrHide == 'show')
    {
        $('#'+elementToChange).show();
    }
    else
    {
        $('#'+elementToChange).hide();
    }
}

function slideNews () {
    // NOTE : This could obviously be done better

    news_slide_show_index = news_slide_show_index + 1;
    news_int_slide_show_index = news_int_slide_show_index + 1;

    if (isDefined('window','newsItems'))
    {
        // grab the news item from the var defined above
        // check if a value exists
        if (newsItems[news_slide_show_index])
        {
           // do nothing for the time being
        }
        else
        {
           // index doesn't exist, restart
           news_slide_show_index = 0;
        }

        // check it again, to make sure we have an index 0
        if (newsItems[news_slide_show_index])
        {
           // populate with news item
           $('#module_news_external_item').html(newsItems[news_slide_show_index]);
        }
    }

    if (isDefined('window','newsIntItems'))
    {
        // internal news
        // grab the news item from the var defined above
        // check if a value exists
        if (newsIntItems[news_int_slide_show_index])
        {
           // do nothing for the time being
        }
        else
        {
           // index doesn't exist, restart
           news_int_slide_show_index = 0;
        }

        // check it again, to make sure we have an index 0
        if (newsIntItems[news_int_slide_show_index])
        {
           // populate with news item
           $('#module_news_internal_item').html(newsIntItems[news_int_slide_show_index]);
        }
    }

    // repeat
    setTimeout ("slideNews()", news_slide_show_timeout);
}

function isDefined(object, variable)
{
    /*alert(object + ']2');
    var object_eval = eval(object);
    var object_variable = object_eval[variable];
    var object_type = typeof(object_variable);
    if (object_type == 'undefined')
    {
        return false;
    }
    else
    {
        return true;
    }*/

    return (typeof(eval(object)[variable]) == 'undefined')? false : true;
}
