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('banner.htm') != -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 < document.getElementById('overlayContent').scrollHeight)
      divHeight = windowHeight - 60;
    else if(document.getElementById('overlayContent').scrollHeight > divHeight && windowHeight > document.getElementById('overlayContent').scrollHeight)
      divHeight = document.getElementById('overlayContent').scrollHeight;

  }
 
  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 overlayFloatObject(element)
{
  var elementPosition = $(element).offset();

  var elementClone = $(element).clone().removeAttr('id').insertBefore($(element)).css({'position':'absolute', 'z-index':'100', 'border-color':'#FFF'});

  if($('#darkerScreenObject').length == 0)
    $(document.createElement("div")).attr("id","darkerScreenObject").appendTo("body");

  $("#darkerScreenObject").bind("click", {clone:elementClone}, overlayUnFloatObject);

  var darkWidth = ( $(window).width() + $('body').scrollLeft() )+"px";

  if($(window).height() > $('body').height())
    var darkHeight = $(window).height()+"px";
  else
    var darkHeight = $('body').height()+40+"px";

  $("#darkerScreenObject").css({"width":darkWidth, "height":darkHeight}).hide().fadeIn();

  $(document.createElement("div")).attr("id","overlayCloseButton")
                                  .html("<img src='/images/common/icon-close-overlay.png' alt='Close' width='30' height='29' />")
                                  .bind("click", {clone:elementClone}, overlayUnFloatObject)
                                  .appendTo("body")
                                  .css({'top':(elementPosition.top-10)+'px',"left":(elementPosition.left+(element).width()-15)+'px'})
                                  .hide().fadeIn();
}

function overlayUnFloatObject(event)
{
  $("#darkerScreenObject").remove();
  $("#overlayCloseButton").remove();
  $(event.data.clone).remove();
}

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 trackingForm(element, event)
{
  return loadTrackingLink($(element).attr('action')+'?'+$(element).serialize());
}

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, 740, true);

    if($('#googleAdOverlayContainer').length > 0 && google != undefined)
      var googleAdOverlay = new google.ads.search.Ad(googleAdOptionsOverlay);

    return false;
  }
}

function loadProductInfoOverlay(url, additionalParams, event)
{
  showLoadingOverlay();

  if(additionalParams == undefined || additionalParams == null)
    additionalParams = '';
  else
    url = url + '?' + additionalParams;

  $.ajax({ 
     type: "GET", 
     url: url,
     cache: false,
     error: function() { unexpectedError(); },
     success: function(response)
     {
       loadOverlay(null,response,920,null);
       resizeOverlay(920,450,false,true);
     } 
   });
    
   if(event != undefined)
     disableParentClick(event);
}

/** 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,cssClass,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 - 10;
  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 + 10;

  if(descriptionTop < 0)
    descriptionTop  = 0;
  if(arrowTop < 0)
    arrowTop  = 0;

  if(arrowTop > (descriptionTop + divHeight - 40))
    arrowTop = topY + 10;

  $("#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 **/
function subMainMenu(element, sectionId, cssClass)
{
  var heightColumn = 0;

  $.doTimeout('subMainMenuOut');
  $.doTimeout('subMainMenuIn');

  var subMenuElementId = $(element).attr('id')+'_sub';
  var subMenuTab = $(element).text();

  if($('#subMainMenu #'+subMenuElementId).length == 0)
  {
    $('<div/>').attr('id',subMenuElementId).addClass('submenu').html('<div class="menuLoading">Loading Menu...</div>').appendTo('#subMainMenu');
    
    $.ajax({ 
      type: "GET", 
      url: '/content/menu-request.htm?sectionId='+sectionId,
      cache: false,
      error: function() { $.doTimeout('subMainMenuIn'); $('#subMainMenu').slideUp(); unexpectedError(); },
      success: function(response)
      {
        $('<div/>').html(response).children('.submenu').each(function()
        {
          if($('#subMainMenu #'+$(this).attr('id')).length == 1)
            $('#subMainMenu #'+$(this).attr('id')).html($(this).html());
          else if(subMenuElementId != $(this).attr('id'))
            $('<div/>').attr('id',$(this).attr('id')).html($(this).html()).addClass('submenu').appendTo('#subMainMenu').hide();
          else
            $('<div/>').attr('id',$(this).attr('id')).html($(this).html()).addClass('submenu').appendTo('#subMainMenu');

          subMainMenuColumnHeight($(this).attr('id'));
        });
      }
    });
  }

  $('#subMainMenu .submenu').hide();
  $('#'+subMenuElementId).show();

  if($('#subMainMenu:visible').length == 1 && $("#subMainMenu").queue("fx").length == 0)
  {
    $('#subMainMenu').attr('class','').addClass(cssClass);
    $(element).bind('mouseout', function() { $.doTimeout('subMainMenuOut', 300, subMainMenuOut) });
    mainMenuNotSelected($('#mainMenu .selected'));
    mainMenuNotSelected($('#mainMenuWider .selected'));
    mainMenuSelected(element);
    subMainMenuColumnHeight(subMenuElementId);
  }
  else
  {
    $(element).bind('mouseout', function() { $.doTimeout('subMainMenuOut', 100, subMainMenuOut) })
              .bind('click', function() { $.doTimeout('subMainMenuIn'); });
    $('#subMainMenu').bind('mouseover', function() { $.doTimeout('subMainMenuOut'); })
                     .bind('mouseout', function() { $.doTimeout('subMainMenuOut', 100, subMainMenuOut) });

    $.doTimeout('subMainMenuIn', 300, function() {

      $('#subMainMenu').attr('class','').addClass(cssClass);

      mainMenuNotSelected($('#mainMenu .selected'));
      mainMenuNotSelected($('#mainMenuWider .selected'));
      mainMenuSelected(element);
      
      $('#subMainMenu').stop().css('height','auto').slideDown('fast', function() {
        subMainMenuColumnHeight(subMenuElementId)
      });

    });
  }
}

