﻿var v_inpProductNo = null;
var v_inpLandscape = null;
var v_inpRange = null;

var v_PreviewProductNo = null;
var v_PreviewRange = null;

var baseURL = null;
var isFlowers = null;

var v_PreviewRangeLink = null;

var v_PreviewDescriptionFrame = null;

var v_PreviewImageListItem = null;
var v_PreviewFrontListItem = null;
var v_PreviewInsideListItem = null;
var v_PreviewBackListItem = null;
var v_PreviewDescriptionListItem = null;


var v_PreviewInsideImageContainer = null;
var v_PreviewInsideImage1 = null;
var v_PreviewInsideImage2 = null;
var v_PreviewInsideCopy = null;

var v_PreviewBackImage = null;
var v_PreviewBackCopy = null;

var v_PreviewDescriptionCopy = null;

var v_ArrowButtonNext = null;
var v_ArrowButtonPrev = null;
var v_PrevPageArrow = null;
var v_NextPageArrow = null;

var v_cbProductSize = null;

var productInfoUrl = null;
var favouritesUrl = null;

var noCards = 0;

var itemsXPage = 9;
var currentItemIndex = 0;
var currentPage = null;

var currentPageButtonNo = 1;
var currentPageSet = 1;

var imageLoaded = false;


// JQuery variables
var $IconStar = null;
var $IconSent = null;
var $IconCamera = null;
var $FrontImage = null;

var $PreviewImageFrame = null;
var $PreviewFrontFrame = null;
var $PreviewInsideFrame = null;
var $PreviewBackFrame = null;
var $PreviewDescriptionFrame = null;

var $PreviewFrontImage = null;
var $PreviewFrontCopy = null;

function LoadJQueryVariables() { // to be called on the document.ready() event
  // preview area icons
  $IconStar   = jQuery('input[icon=star]');
  $IconSent   = jQuery('input[icon=sent]');
  $IconCamera = jQuery('img[icon=camera]');
  
  // preview images
  $FrontImage = jQuery('img[previewImage]');
  
  // preview frames (div showing in the left hand)
  $PreviewImageFrame        = jQuery('div[previewImageFrame]');
  $PreviewFrontFrame        = jQuery('div[previewFrontFrame]');
  $PreviewInsideFrame       = jQuery('div[previewInsideFrame]');
  $PreviewBackFrame         = jQuery('div[previewBackFrame]');
  $PreviewDescriptionFrame = jQuery('div[previewImageFrame]');
  
  $PreviewFrontImage = jQuery('img[previewFrontImage]');
  $PreviewFrontCopy = jQuery('div[previewFrontCopy]');

}


_st = window.setTimeout;

window.setTimeout = function(fRef, mDelay) {
  if (typeof fRef == "function") {
    var argu = Array.prototype.slice.call(arguments, 2);
    var f = (function() { fRef.apply(null, argu); });
    return _st(f, mDelay);
  }
  return _st(fRef, mDelay);
}

var hostName = null;
function getHost() {
  if (!hostName) {
    var a = document.URL.split('//'); // split at protocol
    a = (a[1] ? a[1] : a[0]).split('/');
    // use last element of a; split at /
    // host is a[0]
    var hostName = a[0];
    if (hostName == 'xlocalhost') {
      hostName = a[0] + '/' + a[1];
      hostName = '/MoonpigWeb';
    }
    else {
      hostName = '';
    }
  }
  return hostName;
}

function doImageLoaded() {
  imageLoaded = true;
}

//////////
//use class name to select right background animated graphic

/////////////
function LoadProductInfo(moonpigProductNo, page1PortraitScaling, page1LandscapeScaling, middlePortraitScaling, middleLandscapeScaling, selectedItemIndex) {
  if (!productInfoUrl) {
    loadVars();
    LoadJQueryVariables();
  }

  selectItem(selectedItemIndex);

  ShowWaitingImage()

  jQuery.post(// AJAX call to get product info
    productInfoUrl,
    { 'mpn'                   : moonpigProductNo,
      'page1PortraitScaling'  : page1PortraitScaling,
      'page1LandscapeScaling' : page1LandscapeScaling,
      'middlePortraitScaling' : middlePortraitScaling,
      'middleLandscapeScaling': middleLandscapeScaling
    },
    productLoaded,
    'json'
   );
}

var product = null;

