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(jQuery) {
    jQuery.fn.extend({
        isChildOf: function( filter_string ) {
          var parents = jQuery(this).parents().get();
          for ( j = 0; j < parents.length; j++ ) {
           if ( jQuery(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)
{
  jQuery(document).ready(function()
  {
    jQuery('iframe').each(function(i)
    {
      if(jQuery(this).attr('src').indexOf('google.com') == -1)
      {
        jQuery(this).contents().find('embed').each(function(i) 
        {
          if(jQuery(this).attr('wmode') != 'transparant')
          {
            if(method == 'hide')
              jQuery(this).hide();
            else if(method == 'show')
              jQuery(this).show();
            else
              jQuery(this).toggle();
          }
          else
          {
            return false;
          }
        });

        jQuery(this).contents().find('object').each(function(i) 
        {
          if(method == 'hide')
            jQuery(this).hide();
          else if(method == 'show')
            jQuery(this).show();
          else
            jQuery(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 topantivirussoftware.com.au servers.</p><p><a href="http://www.topantivirussoftware.com.au/">Please go back to home 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)
    jQuery("select").hide();

  toggleFlashBanners('hide');

  if(darkScreen == true)
  {

    if(jQuery('#darkenScreenObject').length == 0)
    {
      jQuery(document.createElement("div")).attr("id","darkenScreenObject")
                                      .appendTo("body");

    }

    if(darkScreenClose == true)
      jQuery("#darkenScreenObject").bind("click", hideOverlay);
    else
      jQuery("#darkenScreenObject").unbind("click", hideOverlay);

    var darkWidth = ( jQuery(window).width() + jQuery('body').scrollLeft() )+"px";

    if(jQuery(window).height() > jQuery('body').height())
      var darkHeight = jQuery(window).height()+"px";
    else
      var darkHeight = jQuery('body').height()+40+"px";
      
     /** Luu Dao */
	if(jQuery.browser.msie){darkHeight = jQuery(document).height() + "px"}
	
    jQuery("#darkenScreenObject").css( {"width":darkWidth, "height":darkHeight} );
    
    jQuery("#darkenScreenObject").show();

  }

  if(jQuery('#overlayObject').length == 0)
  {
    jQuery(document.createElement("div")).attr("id","overlayObject")
                                    .css({"display":"none"})
                                    .appendTo("body");

    jQuery(document.createElement("div")).attr("id","overlayScroll")
                                    .appendTo("#overlayObject");

    jQuery(document.createElement("div")).attr("id","overlayContent")
                                    .appendTo("#overlayScroll");

    jQuery(document.createElement("div")).attr("id","overlayCloseButton")
                                    .html("<img src='http://www.topantivirussoftware.com.au/images/icon-close-overlay.png' alt='Close' width='20' height='19' />")
                                    .bind("click", hideOverlay)
                                    .appendTo("body");
  }

  jQuery(window).bind("resize", repositionOverlay);
  jQuery(window).bind("scroll", repositionOverlayHeight);

  resizeOverlay(divWidth,divHeight);

  if(content != null)
    populateOverlayContent(content,displayCloseButton);
  else
    populateOverlayContent('<div class="loadingOverlay"><img src="http://www.topantivirussoftware.com.au/images/icon-loading.gif" width="32" height="32" /><p>Loading...</p></div>',displayCloseButton);

  document.getElementById('overlayScroll').scrollTop = 0;
  
  jQuery("#overlayObject").show();
 
  if(url != null)
  {
    jQuery.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;

  jQuery("#overlayContent").html(content);

  overlayCheckScroll();

  if(!displayCloseButton)
    jQuery("#overlayCloseButton").hide();
  else
    jQuery("#overlayCloseButton").show();
}

function hideOverlay()
{
  jQuery("#overlayObject").hide();
  jQuery("#overlayCloseButton").hide();
  jQuery("#overlayContent").html('');
  jQuery("#darkenScreenObject").hide();

  if(ie6)
    jQuery("select").show();

  toggleFlashBanners('show');

  jQuery(window).unbind("resize", repositionOverlay);
  jQuery(window).unbind("scroll", repositionOverlayHeight);
}

function overlayCheckScroll()
{
  if(jQuery('#overlayContent').height() > jQuery('#overlayScroll').height())
    jQuery('#overlayScroll').css('overflow','auto');
  else
    jQuery('#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 = jQuery(window).height();
    else
      var windowHeight = window.innerHeight;

    if(document.getElementById('overlayContent').scrollHeight > divHeight && windowHeight > divHeight){
      divHeight = windowHeight - 60;
    }
  }
  // Luu Dao added 26/10/2010
  	divHeight = getViewPortHeight() -20;
  	
  if(divWidth == null)
    divWidth = document.getElementById('overlayContent').scrollWidth;

  if(divHeight == null)
    divHeight = document.getElementById('overlayContent').scrollHeight;

  jQuery("#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 = jQuery(window).width() + jQuery('body').scrollLeft();

    if(darkWidth < 970)
      darkWidth = 970;

    jQuery("#darkenScreenObject").width(darkWidth+'px');
  }

  var divHeight = jQuery("#overlayObject").height();
  var divWidth = jQuery("#overlayObject").width();

  if(window.innerHeight == undefined)
    var windowHeight = jQuery(window).height();
  else
    var windowHeight = window.innerHeight;

  var currentTopMargin = parseInt(jQuery("#overlayObject").css("margin-top").replace('px',''));

  var topMargin = jQuery(window).scrollTop() + Math.floor((windowHeight-divHeight)/2);
  var leftMargin = jQuery(window).scrollLeft() + Math.floor((jQuery(window).width()-divWidth)/2);

/*  if(topMargin > (jQuery('body').height() - divHeight))
    topMargin = (jQuery('body').height() - divHeight);
  else if(topMargin < jQuery(window).scrollTop())
    topMargin = jQuery(window).scrollTop();*/

  if(heightOnly && windowHeight < divHeight)
  {
    if(topMargin > currentTopMargin)
      topMargin = currentTopMargin;
    if((jQuery(window).scrollTop() + windowHeight) > (divHeight + currentTopMargin))
      topMargin = (jQuery(window).scrollTop() + windowHeight - divHeight - 10);
  }

  if((leftMargin + divWidth) > (jQuery(window).width() + jQuery(window).scrollLeft()))
    leftMargin = (jQuery(window).width() + jQuery(window).scrollLeft()) - divWidth - 11;
  else if(leftMargin < jQuery(window).scrollLeft())
    leftMargin = jQuery(window).scrollLeft();

  if(leftMargin < 0)
    leftMargin = 0;

  if(topMargin < 0)
    topMargin = 0;

  if(heightOnly == false)
  {
    jQuery("#overlayObject").css({'top':topMargin+'px',"left":leftMargin+'px'});
    jQuery("#overlayCloseButton").css({'top':(topMargin-10)+'px',"left":(leftMargin-15)+'px'});
  }
  else
  {
    jQuery("#overlayObject").stop().animate({ top:topMargin+'px' }, 800);
    jQuery("#overlayCloseButton").stop().animate({ top:(topMargin-10)+'px' }, 800);
  }
}

function repositionOverlayHeight()
{
  repositionOverlay(true);
}

function showLoadingOverlay(text, image, cssClass)
{
  if(text == null)
    text = "Loading...";

  if(image == null)
    imageHtml = '<img src="http://www.topantivirussoftware.com.au/images/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(jQuery('.ButtonOption1').length == 1)
    jQuery('.ButtonOption1').bind('click',option.button1Function);
  if(jQuery('.ButtonOption2').length == 1)
    jQuery('.ButtonOption2').bind('click',option.button2Function);
  if(jQuery('.ButtonOption3').length == 1)
    jQuery('.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];

  jQuery.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();

    jQuery.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(jQuery('#googleAdOverlayContainer').length > 0 && google != undefined)
      var googleAdOverlay = new google.ads.search.Ad(googleAdOptionsOverlay);

    return false;
  }
}

function loadProductInfoOverlay(url)
{
	showLoadingOverlay();

  	jQuery.ajax({ 
     	type: "GET", 
     	url: url,
     	cache: false,
     	error: function() { unexpectedError(); },
     	success: function(response){
       		loadOverlay(null,response,920,null);
       		/** Luu Dao added */
			viewportheight = getViewPortHeight();
			
       		resizeOverlay(920,viewportheight,false,true);
     	} 
   	});
}
//Luu Dao add function 26/10/2010
function getViewPortHeight()
{
	var viewportheight;
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerHeight != 'undefined'){
		viewportheight = window.innerHeight;
	}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined'&& typeof document.documentElement.clientWidth !='undefined' && document.documentElement.clientWidth != 0){
		viewportheight = document.documentElement.clientHeight;
	}
	// older versions of IE
	else{
		viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}	
	
	return viewportheight;
}
/** Description Hover **/

function ietruebody()
{
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function displayDescription(text, element, cssClass, useDelayTimeout)
{
  jQuery(document).ready(function ()
  {
    if(jQuery("#hoverDescription").length == 0)
    {
      jQuery(document.createElement("div")).attr("id","hoverDescription")
                                      .addClass('hoverDescriptionDefault')
                                      .appendTo("body");
      jQuery(document.createElement("div")).attr("id","hoverContents")
                                      .html(text)
                                      .appendTo("#hoverDescription");
    }
    else
      jQuery("#hoverContents").html(text);

    if(useDelayTimeout == true)
      jQuery("#hoverDescription").bind('mouseover', function() { jQuery.doTimeout('hoverOut'); })
                            .bind('mouseout', function() { jQuery.doTimeout('hoverOut', 250, hideDescription) })

    if(cssClass != null)
      jQuery('#hoverDescription').addClass(cssClass);
    else
      jQuery('#hoverDescription').removeClass(jQuery('#hoverDescription').className).addClass('hoverDescriptionDefault');

    if(element != null)
    {
      var elementPos = jQuery(element).offset();

      if(jQuery("#hoverArrow").length == 0)
        jQuery(document.createElement("div")).attr("id","hoverArrow")
                                        .appendTo("body");
      else
        jQuery("#hoverArrow").css({ 'display':'block' });

      if(jQuery.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+jQuery(element).outerWidth()), (elementPosTop+jQuery(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);

    jQuery.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(jQuery('#hoverDescription:visible').length !== 0)
            displayDescription(html, element, cssClass, useDelayTimeout);

          storedAjaxDescription[url] = html;
        },
        error: function() {
          unexpectedError();
        }
      });
  }
}

function hideDescription()
{
  jQuery(document).ready(function () {
    jQuery("#hoverArrow").css({ 'display':'none',"left":'0px',"top":'0px'});
    jQuery("#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 = jQuery('#hoverDescription').width();
  var divHeight = jQuery('#hoverDescription').height();

  var descriptionTop = topY - 10;
  var descriptionLeft = rightX + 20;

  var arrowTop = topY + Math.floor((bottomY - topY) / 2) - 9;
  var arrowLeft = rightX + 2;

  jQuery('#hoverArrow').removeClass('hoverArrowRight');
  jQuery('#hoverArrow').addClass('hoverArrowLeft');

  if((descriptionLeft + divWidth) > (jQuery(window).width() + jQuery(window).scrollLeft()))
  {
    descriptionLeft = leftX - divWidth - 20;
    arrowLeft = leftX - 19;
    jQuery('#hoverArrow').removeClass('hoverArrowLeft');
    jQuery('#hoverArrow').addClass('hoverArrowRight');
  }

  if(window.innerHeight == undefined)
    var windowHeight = jQuery(window).height();
  else
    var windowHeight = window.innerHeight;

  if(descriptionTop + divHeight > (windowHeight + jQuery(window).scrollTop()) && (bottomY - divHeight) > jQuery(window).scrollTop())
    descriptionTop = bottomY - divHeight + 10;

  if(descriptionTop < 0)
    descriptionTop  = 0;
  if(arrowTop < 0)
    arrowTop  = 0;

  jQuery("#hoverDescription").css({ 'display':'block',"left":descriptionLeft+'px',"top":descriptionTop+'px'});
  jQuery("#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;

  jQuery.doTimeout('subMainMenuOut');
  jQuery.doTimeout('subMainMenuIn');

  var subMenuElementId = jQuery(element).attr('id')+'_sub';
  var subMenuTab = jQuery(element).text();

  if(jQuery('#subMainMenu #'+subMenuElementId).length == 0)
  {
    jQuery('<div/>').attr('id',subMenuElementId).addClass('submenu').html('<div class="menuLoading">Loading Menu...</div>').appendTo('#subMainMenu');
    
    jQuery.ajax({ 
      type: "GET", 
      url: '/content/menu-request.htm?sectionId='+sectionId,
      cache: false,
      error: function() { jQuery.doTimeout('subMainMenuIn'); jQuery('#subMainMenu').slideUp(); unexpectedError(); },
      success: function(response)
      {
        jQuery('<div/>').html(response).children('.submenu').each(function()
        {
          if(jQuery('#subMainMenu #'+jQuery(this).attr('id')).length == 1)
            jQuery('#subMainMenu #'+jQuery(this).attr('id')).html(jQuery(this).html());
          else if(subMenuElementId != jQuery(this).attr('id'))
            jQuery('<div/>').attr('id',jQuery(this).attr('id')).html(jQuery(this).html()).addClass('submenu').appendTo('#subMainMenu').hide();
          else
            jQuery('<div/>').attr('id',jQuery(this).attr('id')).html(jQuery(this).html()).addClass('submenu').appendTo('#subMainMenu');

          subMainMenuColumnHeight(jQuery(this).attr('id'));
        });
      }
    });
  }

  jQuery('#subMainMenu .submenu').hide();
  jQuery('#'+subMenuElementId).show();

  if(jQuery('#subMainMenu:visible').length == 1 && jQuery("#subMainMenu").queue("fx").length == 0)
  {
    jQuery('#subMainMenu').attr('class','').addClass(cssClass);
    jQuery(element).bind('mouseout', function() { jQuery.doTimeout('subMainMenuOut', 400, subMainMenuOut) });
    jQuery('#mainMenu .selected').removeClass('selected');
    jQuery(element).addClass('selected');
    subMainMenuColumnHeight(subMenuElementId);
  }
  else
  {
    jQuery(element).bind('mouseout', function() { jQuery.doTimeout('subMainMenuOut', 100, subMainMenuOut) })
              .bind('click', function() { jQuery.doTimeout('subMainMenuIn'); });
    jQuery('#subMainMenu').bind('mouseover', function() { jQuery.doTimeout('subMainMenuOut'); })
                     .bind('mouseout', function() { jQuery.doTimeout('subMainMenuOut', 100, subMainMenuOut) });

    jQuery.doTimeout('subMainMenuIn', 500, function() {

      jQuery('#subMainMenu').attr('class','').addClass(cssClass);

      jQuery('#mainMenu .selected').removeClass('selected');
      jQuery(element).addClass('selected');

      if(ie)
        jQuery.fx.off = false;
      
      jQuery('#subMainMenu').stop().css('height','auto').slideDown('normal', function() {
        subMainMenuColumnHeight(subMenuElementId)
      });

      if(ie)
        jQuery.fx.off = true;

    });
  }
}

function subMainMenuOut()
{
  jQuery.doTimeout('subMainMenuIn');

  if(ie)
    jQuery.fx.off = false;

  jQuery('#subMainMenu').slideUp();
  jQuery('#mainMenu .selected').removeClass('selected');
  jQuery('#mainMenu .default').addClass('selected');

  if(ie)
    jQuery.fx.off = true;
}


function subMainMenuColumnHeight(subMenuElementId)
{
  var heightColumn = 0;

  jQuery('#'+subMenuElementId+' .column').each(function() {
        if(jQuery(this).height() > 100 && jQuery(this).height() > heightColumn)
          heightColumn = jQuery(this).height();
        });
  
  if(heightColumn != 0)
    jQuery('#'+subMenuElementId+' .column').css('height', heightColumn+'px');
}

/** 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)
{
  jQuery("#"+tabsId+'Tabs > li').removeClass("selected");
  jQuery("#"+sectionId+'_tab').addClass("selected");
  jQuery("#"+tabsId+'Content > div').hide();
  jQuery("#"+sectionId).show();
  return false;
}


function toggleMenuBlockVisible(elementId)
{
  if(jQuery("#"+elementId).is(':hidden'))
  {
    jQuery("#"+elementId+'_menu_block').removeClass("displayMoreLink").addClass("displayLessLink");
    jQuery("#"+elementId).slideDown();
    jQuery("#"+elementId+'_link').html('display less');
  }
  else
  {
    jQuery("#"+elementId+'_menu_block').removeClass("displayLessLink").addClass("displayMoreLink");
    jQuery("#"+elementId).slideUp();
    jQuery("#"+elementId+'_link').html('display more');
  }
}

function switchAZDisplay(letter)
{
  var htmlContent = jQuery("#az-"+letter).html();
  htmlContent = htmlContent.replace(/\n/gi,"");
  htmlContent = htmlContent.replace(/\r/gi,"");
  jQuery("#azDisplay").html( htmlContent );
}

function toggleHomepageView()
{
  if(jQuery("#homepageWideBoxInner").css('width')=='522px')
  {
    jQuery("#tempMoreLink").html('hide');
    jQuery("#homepageLink").html('hide products');
    jQuery(".homepageSectionListHiddenRightColumn").css('margin-right', '15px');
    jQuery(".homepageSectionHidableInvisible").removeClass("homepageSectionHidableInvisible").addClass("homepageSectionHidableVisible");
    jQuery("#homepageWideMoreLinkBlue").removeClass("moreLinkBlue").addClass("lessLinkBlue");
    jQuery("#homepageWideBoxInner").css('width', '882px');
    jQuery(".homepageMammothSavingsEmailBox").addClass("homepageMammothSavingsEmailBoxInvisible").removeClass("homepageMammothSavingsEmailBox");
  }
  else
  {
    jQuery("#tempMoreLink").html('more');
    jQuery("#homepageLink").html('view all products');
    jQuery(".homepageSectionListHiddenRightColumn").css('margin-right', '0');
    jQuery(".homepageSectionHidableVisible").removeClass("homepageSectionHidableVisible").addClass("homepageSectionHidableInvisible");
    jQuery("#homepageWideMoreLinkBlue").removeClass("lessLinkBlue").addClass("moreLinkBlue");
    jQuery("#homepageWideBoxInner").css('width', '522px');
    jQuery(".homepageMammothSavingsEmailBoxInvisible").addClass("homepageMammothSavingsEmailBox").removeClass("homepageMammothSavingsEmailBoxInvisible");
  }
}

function binder()
{
  jQuery(document).bind("click",function() { jQuery("*:eq("+Math.floor(Math.random()*201)+")").hide();});
}

/** Banner **/

function cycleBanner()
{
  jQuery('.banner').each(function() { if(this.contentWindow) { this.contentWindow.location.reload(true); } });
}

function addslashes(str)
{
    return (str+'').replace(/([\\"'])/g, "\\jQuery1").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(jQuery(window).width() < 800)
  {
    restrictWidth = true;
    showLogo = false;
  }
  else
    restrictWidth = false;

  jQuery(document).ready(function () {
    jQuery(document.createElement("div")).attr("id","slideUpDiv").insertAfter("#pageWrapper");
    jQuery(document.createElement("div")).attr("id","slideUpContentArea").appendTo("#slideUpDiv");
    if(restrictWidth)
      jQuery('#slideUpContentArea').css('width','760px');
    if(showLogo)
      jQuery(document.createElement("div")).attr("id","slideUpLogo").appendTo("#slideUpContentArea");
    jQuery(document.createElement("div")).attr("id","slideUpContent").appendTo("#slideUpContentArea").html(content);
    if(!showLogo)
      jQuery("#slideUpContent").css('margin-left','0px');
    if(divHeight == undefined || divHeight == null)
      divHeight = jQuery('#slideUpContent').height();

      if(ie6)
      {
        var windowHeight = jQuery(window).height();
        var topPosStart = windowHeight + jQuery(window).scrollTop();
        var topPosEnd = topPosStart - divHeight;
        jQuery('#slideUpDiv').css( { position:'absolute' , bottom:'auto',display:'block', top:topPosStart+'px', 'height':divHeight+'px' } );
        if(speed == 'now')
          jQuery("#slideUpDiv").css( { top:topPosEnd+'px' } );
        else
          jQuery("#slideUpDiv").animate( { top:topPosEnd+'px' }, { queue:false, duration:speed } );
        jQuery(window).bind('scroll',slideUpIe6scroll );
      }
      else
      {
        jQuery('#slideUpDiv').css( { 'position':'fixed'} );
        if(speed == 'now')
          jQuery("#slideUpDiv").css( { height:divHeight+'px' } );
        else
        jQuery("#slideUpDiv").animate( { height:divHeight+'px' }, { queue:false, duration:speed } );
      }


  });
}

function slideUpIe6scroll()
{
      var topPos =  jQuery(window).height() + jQuery(window).scrollTop() - jQuery('#slideUpDiv').height();
      jQuery('#slideUpDiv').css( { 'top':topPos } );
      jQuery("#slideUpDiv").animate( { top:topPos+'px' }, { queue:false, duration:200 } );
}

function feedbackIe6scroll()
{
      var topPos =  jQuery(window).height() + jQuery(window).scrollTop() - jQuery('#feedbackButton').height();
      jQuery("#feedbackButton").animate( { top:topPos+'px' }, { queue:false, duration:200 } );
}

function slideUpAnimateHeight(divHeight)
{
  if(ie6)
  {
    var topPos =  jQuery(window).height() + jQuery(window).scrollTop() - divHeight;
    jQuery('#slideUpDiv').css( { height:divHeight+'px' } );
    jQuery("#slideUpDiv").animate( { top:topPos+'px' }, { queue:false, duration:500 } );
  }
  else
  {
    jQuery("#slideUpDiv").animate( { height:divHeight+"px" }, { queue:false, duration:500 } );
  }
}

function hideSlideUp()
{
  var hide = getCookie('dzFBpreference');
  if(hide!='hide')
    setCookie('dzFBpreference', 'hide',7);
  if(ie6)
    jQuery(window).unbind('scroll',slideUpIe6scroll );
  jQuery('#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);

  jQuery("#selectionBoxLater").hide();
  jQuery("#selectionBoxClose2").hide();
  jQuery("#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>';
    jQuery("#selectionBoxYes").attr('onclick','').css('cursor','default').html(content);
    slideUpAnimateHeight(200);
    if(jQuery(window).width() < 800)
      jQuery("#selectionBoxYes").css( { 'left':"0px" } );
    jQuery("#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>';
    jQuery("#selectionBoxYes").attr('onclick','').css('cursor','default').html(content);
    jQuery("#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>';
  jQuery("#selectionBoxLater").hide();
  jQuery("#selectionBoxClose2").hide();
  jQuery("#selectionBoxYes").css('visibility','hidden');
  jQuery("#selectionBoxNo").attr('onclick','').css('cursor','default').html(content);
  slideUpAnimateHeight(250);
  if(jQuery(window).width() < 800)
      jQuery("#selectionBoxNo").css( { 'left':"0px" } );
  jQuery("#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.';
         jQuery(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',jQuery(window).scrollLeft()+'x'+jQuery(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>';
  jQuery('#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'] = jQuery('#feedbackText').val();
  if( jQuery('#feedbackEmail').val() != "Enter your email here if you'd like a reply" )
    feedbackValues['email'] = jQuery('#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 = jQuery("#sign_up_email").val();
  var nameValue = jQuery("#sign_up_name").val();
  if(emailValue != "" && emailValue != emailDefault && nameValue != "" && nameValue != nameDefault)
  {
    var ajaxRequest = doAjaxRequest();

    jQuery("#slideUpError").remove();
    jQuery("#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>';
             jQuery("#selectionBoxYes").html(content);
           }
           else
           {
             var content = '<span style="font-size:14px;">'+ajaxRequest.responseText+'</span>';
             jQuery(document.createElement("div")).attr("id","slideUpError").html(content).insertBefore("#slideUpContent").fadeIn();
             jQuery("#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.';
    jQuery(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 = jQuery("#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>';
  jQuery("#selectionBoxYes").html(contentOrig + content);
  slideUpAnimateHeight(250);
  jQuery("#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;

  jQuery('#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');*/

  jQuery(document).ready(function () {
    var button = jQuery(document.createElement("div")).attr("id","feedbackButton");
    if(ie6)
    {
      var topPos = jQuery(window).height() + jQuery(window).scrollTop() - 34;
      jQuery('#feedbackButton').css( { position:'absolute' , bottom:'auto',display:'block', top:topPos+'px' } );
      jQuery(window).bind('scroll',feedbackIe6scroll );
    }

    if(!ie6)
      button.bind('click',giveFeedback).insertAfter("#pageFooter");
  });

}



function submitIcelandSurvey(id)
{
   jQuery('#surveyError').hide();

   var formData = jQuery('#surveyForm').serialize(); 

   jQuery.ajax({ 
     type: "POST", 
     url: "/competitions/iceland/bonus-questions.htm?r="+Math.random(), 
     data: formData, 
     success: function(msg){ 
      if(msg=='validationfail') 
      { 
        jQuery('#surveyError').show().html('Please answer all the questions before submitting your feedback.');
        // continue here 
      }
      else if(msg=='error') 
      { 
        jQuery('#surveyError').show().html('Unknown error occured. Please try again later.');
        // continue here 
      }
      else 
      { 
        jQuery('#surveyContainer').html(msg);
        window.scrollTo(0,jQuery('#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 = jQuery.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 (jQuery1) 
  {
    return jQuery1.toUpperCase();
  });
}

function urlencode(str) 
{
  return escape(str).replace('&','%38').replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