function subMainMenuOut()
{
  $.doTimeout('subMainMenuIn');

  $('#subMainMenu').slideUp('fast');
  mainMenuNotSelected($('#mainMenu .selected'));
  mainMenuNotSelected($('#mainMenuWider .selected'));
  mainMenuSelected($('#mainMenu .default'));
  mainMenuSelected($('#mainMenuWider .default'));
}

function mainMenuSelected(element)
{
  if($(element).hasClass('red'))
    $(element).addClass('redSelected');
  else if($(element).hasClass('blue'))
    $(element).addClass('blueSelected');
  else if($(element).hasClass('green'))
    $(element).addClass('greenSelected');

  $(element).addClass('selected');
}

function mainMenuNotSelected(element)
{
  if($(element).hasClass('red'))
    $(element).removeClass('redSelected');
  else if($(element).hasClass('blue'))
    $(element).removeClass('blueSelected');
  else if($(element).hasClass('green'))
    $(element).removeClass('greenSelected');

  $(element).removeClass('selected');
}

function subMainMenuColumnHeight(subMenuElementId)
{
  var heightColumn = 0;

  $('#'+subMenuElementId+' .column').each(function() {
        if($(this).height() > 100 && $(this).height() > heightColumn)
          heightColumn = $(this).height();
        });
  
  if(heightColumn != 0)
    $('#'+subMenuElementId+' .column').css('height', heightColumn+'px');
}

var doMainMenuFooterRotate = true;

function mainMenuFooterRotate()
{
  if(doMainMenuFooterRotate)
  {
    if($('.mainMenuFooterRotate:visible').next().length != 0)
      var nextElement = $('.mainMenuFooterRotate:visible').next();
    else
      var nextElement =  $('.mainMenuFooterRotate').first();

    $.doTimeout('mainMenuFooterRotate', 12000, mainMenuFooterRotate, true);

    mainMenuFooterChangeElement(nextElement, false);
  }
}

function mainManuFooterSelectNumber(number)
{
  doMainMenuFooterRotate = false;
  $.doTimeout('mainMenuFooterRotate');
  var nextElement = $('.mainMenuFooterRotate:eq('+(number-1)+')');
  mainMenuFooterChangeElement(nextElement, true);
}