function productLoaded(data) {
  product = data;

  try {
    if (pageTracker) {
          pageTracker._trackEvent('New Card Gallery', 'View ' + product.moonpigProductNo, '', 0);
      }
  }
  catch (ex) {
  }  

  v_inpProductNo.value = product.moonpigProductNo;
  v_inpLandscape.value = (product.landscape ? "True" : "False");
  v_inpRange.value = product.range;
  var isMug = product.productCategoryId == 11;
  var isTShirt = product.productCategoryId == 12;
  //alert(v_inpProductNo.value);
  
  // show the front image when a new product is selected
  PreviewShowImage();

  // enable / disable prev and next card buttons
  if (currentItemIndex == 0) {
    jQuery('img[userAction=PreviousItem]')
      .attr('src', baseURL + 'CardGallery/images/arrowPrevious_inactive_white.gif')
      .attr('active', 'false')
      .css('cursor', 'default');
  }
  else {
    jQuery('img[userAction=PreviousItem]')
      .attr('src', baseURL + 'CardGallery/images/arrowPrevious_active_white.gif')
      .attr('active', 'true')
      .css('cursor', 'pointer');
  }
  if (currentItemIndex == noCards - 1) {
    jQuery('img[userAction=NextItem]')
      .attr('src', baseURL + 'CardGallery/images/arrowNext_inactive_white.gif')
      .attr('active', 'false')
      .css('cursor', 'default');
  }
  else {
    jQuery('img[userAction=NextItem]')
      .attr('src', baseURL + 'CardGallery/images/arrowNext_active_white.gif')
      .attr('active', 'true')
      .css('cursor', 'pointer');
  }


  $('#spanCardNoLabel').text((isMug ? 'Mug' : (isTShirt ? "T-Shirt" : "Card")));

  v_PreviewProductNo.innerHTML = product.moonpigProductNo;
  //v_PreviewRange.innerHTML = product.range;
  v_PreviewRangeLink.href = baseURL + 'CardGallery/' + (isMug ? "Gifts/Mugs/" : (isTShirt ? "Gifts/T-Shirts/" : "Greeting+Cards/")) + 'Range/' + product.range + '/gallery.aspx';
  $(v_PreviewRangeLink).text(product.range);

  $FrontImage.attr('src', product.page1ImageUrl);

  // set the text and small preview image for the 'Front' preview tab
  $PreviewFrontCopy.html(product.plainText);
  $PreviewFrontImage.attr('src', product.page1ImageUrl);

  // set the text and images for the inside pages
  v_PreviewInsideCopy.innerHTML = product.insideText.replace(/\n/g, '<br />');
  if (v_PreviewInsideCopy.innerHTML.length == 0) {
    jQuery('div[insideMessage]').css('display', 'none');
    jQuery('div[insideCopy]').css('display', 'none');
  }
  else {
    jQuery('div[insideMessage]').css('display', 'block');
    jQuery('div[insideCopy]').css('display', 'block');
  }
  if (product.page2ImageUrl) {
    v_PreviewInsideImage1.src = product.page2ImageUrl;
  }
  else {
    v_PreviewInsideImage1.src = baseURL + '/App_Themes/Moonpig/images/Christmas/animated_background.gif';
  }
  if (product.page3ImageUrl) {
    v_PreviewInsideImage2.src = product.page3ImageUrl;
  }
  else {
    v_PreviewInsideImage2.src = baseURL + '/App_Themes/Moonpig/images/Christmas/animated_background.gif';
  }
  
  if (isMug || isTShirt) {
    $('li[giftPreview]').css('display', 'inline');
    $('li[preview] a').text((product.productCategoryId == 11 ? 'Mug' : (product.productCategoryId == 12 ? 'T-Shirt' : 'Card')));
    $('li[frontPreview] a').text("Personalise");
    $('li[insidePreview]').css('display', 'none');
    $('.productDetails[GiftPreview] div[MugPreview]').css('display', (product.productCategoryId == 11 ? "block" : "none"));
    $('.productDetails[GiftPreview] div[TShirtPreview]').css('display', (product.productCategoryId == 12 ? "block" : "none"));
    if (isTShirt) {
      $('.productDetails[GiftPreview] div[TShirtPreview] img[TShirtPreview]').attr('src', globalPath + 'images/GiftPreviewImages/GetGiftGalleryImage.ashx?pw=334&productId=' + product.productId + '&mpn=' + product.moonpigProductNo + "&sv=" + mpSessionId + "&TShirt=1");
    }
    else if (isMug) {
      $('.galleryPage .productDetails .mugPreview .mugSmallPreview div').removeClass('selectedMug');
      $('.galleryPage .productDetails .mugPreview img[MugLargePreview]').attr('src', globalPath + 'images/GiftPreviewImages/GetGiftGalleryImage.ashx?pw=300&productId=' + product.productId + '&mpn=' + product.moonpigProductNo + "&sv=" + mpSessionId + "&Mug=1");
      $('.galleryPage .productDetails .mugPreview img[SmallA]').attr('src', globalPath + 'images/GiftPreviewImages/GetGiftGalleryImage.ashx?pw=300&productId=' + product.productId + '&mpn=' + product.moonpigProductNo + "&sv=" + mpSessionId + "&Mug=2");
      $('.galleryPage .productDetails .mugPreview img[SmallB]').attr('src', globalPath + 'images/GiftPreviewImages/GetGiftGalleryImage.ashx?pw=300&productId=' + product.productId + '&mpn=' + product.moonpigProductNo + "&sv=" + mpSessionId + "&Mug=3");
      $('.galleryPage .productDetails .mugPreview img[SmallF]').attr('src', globalPath + 'images/GiftPreviewImages/GetGiftGalleryImage.ashx?pw=300&productId=' + product.productId + '&mpn=' + product.moonpigProductNo + "&sv=" + mpSessionId + "&Mug=1").parent().addClass('selectedMug');
    }
  }
  else {
    $('li[giftPreview]').css('display', 'none');
    $('li[preview] a').text((product.productCategoryId == 11 ? 'Mug' : (product.productCategoryId == 12 ? 'T-Shirt' : 'Card')));
    $('li[frontPreview] a').text("Front");
    $('li[insidePreview]').css('display', 'inline');
  }

  // back of the card
  
  // show/hide the Back tab
  if (!product.editableBack) {
    jQuery('li[backTab]').css('display', 'none');
  }
  else {
    jQuery('li[backTab]').css('display', 'inline');
  }

  if (product.backText == null) {
    product.backText = '';
  }

  // show/hide 'highlighted' message
  if (product.backText.length == 0) {
    v_PreviewBackCopy.style.display = 'none';
    jQuery('div[backMessage]').css('display', 'none');
  }
  else {
    jQuery('div[backMessage]').css('display', 'block');
    v_PreviewBackCopy.style.display = 'block';
    v_PreviewBackCopy.innerHTML = product.backText;
  }

  // show/hide 'text can be added' message
  if (product.textAreasBack) {
    jQuery('div[bottomMessageBack]')
      .css('display', 'block')
      .html('Text can be added in the next step');
  }
  else {
    jQuery('div[bottomMessageBack]').css('display', 'none');
  }

  if (!product.textAreasBack && product.backText.length == 0) {
    jQuery('div[bottomMessageBack]')
      .html('There are no editable regions')
      .css('display', 'block');
  }
  
  v_PreviewBackImage.src = product.backImageUrl;

  // set the description text
  v_PreviewDescriptionCopy.innerHTML = product.description;

  EnableDisablePageArrows();

  SetPaperType();

  SetAvailableSizes();

  ManageIcons();

  LoadFavCategoriesSelect();

  SetAlsoAvailableAs();

  //setTimeout('loadTextItemsNew()', 100);
}

