function InitBoxOut() {
  $(".cms-BoxOut:last-child").css({"float":"none", "width":"auto", "margin":"0"});
}


function InitAccordian() {

  $(".Accordian .Acc-Item").hide();
  
}

function InitImageExpander() {

  $(".object123 img").each( function() {
   
   if ( this.parentNode.tagName.toLowerCase() == "a" || $(this).hasClass("no-expand") )
     return;


   var link = $("<a></a>");

   var src = this.src.replace(/.*?\/file\/(\d+).*/, "$1");

   var filename = this.src.substr(this.src.lastIndexOf(".")+1, this.src.length);

   src = "/site/file/" + src + "/resize/h600/file." + filename;  
   link.attr("href", src);

   link.click( function() {
     $(this).colorbox( { opacity:0.85, close:"close" } );  
   });

   $(this).wrap(link);

  });

  return false;


}

function InitFloatColumns() {

  $(".FloatCols").each( function() {

    var iCols = $(this).attr("columns");


    $(this).children().css({"display":"inline-block", "position":"relative" });

    $(this).children().each(function(i) {


      var iWidth = 960;
      var iLeft = 0;

      iCols = parseInt(iCols);

      switch (i % iCols) {
        case 0 : 
          iLeft = 0 - $(this).position().left;
          break;
        case 1 : 
          iLeft = 0 - $(this).position().left + 240;
          break;
        case 2 : 
          iLeft = 0 - $(this).position().left + 480;
          break;
        case 3 : 
          iLeft = 0 - $(this).position().left + 720;
          break;
      }

      var iTop = 0;
      var oPrev = $(this).prevAll()[iCols-1];
      if ($(oPrev).size() > 0) {
        iTop = 0 - $(this).position().top + $(oPrev).position().top + $(oPrev).outerHeight(true);
      }

      
      $(this).css({"left": iLeft + "px", "top": iTop + "px" });
    })




  });

}

function InitCustomise() {

  $(".Customise a").bind("click", function() {
    $(this).parent().children(".HiddenPanel").slideToggle();
    return false;
  }).parent().show();

}

function InitCarousel() {
   
    $(".Carousel").each( function() {

      if ( $(this).hasClass("Initiated") == false ) {    

        $("<a/>").addClass("next").html("<span>Next</span>").attr("href", "#").appendTo( $(this) ).insertAfter( $(this) );;
        $("<a/>").addClass("prev").html("<span>Previous</span>").attr("href", "#").appendTo( $(this) ).insertBefore( $(this) );
	$(this).addClass("Initiated");
     
        $(this).jCarouselLite({
          btnNext: ".next",
          btnPrev: ".prev",
          start: -1,
          showPaging: true,
          visible: 4
        });
  
      }

    });


}



function InitNav() {

  if ( $("#MainNav").hasClass("Init") )
    return;

  $("#MainNav").addClass("Init").children("li").hoverIntent( MouseEnterNav, MouseLeaveNav );



  $("<span class=\"LineHide\"/>").insertBefore( $("#MainNav>li>a"));  

  $("#MainNav div.DropDown").parent().addClass("HasSubItems");
  $("#MainNav div.DropDown").prepend($("<div class='Top'/>")).append($("<div class='Bottom'/>"));

}

function MouseEnterNav() {

    if ($(this).next("li").next("li").size() > 0) {
      $(this).next("li").children("a").addClass("RemoveLine");
    }

    $(this).addClass("Hover");

    $(this).children("div:has(*)").show();
    $(this).children("span.LineHide").width( $(this).width());
   
    $(this).removeClass("HideBG");

}

function MouseLeaveNav() {
    $(this).removeClass("Hover");

    $(this).addClass("HideBG");
    $(this).children("div").hide();


    $(this).next("li").children("a").removeClass("RemoveLine");
}



function InitTableRows() {

  $("table tr:odd").addClass("alt");

}



function InitLastChild() {
  $("li:last-child").addClass("last");
  $("li:first-child").addClass("first");

  $("dd:last-child").addClass("last");
  $("dd:first-child").addClass("first");

  $("dt:last-child").addClass("last");
  $("dt:first-child").addClass("first");

}

