var timer;

$(document).ready(function()
{
  //enhanceHeadings();
  
  prepareCameraFinder();
  
  createHelpTips();
  activateHelpTips();
  
  prepareExpandableBoxes();
  
  prepareTabs();
  prepareCarousels();
  
  prepareSearchForm();
  
  // lightbox initialisation
  $('a[rel*="lightbox"]').lightBox();
    
  $('#home .column:odd').addClass('two');
  
  // SLIDESHOW
  if($('div#slideshow').length)
  {
    $('div#slideshow').slideshow();
    
    skipToNextSlide('firstcall');
  }
  
  if ( $('div.divNeedToLogin').length )
  {
    $('div.divNeedToLogin').hide();
    
    $('dl#articleRating dd strong').bind(
      'mouseover',function(){
        $('div.divNeedToLogin').show();
      }
    ).bind(
      'mouseout',function(){
        $('div.divNeedToLogin').hide();
      }
    );
    
    $('div.divNeedToLogin').bind(
      'mouseover',function(){
        $('div.divNeedToLogin').show();
      }
    ).bind(
      'mouseout',function(){
        $('div.divNeedToLogin').hide();
      }
    );
  }
});

function enhanceHeadings()
{
  $('div.column h2').each(function(){
    $(this).replaceWith('<div class="headerContainer"><h2>'+$(this).html()+'</h2><img class="glyph" src="./media/img/heading_glyph.gif" alt="glyph" /></div> <!-- .headerContainer -->');
  });
}

function prepareSearchForm()
{
  $('#ctl00_Searchform1_txtSearchKeywords').click(function()
  {
    if(this.value==this.defaultValue)this.value='';
  });
  
  $('#btnSubmitSearchForm').click(function()
  {
    if($('#ctl00_Searchform1_txtSearchKeywords').val().trim()=='')
    {
      BlockAlert('Enter your search term');
      $('#ctl00_Searchform1_txtSearchKeywords').focus();
      return false;
    }
    else
    {
      redirectToSearch();
      return false;
    }
  });
  
  $("#ctl00_Searchform1_txtSearchKeywords").keypress(
  function (e) 
  {
    if(e.which==13)
    {
      redirectToSearch();
      return false;
    }
  }
  );
}

/* ie not handling the enter key very nicely */
/*
$(document).ready(function()
{
  if ($.browser.msie) 
  {
    $(".article .form li input").keypress(function (e)
    {
      if(e.which==13) {return false;}
    });
  }
});
*/

function redirectToSearch()
{
  document.location.href = '/site-search-results?q=' + $('#ctl00_Searchform1_txtSearchKeywords').val();
}

function prepareCameraFinder()
{
  $('div#cameraFinder div.panel ins img').click(function(){
    top.location=$(this).parent().parent().parent().parent().parent().attr('href');
  });
  
  /*
  $('div#cameraFinder div.panel a').each(function()
  {
    $(this).click(function()
    {
      if ( $(this).parent().hasClass('open') )
      {
        $(this).parent().find('form').slideUp('slow',function(){ $(this).parent().removeClass('open'); });
      }
      else
      {
        $(this).parent().addClass('open');
        $(this).parent().find('form').css('display','none');
        
        $(this).parent().find('form').slideDown('slow');
      }
      
      return false;
    });
  });
  */
}

function restoreMouseOvers()
{
  $('div#cameraFinder div.panel:not(.open) a').each(function()
  {
    $(this).bind(
      'mouseover',function(){
        $(this).css('background-color','#D6D6D6');
      }
    ).bind(
      'mouseout',function(){
        $(this).css('background-color','#E9E9E9');
      }
    );
  });
}

function createHelpTips()
{
  $('div.helpTip').each(function()
  {
    if ( !$(this).parent().hasClass('open') )
    {
      $(this).before('<span class="helpTipReveal">?</span>');
      $(this).append('<img src="/media/img/helpTipTag.gif" alt="help tip tag" />');
    }
  });
}

function activateHelpTips()
{
  $('span.helpTipReveal').bind(
    'mouseover',function(){
      $(this).next('div.helpTip').show();
      $(this).parent().find('a').css('background-color','#D6D6D6');
    }
  ).bind(
    'mouseout',function(){
      $(this).next('div.helpTip').hide();
      $(this).parent().find('a').css('background-color','#E9E9E9');
      restoreMouseOvers();
    }
  );
}

function prepareExpandableBoxes()
{
  $('div#emailBestDealsForm').hide();
  
  $('a#emailBestDeals').click(function()
  {
    $('div#emailBestDealsForm').slideToggle();
    return false;
  });
  
  //$('div#commentsBox').hide();
  $('div#friendsBox').hide();
  
  $('a#toggleComments').click(function()
  {
    if ( $('a#toggleFriend').hasClass('active') )
    {
      $('a#toggleFriend').removeClass('active');
      $('div#friendsBox').slideUp();
    }
    
    if ( $(this).hasClass('active') )
    {
      $(this).removeClass('active');
      $('div#commentsBox').slideUp();
    }
    else
    {
      $(this).addClass('active');
      $('div#commentsBox').slideDown();
    }
    return false;
  });
  
  $('a#toggleFriend').click(function()
  {
    if ( $('a#toggleComments').hasClass('active') )
    {
      $('a#toggleComments').removeClass('active');
      $('div#commentsBox').slideUp();
    }
    
    if ( $(this).hasClass('active') )
    {
      $(this).removeClass('active');
      $('div#friendsBox').slideUp();
    }
    else
    {
      $(this).addClass('active');
      $('div#friendsBox').slideDown();
    }
    return false;
  });
  
  $('div#postCommentForm').hide();
  
}