function ShowWaitingImage() {
  var classType = 'portrait';

  var $SelectedItem = jQuery('div[productFrameNo]').filter('.selected');
  
  if ($SelectedItem.hasClass('square')) {
    classType = 'square';
  }
  else if ($SelectedItem.hasClass('landscape')) {
    classType = 'landscape';
  }
  else if ($SelectedItem.hasClass('mug')) {
    classType = 'mug';
  }

  
  $PreviewImageFrame.removeAttr('class').addClass('productImage').addClass(classType);
  //v_PreviewFrontImage.className = classType;
  $PreviewFrontImage.removeAttr('class').addClass(classType);
  v_PreviewBackImage.className = classType;
  v_PreviewInsideImageContainer.className = classType;

  $FrontImage.attr('src', baseURL + 'CardGallery/images/ajax-loader_snake_large_' + classType + '.gif');

}

function SetPaperType() {
  var $PaperType = jQuery('div[paperType]');
  if (product.productCategoryId == 11 || product.productCategoryId == 12) {
    $('.paperTypeTitle').text('Product information');
    if (product.productCategoryId == 11) {
      $PaperType.html('A full wrap printed, dishwasher safe, 10oz white ceramic mugs.');
    }
    else if (product.productCategoryId == 12) {
    $PaperType.html('The classic white 100% cotton T-shirts are available for men, women - in a flattering fitted style - and kids in a range of sizes.');
    }
  }
  else {
    $('.paperTypeTitle').text('Paper type');
    switch (product.paperType) {
      case '1':
        $PaperType.html('Smooth card with varnished finish');
        break;
      case '2':
        $PaperType.html('Textured card with unvarnished finish');
        break;
      case '3':
        $PaperType.html('Textured card with embroidered patch');
        break;
      case '4':
        $PaperType.html('Smooth card with unvarnished finish');
        break;
    }
  }
}

function LoadSaveFavourites(moonpigProductNo, favCateogory, action) {

  if (action == 'save') {
    $IconStar
      .attr('src', baseURL + 'CardGallery/images/iconStar_on.png')
      .attr('isFavourite', 'true');
  }
  else {
    $IconStar
      .attr('src', baseURL + 'CardGallery/images/iconStar_off.png')
      .attr('isFavourite', 'false');
  }
  LoadFavCategoriesSelect();
  jQuery.post(
    favouritesUrl,
    { 'mpn': moonpigProductNo,
      'fcat': favCateogory,
      'a': action
    },
    function(data) {
      // we dont need to do anything here
      return false;
    });

}


var sentMessage = 'sent';