function mainMenuFooterChangeElement(element, instant)
{
  if($(element).hasClass('red'))
    $('#mainMenuFooterColourSecondary').show().removeClass('mainMenuGreen').removeClass('mainMenuBlue').addClass('mainMenuRed');
  else if($(element).hasClass('blue'))
    $('#mainMenuFooterColourSecondary').show().removeClass('mainMenuGreen').removeClass('mainMenuRed').addClass('mainMenuBlue');
  else if($(element).hasClass('green'))
    $('#mainMenuFooterColourSecondary').show().removeClass('mainMenuBlue').removeClass('mainMenuRed').addClass('mainMenuGreen');

  if(instant)
  {
    $('.mainMenuFooterRotate:visible').hide();

    if($(element).hasClass('red'))
      $('#mainMenuFooterColour').show().removeClass('mainMenuGreen').removeClass('mainMenuBlue').addClass('mainMenuRed');
    else if($(element).hasClass('blue'))
      $('#mainMenuFooterColour').show().removeClass('mainMenuGreen').removeClass('mainMenuRed').addClass('mainMenuBlue');
    else if($(element).hasClass('green'))
      $('#mainMenuFooterColour').show().removeClass('mainMenuBlue').removeClass('mainMenuRed').addClass('mainMenuGreen');

    $(element).show();
  }
  else
  {
    $('.mainMenuFooterRotate:visible').fadeOut(500, function() {
        $('#mainMenuFooterColour').fadeOut(300, function() {
          if($(element).hasClass('red'))
            $('#mainMenuFooterColour').show().removeClass('mainMenuGreen').removeClass('mainMenuBlue').addClass('mainMenuRed');
          else if($(element).hasClass('blue'))
            $('#mainMenuFooterColour').show().removeClass('mainMenuGreen').removeClass('mainMenuRed').addClass('mainMenuBlue');
          else if($(element).hasClass('green'))
            $('#mainMenuFooterColour').show().removeClass('mainMenuBlue').removeClass('mainMenuRed').addClass('mainMenuGreen');

          $(element).fadeIn(500);
        });
    });
  }
}

/** Member Stuff **/

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(400, function() { setupShowImageWhenScroll(); });
    $("#"+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 );
}