function InitAddHover() {
  $(".AddHover").mouseenter( function() {
    $(this).addClass("Hover");
  });

  $(".AddHover").mouseleave( function() {
    $(this).removeClass("Hover");
  });

}


function InitDefaultFields() {

  var active_color = '#000';
  var inactive_color = '#ccc';

  $("input.default-value").css("color", inactive_color);
  var default_values = new Array();
  $("input.default-value").focus(function() {
    if (!default_values[this.id]) {
      default_values[this.id] = this.value;
    }
    if (this.value == default_values[this.id]) {
      this.value = '';
      this.style.color = active_color;
    }
    $(this).blur(function() {
      if (this.value == '') {
        this.style.color = inactive_color;
        this.value = default_values[this.id];
      }
    });
  });
}


function ShowTab(Link) {
  var Index = $(Link).parent().prevAll("li").size();


  $(Link).parents("ul").find("li").removeClass("Selected");
  $(Link).parent().addClass("Selected");
 
  var Tabs = $(Link).parents(".Col1").find(".SectionTabContent, .EAtlasTabContent");

  Tabs.hide();
  Tabs.eq(Index).show();

  return false;
  

}


function PrintPage(Link) {
  var iWidth = Math.min($(window).width(), 600);
  var iHeight  = Math.min($(window).height(), 800);

  var win = window.open (Link.href,"PrintWindow","status=1,width=" + iWidth + ",height=" + iHeight + ",scrollbars=yes,menubar=yes"); 

  win.focus();

  return false;
}


function ToogleInfoLevel(Items) {

  $(Items).each( function() {

    if ( $(this).find("ul:visible").size() > 0 ) {    
      $(this).find("p").show().unbind("click").bind( "click", function() { ToogleInfoLevel( $(this).parents(".InfoLevels") ); return false; } );
      $(this).find("ul").slideToggle("slow");
      $(this).find(".Less").remove();
    }
    else {
      $(this).find("ul").slideToggle("slow");
      $(this).append( $("<a href='#' class='Less'>Hide</a>").bind(  "click", function() { ToogleInfoLevel( $(this).parent() ); return false; } ) );
    }

  });

  return false;
}


function ToggleConcertina(Link) {
  $(Link).parent().next().slideToggle("slow");
  return false;
}

jQuery.fn.innerWrap = function() {
	var a, args = arguments;
	return this.each(function() {
		if (!a)
			a = jQuery.clean(args, this.ownerDocument);
		// Clone the structure that we’re using to wrap
		var b = a[0].cloneNode(true),
		    c = b;
		// Find the deepest point in the wrap structure
		while ( b.firstChild )
			b = b.firstChild;
		// append the child nodes to the wrapper
		jQuery.each(this.childNodes, function(i, node) { 
			b.appendChild(node); 
		});
		jQuery(this)
			// clear the element
			.empty()
			// add the new wrapper with the previous child nodes appended
			.append(c);
	});
};


function InitTextEditRestrictions() {


  $("input.RestrictCurrency").keydown(function (e) {
      var i = e.keyCode || e.charCode;
 
      if (i == 8 || i == 46 || i == 110 || i == 190 || (i >= 48 && i <= 57) || (i >= 96 && i <= 105) ) {
        return true;
      }
      return false;
    
  })


}


function OpenBlogComments(Link) {
  $(Link).parent().find(".CommentForm").slideToggle();
  return false;
}





function ShowSocialMedia(Link) {
 

  var oLink = $(Link);
  var oDiv = $("<div class=\"SocialMediaPopup\"/>")		
		.append( $(".SocialMedia").clone() )
	    	.css( {"position":"absolute", "width":"300px", "left": oLink.offset().left-150 + "px", "top":oLink.offset().top-75 + "px"} )
		.hide()
		.fadeIn(1000)
		.bind("mouseleave", function() { 
						$(this).fadeOut(1000, 
						function() { $(this).remove(); }
						) 
					      });


  $("body").append(oDiv);


 return false;
}