function ManageIcons() {
  var isMug = product.productCategoryId == 11;
  var isTShirt = product.productCategoryId == 12;
  
  if (product.isPhotoUpload) {
    $IconCamera.css('display', 'inline');
    $('.uploadCount').html('(' /*+ product.mandatoryPhotoUploadCount + '/' */+ product.photoUploadCount + ')');
    //$('.uploadCount').attr('title', 'You ' + (product.mandatoryPhotoUploadCount == product.photoUploadCount ? 'will need to' : 'can') + ' upload ' + product.photoUploadCount + ' photos' + (product.mandatoryPhotoUploadCount > 0 && product.mandatoryPhotoUploadCount < product.photoUploadCount ? ' of which ' + product.mandatoryPhotoUploadCount + ' have to be uploaded' : ''));
    optionalPhotoCount = product.photoUploadCount - product.mandatoryPhotoUploadCount;
    if (product.photoUploadCount == 1)
    {
      strText = 'There is <b>' + product.photoUploadCount + '</b> photo to be uploaded (' + (product.mandatoryPhotoUploadCount > 0 ? 'required' : 'optional') + ')';
    }
    else
    {
      strText = 'There are <b>' + product.photoUploadCount + '</b> photos to be uploaded.' + (product.mandatoryPhotoUploadCount > 0 ? '<br /><b>' + product.mandatoryPhotoUploadCount + '</b> photo' + (product.mandatoryPhotoUploadCount == 1 ? ' is' : 's are') + ' required' : '') + (optionalPhotoCount > 0 ? '<br /><b>' + optionalPhotoCount + '</b> photo' + (optionalPhotoCount == 1 ? ' is' : 's are') + ' optional' : '') 
    }
    strText += '<br />'
    + (product.frontPhotoUploadCount > 0 ? '<br />' + '<b>Front:</b> ' + (product.frontMandatoryPhotoUploadCount > 0 ? product.frontMandatoryPhotoUploadCount + ' photo' + (product.frontMandatoryPhotoUploadCount > 1 ? 's' : '') + ' required' : '') +
      (product.frontMandatoryPhotoUploadCount > 0 && product.frontPhotoUploadCount - product.frontMandatoryPhotoUploadCount > 0 ? ',' : '') + (product.frontPhotoUploadCount - product.frontMandatoryPhotoUploadCount > 0 ? product.frontPhotoUploadCount - product.frontMandatoryPhotoUploadCount + ' photo' + (product.frontPhotoUploadCount - product.frontMandatoryPhotoUploadCount > 1 ? 's' : '') + ' optional' : '') : '')
    + (product.insidePhotoUploadCount > 0 ? '<br />' + '<b>Inside:</b> ' + (product.insideMandatoryPhotoUploadCount > 0 ? product.insideMandatoryPhotoUploadCount + ' photo' + (product.insideMandatoryPhotoUploadCount > 1 ? 's' : '') + ' required' : '') +
      (product.insideMandatoryPhotoUploadCount > 0 && product.insidePhotoUploadCount - product.insideMandatoryPhotoUploadCount > 0 ? ',' : '') + (product.insidePhotoUploadCount - product.insideMandatoryPhotoUploadCount > 0 ? product.insidePhotoUploadCount - product.insideMandatoryPhotoUploadCount + ' photo' + (product.insidePhotoUploadCount - product.insideMandatoryPhotoUploadCount > 1 ? 's' : '') + ' optional' : '') : '')
    + (product.backPhotoUploadCount > 0 ? '<br />' + '<b>Back:</b> ' + (product.backMandatoryPhotoUploadCount > 0 ? product.backMandatoryPhotoUploadCount + ' photo' + (product.backMandatoryPhotoUploadCount > 1 ? 's' : '') + ' required' : '') +
      (product.backMandatoryPhotoUploadCount > 0 && product.backPhotoUploadCount - product.backMandatoryPhotoUploadCount > 0 ? ',' : '') + (product.backPhotoUploadCount - product.backMandatoryPhotoUploadCount > 0 ? product.backPhotoUploadCount - product.backMandatoryPhotoUploadCount + ' photo' + (product.backPhotoUploadCount - product.backMandatoryPhotoUploadCount > 1 ? 's' : '') + ' optional' : '') : '')
    $('.uploadCount').parent().attr('tooltipText', strText);
    
  }
  else {
    $IconCamera.css('display', 'none');
    $('.uploadCount').html('');
    $('.uploadCount').parent().attr('tooltipText', '');
  }

  if (product.isFavourite) {
    $IconStar.attr('src', baseURL + 'CardGallery/images/iconStar_on.png');
    $IconStar.attr('isFavourite', 'true');
  }
  else {
    $IconStar.attr('src', baseURL + 'CardGallery/images/iconStar_off.png');
    $IconStar.attr('isFavourite', 'false');
  }

  var strToolTipText = '';
  if ($IconSent.attr('loggedin') == '0') {// user not logged in, show the envelope and do nothing else
    $IconSent.attr('src', baseURL + 'CardGallery/images/iconSent_off.png');
    strToolTipText = 'Log in to see if you have sent this ' + (isMug ? 'Mug' : (isTShirt ? 'T-Shirt' : 'card')) + ' before';

    if (strToolTipText != '') {
      $IconSent.attr('tooltipText', strToolTipText);
    }
  }
  else {// user logged in, show the tooltip message
    if (product.PreviousSentAddresses[0]) {
      var strText = "<div class='tooltipTitle'>You have previously sent this " + (isMug ? 'Mug' : (isTShirt ? 'T-Shirt' : 'card')) + " to</div>";

      for (i = 0; i < product.PreviousSentAddresses.length; i++) {
        address = product.PreviousSentAddresses[i];
        strText += "<div class='sentList'>" + address.FirstName + ' ' + address.LastName + ' on ' + address.OrderDate + '</div>';
      }

      strToolTipText += strText;

      $IconSent.attr('ProductNo', product.moonpigProductNo);
    }

    if (product.SentToMe > 0) {
      var times = '';
      if (product.SentToMe == 1) {
        times = 'once';
      }
      else if (product.SentToMe == 2) {
        times = 'twice';
      }
      else {
        times = product.SentToMe + ' times';
      }

      var strText = "<div class='tooltipTitle'>You sent this " + (isMug ? 'Mug' : (isTShirt ? 'T-Shirt' : 'card')) + " back to yourself " + times + "</div>";
      strToolTipText += strText;

      $IconSent.attr('ProductNo', product.moonpigProductNo);
    }
    if (strToolTipText != '') {
      strToolTipText += "<div class='envelopefooter'>Click on the envelope to view your order history</div>";
      $IconSent.attr('tooltipText', strToolTipText);
      
      // there are some previously sent, show the active envelope image
      $IconSent
        .attr('src', baseURL + 'CardGallery/images/iconSent.png')
        .attr('active', '1');
    }
    else {
      strToolTipText = "You haven't sent this " + (isMug ? 'Mug' : (isTShirt ? 'T-Shirt' : 'card')) + " before";
      $IconSent.attr('tooltipText', strToolTipText);
      // there are no previously sent, show the inactive envelope image
      $IconSent
        .attr('src', baseURL + 'CardGallery/images/iconSent_off.png')
        .attr('active', '0');
    }
  }

}

