var loadScripts = [];
var unloadScripts = [];
function addLoader(func){
	loadScripts.push(func);
}

function addUnloader(func)
{
    unloadScripts.push(func);
}

function callLoadScripts(){
	//mobile load script .... must be loaded before everything else.
	//mobileRedirect();

	for(var i=0;i < loadScripts.length;i++){
//		alert('calling ' + loadScripts[i]);
		loadScripts[i]();
	}
}
function callUnLoadScripts(){
	for(var i=0;i < unloadScripts.length;i++){
//		alert('calling ' + loadScripts[i]);
		unloadScripts[i]();
	}
}
window.onload = callLoadScripts;
window.onunload = callUnLoadScripts;

function getFormValue(key){
	return('');
}
function ChangeSrc(type)
{
    if(type == 'true')
        document.getElementById('NewBannerImage').src = '/template-images/_/layout/header/header_box.png';
    else
        document.getElementById('NewBannerImage').src = '/template-images/_/layout/header/header.png';
}
function saveFormValue(key,value){
	// stub function
}

function copy(inElement) {
	if (inElement.createTextRange) {
		var range = inElement.createTextRange();
		//if (range && BodyLoaded==1){
		range.execCommand('Copy');
		//}
	} else {
		var flashcopier = 'flashcopier';
		if(!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="/wcm/site/csi/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}

var rotatorPage = 1;
var rotatorRegion = "-1";
var rotatorTopic = "-1";

function setupMediaAccessRotator(){
	//alert("page load");
	//disableRotatorButton("Left");
	//enableRotatorButton("Right",1)
}



function populateMediaAccessRotator(){
	if(rotatorRegion == ""){
		rotatorRegion = "-1";
	}
	if(rotatorTopic == ""){
		rotatorTopic = "-1";
	}
	currentServerRequest = csSendServerRequest("/processors/PressCentreProcessor/Rotator?page=" + rotatorPage + "&rqsb=" + new Date().getTime() + "&region=" + rotatorRegion + "&category=" + rotatorTopic,populateMediaAccessRotatorHandler);
}

function populateMediaAccessRotatorHandler(data){
	eval(data);
}

function setMediaAccessRotatorImage(id,image,altText,href){
	var li = $("rotator" + id);
	if(li){
		var img = li.getElementsBySelector("img")[0];
		img.src = image;
		img.alt = altText;
		img.title = altText;
		
		var a = li.getElementsBySelector("a")[0];
		a.href = href;
	}
}

function dummy(){

}

function enableRotatorButton(name,pageIncrement){
	//alert('enable ' + name);
	var rotate = $('rotate' + name);
	
	if(rotate){
		rotate.setStyle({backgroundColor:'#e9f3ff',cursor:'pointer'});
		rotate.addClassName('enableRotator');
		rotate.removeClassName('disableRotator');
		
		rotate.onclick = function(){
			//alert(rotatorPage + " + " + pageIncrement);
			rotatorPage = rotatorPage + pageIncrement;
			//alert(rotatorPage);
			populateMediaAccessRotator();
		}
		
		var anchor = rotate.getElementsBySelector("a")[0]
		if(anchor){
			//anchor.href = 'javascript:alert("here !!!");';
			//anchor.href = null;
			anchor.href = 'javascript:dummy()';
		}
	}
}

function disableRotatorButton(name){
	//alert('disable ' + name);
	var rotate = $('rotate' + name);
	
	if(rotate){
		rotate.setStyle({backgroundColor:'#e9f3ff',cursor:'default'});
		rotate.addClassName('disableRotator');
		rotate.removeClassName('enableRotator');
		
		rotate.onclick = null;
		
		var anchor = rotate.getElementsBySelector("a")[0]
		if(anchor){
			anchor.href = null;
			anchor.href = 'javascript:dummy()';
		}
	}
}

/*New Home page changes*/
/*function ClearSearchbox()
{
   var InputBox = document.getElementById('searchPhrase');
 
  if( InputBox.style.backgroundImage != '' && InputBox.value == '')
   {
       InputBox.style.backgroundImage = '';
    }
}
function TypeSearchString()
{
      var InputBox = document.getElementById('searchPhrase');
 
     if( InputBox.style.backgroundImage == '' && InputBox.value == '')
    {
        InputBox.style.backgroundImage = 'url(/template-images/_/layout/homepage/searchoursite.png)';
     }
}*/
function ClearSearchbox()
{
    if(document.getElementById('searchPhrase').value == 'Search our site')
        document.getElementById('searchPhrase').value = '';
}
function TypeSearchString()
{
    if(document.getElementById('searchPhrase').value == '')
        document.getElementById('searchPhrase').value = 'Search our site';
}
function ClearSearchtext(Type)
{
    if(document.getElementById('postcode'+Type).value == "Enter postcode or 'Ireland'")
        document.getElementById('postcode'+Type).value = '';
}
function EnterSearchtext(Type)
{
    if(document.getElementById('postcode'+Type).value == '')
        document.getElementById('postcode'+Type).value = "Enter postcode or 'Ireland'";
}

var selectedNDiv = 1;
var selectedEDiv = 1;

function expandone(Direction,DivId,pageNolabel,Count)
{
   if(Count > 0)
   {
        var previousDivObj = '';
        var selectedDivObj = '';
        var selectedpage;
        
        if(DivId == 'Newsdiv')
            selectedpage = selectedNDiv;
        else if(DivId == 'Eventsdiv')
            selectedpage = selectedEDiv;
            
        if(Direction == 'F')
        {
			previousDivObj=document.getElementById(DivId+selectedpage);
			previousDivObj.style.display="none";
			if(DivId == 'Newsdiv')
			{
	            selectedNDiv=(selectedNDiv<Count) ? selectedNDiv+1 : 1;
		        document.getElementById(pageNolabel).innerHTML = selectedNDiv + " of "+Count ;
				selectedpage = selectedNDiv;
			}
			else if(DivId == 'Eventsdiv')
			{
				selectedEDiv=(selectedEDiv<Count) ? selectedEDiv+1 : 1;
				document.getElementById(pageNolabel).innerHTML = selectedEDiv + " of "+Count ;
				SetImgContent('EImgdiv',selectedEDiv);
				selectedpage = selectedEDiv;
			}
			selectedDivObj=document.getElementById(DivId+selectedpage);      
			selectedDivObj.style.display="block";
        }
        else if(Direction == 'B')
        {
			previousDivObj=document.getElementById(DivId+selectedpage);
			previousDivObj.style.display="none";
			if(DivId == 'Newsdiv')
			{
	            selectedNDiv=(selectedNDiv>1) ? selectedNDiv-1 : Count;
		        document.getElementById(pageNolabel).innerHTML = selectedNDiv + " of  "+Count ;
			    selectedpage = selectedNDiv;
	        }
		    else if(DivId == 'Eventsdiv')
			{
				selectedEDiv=(selectedEDiv>1) ? selectedEDiv-1 : Count;
				document.getElementById(pageNolabel).innerHTML = selectedEDiv + " of "+Count ;
				SetImgContent('EImgdiv',selectedEDiv);
				selectedpage = selectedEDiv;
			}
			selectedDivObj=document.getElementById(DivId+selectedpage);
			selectedDivObj.style.display="block";
        }
    }
}
function SetImgContent(DivImg,selected)
{
	if(document.getElementById(DivImg+selected) != undefined){
		var Setimg = document.getElementById(DivImg+selected).innerHTML;
		var Setimg = Setimg.toLowerCase(); 
        if(Setimg.indexOf('<img ') == -1)
        {
            var ImgDetails = Setimg.split('-');
            if(ImgDetails[2] && ImgDetails[2] != '')
                document.getElementById(DivImg+selected).innerHTML = "<a href=' "+ ImgDetails[2]+"' ><img src='" + ImgDetails[0] + "' alt='" + ImgDetails[1] + "'  width='211px' height='107px' /></a>";
            else
                document.getElementById(DivImg+selected).innerHTML = "<img src='" + ImgDetails[0] + "' alt='" + ImgDetails[1] + "'  width='211px' height='107px' />";
        }
	}
}

var selectedWhatDiv=1;
var selectedWhoDiv =1;

function expandsection(Direction,DivId,pageNolabel,Count)
{
   if(Count > 0)
   {
            var previousDivObj = '';
            var selectedDivObj = '';
            var selectedpage;
            if(DivId == 'Whodiv')
                selectedpage = selectedWhoDiv;
            else if(DivId == 'Whatdiv')
                selectedpage = selectedWhatDiv;
            if(Direction == 'F')
            {
            previousDivObj=document.getElementById(DivId+selectedpage);
            previousDivObj.style.display="none";
            if(DivId == 'Whodiv')
            {
                selectedWhoDiv=(selectedWhoDiv<Count)? selectedWhoDiv+1 : 1;
                document.getElementById(pageNolabel).innerHTML = selectedWhoDiv + " of "+Count ;
                SetImgContent('Whoimgdiv',selectedWhoDiv);
                selectedpage = selectedWhoDiv;
             }
            else if(DivId == 'Whatdiv')
             {
                selectedWhatDiv=(selectedWhatDiv<Count)? selectedWhatDiv+1 : 1;
                document.getElementById(pageNolabel).innerHTML = selectedWhatDiv + " of "+Count ;
                SetImgContent('Whatimgdiv',selectedWhatDiv);
                selectedpage = selectedWhatDiv;
              }
            selectedDivObj=document.getElementById(DivId+selectedpage);      
            selectedDivObj.style.display="block";
            
            }
            else if(Direction == 'B')
            {
            previousDivObj=document.getElementById(DivId+selectedpage);
            previousDivObj.style.display="none";
             if(DivId == 'Whodiv')
            {
                selectedWhoDiv=(selectedWhoDiv>1)? selectedWhoDiv-1 : Count;
                document.getElementById(pageNolabel).innerHTML = selectedWhoDiv + " of "+Count ;
                SetImgContent('Whoimgdiv',selectedWhoDiv);
                selectedpage = selectedWhoDiv;
             }
             else if(DivId == 'Whatdiv')
             {
                 selectedWhatDiv=(selectedWhatDiv>1)? selectedWhatDiv-1 : Count;
                 document.getElementById(pageNolabel).innerHTML = selectedWhatDiv + " of "+Count ;
                SetImgContent('Whatimgdiv',selectedWhatDiv);
                 selectedpage = selectedWhatDiv;
             }
            selectedDivObj=document.getElementById(DivId+selectedpage);
            selectedDivObj.style.display="block";
            }
    }
}
var count = 0;
function ToggleLatestDiv(DivName)
{
    //count = 0;
    //maximisepanel(DivName);
    document.getElementById(DivName).style.display = "";
    document.getElementById(DivName+'Img').src = "/template-images/_/layout/homepage/arrow_down.png";
   if(DivName == 'LatestEvents')
   {
        /*if(document.getElementById('LatestShouts').style.display == "")
        {
            count=0;
            minimisepanel('LatestShouts');
        }
        if(document.getElementById('LatestNews').style.display == "")
        {
            count=0;
            minimisepanel('LatestNews');
        }*/
        
        document.getElementById('LatestShouts').style.display = "none";
        document.getElementById('LatestShoutsImg').src = "/template-images/_/layout/homepage/arrow_right.png";
        document.getElementById('LatestNews').style.display = "none";
        document.getElementById('LatestNewsImg').src = "/template-images/_/layout/homepage/arrow_right.png";
    }
    else if(DivName == 'LatestShouts')
    {
         /*if(document.getElementById('LatestEvents').style.display == "")
        {
            count=0;
            minimisepanel('LatestEvents');
        }
        if(document.getElementById('LatestNews').style.display == "")
        {
            count=0;
            minimisepanel('LatestNews');
        }*/
        document.getElementById('LatestNews').style.display = "none";
        document.getElementById('LatestNewsImg').src = "/template-images/_/layout/homepage/arrow_right.png";
        document.getElementById('LatestEvents').style.display = "none";
        document.getElementById('LatestEventsImg').src = "/template-images/_/layout/homepage/arrow_right.png";
    }
    else if(DivName == 'LatestNews')
    {
       /*if(document.getElementById('LatestShouts').style.display == "")
        {
            count=0;
            minimisepanel('LatestShouts');
        }
        if(document.getElementById('LatestEvents').style.display == "")
        {
            count=0;
            minimisepanel('LatestEvents');
        }*/
        document.getElementById('LatestShouts').style.display = "none";
        document.getElementById('LatestShoutsImg').src = "/template-images/_/layout/homepage/arrow_right.png";
        document.getElementById('LatestEvents').style.display = "none";
        document.getElementById('LatestEventsImg').src = "/template-images/_/layout/homepage/arrow_right.png";
    }
}
var iHeight = 295;
var collapseStep = 10 ;
var Speed = 2;
var defaultheight = 295;
var mindefaultheight = 5;
function maximisepanel(DivId)
{ 
          try
          {
               var  objDiv = document.getElementById(DivId);
                 if(count == 0)
                 {
                      objDiv.style.height = mindefaultheight+'px';
                      objDiv.style.filter =  'alpha(opacity=0)';
                      objDiv.style.opacity = 0;
                      if(DivId == 'LatestNews')
                          document.getElementById("Latestnewstable").style.display = "none";
                      else if(DivId == 'LatestEvents')
                           document.getElementById("Latesteventstable").style.display = "none";
                 }
                objDiv.style.display = "";
                var t = parseInt(objDiv.style.height);
                objDiv.style.opacity = t/iHeight;
                objDiv.style.filter = 'alpha(opacity='+(t/iHeight)*100+')';
                if(t == 295)
                {
                     if(DivId == 'LatestNews')
                        document.getElementById("Latestnewstable").style.display = "";
                     else if(DivId == 'LatestEvents')
                           document.getElementById("Latesteventstable").style.display = "";
                 }
                if(t<=(iHeight-collapseStep))
                {	
                        t=t+collapseStep ;
                        count = count +1;
    	     objDiv.style.height = t+'px';
    	     setTimeout( "maximisepanel('"+DivId+"');",Speed);
                }
            }
            catch(e)
            {
                  if(DivId == 'LatestNews')
                        document.getElementById("Latestnewstable").style.display = "";
                  else if(DivId == 'LatestEvents')
                         document.getElementById("Latesteventstable").style.display = "";
            }
}
/*function minimisepanel(DivId)
{
             try
             {
                    var objDiv = document.getElementById(DivId);
                      if(count == 0)
                      {
                          objDiv.style.height = defaultheight+'px';
                           objDiv.style.filter =  'alpha(opacity=100)';
                           objDiv.style.opacity = 1;
                             if(DivId == 'LatestNews')
                                  document.getElementById("Latestnewstable").style.display = "none";
                              else if(DivId == 'LatestEvents')
                                   document.getElementById("Latesteventstable").style.display = "none";
                       }
                  
                        var t = parseInt(objDiv.style.height);
                        objDiv.style.opacity = (iHeight/t);
                       objDiv.style.filter = 'alpha(opacity=' + (iHeight/t)/100 + ')';
                        if(t>0)
                        {	t=t-collapseStep ;
                                       count = count +1;
                                       if(t<=0)
                                            {
                                                objDiv.style.display = "none";
                                            }
                                            else
                                            {
                        	objDiv.style.height = t+'px';
                        	setTimeout( "minimisepanel('"+DivId+"');",Speed);
                        	}
                        }
               }
               catch(e)
               {
               }
}*/
function ValidatePostcode(Type)
{
    var myPostCode = document.getElementById('postcode'+Type).value;
    if (!checkPostCode (myPostCode)) 
    {
       if(myPostCode.toUpperCase() != 'IRELAND')
       {
            alert ("Postcode has invalid format");
            return false;
       }
    }
}
/*==============================================================================

Parameters:    toCheck - postcodeto be checked. 

This function checks the value of the parameter for a valid postcode format. The 
space between the inward part and the outward part is optional, although is 
inserted if not there as it is part of the official postcode.

If the postcode is found to be in a valid format, the function returns the 
postcode properly formatted (in capitals with the outward code and the inward
code separated by a space. If the postcode is deemed to be incorrect a value of 
false is returned.
-----------------------------------------------------------------------------*/

function checkPostCode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}
function GetProtocol(Name)
{
   var FinalProtocol = '';
   if(Name == 'h' || Name == 'http')
       FinalProtocol = 'http://';
    else if(Name == 'f' || Name == 'ftp')
       FinalProtocol = 'ftp://';
     else if(Name == 'm' || Name == 'mailto')
       FinalProtocol = 'mailto:';
     else if(Name == 'hs' || Name == 'https')
       FinalProtocol = 'https://';
    
     return FinalProtocol;
}
function ChangeKeyMessage(IndImageId,Imagesrc,Imagealt,LinkMain,LinkProtocol,LinkTarget)
{
   var SmallImgId = document.getElementById(IndImageId);
   ClearAllBorders();
   SmallImgId.style.borderColor = '#000066';
   SmallImgId.style.borderWidth = '3px';
   SmallImgId.style.borderStyle = 'solid';
    var KeyImgId = document.getElementById('KeyMessage');
    KeyImgId.src = Imagesrc;
    KeyImgId.alt = Imagealt;
    KeyImgId.title = Imagealt;
    var KeyImgAlt = document.getElementById('KeyMessagealt');
    KeyImgAlt.href = GetProtocol(LinkProtocol)+LinkMain;
    if(LinkTarget != '')
        KeyImgAlt.target = LinkTarget;
}
function SetDelayKeyMessage()
{
    setTimeout( "RotateKeyImages();",7000);
}
function RotateKeyImages()
{
    if(( document.getElementById('keymessage1').style.borderColor.indexOf('rgb(0, 0, 102)') != -1  ||  document.getElementById('keymessage1').style.borderColor.indexOf('#000066') != -1 ) && (document.getElementById('keymessage1').style.borderWidth.indexOf('3px') != -1))
    {
         var objImg2 = document.getElementById('keymessage2');
         objImg2.onclick();
         setTimeout( "RotateKeyImages();",7000);
    }
    else if(( document.getElementById('keymessage2').style.borderColor.indexOf('rgb(0, 0, 102)') != -1  ||  document.getElementById('keymessage2').style.borderColor.indexOf('#000066') != -1 ) && (document.getElementById('keymessage2').style.borderWidth.indexOf('3px') != -1))
    {
         var objImg3 = document.getElementById('keymessage3');
         objImg3.onclick();
         setTimeout( "RotateKeyImages();",7000);
    }
    else if(( document.getElementById('keymessage3').style.borderColor.indexOf('rgb(0, 0, 102)') != -1  ||  document.getElementById('keymessage3').style.borderColor.indexOf('#000066') != -1 ) && (document.getElementById('keymessage3').style.borderWidth.indexOf('3px') != -1))
    {
         var objImg4 = document.getElementById('keymessage4');
         objImg4.onclick();
         setTimeout( "RotateKeyImages();",7000);
    }
    else if(( document.getElementById('keymessage4').style.borderColor.indexOf('rgb(0, 0, 102)') != -1  ||  document.getElementById('keymessage4').style.borderColor.indexOf('#000066') != -1 ) && (document.getElementById('keymessage4').style.borderWidth.indexOf('3px') != -1))
    {
         var objImg1 = document.getElementById('keymessage1');
         objImg1.onclick();
         setTimeout( "RotateKeyImages();",7000);
    }
}

function ClearAllBorders()
{
   document.getElementById('keymessage1').style.borderColor = '';
   document.getElementById('keymessage1').style.borderWidth ='';
   document.getElementById('keymessage1').style.borderStyle='';
   document.getElementById('keymessage2').style.borderColor = '';
   document.getElementById('keymessage2').style.borderWidth ='';
   document.getElementById('keymessage2').style.borderStyle='';
   document.getElementById('keymessage3').style.borderColor = '';
   document.getElementById('keymessage3').style.borderWidth ='';
   document.getElementById('keymessage3').style.borderStyle='';
   document.getElementById('keymessage4').style.borderColor = '';
   document.getElementById('keymessage4').style.borderWidth ='';
   document.getElementById('keymessage4').style.borderStyle='';
}

/*New Home page changes*/
function RedirectToPage(tourl){
	window.location.href = tourl;
}

//checks the user agent string and sees whether it is a mobile device ... this is likely to break as browsers change.
/*function mobileRedirect(){
	var userAgentString = navigator.userAgent;

    userAgentString = userAgentString.toLowerCase();

    var mobiles = ['blackberry', 'iphone', 'android', 'ipod', 'iemobile', 'msie', 'windows ce', 'symbianos', 'opera mini', 'webos'];

    for(var i = 0; i < mobiles.length; i++){
        if(userAgentString.indexOf(mobiles[i])> -1){
            //If the request isn't from the mobile website and is on the homepage then do the redirect
            if(!isFromMobi() && isHomePage()){
			        window.location = "http://www.rnli.mobi";
            }
        }
    }
}*/

// checks whether if the web request is coming from mobi website
// checks to see if the query string exists
/*function isFromMobi(){
    var queryStringParams = param();
	
    if(queryStringParams.from_mobile == "true"){
        return true;
    }
    return false;
}*/

//checks that the page is the RNLI homepage
/*function isHomePage(){
    if((location.host == "www.rnli.org.uk") && (location.pathname = "")){
        return true;
    }
    return false;
}*/