function SetAjax(SourceId, DestId, Url, Function) {

  var Data = null;
  var Method = "GET";

  if ( Url.nodeType && Url.tagName.toLowerCase() == "form"  ) {
    var Query = $(Url).serialize();

    Method = Url.method;

    if (Method.toLowerCase() == 'get') {
      Url = Url.action.replace(/\?.*/igm, '');
      Url = Url + "?" + Query;
    }
    else {
      Url = Url.action;
      Data = Query;
    }


  }


  var El = $(DestId);
  var Img = new Image();

  El.height( El.height() ).width( El.width() );
  El.html( "<div><img src='/site/file/1004415/Ajax-loader.gif' /></div>" );
  El.find("img").css( {"margin-left":"auto", "margin-right":"auto", "float":"none", "display":"block"} );

  if ( El.height() < 47)
    El.find("div").css( {"line-height": El.height() + "px"} );
  else
    El.find("div").css( {"margin-top":"15px"} );

    

  $.scrollTo(El, {"duration":500, "offset": -50, "axis": "y"});

  
  $.ajax({
    url: Url,
    dataType: "html",
    type: Method,
    data: Data,
    success: function(data) { 

        var sRegEx = new RegExp("[\\s\\S]*?<body[^>]*>([\\s\\S]*?)</body>[\\s\\S]*", "ig"); 
        data = data.replace( sRegEx , "$1");        

        var Tmp = $("<div/>").html(data);

	El.html( Tmp.find(SourceId).html() ); 

	El.height("auto");  

        if (Function != null) {
          Function(data);
	}

     
    },
    error: function() {
      El.html("Sorry, an error occurred");
      El.height("auto");  
    }
  });


  return false;

}


function SubmitFieldset(fieldsetName)
{
    $('body').append('<form id="form-to-submit" style="visibility:hidden;"></form>');
    
    $('#form-to-submit').html($(fieldsetName).clone());
    
    var data = $('#form-to-submit').serialize();
    
    $('#form-to-submit').remove();
    
}


function ShowInPopUp(LinkObj, Selector, Height, Width, Func) {

  var Url;
  if (typeof LinkObj == "string") {
    Url = LinkObj;
  }
  else if (LinkObj.tagName.toLowerCase() == "a" ) {
    Url = LinkObj.href;
  }



  var data = $.get(LinkObj, function(data) {     
      if ( Selector != null )

      if (Height !=null && Width != null) {
        $.colorbox({"html": $(data).find(Selector).html(), "height": Height, "width": Width, "onComplete":Func });
      }
      else {
        $.colorbox({"html": $(data).find(Selector).html(), "onComplete":Func });
      }
  });

  return false;
  

}



function InitOrgDesc(link) {
  $("#DescWrap div.Desc").hide();
  $("#DescWrap a.Lang").removeClass("Selected");

  if (link != null) {
    document.location.hash = $(link).attr("href").replace("#", "");
  }

  Lang = document.location.hash.toLowerCase();


  if (Lang == '#english') {
    $("#DescWrap div.English").show();  
    $("#DescWrap a.English").addClass("Selected");  
  }
  else if (Lang == '#french')  {
    $("#DescWrap div.French").show();
    $("#DescWrap a.French").addClass("Selected");  
  }
  else if (Lang == '#portuguese') {
    $("#DescWrap div.Portuguese").show();
    $("#DescWrap a.Portuguese").addClass("Selected");  
  }

  else if (Lang == '#spanish') {
    $("#DescWrap div.Spanish").show();
    $("#DescWrap a.Spanish").addClass("Selected");  
  }

  else {
    $("#DescWrap div.English").show();  
    $("#DescWrap a.English").addClass("Selected");  
  }

}

function initHomePage() {
 
  $(".HomeCarousel div.Text li a").each( function() {

    if ( this.href.indexOf( location.hostname ) > -1 )
      $(this).parent().addClass("internal-link");
    else
      $(this).parent().addClass("external-link");

  });

  $(".HomeCarousel").find( ".ThumbsSleeve>div" ).hoverIntent( LoadCarousel, UnloadCarousel );
}

function UnloadCarousel() {

}