function SaveFavouritesDialog(existing) {
  var category = '';
  if (existing) {
    var combo = document.getElementById('ddlCategories');
    var index = combo.selectedIndex;
    category = combo[index].text;
    jQuery('#dialog').dialog('close');
  }
  else {
    category = document.getElementById('txtFavNewCategory').value;
  }
  LoadSaveFavourites(product.moonpigProductNo, category, 'save');
  return false;
}

function DeleteFavouriteDialog() {
  LoadSaveFavourites(product.moonpigProductNo, '', 'delete');
}

function EnableDisablePageArrows() {
  if (!v_NextPageArrow) {
    v_NextPageArrow = document.getElementById('ctl00_contentMain_imgArrowNextPage');
  }
  if (!v_PrevPageArrow) {
    v_PrevPageArrow = document.getElementById('ctl00_contentMain_imgArrowPreviousPage');
  }
  if (!v_NextPageArrow) {
    setTimeout(EnableDisablePageArrows, 100);
    return;
  }
  if (currentPageButtonNo == 1) {
    jQuery('.arrow[userAction=PreviousPage]')
      .attr('src', baseURL + 'CardGallery/images/arrowPrevious_inactive_beige.gif')
      .attr('active', 'false')
      .css('cursor', 'default');
  }
  else {
    jQuery('.arrow[userAction=PreviousPage]')
      .attr('src', baseURL + 'CardGallery/images/arrowPrevious_active_beige.gif')
      .attr('active', 'true')
      .css('cursor', 'pointer');
  }
  var pages = parseInt(noCards / itemsXPage);
  if (noCards % itemsXPage > 0) pages = pages + 1;
  if (currentPageButtonNo == pages) {
    jQuery('.arrow[userAction=NextPage]')
      .attr('src', baseURL + 'CardGallery/images/arrowNext_inactive_beige.gif')
      .attr('active', 'false')
      .css('cursor', 'default');
  }
  else {
    jQuery('.arrow[userAction=NextPage]')
      .attr('src', baseURL + 'CardGallery/images/arrowNext_active_beige.gif')
      .attr('active', 'true')
      .css('cursor', 'pointer');
  }
  if (noCards < 10) {
    v_PrevPageArrow.style.display = 'none';
    v_NextPageArrow.style.display = 'none';
  }
}

function LoadFavCategoriesSelect() {
  Combo = document.getElementById('ddlCategories');
  Combo.options.length = 0;
  var curCategory;

  defaultIndex = (product.FavCategories.length == 1 ? 0 : -1);
  for (i = 0; i < product.FavCategories.length; i++) {
    curCategory = product.FavCategories[i];
    if (curCategory.Category != '') {
      defaultIndex = i;
    }
    Combo.options[i] = new Option(curCategory.Category, i);
  }
  Combo.value = 0;
  document.getElementById('txtFavNewCategory').value = '';

  if (Combo.options.length == 0) {
    Combo.style.display = "none";
    //document.getElementById('spanCategoriesCombo').style.display = "none";
    document.getElementById('ctl00_contentMain_btnFavYesCombo').style.display = "none";
    document.getElementById('divCategoriesCombo').style.display = "none";
    document.getElementById('divCategoriesText').innerHTML = 'Enter a category name and click add';
    jQuery('#divFavText').removeClass('floatRight').addClass('floatLeft').removeClass('item').addClass('item2');
    jQuery('#divFavCombo').css('display','none');
  }
  else {
    Combo.style.display = "inline";
    document.getElementById('divCategoriesCombo').style.display = "block";
    //document.getElementById('spanCategoriesCombo').style.display = "inline";
    document.getElementById('ctl00_contentMain_btnFavYesCombo').style.display = "inline";
    document.getElementById('divCategoriesCombo').innerHTML = 'Select a category name and click add';
    document.getElementById('divCategoriesText').innerHTML = 'Enter a new category name and click add';
    jQuery('#divFavText').removeClass('floatLeft').addClass('floatRight').removeClass('item2').addClass('item');;
    jQuery('#divFavCombo').css('display','inline');
  }

}

function GetProductCategoryFriendlyText(productCategoryId) {
  switch (productCategoryId) {
    case 1:
      return 'card';
      break;
    case 11:
      return 'mug';
      break;
    case 12:
      return 't-shirt';
      break;
  }
}

function GetProductCategoryLinkUrl(productCategoryId, moonpigProductNo) {
  switch (productCategoryId) {
    case 1:
      return globalPath + 'CardGallery/Greeting+Cards/keyword/%22' + moonpigProductNo + '%22/gallery.aspx';
      break;
    case 11:
      return globalPath + 'Gifts/Mugs/keyword/%22' + moonpigProductNo + '%22/gallery.aspx';
      break;
    case 12:
      return globalPath + 'Gifts/T-Shirts/keyword/%22' + moonpigProductNo + '%22/gallery.aspx';
      break;
  }
}

