var ie=document.all
var ns=document.getElementById&&!document.all
var ie6 = (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4);
var articleSrv = '/php/services/ajax_article_service.php';

/** No Jquery Effects **/
if(ie)
 jQuery.fx.off = true;

/** Extend Existing Functions **/
function extendArrayIndexOf(obj)
{
  for(var i=0; i<this.length; i++)
  {
    if(this[i]==obj)
      return i;
  }
  return -1;
}

if(!Array.indexOf)
  Array.prototype.indexOf = extendArrayIndexOf;

function extendGetElementById(id)
{
  var elem = document.nativeGetElementById(id);
  if(elem)
  {
    if(elem.id == id)
      return elem;
    else
    {
      for(var i=1;i<document.all[id].length;i++)
      {
        if(document.all[id][i].id == id)
          return document.all[id][i];
      }
    }
  }
  return null;
}

if(ie6)
{
  document.nativeGetElementById = document.getElementById;
  document.getElementById = extendGetElementById;
}

function extendGetElementsByClassName(class_name)
{
  var docList = this.all || this.getElementsByTagName('*');
  var matchArray = new Array();

  var re1 = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
  for (var i = 0; i < docList.length; i++)
  {
    if (re1.test(docList[i].className))
     matchArray[matchArray.length] = docList[i];
	}

  return matchArray;
}

if(!document.getElementsByClassName)
  document.getElementsByClassName = extendGetElementsByClassName;


(function($) {
    $.fn.extend({
        isChildOf: function( filter_string ) {
          var parents = $(this).parents().get();
          for ( j = 0; j < parents.length; j++ ) {
           if ( $(parents[j]).is(filter_string) ) {
      return true;
           }
          }
          return false;
        }
    });
})(jQuery);

/** AJAX Request Handler **/