function prepareTabs()
{
  // Tabbed Info
  $('#tabbedInfo ul').css('display','block');
  $('#tabbedInfo').tabs({ fxFade: true, fxSpeed: 'fast' });
}

function prepareCarousels()
{
  if ( $('#imageCarousel').length )
  {
    // Make sure there are more than 4 images...
    if ( $('#imageCarousel li').length > 5 )
    {
      $('#imageCarousel').jcarousel({ scroll:5,visible:5 });
    }
    else
    {
      $('#imageCarousel').replaceWith('<div class="carouselContainer"><ul id="imageCarousel">'+$('#imageCarousel').html()+'</ul></div>');
    }
    
    $('#imageCarousel a').click(function(){
      var src  = $(this).attr('href');;
      $('img#mainImage').attr('src',src);
      return false;
    });
  }
}

/* 
 * SLIDESHOW
 * 
 * Based upon:
 * jQuery Coda-Slider v1.1 - http://www.ndoherty.com/coda-slider
 * Copyright (c) 2007 Niall Doherty
 */
$.fn.slideshow = function(settings)
{
  return this.each(function()
  {
    var container  = $(this);
    
    var slideWidth = container.find('div.slide').width();
    var slideCount = container.find('div.slide').size();
    var slideshowWidth = slideWidth*slideCount;
    
    container.find('div.slideshow').css("width",slideshowWidth);
    
    var cslide = 1;
    
    container.each(function(i)
    {
      $('li#slide1 a').click(function(){skipTo('1');return false;});
      $('li#slide2 a').click(function(){skipTo('2');return false;});
      $('li#slide3 a').click(function(){skipTo('3');return false;});
      
      function skipTo(slide)
      {
        var cnt = -(slideWidth*(slide-1));
            
        $('div.slideshow').animate({ marginLeft: cnt+"px" },750);
        
        $('li#slide1').removeClass('active');
        $('li#slide2').removeClass('active');
        $('li#slide3').removeClass('active');
        
        switch(slide)
        {
          case '1':
            $('li#slide1').addClass('active');
            break;
          case '2':
            $('li#slide2').addClass('active');
            break;
          case '3':
            $('li#slide3').addClass('active');
            break;
        }
      }
    });
  });
};

function skipToNextSlide(a)
{
  clearTimeout(timer);
  
  timer = setTimeout('skipToNextSlide()',10000);
  
  if ( typeof(a) == 'undefined' ) // Not initial page load...
  {
    switch( $('ul#slideshowControl li.active').attr('id').substring(5) )
    {
      case '1' : changeSlide('2'); break;
      case '2' : changeSlide('3'); break;
      case '3' : changeSlide('1'); break;
    }
  }
}

function changeSlide(i)
{
  var container  = $('div#slideshow');
  
  var slideWidth = container.find('div.slide').width();
  var slideCount = container.find('div.slide').size();
  var slideshowWidth = slideWidth*slideCount;
  
  container.find('div.slideshow').css("width",slideshowWidth);
  
  var cnt = -(slideWidth*(i-1));
  
  $('div.slideshow').animate({ marginLeft: cnt+"px" },750);
  
  $('li#slide1').removeClass('active');
  $('li#slide2').removeClass('active');
  $('li#slide3').removeClass('active');
  
  switch(i)
  {
    case '1':
      $('li#slide1').addClass('active');
      break;
    case '2':
      $('li#slide2').addClass('active');
      break;
    case '3':
      $('li#slide3').addClass('active');
      break;
  }
}

function BlockAlert(aMessage)
{
  $.blockUI({
    message:'<h1>' + aMessage + '</h1>',
    css:
    {
      border: 'none',
      padding: '15px',
      backgroundColor: '#000',
      '-webkit-border-radius': '10px',
      '-moz-border-radius': '10px',
      opacity: '.5',
      color: '#fff'
    }
  });
  
  setTimeout($.unblockUI,2000);
}


function hideFormOptions(value)
{
  // Toogle visibility of search form option panel
  // dependant on search for Compact Cameras under £250
  if (value == '0,250') {
    $("#cscSearch_CompactForm_featureslist").css("display", "none");
    $(".CameraFinderForm .optional").css("display", "none");
    $(".compactsearchmessage").css("display", "block");
  }
  else {
    $("#cscSearch_CompactForm_featureslist").css("display", "block");
    $(".CameraFinderForm .optional").css("display", "block");
    $(".compactsearchmessage").css("display", "none");
  }
}

String.prototype.trim = function()
{
  return this.replace(/^\s+|\s+$/g,"");
}

function rate(rating)
{
    jQuery.ajax(
    {
    url: '/assets/handlers/rate.ashx?rating=' + rating + '&type=' + ratingType + '&idToRate=' + idToRate,
    type: 'GET',
    dataType: 'text',
    cache: true,
    async:true,
    timeout: 120000,
    error: function()
        {
            alert('Error rating, please try again later');
        },
    success: function(somehtml)
        {
           if(somehtml == 'OK')
           {
            //set all rating displays to the rated amount
            //$(".rating:eq(0)").replaceWith('<span class="stars' + rating + '">' + rating + ' Stars</span>');
            //$(".rating:eq(0)").replaceWith('<strong class="stars' + rating + '">' + rating + ' Stars</strong>');
            
            $(".rating").replaceWith('<strong class="stars' + rating + '">' + rating + ' Stars</strong>');
           }     
        }
    });
}