function SetAlsoAvailableAs() {
  if (product.alsoAvailableAs.length == 0) {
    $('.alsoAvailable').text('');
    return;
  }
  strMessage = "This design is also available as ";
  for (index = 0; index < product.alsoAvailableAs.length; index++) {
    strMessage += (index == 0 ? "a " : (index == product.alsoAvailableAs.length - 1 ? "and a " : ", a ")) + 
      "<a href='" + GetProductCategoryLinkUrl(product.alsoAvailableAs[index].productCategoryId, product.alsoAvailableAs[index].moonpigProductNo) + "'>" +
      GetProductCategoryFriendlyText(product.alsoAvailableAs[index].productCategoryId) + "</a> ";
  }
  $('.alsoAvailable').html(strMessage);
}

function SetAvailableSizes() {
  Combo = v_cbProductSize;
  Combo.options.length = 0;
  //    defaultIndex = product.defaultProductTypeId;
  defaultIndex = (product.availableProductTypes.length == 1 ? 0 : -1);
  var item = 0;
  for (i = 0; i < product.availableProductTypes.length; i++) {
    productType = product.availableProductTypes[i];
    if (productType.productTypeId == 1) {
      defaultIndex = i;
    }
    if ((isFlowers == 'False') || (isFlowers && productType.productTypeId == 1) || (isFlowers && productType.productTypeId == 13)) {
      Combo.options[item] = new Option(productType.description + (productType.minBundle == 0 ? "" : " (" + (productType.minBundle == 1 ? productType.price : productType.minBundle + " for " + productType.price) + ")"), productType.productTypeId);
      item++;
    }
  }
  Combo.value = product.defaultProductTypeId;

  // reset the inside images
  var $imageInside1 = jQuery('img[inside1]');
  var $imageInside2 = jQuery('img[inside2]');

  if (product.landscape) {
    $imageInside1.css('width', '145px').css('height', '100px')
                  .attr('imgWidth', '145px').attr('imgHeight', '100px');
    $imageInside2.css('width', '145px').css('height', '100px')
                  .attr('imgWidth', '145px').attr('imgHeight', '100px');
  }
  else {
    $imageInside1.css('height', '145px').css('width', '100px')
                  .attr('imgHeight', '145px').attr('imgWidth', '100px');
    $imageInside2.css('height', '145px').css('width', '100px')
                  .attr('imgHeight', '145px').attr('imgWidth', '100px');
  }
  $imageInside2.css('display', 'inline');
}

var currentSelectedItem = null;

function selectItem(selectedItemIndex) {
  jQuery('div').removeClass('selected');
  jQuery('div[productFrameNo=' + selectedItemIndex + ']').addClass('selected');
  currentItemIndex = selectedItemIndex;  
}

function showPage(newPageNo, imageNumber) {

  // dont show the next pageset button if there are less 5 pages or less (45 cards)
  if (noCards <= 45) {
    jQuery('li[PageSetAction=next]').css('display', 'none');
  }
  var firstImageNo = 0;
  firstImageNo = (newPageNo - 1) * itemsXPage;

  ShowNewPage(newPageNo);

  if (imageNumber > 0 && imageNumber < 10) {
    LoadImages(firstImageNo, imageNumber, newPageNo);
  }
  else {
    LoadImages(firstImageNo, 1, newPageNo);
  }
  
  if (noCards < 10) {    
    //  hide page set "..." buttons
    jQuery('a[PageSetAction]').css('display', 'none');
    // hide all page buttons
    jQuery('li[pageLinkNumber]').css('display', 'none');
  }

  DisplayCardNumbers(newPageNo); 
  
  ChangePageButton(newPageNo);
}

function DisplayCardNumbers(newPageNo) {
  var initial = ((newPageNo - 1) * itemsXPage) + 1;
  var end = initial + 8;
  if (end > noCards) end = noCards;
  jQuery('span[id$=lblHeader]')
    .text(initial + '-' + end + ' of ' + noCards + ' Designs');
}

function ChangePageButton(pageButtonNo) {
  jQuery('li[pageLinkNumber=' + currentPageButtonNo + ']').removeClass('selected');
  jQuery('li[pageLinkNumber=' + pageButtonNo + ']').addClass('selected');
  currentPageButtonNo = pageButtonNo;
}

function LoadImages(firstImageNo, imageSelectedIndex, newPageNo) {
  var imagesLoaded = true;
  // display images if we hit this page first time
  jQuery("div[pageNo=" + newPageNo + "]")
  // if the image has not been loaded has the 'imageFile' attribute
    .find("img[imageFile]")
    .each(function() {
      if (jQuery(this).attr('src') != jQuery(this).attr('imageFile')) {
        jQuery(this)
        .attr('src', jQuery(this).attr('imageFile'))
      }
    })

// click the selected image-


  var imageno = ((newPageNo - 1) * itemsXPage) + imageSelectedIndex - 1;
  jQuery("img[imageNo=" + imageno + "]").click();
  if (!imagesLoaded) {
    //setTimeout(function() { LoadImages(firstImageNo, imageSelectedIndex, newPageNo); }, 5000);
  }
}

var times = '';

function ShowNewPage(newPageNo) {
  jQuery("div[pageNo=" + currentPageButtonNo + ']').css('display', 'none');
  jQuery("div[pageNo=" + newPageNo + ']').css('display', 'block');
}

////////////////////////////
// show next / prev pagesets
////////////////////////////