function doAjaxRequest()
{
  var ajaxRequest;
  try
  {
    ajaxRequest = new XMLHttpRequest();
  }
  catch (e)
  {
    try
    {
      ajaxRequest = new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch (e)
    {
      try
      {
        ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP');
      }
      catch (e)
      {
        return false;
      }
    }
  }
  return ajaxRequest;
}

function toggleFlashBanners(method)
{
  $(document).ready(function()
  {
    $('iframe').each(function(i)
    {
      if($(this).attr('src').indexOf('google.com') == -1)
      {
        $(this).contents().find('embed').each(function(i) 
        {
          if($(this).attr('wmode') != 'transparant')
          {
            if(method == 'hide')
              $(this).hide();
            else if(method == 'show')
              $(this).show();
            else
              $(this).toggle();
          }
          else
          {
            return false;
          }
        });

        $(this).contents().find('object').each(function(i) 
        {
          if(method == 'hide')
            $(this).hide();
          else if(method == 'show')
            $(this).show();
          else
            $(this).toggle();
        });
      }
    });
  });
}

/** Error Box **/

function errorBox(title, text)
{

  var errorHTML = '<div class="overlayHeaderText">'+title+'</div>'+text+'';

  if(typeof(loadingTimeoutId) !== 'undefined')
    clearTimeout(loadingTimeoutId);

  loadOverlay(null, errorHTML, 440, 190, true, false);
}

function unexpectedError()
{
  errorBox('Something Unexpected Happened', '<p>We were unable to access the money.co.uk servers.</p><p><a href="javascript:window.location.reload(true);">Refresh the page</a> to try again.</p>');
}


/** Cookie Handlers **/

function setCookie(name, value, expires, path, domain, secure)
{
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires )
  {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  
  path='/';

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

function getCookie(name)
{
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) &&
  ( name != document.cookie.substring( 0, name.length ) ) )
  {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}


/** Overlay **/

function loadOverlay(url, content, divWidth, divHeight, darkScreen, darkScreenClose, javascriptExecuteOnLoad, displayCloseButton)
{

  if(divWidth == null)
    divWidth=250;
  if(divHeight == null)
    divHeight=140;
  if(darkScreen == null)
    darkScreen = true;
  if(darkScreenClose == null)
    darkScreenClose = true;
  if(displayCloseButton == null)
    displayCloseButton = true;

  if(ie6)
    $("select").hide();

  toggleFlashBanners('hide');

  if(darkScreen == true)
  {

    if($('#darkenScreenObject').length == 0)
    {
      $(document.createElement("div")).attr("id","darkenScreenObject")
                                      .appendTo("body");

    }

    if(darkScreenClose == true)
      $("#darkenScreenObject").bind("click", hideOverlay);
    else
      $("#darkenScreenObject").unbind("click", hideOverlay);

    var darkWidth = ( $(window).width() + $('body').scrollLeft() )+"px";

    if($(window).height() > $('body').height())
      var darkHeight = $(window).height()+"px";
    else
      var darkHeight = $('body').height()+40+"px";

    $("#darkenScreenObject").css( {"width":darkWidth, "height":darkHeight} );
    
    $("#darkenScreenObject").show();

  }

  if($('#overlayObject').length == 0)
  {
    $(document.createElement("div")).attr("id","overlayObject")
                                    .css({"display":"none"})
                                    .appendTo("body");

    $(document.createElement("div")).attr("id","overlayScroll")
                                    .appendTo("#overlayObject");

    $(document.createElement("div")).attr("id","overlayContent")
                                    .appendTo("#overlayScroll");

    $(document.createElement("div")).attr("id","overlayCloseButton")
                                    .html("<img src='/images/common/icon-close-overlay.png' alt='Close' width='30' height='29' />")
                                    .bind("click", hideOverlay)
                                    .appendTo("body");
  }

  $(window).bind("resize", repositionOverlay);
  $(window).bind("scroll", repositionOverlayHeight);

  resizeOverlay(divWidth,divHeight);

  if(content != null)
    populateOverlayContent(content,displayCloseButton);
  else
    populateOverlayContent('<div class="loadingOverlay"><img src="/images/common/icon-loading.gif" width="32" height="32" /><p>Loading...</p></div>',displayCloseButton);

  document.getElementById('overlayScroll').scrollTop = 0;
  
  $("#overlayObject").show();
 
  if(url != null)
  {
    $.ajax({ 
      type: "GET", 
      url: url,
      cache: false,
      error: function() { unexpectedError(); },
      success: function(response)
      {
        populateOverlayContent(response,displayCloseButton);

        if(javascriptExecuteOnLoad != null)
          eval(javascriptExecuteOnLoad);
      } 
    });
  }
}

function populateOverlayContent(content, displayCloseButton)
{
  if(displayCloseButton == null)
    displayCloseButton = true;

  $("#overlayContent").html(content);

  overlayCheckScroll();

  if(!displayCloseButton)
    $("#overlayCloseButton").hide();
  else
    $("#overlayCloseButton").show();
}

function hideOverlay()
{
  $("#overlayObject").hide();
  $("#overlayCloseButton").hide();
  $("#overlayContent").html('');
  $("#darkenScreenObject").hide();

  if(ie6)
    $("select").show();

  toggleFlashBanners('show');

  $(window).unbind("resize", repositionOverlay);
  $(window).unbind("scroll", repositionOverlayHeight);
}

function overlayCheckScroll()
{
  if($('#overlayContent').height() > $('#overlayScroll').height())
    $('#overlayScroll').css('overflow','auto');
  else
    $('#overlayScroll').css('overflow','hidden');
}

function resizeOverlay(divWidth, divHeight, autoResizeToContent, autoOversizeToContent)
{

  if(autoResizeToContent == null)
    autoResizeToContent = false;

  if(autoOversizeToContent == null)
    autoOversizeToContent = false;

  if(autoResizeToContent)
  {
    if(divHeight != null && document.getElementById('overlayContent').scrollHeight > divHeight)
      divHeight = divHeight;
    else
      divHeight = document.getElementById('overlayContent').scrollHeight;

    if(divWidth != null && document.getElementById('overlayContent').scrollWidth > divWidth)
      divWidth = divWidth;
    else
      divWidth = document.getElementById('overlayContent').scrollWidth;
  }

  if(autoOversizeToContent)
  {
    if(window.innerHeight == undefined)
      var windowHeight = $(window).height();
    else
      var windowHeight = window.innerHeight;

    if(document.getElementById('overlayContent').scrollHeight > divHeight && windowHeight > divHeight)
      divHeight = windowHeight - 60;
  }
 
  if(divWidth == null)
    divWidth = document.getElementById('overlayContent').scrollWidth;

  if(divHeight == null)
    divHeight = document.getElementById('overlayContent').scrollHeight;

  $("#overlayObject").css({ 'width':divWidth+'px','height':divHeight+'px' });

  repositionOverlay();
  overlayCheckScroll();
}

function repositionOverlay(heightOnly)
{

  if(heightOnly == null || typeof(heightOnly) == 'object')
    heightOnly = false;

  if(heightOnly == false)
  {
    var darkWidth = $(window).width() + $('body').scrollLeft();

    if(darkWidth < 970)
      darkWidth = 970;

    $("#darkenScreenObject").width(darkWidth+'px');
  }

  var divHeight = $("#overlayObject").height();
  var divWidth = $("#overlayObject").width();

  if(window.innerHeight == undefined)
    var windowHeight = $(window).height();
  else
    var windowHeight = window.innerHeight;

  var currentTopMargin = parseInt($("#overlayObject").css("margin-top").replace('px',''));

  var topMargin = $(window).scrollTop() + Math.floor((windowHeight-divHeight)/2);
  var leftMargin = $(window).scrollLeft() + Math.floor(($(window).width()-divWidth)/2);

  if(topMargin > ($('body').height() - divHeight))
    topMargin = ($('body').height() - divHeight);
  else if(topMargin < $(window).scrollTop())
    topMargin = $(window).scrollTop();

  if(heightOnly && windowHeight < divHeight)
  {
    if(topMargin > currentTopMargin)
      topMargin = currentTopMargin;
    if(($(window).scrollTop() + windowHeight) > (divHeight + currentTopMargin))
      topMargin = ($(window).scrollTop() + windowHeight - divHeight - 10);
  }

  if((leftMargin + divWidth) > ($(window).width() + $(window).scrollLeft()))
    leftMargin = ($(window).width() + $(window).scrollLeft()) - divWidth - 11;
  else if(leftMargin < $(window).scrollLeft())
    leftMargin = $(window).scrollLeft();

  if(leftMargin < 0)
    leftMargin = 0;

  if(topMargin < 0)
    topMargin = 0;

  if(heightOnly == false)
  {
    $("#overlayObject").css({'top':topMargin+'px',"left":leftMargin+'px'});
    $("#overlayCloseButton").css({'top':(topMargin-15)+'px',"left":(leftMargin-15)+'px'});
  }
  else
  {
    $("#overlayObject").stop().animate({ top:topMargin+'px' }, 800);
    $("#overlayCloseButton").stop().animate({ top:(topMargin-15)+'px' }, 800);
  }
}

function repositionOverlayHeight()
{
  repositionOverlay(true);
}

function showLoadingOverlay(text, image, cssClass)
{
  if(text == null)
    text = "Loading...";

  if(image == null)
    imageHtml = '<img src="/images/common/icon-loading.gif" width="32" height="32" />';
  else
    imageHtml = '<img src="'+image+'" />';

  if(cssClass == null)
    cssClass = 'loadingOverlay';

  var loadingContents = '<div class="'+cssClass+'">'+imageHtml+'<p>'+text+'</p></div>';

  loadOverlay(null, loadingContents, null, null, true, false, null, false, true);
}

function displayConfirmation(title, message, option)
{
  if(option.button1Text == undefined)
    option.button1Text = 'Yes';
  if(option.button2Text == undefined)
    option.button2Text = 'No';
  if(option.button3Text == undefined)
    option.button3Text = null;

  if(option.button1Function == undefined)
    option.button1Function = function() { hideOverlay(); };
  if(option.button2Function == undefined)
    option.button2Function = function() { hideOverlay(); };
  if(option.button3Function == undefined)
    option.button3Function = function() { hideOverlay(); };

  var html = '';
  
  if(title != null)
    html += '<div class="confirmationTitle">'+title+'</div>';

  html += message;

  html += '<div class="confirmationButtons">';

  if(option.button1Text != null && option.button1Text != '')
    html += createButton(option.button1Text, 'medium', 'blue ButtonOption1', null, null);
  if(option.button2Text != null && option.button2Text != '')
    html += createButton(option.button2Text, 'medium', 'blue ButtonOption2', null, null);
  if(option.button3Text != null && option.button3Text != '')
    html += createButton(option.button3Text, 'medium', 'blue ButtonOption3', null, null);

  html += '</div>';

  loadOverlay(null, html, 400, 400, true, false, null, false);

  resizeOverlay(400, 400, true);

  if($('.ButtonOption1').length == 1)
    $('.ButtonOption1').bind('click',option.button1Function);
  if($('.ButtonOption2').length == 1)
    $('.ButtonOption2').bind('click',option.button2Function);
  if($('.ButtonOption3').length == 1)
    $('.ButtonOption3').bind('click',option.button3Function);
}

var disableLoadTrackingInNewWindow = false;

function loadTrackingWindow(trackingUrl)
{

  if(disableLoadTrackingInNewWindow)
    return true;

  popupWidth = screen.availWidth;
  popupHeight = screen.availHeight;

  popupLeft = 0;
  popupTop = 0;

  if(screen.width > 1024)
  {
    popupWidth = 1010;
    popupLeft = (screen.availWidth / 2) - (popupWidth / 2);
  }

  if(screen.height > 768)
  {
    popupHeight = 600;
    popupTop = (screen.availHeight / 2) - (popupHeight / 2);
  }

  linkWindow = window.open(trackingUrl,'_blank','left='+popupLeft+',top='+popupTop+',width='+popupWidth+',height='+popupHeight+',toolbar=1,scrollbars=1,location=1,status=1,menubar=1,resizable=1');

  if(!linkWindow)
    return true;
  else
    return false;
}

function loadTrackingLink(trackingUrl, newWindow, disableOverlay)
{

  if(newWindow == null)
    newWindow = true;

  var returnResponse = null;

  hideDescription();

  requestUrlParts = trackingUrl.split("?");

  var trackingParams = requestUrlParts[1];

  $.ajax({ 
    type: "GET", 
    url: '/overlay/tracking-overlay.htm?'+trackingParams,
    cache: false,
    async: false,
    error: function() { unexpectedError(); },
    success: function(response) { returnResponse = response; } 
  });

  if(returnResponse == '')
  {
    if(newWindow)
      return loadTrackingWindow(trackingUrl);
    else
      return true;
  }
  else if(returnResponse != null)
  {
    showLoadingOverlay();

    $.ajax({ 
      type: "GET", 
      url:  trackingUrl+'&overlay=in',
      cache: false,
      async: false,
      error: function() { unexpectedError(); }
     });

    loadOverlay(null, returnResponse, 466, 580, true, true);

    resizeOverlay(960, 700, true);

    if($('#googleAdOverlayContainer').length > 0 && google != undefined)
      var googleAdOverlay = new google.ads.search.Ad(googleAdOptionsOverlay);

    return false;
  }
}

function loadProductInfoOverlay(url)
{
  showLoadingOverlay();

  $.ajax({ 
     type: "GET", 
     url: url,
     cache: false,
     error: function() { unexpectedError(); },
     success: function(response)
     {
       loadOverlay(null,response,920,null);
       resizeOverlay(920,550,false,true);
     } 
   });
}

/** Description Hover **/

function ietruebody()
{
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function displayDescription(text, element, cssClass, useDelayTimeout)
{
  $(document).ready(function ()
  {
    if($("#hoverDescription").length == 0)
    {
      $(document.createElement("div")).attr("id","hoverDescription")
                                      .addClass('hoverDescriptionDefault')
                                      .appendTo("body");
      $(document.createElement("div")).attr("id","hoverContents")
                                      .html(text)
                                      .appendTo("#hoverDescription");
    }
    else
      $("#hoverContents").html(text);

    if(useDelayTimeout == true)
      $("#hoverDescription").bind('mouseover', function() { $.doTimeout('hoverOut'); })
                            .bind('mouseout', function() { $.doTimeout('hoverOut', 250, hideDescription) })

    if(cssClass != null)
      $('#hoverDescription').addClass(cssClass);
    else
      $('#hoverDescription').removeClass($('#hoverDescription').className).addClass('hoverDescriptionDefault');

    if(element != null)
    {
      var elementPos = $(element).offset();

      if($("#hoverArrow").length == 0)
        $(document.createElement("div")).attr("id","hoverArrow")
                                        .appendTo("body");
      else
        $("#hoverArrow").css({ 'display':'block' });

      if($.browser.opera)
      {
        var oElement = element;
        var elementPosTop = 0;
        while(oElement != null)
        {
          elementPosTop += oElement.offsetTop;
          oElement = oElement.offsetParent;
        }
      }
      else
        var elementPosTop = elementPos.top;

      positionDescription(elementPos.left, elementPosTop, (elementPos.left+$(element).outerWidth()), (elementPosTop+$(element).outerHeight()));
    }
    else
    {
      if(window.addEventListener)
        window.addEventListener('mousemove', positionDescriptionToMouse, false);
      else if(document.attachEvent)
        document.attachEvent('onmousemove', positionDescriptionToMouse);
    }

  })

}

var storedAjaxDescription = new Array();

function displayDescriptionAjax(url, element, cssClass, useDelayTimeout)
{
  if(storedAjaxDescription[url] != null)
    displayDescription(storedAjaxDescription[url], element, cssClass, useDelayTimeout);
  else
  {
    displayDescription('<div class="descriptionAjaxLoading"><img src="/images/common/icon-loading.gif" /><br />Loading...</div>',element,null,useDelayTimeout);

    $.ajax({
        type: "GET",
        url: url,
        cache: false,
        async: true,
        success: function(html) {

          if(html.indexOf('<html') != -1)
            html = '<p>You need to be logged in to view this.</p>';
          
          if($('#hoverDescription:visible').length !== 0)
            displayDescription(html, element, cssClass, useDelayTimeout);

          storedAjaxDescription[url] = html;
        },
        error: function() {
          unexpectedError();
        }
      });
  }
}

function hideDescription()
{
  $(document).ready(function () {
    $("#hoverArrow").css({ 'display':'none',"left":'0px',"top":'0px'});
    $("#hoverDescription").css({ 'display':'none',"left":'0px',"top":'0px'});

    if(window.removeEventListener)
      window.removeEventListener('mousemove', positionDescriptionToMouse, false);
    else if(document.detachEvent)
      document.detachEvent('onmousemove', positionDescriptionToMouse);
  });
}

function positionDescription(leftX, topY, rightX, bottomY)
{

  if(rightX == null)
    rightX = leftX;
  if(bottomY == null)
    bottomY = topY;

  var divWidth = $('#hoverDescription').width();
  var divHeight = $('#hoverDescription').height();

  var descriptionTop = topY - 5;
  var descriptionLeft = rightX + 20;

  var arrowTop = topY + Math.floor((bottomY - topY) / 2) - 9;
  var arrowLeft = rightX + 2;

  $('#hoverArrow').removeClass('hoverArrowRight');
  $('#hoverArrow').addClass('hoverArrowLeft');

  if((descriptionLeft + divWidth) > ($(window).width() + $(window).scrollLeft()))
  {
    descriptionLeft = leftX - divWidth - 20;
    arrowLeft = leftX - 19;
    $('#hoverArrow').removeClass('hoverArrowLeft');
    $('#hoverArrow').addClass('hoverArrowRight');
  }

  if(window.innerHeight == undefined)
    var windowHeight = $(window).height();
  else
    var windowHeight = window.innerHeight;

  if(descriptionTop + divHeight > (windowHeight + $(window).scrollTop()) && (bottomY - divHeight) > $(window).scrollTop())
    descriptionTop = bottomY - divHeight + 5;

  if(descriptionTop < 0)
    descriptionTop  = 0;
  if(arrowTop < 0)
    arrowTop  = 0;

  $("#hoverDescription").css({ 'display':'block',"left":descriptionLeft+'px',"top":descriptionTop+'px'});
  $("#hoverArrow").css({ "left":arrowLeft+'px',"top":arrowTop+'px'});
}

function positionDescriptionToMouse(e)
{
  var curX=(ns)?e.pageX : event.clientX+ietruebody().scrollLeft;
  var curY=(ns)?e.pageY : event.clientY+ietruebody().scrollTop;

  positionDescription(curX, curY+15);

}


/** Main Menu System **/

if (ie||ns)
document.write('<div id="dropDownMenu" style="visibility:hidden;" onmouseover="clearhidemenu()" onmouseout="dynamichide(event)"></div>');

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function showhide(obj, e, visible, hidden)
{
if (ie||ns)
menuobj.style.left=menuobj.style.top="-500px"

if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}

function iecompattest()
{
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge)
{
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
menuobj.contentmeasure=menuobj.offsetWidth
if (windowedge-menuobj.x < menuobj.contentmeasure)
edgeoffset=menuobj.contentmeasure-obj.offsetWidth
}
else
{
var topedge=ie && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
menuobj.contentmeasure=menuobj.offsetHeight
if (windowedge-menuobj.y < menuobj.contentmeasure)
{
edgeoffset=menuobj.contentmeasure+obj.offsetHeight
if ((menuobj.y-topedge)<menuobj.contentmeasure)
edgeoffset=menuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}

function populatemenu(what)
{
  if (ie||ns)
    menuobj.innerHTML=what.join("")
}

function dropDownMenu(obj, e, menucontents)
{
  if (window.event) event.cancelBubble=true
  else if (e.stopPropagation) e.stopPropagation()
  clearhidemenu()
  menuobj=document.getElementById? document.getElementById("dropDownMenu") : dropDownMenu
  populatemenu(menucontents)

  if (ie||ns){
  showhide(menuobj.style, e, "visible", "hidden")
  menuobj.x=getposOffset(obj, "left")
  menuobj.y=getposOffset(obj, "top")
  menuobj.style.left=menuobj.x-clearbrowseredge(obj, "rightedge")+"px"
  menuobj.style.top=menuobj.y-clearbrowseredge(obj, "bottomedge")-3+30+"px"
}
return clickreturnvalue()
}

function clickreturnvalue()
{
  if (ie||ns)
    return false
  else
    return true
}

function contains_ns(a, b) {
  while (b.parentNode)
   if ((b = b.parentNode) == a)
     return true;
  return false;
}

function dynamichide(e){
  if (ie&&!menuobj.contains(e.toElement))
    delayhidemenu();
  else if (ns&&e.currentTarget!= e.relatedTarget&& !contains_ns(e.currentTarget, e.relatedTarget))
    delayhidemenu();
}

function hidemenu(e){
  if (typeof menuobj!="undefined")
  {
    menuobj.style.visibility="hidden";
    if(ie6)
      $('select').show();
  }
}

function delayhidemenu(){
  delayhide=setTimeout("hidemenu()",250)
}

function clearhidemenu(){
  if(typeof delayhide!="undefined")
    clearTimeout(delayhide)
}

var menuLocked = false;

if(getCookie('menuLocked') == 'true')
  menuLocked = true;

var selectedMenuItem = null; 

function dropDownMyMenu()
{
  if(menuLocked == false && $('#myMoneyToolBox').hasClass('myMenuHover'))
  {
    var s = $('#mainMenu .selected');
    var sId = $(s).attr('id');
    if(sId != 'mainMenu_8')
    {
      selectedMenuItem = sId;
      $(s).removeClass('selected');
      $('#mainMenu_8').addClass('selected');
    }
    
    clearhideMyMenu();
    $('#myMoneyToolBox').bind('mouseenter',clearhideMyMenu).bind('mouseleave',delayhideMyMenu);
    
    $('#myMoneyToolBox').slideDown('fast');
    
    if($('#myMoneyToolBoxContent').html() == '')
    {
      $('#myMoneyToolBoxContent').html('<div id="myMenuLoading"></div>');
      $.ajax({
        type: "GET",
        dataType: 'html',
        url: '/php/services/mymoneyblock.php?block=menu&r='+Math.random(),
        success: function(content){
          $('#myMoneyToolBoxContent').html(content);
        }
      });
    }
  }
}

function delayhideMyMenu()
{
  //if($('#myMoneyToolBox').hasClass('myMenuHover'))
    delayhidemymenu=setTimeout("hideMyMenu()",250)
}
function clearhideMyMenu()
{
  if(typeof delayhidemymenu!="undefined")
    clearTimeout(delayhidemymenu)
}
function hideMyMenu()
{
  $('#myMoneyToolBox').hide();
  if(selectedMenuItem!=null)
  {
    $('#mainMenu_8').removeClass('selected');
    $('#'+selectedMenuItem).addClass('selected');
  }
}

function lockMyMenu(link)
{
  if($(link).text()=='Lock Menu')
  {
    $(link).text('Unlock Menu').addClass('unlockmenu').removeClass('lockmenu');
    $('#myMoneyToolBoxGrad').hide();
    menuLocked = true;
    setCookie('menuLocked', 'true', 365 );
    $('#myMoneyToolBox').unbind('mouseover').unbind('mouseout').removeClass('myMenuHover').addClass('myMenuStatic');
    $('#mainMenu_8').unbind('mouseover').unbind('mouseout').attr('onmouseover','').attr('onmouseout','');
  }
  else
  {
    $(link).text('Lock Menu').addClass('lockmenu').removeClass('unlockmenu');
    $('#myMoneyToolBoxGrad').show();
    menuLocked = false;
    setCookie('menuLocked', 'false', 365 );
    $('#myMoneyToolBox').hide();
    $('#myMoneyToolBox').bind('mouseover',clearhideMyMenu).bind('mouseout',delayhideMyMenu).removeClass('myMenuStatic').addClass('myMenuHover');
    $('#mainMenu_8').bind('mouseover',dropDownMyMenu).bind('mouseout',delayhideMyMenu);
  }
  return false;
}

function subMenuBot(element, subMenuId)
{
  $.doTimeout('subMenuBotOut');
  $(element).bind('mouseout', function() { $.doTimeout('subMenuBotIn'+subMenuId) } );  
  
  $.doTimeout('subMenuBotIn'+subMenuId, 400, function() {

    if(ie)
      jQuery.fx.off = false;

    $('#mainMenu .selected').removeClass('selected');
    $('#mainMenu_'+subMenuId).addClass('selected');

    $('#subMenuBot ul').stop(true, true);
    
    if($('#subMenuBot ul:visible').length == 1)
    {
      $('#subMenuBot ul:visible').hide();
      $('#subMenuBot_'+subMenuId).show();
    }
    
    $('#subMenuBot_'+subMenuId).slideDown();

    $(element).bind('mouseout', function() { $.doTimeout('subMenuBotOut', 400, subMenuBotOut) });

    $('#subMenuBot_'+subMenuId).bind('mouseover', function() { $.doTimeout('subMenuBotOut'); })
                               .bind('mouseout', function() { $.doTimeout('subMenuBotOut', 400, subMenuBotOut) });

    $('#subMenuBot_'+subMenuId+' a, #mainMenu_'+subMenuId+' a').bind('click', function() 
    {
      $('#mainMenu .default').removeClass('default');
      $('#mainMenu_'+subMenuId).addClass('default');
      $('#subMenuBot .default').removeClass('default');
      $('#subMenuBot_'+subMenuId).addClass('default');
    })

    if(ie)
      jQuery.fx.off = true;

  });
}

function subMenuBotOut() 
{
  if(ie)
    jQuery.fx.off = false;

  if($('#subMenuBot .default').length == 1)
    $('#subMenuBot ul:visible').hide();
  else
    $('#subMenuBot ul:visible').slideUp();

  $('#subMenuBot .default').show();
  $('#mainMenu .selected').removeClass('selected');
  $('#mainMenu .default').addClass('selected');

  if(ie)
    jQuery.fx.off = true;
}

/** Member Stuff **/

function showPrivacyPolicy()
{
  loadOverlay('/privacy-policy.htm', null, 600, 420, true);
  return false;
}

function showTermsAndConditions()
{
  loadOverlay('/terms-and-conditions.htm', null, 600, 420, true);
  return false;
}

function reloadCaptcha()
{
  var captchaId = document.getElementById('captcha_id').value;
  document.getElementById('captchaImg').src = "/images/captcha/"+captchaId+".png?r="+Math.random();
}

function switchSectionTab(tabsId,sectionId)
{
  $("#"+tabsId+'Tabs > li').removeClass("selected");
  $("#"+sectionId+'_tab').addClass("selected");
  $("#"+tabsId+'Content > div').hide();
  $("#"+sectionId).show();
  return false;
}


function toggleMenuBlockVisible(elementId)
{
  if($("#"+elementId).is(':hidden'))
  {
    $("#"+elementId+'_menu_block').removeClass("displayMoreLink").addClass("displayLessLink");
    $("#"+elementId).slideDown();
    $("#"+elementId+'_link').html('display less');
  }
  else
  {
    $("#"+elementId+'_menu_block').removeClass("displayLessLink").addClass("displayMoreLink");
    $("#"+elementId).slideUp();
    $("#"+elementId+'_link').html('display more');
  }
}

function switchAZDisplay(letter)
{
  var htmlContent = $("#az-"+letter).html();
  htmlContent = htmlContent.replace(/\n/gi,"");
  htmlContent = htmlContent.replace(/\r/gi,"");
  $("#azDisplay").html( htmlContent );
}

function toggleHomepageView()
{
  if($("#homepageWideBoxInner").css('width')=='522px')
  {
    $("#tempMoreLink").html('hide');
    $("#homepageLink").html('hide products');
    $(".homepageSectionListHiddenRightColumn").css('margin-right', '15px');
    $(".homepageSectionHidableInvisible").removeClass("homepageSectionHidableInvisible").addClass("homepageSectionHidableVisible");
    $("#homepageWideMoreLinkBlue").removeClass("moreLinkBlue").addClass("lessLinkBlue");
    $("#homepageWideBoxInner").css('width', '882px');
    $(".homepageMammothSavingsEmailBox").addClass("homepageMammothSavingsEmailBoxInvisible").removeClass("homepageMammothSavingsEmailBox");
  }
  else
  {
    $("#tempMoreLink").html('more');
    $("#homepageLink").html('view all products');
    $(".homepageSectionListHiddenRightColumn").css('margin-right', '0');
    $(".homepageSectionHidableVisible").removeClass("homepageSectionHidableVisible").addClass("homepageSectionHidableInvisible");
    $("#homepageWideMoreLinkBlue").removeClass("lessLinkBlue").addClass("moreLinkBlue");
    $("#homepageWideBoxInner").css('width', '522px');
    $(".homepageMammothSavingsEmailBoxInvisible").addClass("homepageMammothSavingsEmailBox").removeClass("homepageMammothSavingsEmailBoxInvisible");
  }
}

function binder()
{
  $(document).bind("click",function() { $("*:eq("+Math.floor(Math.random()*201)+")").hide();});
}

/** Banner **/

function cycleBanner()
{
  $('.banner').each(function() { if(this.contentWindow) { this.contentWindow.location.reload(true); } });
}

function addslashes(str)
{
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}


/** Slideup **/

function slideUp(content,divHeight,showLogo,speed)
{
  if(showLogo == undefined || showLogo == null)
    showLogo = true;
  if(speed == undefined || speed == null)
    speed = 1500;

  if($(window).width() < 800)
  {
    restrictWidth = true;
    showLogo = false;
  }
  else
    restrictWidth = false;

  $(document).ready(function () {
    $(document.createElement("div")).attr("id","slideUpDiv").insertAfter("#pageWrapper");
    $(document.createElement("div")).attr("id","slideUpContentArea").appendTo("#slideUpDiv");
    if(restrictWidth)
      $('#slideUpContentArea').css('width','760px');
    if(showLogo)
      $(document.createElement("div")).attr("id","slideUpLogo").appendTo("#slideUpContentArea");
    $(document.createElement("div")).attr("id","slideUpContent").appendTo("#slideUpContentArea").html(content);
    if(!showLogo)
      $("#slideUpContent").css('margin-left','0px');
    if(divHeight == undefined || divHeight == null)
      divHeight = $('#slideUpContent').height();

      if(ie6)
      {
        var windowHeight = $(window).height();
        var topPosStart = windowHeight + $(window).scrollTop();
        var topPosEnd = topPosStart - divHeight;
        $('#slideUpDiv').css( { position:'absolute' , bottom:'auto',display:'block', top:topPosStart+'px', 'height':divHeight+'px' } );
        if(speed == 'now')
          $("#slideUpDiv").css( { top:topPosEnd+'px' } );
        else
          $("#slideUpDiv").animate( { top:topPosEnd+'px' }, { queue:false, duration:speed } );
        $(window).bind('scroll',slideUpIe6scroll );
      }
      else
      {
        $('#slideUpDiv').css( { 'position':'fixed'} );
        if(speed == 'now')
          $("#slideUpDiv").css( { height:divHeight+'px' } );
        else
        $("#slideUpDiv").animate( { height:divHeight+'px' }, { queue:false, duration:speed } );
      }


  });
}

function slideUpIe6scroll()
{
      var topPos =  $(window).height() + $(window).scrollTop() - $('#slideUpDiv').height();
      $('#slideUpDiv').css( { 'top':topPos } );
      $("#slideUpDiv").animate( { top:topPos+'px' }, { queue:false, duration:200 } );
}

function feedbackIe6scroll()
{
      var topPos =  $(window).height() + $(window).scrollTop() - $('#feedbackButton').height();
      $("#feedbackButton").animate( { top:topPos+'px' }, { queue:false, duration:200 } );
}

function slideUpAnimateHeight(divHeight)
{
  if(ie6)
  {
    var topPos =  $(window).height() + $(window).scrollTop() - divHeight;
    $('#slideUpDiv').css( { height:divHeight+'px' } );
    $("#slideUpDiv").animate( { top:topPos+'px' }, { queue:false, duration:500 } );
  }
  else
  {
    $("#slideUpDiv").animate( { height:divHeight+"px" }, { queue:false, duration:500 } );
  }
}

function hideSlideUp()
{
  var hide = getCookie('dzFBpreference');
  if(hide!='hide')
    setCookie('dzFBpreference', 'hide',7);
  if(ie6)
    $(window).unbind('scroll',slideUpIe6scroll );
  $('#slideUpDiv').remove();
  return false;
}

function dontShowSlideUp()
{
  hideSlideUp();
  setCookie('dzFBpreference', 'hide',90);
  return false;
}

function feedbackLater()
{
  hideSlideUp();
  setCookie('dzFBpreference', 'showLater');
  var time = new Date();
  var now = parseInt(time.getTime());
  var laterTime = now + (1000 * 60 * 2);
  setCookie('dzFBlater', laterTime);
  checkShowLaterTiming();
}

function feedbackYes(userInitiatedFB)
{
  setCookie('dzFBpreference', 'hide',30);

  $("#selectionBoxLater").hide();
  $("#selectionBoxClose2").hide();
  $("#selectionBoxNo").hide();
  var content = '';
  if(userInitiatedFB)
  {
    var emailMessage = "Enter your email here if you'd like a reply";
    content = '<div class="selectIcon"><img src="/images/common/button-feedback-yes.jpg" alt="Yes" width="88" height="34" /></div>' +
              '<div class="topTextLine">Fantastic! We\'d love to hear your feedback.</div>' +
              '<div id="feedbackForm">' +
              '<table cellpadding="0" cellspacing="0" border="0"><tr><td colspan="2"><textarea id="feedbackText"></textarea></td></tr>' +
              '<tr><td><input id="feedbackEmail" value="'+emailMessage+'" onfocus="if(this.value==\''+addslashes(emailMessage)+'\'){this.value=\'\';}" onblur="if(this.value==\'\'){this.value=\''+addslashes(emailMessage)+'\';}" /></td>' +
              '<td align="right"><img src="/images/common/button-submit-feedback.gif" onclick="sendFeedbackComment();" style="cursor:pointer;" /></td></tr></table>' +
              '</div>';
    $("#selectionBoxYes").attr('onclick','').css('cursor','default').html(content);
    slideUpAnimateHeight(200);
    if($(window).width() < 800)
      $("#selectionBoxYes").css( { 'left':"0px" } );
    $("#selectionBoxYes").animate( { width:"575px",height:"150px"  }, { queue:false, duration:500 } );
  }
  else
  {
    content = '<div class="selectIcon"><img src="/images/common/button-feedback-yes.jpg" alt="Yes" width="88" height="34" /></div>' +
              '<div class="topTextLine">Fantastic! <a href="#" onclick="return bookMark();">Click to add us to your web favourites</a>, so you can easily find us again.</div>';
    $("#selectionBoxYes").attr('onclick','').css('cursor','default').html(content);
    $("#selectionBoxYes").animate( { width:"676px" }, { queue:false, duration:500 } );

    bookPromoTimer = setTimeout(function() {
        showExtraBookContent();
    }, 10000);
  }

}

function feedbackNo()
{
  setCookie('dzFBpreference', 'hide',30);

  var emailMessage = "Enter your email here if you'd like a reply";
  var content = '<div class="selectIcon"><img src="/images/common/button-feedback-no.jpg" alt="No" width="78" height="34" /></div>' +
                '<div class="topTextLine">Sorry we have been unable to deliver what you were looking for.</div>' +
                '<div id="feedbackForm">We\'d really appreciate your feedback on why our site didn\'t meet your expectations, and how we could improve it. Thank you.' +
                '<table cellpadding="0" cellspacing="0" border="0"><tr><td colspan="2"><textarea id="feedbackText"></textarea></td></tr>' +
                '<tr><td><input id="feedbackEmail" value="'+emailMessage+'" onfocus="if(this.value==\''+addslashes(emailMessage)+'\'){this.value=\'\';}" onblur="if(this.value==\'\'){this.value=\''+addslashes(emailMessage)+'\';}" /></td>' +
                '<td align="right"><img src="/images/common/button-submit-feedback.gif" onclick="sendFeedbackComment();" style="cursor:pointer;" /></td></tr></table>' +
                '</div>';
  $("#selectionBoxLater").hide();
  $("#selectionBoxClose2").hide();
  $("#selectionBoxYes").css('visibility','hidden');
  $("#selectionBoxNo").attr('onclick','').css('cursor','default').html(content);
  slideUpAnimateHeight(250);
  if($(window).width() < 800)
      $("#selectionBoxNo").css( { 'left':"0px" } );
  $("#selectionBoxNo").animate( { width:"565px",height:"200px" }, { queue:false, duration:500 } );

}

var feedbackValues = new Array;
var submittingFeedback = false;
var submittingRegistration = false;

function sendFeedback()
{
  var ajaxRequest = doAjaxRequest();

  if(ajaxRequest)
  {
   ajaxRequest.onreadystatechange = function()
   {
     if(ajaxRequest.readyState == 4)
     {
       if(ajaxRequest.responseText != '')
       {
         if(ajaxRequest.responseText=="submitted")
         {
           feedbackSent();
           setCookie('dzFBpreference', 'hide',30);
         }
         else
         {
           var pairs = ajaxRequest.responseText.split("||");
           for(i=0;i<pairs.length;i++)
           {
             var value = pairs[i].split("=");
             feedbackValues[value[0]] = value[1];
           }
         }
       }
       else if(submittingFeedback || submittingRegistration)
       {
         // error occurred while submitting - show error
         var content = 'There was a problem connecting to our servers. Please try again.';
         $(document.createElement("div")).attr("id","slideUpError").html(content).insertBefore("#slideUpContent").fadeIn();
       }
     }
   }

   var param = '';

   param = param + addPostParam('id',feedbackValues['id']);
   param = param + addPostParam('hash',feedbackValues['hash']);
   param = param + addPostParam('site_helpful_YN',feedbackValues['site_helpful_YN']);
   param = param + addPostParam('bookmarked_YN',feedbackValues['bookmarked_YN']);
   param = param + addPostParam('registered_YN',feedbackValues['registered_YN']);
   param = param + addPostParam('user_initiated_YN',feedbackValues['user_initiated_YN']);
   param = param + addPostParam('feedback',feedbackValues['feedback']);
   param = param + addPostParam('email',feedbackValues['email']);
   param = param + addPostParam('screen_resolution',screen.width+'x'+screen.height);
   param = param + addPostParam('scroll_position',$(window).scrollLeft()+'x'+$(window).scrollTop());
   param = param + addPostParam('current_url',location.href);

   ajaxRequest.open('POST', "/feedback/submit.htm?r="+Math.random(), true);
   ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   ajaxRequest.setRequestHeader("Content-length", param.length);
   ajaxRequest.setRequestHeader("Connection", "close");

   ajaxRequest.send(param);

  }

}

function addPostParam(key,value)
{
   if(value != null || value != undefined)
     return encodeURI(key+"="+escape(value)+"&");
   else
     return '';
}

function feedbackSent()
{
  var content = '<div id="feedbackTitle">Thank you for taking the time to give us your feedback.</div><div id="feedbackClose">' +
                      '<a href="#" onclick="return hideSlideUp();">Close [x]</a></div>' +
                      '<div id="selectionBoxClose" class="selectionBox" onclick="hideSlideUp();"><div class="selectIcon"><img src="/images/common/button-feedback-close.gif" alt="Close" width="98" height="34" /></div></div>';
  $('#slideUpContent').html(content);
  slideUpAnimateHeight(80);
}

function answerFeedback(answer,userInitiatedFB)
{
  feedbackValues['site_helpful_YN'] = answer;
  sendFeedback();

  if(answer=='true')
    feedbackYes(userInitiatedFB);
  else if(answer=='false')
    feedbackNo();
}

function sendFeedbackComment()
{
  feedbackValues['feedback'] = $('#feedbackText').val();
  if( $('#feedbackEmail').val() != "Enter your email here if you'd like a reply" )
    feedbackValues['email'] = $('#feedbackEmail').val();
  if(feedbackValues['feedback'] != null && feedbackValues['feedback'] != undefined && feedbackValues['feedback'] != '')
  {
    submittingFeedback = true;
    sendFeedback();
  }
  else
    alert('Please enter a comment before submitting your feedback.');
}

function bookMark()
{
  setCookie('dzBookmarked', 'true', 365 );

  feedbackValues['bookmarked_YN'] = 'true';
  sendFeedback();

  var title = "money.co.uk - Compare 1000's of Financial Products";
  var url = "http://www.money.co.uk/?source=bkmk";

	if(window.sidebar)
		window.sidebar.addPanel(title, url,""); // Firefox Bookmark
	else if(window.external)
		window.external.AddFavorite( url, title); // IE Favorite
	else
		alert("Bookmarking not currently available for your browser.\nPlease use the browser menu to bookmark.");

  showExtraBookContent();
  return false;
}


function registerFromSlideUp()
{
  var emailDefault = 'Please enter your email here';
  var nameDefault = 'First Name';
  var emailValue = $("#sign_up_email").val();
  var nameValue = $("#sign_up_name").val();
  if(emailValue != "" && emailValue != emailDefault && nameValue != "" && nameValue != nameDefault)
  {
    var ajaxRequest = doAjaxRequest();

    $("#slideUpError").remove();
    $("#selectionBoxYes").html('<p style="padding:30px;text-align:center;"><img src="/images/common/icon-loading.gif" alt="Loading..." /></p>');

    if(ajaxRequest)
    {
     ajaxRequest.onreadystatechange = function()
     {
       if(ajaxRequest.readyState == 4)
       {
         if(ajaxRequest.responseText != '')
         {
           if(ajaxRequest.responseText=="true")
           {
             feedbackValues['registered_YN'] = 'true';
             sendFeedback();
             setCookie('dzMember', 'true',365);

             var content = '<div style="padding:10px;"><p>Congratulations! You have successfully registered with money.co.uk.</p>' +
             '<p><strong>Important:</strong> We have sent you an email. Please click on the link in that email in order to confirm your email address and get access to your free book.</p>' +
             '<p style="padding-top:8px;"><a href="#" onclick="return hideSlideUp();">Close</a></p></div>';
             $("#selectionBoxYes").html(content);
           }
           else
           {
             var content = '<span style="font-size:14px;">'+ajaxRequest.responseText+'</span>';
             $(document.createElement("div")).attr("id","slideUpError").html(content).insertBefore("#slideUpContent").fadeIn();
             $("#selectionBoxYes").html('<br/>');
             showExtraBookContent();
           }
         }
         else
         {
           unexpectedError();
         }
       }
     }

     var params = "login_email=" + emailValue + "&first_name=" + nameValue;
     var parameter = encodeURI(params);
     ajaxRequest.open('POST', "/member/signup.htm?r="+Math.random(), true);
     ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     ajaxRequest.setRequestHeader("Content-length", parameter.length);
     ajaxRequest.setRequestHeader("Connection", "close");
     ajaxRequest.send(parameter);
    }
  }
  else
  {
    if(emailValue == "" || emailValue == emailDefault)
      var content = 'Please enter your email and try again.';
    else if(nameValue == "" || nameValue == nameDefault)
      var content = 'Please enter your name and try again.';
    $(document.createElement("div")).attr("id","slideUpError").html('<span style="font-size:18px;">'+content+'</span>').insertBefore("#slideUpContent").fadeIn();
    return false;
  }
}


function showExtraBookContent()
{
  clearTimeout(bookPromoTimer);

  if(getCookie('dzMember') == 'true' || getCookie('dzMember') == 'true')
    return true;

  var valueName = "First Name";
  var valueEmail = "Please enter your email here";
  var contentOrig = $("#selectionBoxYes").html();
  var content = '<div id="suSignUpImg">We will <b>NOT</b> sell or rent your email address.</div>' +
                '<div id="suSignUpText">' +
                '<div id="suSignUpTitle"><span class="redTitle">FREE Mammoth Saving Email</span></div>' +
                '<p>Join 240,000 other subscribers who grab our expert money tips and hottest bargains each week in our special bi-weekly emails.</p>' +
                '<p class="boldText">These deals go fast. Get yours now.</p>' +
                '<div id="suSignUpForm"><input type="text" id="sign_up_email" value="'+valueEmail+'" onfocus="if(this.value==\''+addslashes(valueEmail)+'\'){this.value=\'\';}" onblur="if(this.value==\'\'){this.value=\''+addslashes(valueEmail)+'\';}" />' +
                '<input type="text" id="sign_up_name" value="'+valueName+'" onfocus="if(this.value==\''+addslashes(valueName)+'\'){this.value=\'\';}" onblur="if(this.value==\'\'){this.value=\''+addslashes(valueName)+'\';}" />' +
                '<input type="image" value="Sign Up" src="/images/common/button-slideup-signup.gif" onclick="return registerFromSlideUp();" />' +
                '<div id="suSignUpLinks"><a href="#" onclick="return showTermsAndConditions();">Terms &amp; Conditions</a> | <a href="#" onclick="return showPrivacyPolicy();">Privacy Policy</a></div>' +
                '</div>';
  $("#selectionBoxYes").html(contentOrig + content);
  slideUpAnimateHeight(250);
  $("#selectionBoxYes").animate( { height:"200px" }, { queue:false, duration:500 } );
}



function giveFeedback(userInitiatedFB,immediate)
{

  var preload = new Array();
  preload[0] = '/images/common/button-feedback-yes.jpg';
  preload[1] = '/images/common/button-feedback-no.jpg';
  preload[2] = '/images/common/button-feedback-close.gif';
  preload[3] = '/images/common/bg-slide-up.jpg';
  preload[4] = '/images/common/bg-slide-up-box.gif';

  var loadImage = new Array();
  for (var i = 0; i < preload.length; i++)
  {
    loadImage[i] = new Image;
    loadImage[i].src = preload[i];
  }

  var height = 80;

  if(immediate == null || immediate == undefined)
    immediate = false;
  if(userInitiatedFB == null || userInitiatedFB == undefined)
    userInitiatedFB = false;

  $('#feedbackButton').hide();

  if(userInitiatedFB)
    feedbackValues['user_initiated_YN'] = 'true';
  else
  {
    feedbackValues['user_initiated_YN'] = 'false';

    var showFeedback = getCookie('dzFBpreference');

    if(showFeedback== null || showFeedback == undefined)
      setCookie('dzFBpreference', 'forceShow');

  }
  if(userInitiatedFB && slideUpTimer != undefined)
    clearTimeout(slideUpTimer);

  var commonContent = '<div id="feedbackTitle">Have you found our site helpful?</div><div id="feedbackClose">';
  commonContent = commonContent + '<a href="#" onclick="return hideSlideUp();">Close [x]</a></div>';

  var questionContent = '';

  if(userInitiatedFB)
    questionContent = questionContent + '<div id="selectionBoxYes" class="selectionBox" onclick="answerFeedback(\'true\',true);"><div class="selectIcon"><img src="/images/common/button-feedback-yes.jpg" alt="Yes" width="88" height="34" /></div></div>';
  else
    questionContent = questionContent + '<div id="selectionBoxYes" class="selectionBox" onclick="answerFeedback(\'true\');"><div class="selectIcon"><img src="/images/common/button-feedback-yes.jpg" alt="Yes" width="88" height="34" /></div></div>';
  questionContent = questionContent + '<div id="selectionBoxNo" class="selectionBox" onclick="answerFeedback(\'false\');"><div class="selectIcon"><img src="/images/common/button-feedback-no.jpg" alt="No" width="78" height="34" /></div></div>';
  if(!userInitiatedFB)
  {
    //questionContent = questionContent + '<div id="selectionBoxLater" class="selectionBox" onclick="feedbackLater();"><div class="selectIcon"><img src="/images/common/button-feedback-later.gif" alt="Later" width="170" height="34" /></div></div>';
    questionContent = questionContent + '<div id="selectionBoxLater" class="selectionBox" onclick="hideSlideUp();"><div class="selectIcon"><img src="/images/common/button-feedback-close.gif" alt="Close" width="98" height="34" /></div></div>';
  }
  content = commonContent + questionContent;

  if(immediate)
    slideUp(content,height,true,'now');
  else if(userInitiatedFB)
    slideUp(content,height,true,300);
  else
    slideUp(content,height);
}


function checkShowLaterTiming()
{
  var timeToShow = getCookie('dzFBlater');
  var time = new Date();
  var now = parseInt(time.getTime());
  if(timeToShow < now)
  {
    clearTimeout(slideUpTimer);
    giveFeedback();
  }
  else
  {
    slideUpTimer = setTimeout( "checkShowLaterTiming()", 5000);
  }
}

var slideUpTimer;

function feedback()
{
  /*var showFeedback = getCookie('dzFBpreference');*/

  $(document).ready(function () {
    var button = $(document.createElement("div")).attr("id","feedbackButton");
    if(ie6)
    {
      var topPos = $(window).height() + $(window).scrollTop() - 34;
      $('#feedbackButton').css( { position:'absolute' , bottom:'auto',display:'block', top:topPos+'px' } );
      $(window).bind('scroll',feedbackIe6scroll );
    }

    if(!ie6)
      button.bind('click',giveFeedback).insertAfter("#pageFooter");
  });

}



function submitIcelandSurvey(id)
{
   $('#surveyError').hide();

   var formData = $('#surveyForm').serialize(); 

   $.ajax({ 
     type: "POST", 
     url: "/competitions/iceland/bonus-questions.htm?r="+Math.random(), 
     data: formData, 
     success: function(msg){ 
      if(msg=='validationfail') 
      { 
        $('#surveyError').show().html('Please answer all the questions before submitting your feedback.');
        // continue here 
      }
      else if(msg=='error') 
      { 
        $('#surveyError').show().html('Unknown error occured. Please try again later.');
        // continue here 
      }
      else 
      { 
        $('#surveyContainer').html(msg);
        window.scrollTo(0,$('#surveyContainer').offset().top);
      } 
     } 
   });
}

function loadShareWindow(url)
{
  popupWidth = screen.availWidth;
  popupHeight = screen.availHeight;

  popupLeft = 0;
  popupTop = 0;

  if(screen.width > 799)
  {
    popupWidth = 780;
    popupLeft = (screen.availWidth / 2) - (popupWidth / 2);
  }

  if(screen.height > 599)
  {
    popupHeight = 500;
    popupTop = (screen.availHeight / 2) - (popupHeight / 2);
  }

  linkWindow = window.open(url,'_blank','left='+popupLeft+',top='+popupTop+',width='+popupWidth+',height='+popupHeight+',toolbar=1,scrollbars=1,location=1,status=1,menubar=1,resizable=1');

  return false;
}

function createButton(text, size, colour, href, onClick)
{
  var cssClasses = new Array();
  var html = '';

  var onClick = $.trim(onClick);

  if(size === undefined || size == '' || size == null)
    size = 'medium';
  
  if(colour === undefined || colour == '' || colour == null)
    colour = 'orange'

  if(href == undefined || href == '')
    href = null;

  if(onClick == undefined || onClick == '')
    onClick = null;
  
  cssClasses.push('standardButton');
  cssClasses.push('button'+ucwords(size));
  cssClasses.push('button'+ucwords(colour));

  html += '<input class="'+cssClasses.join(' ')+'"';

  if(onClick != null)
  {
    html += ' onclick="'+onClick;

    if(onClick.indexOf('return ') == -1)
    {
      if(onClick.indexOf(';') == -1)
        html += ';';

      html += ' return false';
    }
    
    html += '"';
  }
  else if (href != null)
    html += ' onclick="window.location=\''+href+'\'; return false;"';
  else
    html += ' onclick="return false;"';
  
  html += ' type="submit" value="'+text+'" />';

  return html;
}

function replaceWordChars(text)
{
    var s = text;

    // smart single quotes and apostrophe
    s = s.replace(/[\u2018|\u2019|\u201A]/g, "\'");

    // smart double quotes
    s = s.replace(/[\u201C|\u201D|\u201E]/g, "\"");

    // ellipsis
    s = s.replace(/\u2026/g, "...");

    // dashes
    s = s.replace(/[\u2013|\u2014]/g, "-");

    // circumflex
    s = s.replace(/\u02C6/g, "^");

    // open angle bracket
    s = s.replace(/\u2039/g, "<");

    // close angle bracket
    s = s.replace(/\u203A/g, ">");

    // spaces
    s = s.replace(/[\u02DC|\u00A0]/g, " ");

    return s;
}

function strip_tags(string)
{
  return string.replace(/(<([^>]+)>)/ig,""); 
}

function trim(str, chars) {  
  return ltrim(rtrim(str, chars), chars);  
}  

function ltrim(str, chars) {  
  chars = chars || "\\s";  
  return str.replace(new RegExp("^[" + chars + "]+", "g"), "");  
}  

function rtrim(str, chars) {  
  chars = chars || "\\s";  
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");  
}

function ucwords(str)
{;
  return (str + '').replace(/^(.)|\s(.)/g, function ($1) 
  {
    return $1.toUpperCase();
  });
}

function urlencode(str) 
{
  return escape(str).replace('&','%38').replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008-2009 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.

	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = Math.max(0, xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = Math.max(0, yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';

        if($(elm).is('#myMoneyToolBoxHeader a'))
        {
          s.top = yPos + 'px';
				  s.left = xPos + 'px';
        }
        else if($(elm).is('.mmtab a'))
        {
				  s.left = (xPos - parseInt(elm.currentStyle.paddingLeft) - 3) + 'px';
          s.top = (yPos - 1) + 'px';
        }
        else
        {
          s.left = (xPos - parseInt(elm.currentStyle.paddingLeft)) + 'px';
          s.top = yPos + 'px';
        }

				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};


IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}