/** 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
      {
        if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod')
          $("#slideUpDiv").css( { 'position':'static'} );
        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 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";
    var nameMessage = "Enter your first name here";
    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"><input class="standardInput" id="feedbackName" value="'+nameMessage+'" onfocus="if(this.value==\''+addslashes(nameMessage)+'\'){this.value=\'\';}" onblur="if(this.value==\'\'){this.value=\''+addslashes(nameMessage)+'\';}" /></td></tr>' +
              '<tr><td colspan="2"><textarea id="feedbackText" class="standardInput"></textarea></td></tr>' +      
              '<tr><td><input class="standardInput" 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(230);
    if($(window).width() < 800)
      $("#selectionBoxYes").css( { 'left':"0px" } );
    $("#selectionBoxYes").animate( { width:"575px",height:"180px"  }, { 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 nameMessage = "Enter your first name here";
  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" style="margin-top:10px;">'+
                '<tr><td colspan="2"><input class="standardInput" id="feedbackName" value="'+nameMessage+'" onfocus="if(this.value==\''+addslashes(nameMessage)+'\'){this.value=\'\';}" onblur="if(this.value==\'\'){this.value=\''+addslashes(nameMessage)+'\';}" /></td></tr>' +
                '<tr><td colspan="2"><textarea id="feedbackText" class="standardInput"></textarea></td></tr>' +
                '<tr><td><input class="standardInput" 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(275);
  if($(window).width() < 800)
      $("#selectionBoxNo").css( { 'left':"0px" } );
  $("#selectionBoxNo").animate( { width:"565px",height:"225px" }, { 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")
         {
           if(feedbackValues['site_helpful_YN'] == 'true')
             feedbackSent();
           else
             feedbackSentNegative();

           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('name',feedbackValues['name']);
   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" style="font-size:26px;">Thank you. May we ask a quick favour?' +
                      '<div style="font-size:20px; font-weight:normal; padding-left:2px; margin-top:5px;">Can you please help us spread the word about money.co.uk because we don’t have big TV advertising budgets like our competitors.<div style="margin-top:10px;">Would you write a short review on <a href="/php/callsite.php?link=25027&channel=FDBK&subchannel=LNK1" target="_blank" style="color:#FFF; text-decoration:underline;">Review Centre</a> about money.co.uk? Even a single sentence would be massively appreciated. Thank you.</div></div></div>'+
                      '<div id="feedbackClose"><a href="#" onclick="return hideSlideUp();">Close [x]</a></div>' +
                      '<div id="selectionBoxClose" style="margin-top:160px;" 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(210);
}

function feedbackSentNegative()
{
  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" style="margin-top:38px;" 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( $('#feedbackEmail').val() != "Enter your first name here")
    feedbackValues['name'] = $('#feedbackName').val();

  if(feedbackValues['feedback'] != null && feedbackValues['feedback'] != undefined && feedbackValues['feedback'] != '')
  {
    submittingFeedback = true;
    sendFeedback();
  }
  else
    alert('Please enter a comment before submitting your feedback.');
}

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 = 600;
    popupLeft = (screen.availWidth / 2) - (popupWidth / 2);
  }

  if(screen.height > 599)
  {
    popupHeight = 400;
    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);
	});
}

function disableParentClick(event)
{
  if(event != undefined && event != null)
  {
    if(event.stopPropagation)
     event.stopPropagation();
    else
     event.cancelBubble = true;
  }
}

function loopContentDivs(parentDivId)
{
  $("#"+parentDivId+">div:visible").fadeOut( function() {
    if( $(this).is(":last-child") )
      var nextDiv = $(this).parent().children().first();
    else
      var nextDiv = $(this).next();
    nextDiv.fadeIn( function() {
      $.doTimeout(8000, function() {
        loopContentDivs(parentDivId);
      });
    });
  });
}

function sendQuestionRegister()
{
  var overlayUrl = '/signup-ask-question.htm?'+$('#questionForm').serialize();    
  loadOverlay(overlayUrl, null, 650, 495);
}

function addFormLoading(formId,cssClass,formElement)
{
  if(cssClass==undefined || cssClass==null)
    cssClass = 'loadingFade';

  if(formElement==undefined || formElement==null)
    formElement = $('#'+formId);

  if(($(formElement).outerHeight(true))!=null)
  {
  var loadingFade = $('<div/>')
      .addClass(cssClass)
      .attr('id',formId+'loading')
      .height( $(formElement).outerHeight(true) )
      .width( $(formElement).width() )
      .insertBefore(formElement);
      
  var marginLeft = $(formElement).css('margin-left');
  if(marginLeft!=undefined)
    loadingFade.css('margin-left',$(formElement).css('margin-left') );

  loadingFade.show();
  }
} // end addFormLoading

function showSuccessMessage(where,formId,message,cssClass,whereElement)
{
  removeFormLoading(formId);

  if(cssClass==undefined || cssClass==null)
    cssClass = 'messageFade';
  
  if(whereElement==undefined || whereElement==null)
    whereElement = $('#'+where);

  if(($(whereElement).outerHeight(true))!=null)
  {
    var loadingFade = $('<div/>')
        .addClass(cssClass)
        .attr('id',formId+'loading')
        .height( $(whereElement).outerHeight(true)-3 )
        .width( $(whereElement).width() )
        .insertBefore(whereElement)
        .html(message);
      
    var marginLeft = $(whereElement).css('margin-left');
    if(marginLeft!=undefined)
      loadingFade.css('margin-left',$(whereElement).css('margin-left') );

    loadingFade.show();
    setTimeout( function() {  $('#'+formId+'loading').fadeOut( 2000, function(){ $('#'+formId+'loading').remove(); }); }, 1000); 
  }
} // end addFormLoading


function removeFormLoading(formId)
{
  $('#'+formId+'loading').fadeOut().remove();
} // end removeFormLoading

function showImageWhenScroll()
{
  var windowBottom = $(window).height() + $(window).scrollTop();
  var windowScroll = $(window).scrollTop();

  $('.scrImgNot:visible').each(function()
  { 
    var imagePosition = $(this).offset();
    var imageHeight = $(this).height();
    var loadImage = false;
    var loadOffset = 150;

    if($(this).attr('loadoffset') !== undefined)
      loadOffset = $(this).attr('loadoffset');

    if((imagePosition.top - loadOffset) < windowBottom && (imagePosition.top + loadOffset + imageHeight) > windowScroll)
      loadImage = true;

    if(loadImage)
    {
      if($(this).children('img').length != 0)
        $(this).children('img').attr('src', $(this).children('img').attr('usrc'));
      else if($(this).children('input').length != 0)
        $(this).children('input').attr('src', $(this).children('input').attr('usrc'));
      else if($(this).attr('ubackgroundimage').length != 0)
        $(this).css('background-image','url(\''+$(this).attr('ubackgroundimage')+'\')');

      $(this).removeClass('scrImgNoLoad');
      $(this).removeClass('scrImgLoad');
      $(this).removeClass('scrImgNot');
    }
  });
}

function setupShowImageWhenScroll()
{
  $.doTimeout('setupShowImageWhenScroll');
  $.doTimeout('setupShowImageWhenScroll', 100, showImageWhenScroll);
}

$(document).ready(function ()
{ 
  $(window).bind("scroll", setupShowImageWhenScroll);
  $(window).bind("resize", setupShowImageWhenScroll);
  $.doTimeout('setupShowImageWhenScroll');
  $.doTimeout('setupShowImageWhenScroll', 100, showImageWhenScroll);
});