function ShowNextPageSet(noPages) {
  jQuery('li[PageSetAction=previous]').css('display', 'inline');
  for (i = currentPageSet; i < currentPageSet + 5; i++) {
    var buttonNo = i;
    jQuery('li[pageLinkNumber=' + buttonNo + ']')
      .css('display', 'none');

    jQuery('li[pageLinkNumber=' + parseInt(buttonNo + 5) + ']')
      .css('display', 'inline');

    if ((buttonNo + 5) >= noPages) {
      jQuery('li[PageSetAction=next]').css('display', 'none');
    }
    
  }
  currentPageSet += 5;

  // show the first page of the set
  jQuery("a[pageLinkNumber=" + currentPageSet + "]").click();
}

function ShowPreviousPageSet(noPages, last) {
  jQuery('li[PageSetAction=next]').css('display', 'inline');
  if (currentPageSet == 1) {
    jQuery('li[PageSetAction=previous]').css('display', 'none');
  }
  for (i = currentPageSet; i < currentPageSet + 5; i++) {
    jQuery('li[pageLinkNumber=' + i + ']')
      .css('display', 'none');

    jQuery('li[pageLinkNumber=' + parseInt(i - 5) + ']')
      .css('display', 'inline');
  }
  currentPageSet -= 5;
  if (currentPageSet == 1) {
    jQuery('li[PageSetAction=previous]').css('display', 'none');
  }

  // show the first page of the set
  if (last) {
    jQuery("a[pageLinkNumber=" + parseInt(currentPageSet + 4) + "]").click();
  }
  else {
    jQuery("a[pageLinkNumber=" + currentPageSet + "]").click();
  }
}

//////////////////////////////////////////
// show different preview panels functions
//////////////////////////////////////////

// shows the front panel of the preview control
function PreviewShowFront() {
  try {
    if (pageTracker) {
      pageTracker._trackEvent('New Card Gallery - Tabs', 'View Front - ' + product.moonpigProductNo, '', 0);
    }
  }
  catch (ex) {
  }
  
  v_PreviewFrontListItem.className = 'selected';
  v_PreviewImageListItem.className = '';
  v_PreviewInsideListItem.className = '';
  v_PreviewBackListItem.className = '';
  v_PreviewDescriptionListItem.className = '';
  $('li[giftPreview]').removeClass('selected');

  $PreviewFrontFrame.css('display', 'block');
  $PreviewImageFrame.css('display', 'none');
  $PreviewInsideFrame.css('display', 'none');
  $PreviewBackFrame.css('display', 'none');
  v_PreviewDescriptionFrame.style.display = 'none';
  $('.productDetails[GiftPreview]').css('display', 'none');
}

// shows the image panel of the preview control
function PreviewShowImage() {
  try {
    if (pageTracker) {
      pageTracker._trackEvent('New Card Gallery - Tabs', 'View Card - ' + product.moonpigProductNo, '', 0);
    }
  }
  catch (ex) {
  }

  v_PreviewFrontListItem.className = '';
  v_PreviewImageListItem.className = 'selected';
  v_PreviewInsideListItem.className = '';
  v_PreviewBackListItem.className = '';
  v_PreviewDescriptionListItem.className = '';
  $('li[giftPreview]').removeClass('selected');

  $PreviewFrontFrame.css('display', 'none');
  $PreviewImageFrame.css('display', 'block');
  $PreviewInsideFrame.css('display', 'none');
  $PreviewBackFrame.css('display', 'none');
  v_PreviewDescriptionFrame.style.display = 'none';
  $('.productDetails[GiftPreview]').css('display', 'none');
}

// shows the Inside panel of the preview control
function PreviewShowInside() {
  try {
    if (pageTracker) {
      pageTracker._trackEvent('New Card Gallery - Tabs', 'View Inside - ' + product.moonpigProductNo, '', 0);
    }
  }
  catch (ex) {
  }

  v_PreviewFrontListItem.className = '';
  v_PreviewImageListItem.className = '';
  v_PreviewInsideListItem.className = 'selected';
  v_PreviewBackListItem.className = '';
  v_PreviewDescriptionListItem.className = '';
  $('li[giftPreview]').removeClass('selected');

  $PreviewFrontFrame.css('display', 'none');
  $PreviewImageFrame.css('display', 'none');
  $PreviewInsideFrame.css('display', 'block');
  $PreviewBackFrame.css('display', 'none');
  v_PreviewDescriptionFrame.style.display = 'none';
  $('.productDetails[GiftPreview]').css('display', 'none');
  
}

// shows the Back panel of the preview control
function PreviewShowBack() {
  try {
    if (pageTracker) {
      pageTracker._trackEvent('New Card Gallery - Tabs', 'View Back - ' + product.moonpigProductNo, '', 0);
    }
  }
  catch (ex) {
  }

  v_PreviewFrontListItem.className = '';
  v_PreviewImageListItem.className = '';
  v_PreviewInsideListItem.className = '';
  v_PreviewBackListItem.className = 'selected';
  v_PreviewDescriptionListItem.className = '';
  $('li[giftPreview]').removeClass('selected');

  $PreviewFrontFrame.css('display', 'none');
  $PreviewImageFrame.css('display', 'none');
  $PreviewInsideFrame.css('display', 'none');
  $PreviewBackFrame.css('display', 'block');
  v_PreviewDescriptionFrame.style.display = 'none';
  $('.productDetails[GiftPreview]').css('display', 'none');
}