function LoadCarousel() {

    $(this).siblings("div.Selected").removeClass("Selected");
    $(this).addClass("Selected");

    $("#MainCarouselItem").attr("class", "MainItem");
    $("#MainCarouselItem").addClass( $(this).attr("class") ).removeClass("Selected");

    $("#MainCarouselItem a").attr( "href", $(this).find("h3 a").attr("href") );
    $("#MainCarouselItem h2 a").text( $(this).find("h3 a").text() );
    $("#MainCarouselItem div.Text").html( $(this).find("div.Text").html() )

    $($("#MainCarouselItem div.HomeCarouselLoader").remove());

    $("<div class='HomeCarouselLoader'></div>").css({"opacity":0.9, "background":"#FFFFFF url(/site/file/1004415/Ajax-loader.gif) no-repeat center center", "height":$("#MainCarouselItem img").outerHeight(), "width":$("#MainCarouselItem img").outerWidth(), "position":"absolute", "top":$("#MainCarouselItem img").position().top, "left":$("#MainCarouselItem img").position().left}).insertAfter($("#MainCarouselItem img"));

    var Img = new Image();

    $(Img).load( function() {
      $("#MainCarouselItem img").attr( "src", Img.src );
      $($("#MainCarouselItem div.HomeCarouselLoader").remove());
    });

    Img.src = ImgArray[ $(this).prevAll("div").size() ];

    return false;


}


function InitColorboxImages() {
  $("img.cms-image-colorbox").each( function() {
    var Url = parseInt(this.src.replace(/.*?\/file\/(\d+)\/.*/igm, "$1"));
    var FileExt = this.src.split('.').pop();
    if ( !isNaN(Url) ) {
      $("<a class='image-colorbox-link' href='/site/file/" + Url+ "/resize/w750/file." + FileExt + "'><span>View larger image</span></a>").insertAfter( $(this) ).colorbox();
    }
  });
}


//function OpenPET(Link) {
//  $.colorbox({href:Link.href, iframe: true, width:800, height: 600});
//  return false;
//}



function InitFormRestrictions() {


  $(".RESTRICT_ALPHANUMERIC").live("keyup keydown", function(e) {          
    if (e.keyCode == 32)
        return false;
    else
        return true;
  });

  $(".RESTRICT_INTEGER").live("keyup keydown", function(e) {     
    if (!e.shiftKey && ((e.keyCode >= 95 && e.keyCode <= 105) || (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 37 && e.keyCode <= 40) || (e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 45)))
        return true;
    else
        return false;
  });  
  
  $(".RESTRICT_DECIMAL").live("keyup keydown", function(e) {      
    if (!e.shiftKey && ((e.keyCode >= 95 && e.keyCode <= 105) || (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 37 && e.keyCode <= 40) || (e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 45 || e.keyCode == 110)))
        return true;
    else
        return false;
  });    

}


function FBSForm_Init() {
  InitFormRestrictions();
}


function FBSForm_Save(Form) {
  InitFormRestrictions(Form);
}


function FBSForm_SelectAddress(Link) {

  $("#AddressDetails .Organisation").val( $(Link).nextAll("input[name=Organisation]").val() );
  $("#AddressDetails .Address1").val( $(Link).nextAll("input[name=Address1]").val() );
  $("#AddressDetails .Address2").val( $(Link).nextAll("input[name=Address2]").val() );
  $("#AddressDetails .Address3").val( $(Link).nextAll("input[name=Address3]").val() );
  $("#AddressDetails .Address4").val( $(Link).nextAll("input[name=Address4]").val() );
  $("#AddressDetails .Town").val( $(Link).nextAll("input[name=Town]").val() );
  $("#AddressDetails .County").val( $(Link).nextAll("input[name=County]").val() );
  $("#AddressDetails .Postcode").val( $(Link).nextAll("input[name=Postcode]").val() );

  return false;

}


function SwitchHomeTabs(Link, Id) {
  $(Link).parents("ul").find("li").removeClass("Selected");
  $(Link).parent().addClass("Selected");
  $(".ContentBox").hide();
  $("#" + Id).show();
  return false;
}