// shows the Description panel of the preview control
function PreviewShowDescription() {
  v_PreviewFrontListItem.className = '';
  v_PreviewImageListItem.className = '';
  v_PreviewInsideListItem.className = '';
  v_PreviewBackListItem.className = '';
  v_PreviewDescriptionListItem.className = 'selected';
  $('li[giftPreview]').removeClass('selected');

  $PreviewFrontFrame.css('display', 'none');
  $PreviewImageFrame.css('display', 'none');
  $PreviewInsideFrame.css('display', 'none');
  $PreviewBackFrame.css('display', 'none');
  v_PreviewDescriptionFrame.style.display = 'block';
  $('.productDetails[GiftPreview]').css('display', 'none');
}

// shows the preview gift panel 
function PreviewShowGift() {
  try {
    if (pageTracker) {
      pageTracker._trackEvent('New Card Gallery - Tabs', 'View Gift Preview - ' + product.moonpigProductNo, '', 0);
    }
  }
  catch (ex) {
  }

  v_PreviewFrontListItem.className = '';
  v_PreviewImageListItem.className = '';
  v_PreviewInsideListItem.className = '';
  v_PreviewBackListItem.className = '';
  v_PreviewDescriptionListItem.className = '';
  $('li[giftPreview]').addClass('selected');

  $PreviewFrontFrame.css('display', 'none');
  $PreviewImageFrame.css('display', 'none');
  $PreviewInsideFrame.css('display', 'none');
  $PreviewBackFrame.css('display', 'none');
  v_PreviewDescriptionFrame.style.display = 'none';
  $('.productDetails[GiftPreview]').css('display', 'block');

}



///////////////////////////////////
// next and previous item functions
///////////////////////////////////

function SelectNextItem() {
  currentItemIndex = parseInt(currentItemIndex) + 1;
  if ((currentItemIndex % itemsXPage) != 0) {
    jQuery("img[imageNo=" + currentItemIndex + "]").click();
  }
  else {
    ShowNextPage(parseInt(noCards / itemsXPage));    
  }
}

function SelectPreviousItem() {
  currentItemIndex = parseInt(currentItemIndex) - 1;
  if ((currentItemIndex % itemsXPage) != 8) {
    jQuery("img[imageNo=" + currentItemIndex + "]").click();
  }
  else {
    ShowPreviousPage(parseInt(noCards / itemsXPage), true);
  }
}

function SelectNextRow() {
  prevIndex = currentItemIndex;
  currentItemIndex = parseInt(currentItemIndex) + 3;
  if (Math.floor(prevIndex / itemsXPage) != Math.floor(currentItemIndex / itemsXPage))
  {
    showPage(Math.ceil(currentItemIndex / itemsXPage) + 1, (currentItemIndex % itemsXPage) + 1);
  }
  else
  {
    jQuery("img[imageNo=" + currentItemIndex + "]").click();
  }
  
/*  if ((currentItemIndex % itemsXPage) != 0) {
    jQuery("img[imageNo=" + currentItemIndex + "]").click();
  }
  else {
    ShowNextPage(parseInt(noCards / itemsXPage));
  }*/
}

function SelectPreviousRow() {
  prevIndex = currentItemIndex;
  currentItemIndex = parseInt(currentItemIndex) - 3;
  if (Math.floor(prevIndex / itemsXPage) != Math.floor(currentItemIndex / itemsXPage)) {
    showPage(Math.ceil(currentItemIndex / itemsXPage), (currentItemIndex % itemsXPage) + 1);
  }
  else {
    jQuery("img[imageNo=" + currentItemIndex + "]").click();
  }
  
/*  currentItemIndex = parseInt(currentItemIndex) - 3;
  if ((currentItemIndex % itemsXPage) != 8) {
    jQuery("img[imageNo=" + currentItemIndex + "]").click();
  }
  else {
    ShowPreviousPage(parseInt(noCards / itemsXPage), true);
  }*/
}



///////////////////////////////////
// next and previous Page functions
///////////////////////////////////
var inPageMove = false;

function ShowPreviousPage(noPages, last) {
  if (currentPageButtonNo > 1) {
    if (currentPageButtonNo % 5 == 1) {
      if (!inPageMove) {
        inPageMove = true;
        ShowPreviousPageSet(noPages, true);
        inPageMove = false;
      }
    }
    else if (!last) {
      if (!inPageMove) {
        inPageMove = true;
        showPage(currentPageButtonNo - 1, 1);
        inPageMove = false;
      }
    }
    else {
      if (!inPageMove) {
        inPageMove = true;
        showPage(currentPageButtonNo - 1, 9);
        inPageMove = false;
      }
    }
  }
}

function ShowNextPage(noPages) {
  var pages = parseInt(noCards / itemsXPage);
  if (noCards % itemsXPage > 0) pages = pages + 1;
  if (currentPageButtonNo < pages) {

    if (currentPageButtonNo % 5 == 0) {
      if (!inPageMove) {
        inPageMove = true;
        ShowNextPageSet(noPages);
        inPageMove = false;
      }
    }
    else {
      if (!inPageMove) {
        inPageMove = true;
        showPage(currentPageButtonNo + 1, 1);
        inPageMove = false;
      }
    }
  }
}

/////////////////////////////////
// set page arrow buttons objects
/////////////////////////////////

function SetPageArrowButton(arrowButtonId, previous) {
  if (previous) {
    v_PrevPageArrow = document.getElementById(arrowButtonId);
  }
  else {
    v_NextPageArrow = document.getElementById(arrowButtonId);
  }
}