var LovedItem = {
  cacheEnabled: false,
  fetchUrl: "rest/product", // URL to call to get an item
  boxElement: null,
  lovedNavElement: null,
  itemCount: 0,
  checkCacheEnabled: function() {
    // Do a check if modernizr is not enabled
    try {
      return 'localStorage' in window && window['localStorage'] !== null;
    } catch(e) {
      return false;
    }
  },
  init: function() {
    $('.loved').click(this.display.toggle);
    this.boxElement = $('.loved-box');
    this.lovedNavElement = $('.loved span');
    $('#lovedItemClear').click(this.clear);

    var items = LovedItem.getItems();
    LovedItem.updateItemCount(items.length);

    LovedItem.display.updatePage()

    this.cacheEnabled = $('html').hasClass('localstorage');
    if (!this.cacheEnabled) this.cacheEnabled = this.checkCacheEnabled();
    if (!this.cacheEnabled) return false;

    this.cache.init();
  },
  item: {
    fetch: function(id) {
      // Check and return local cache
      if (LovedItem.cacheEnabled) {
        if (LovedItem.cache.get(id)) return;
      }

      // Else look it up
      $.get(LovedItem.fetchUrl, {"id": id}, function(data) {
        // Store it in cache
        if (LovedItem.cacheEnabled) LovedItem.cache.set(id, data);
        LovedItem.item.draw(data);
      }, 'json');
    },
    draw: function(item) {
      var gallery = LovedItem.boxElement.find('.gall-holder ul');
      var lastLi = gallery.find('li:last');
      if (lastLi.length === 0 || lastLi.children().length === 6) {
        lastLi = $('<li></li>').appendTo(gallery);
      }

      var productContent = getLovedSource(item.productLink, item.productTitle, item.lovedThumbnail, item.productId);
      $(productContent).appendTo(lastLi);
      if (gallery.find('a.lovedItemWrapper').length == LovedItem.itemCount) setTimeout('LovedItem.finaliseReload()', 500);
    },
    checkStatus: function(id) {
      var items = LovedItem.getItems();
      return ($.inArray(id.toString(), items) !== -1);
    }
  },
  cache: {
    storageObject: null,
    cleanupInterval: 30 * 60 * 1000, // 30 mins
    init: function() {
      this.storageObject = window.localStorage;

      // Add some helper functions to the Storage prototype
      // Enables serialisation and deserialisation of JSON objects
      Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
      }
      Storage.prototype.getObject = function(key) {
        return this.getItem(key) && JSON.parse(this.getItem(key));
        //return JSON.parse(this.getItem(key));
      }

      if (this.storageObject.getItem('lastFetched')) {
        var lastFetched = new Date(this.storageObject.getItem('lastFetched')),
            currentTime = new Date();

        if ((currentTime.getTime() - lastFetched.getTime()) > this.cleanupInterval) {
          this.storageObject.clear();
        }
      }
    },
    get: function(id) {
      var item = this.storageObject.getObject('item-' + id);
      if (item !== null) {
        this.updateTimestamp();
        LovedItem.item.draw(item);
        return true
      }
      return false;
    },
    set: function(id, data) {
      this.storageObject.setObject('item-' + id, data);
      this.updateTimestamp();
    },
    updateTimestamp: function() {
      this.storageObject.setItem('lastFetched', new Date().toUTCString());
    }
  },
  display: {
    toggle: function(e) {
      e.preventDefault();
      LovedItem.boxElement.stop(true, true);
      if (LovedItem.boxElement.height() == 0) {
        LovedItem.reloadAll();
        LovedItem.display.show();
      } else {
        LovedItem.display.hide();
      }
      return false;
    },
    show: function() {
      $('.carousel').css({'display' : 'block'});
      $('.add-nav li a.loved').parent().addClass('active');
      LovedItem.boxElement.animate({height: '139px'}, {
        duration: 500,
        easing: "easeOutExpo"
      });

    },
    hide: function() {
      $('.add-nav li a.loved').parent().removeClass('active');
      LovedItem.boxElement.animate({height: '0px'}, {
        duration: 500,
        easing: "easeInExpo",
        complete: function() {
          $('.carousel').css({'display' : 'none'});
          LovedItem.display.updatePage();
        }
      });
    },
    updatePage: function() {
      $('a.lovedItem').removeClass('lovedItem').hide();
      $('a.lovedToggleProduct').show();
      $('a.lovedToggle, a.lovedToggleProduct').each(function(index, elem) {
        if (LovedItem.item.checkStatus($(elem).attr('href')))
          $(elem).addClass('lovedItem').show();
      });
    }
  },
  updateItemCount: function(items) {
    LovedItem.itemCount = items;
    if (parseInt(items) == 0) {
      this.lovedNavElement.text('');
    } else {
      this.lovedNavElement.text('(' + items + ')');
    }
  },
  remove: function(id) {
    var url = 'rest/productLovedCollectionItemRemove/' + id;
    var baseTags = document.getElementsByTagName('base');
    if (url.search(/^http(s)?:\/\//i) < 0 && baseTags != undefined && baseTags.length > 0) {
      url = baseTags[0].href + url;
    }
    $.get(url, function(data, textStatus, xmlHttpRequest) {
      var items = LovedItem.getItems();
      LovedItem.updateItemCount(items.length);
      LovedItem.display.updatePage();
      LovedItem.reloadAll();
    });
  },
  getItems: function() {
    var items = unescape(readCookie('productLovedCollection'));
    if (items !== null && items !== "null") {
      items = items.split(',');
    } else {
      items = [];
    }
    return items;
  },
  clear: function() {
    var url = 'rest/productLovedCollectionClear';
    var baseTags = document.getElementsByTagName('base');
    // If the url doesn't already contain a full URL then append the base href
    if (url.search(/^http(s)?:\/\//i) < 0 && baseTags != undefined && baseTags.length > 0) {
      url = baseTags[0].href + url;
    }
    $.get(url, function() {
      var items = LovedItem.getItems();
      LovedItem.updateItemCount(items.length);
      LovedItem.display.hide();
    });

    return false;
  },
  reloadAll: function() {
    var gallery = LovedItem.boxElement.find('.gall-holder ul');
    gallery.empty();
    var items = LovedItem.getItems();
    LovedItem.updateItemCount(items.length);
    $.each(items, function(index, item) {
      LovedItem.item.fetch(item);
    });
  },
  finaliseReload: function() {
    initGall();
    if ($('div.carousel h3.message').length > 0) {
      $('div.carousel h3.message').remove();
    }
    if (LovedItem.itemCount <= 6) {
      $('div.carousel a.link-prev, div.carousel a.link-next').hide();
      /*if (LovedItem.itemCount < 1) {
       $('div.carousel').append('<h3 class="message">You currently have no loved items</h3>');
       }*/
    } else {
      $('div.carousel a.link-prev, div.carousel a.link-next').show();
    }

    $('.removeLovedProduct').click(function(e) {
      e.preventDefault();
      id = $(this).html();
      LovedItem.remove(id);
    });
  }
}

var productNavHeightThreshold = 550;

$(document).ready(function() {

  var agent = navigator.userAgent.toLowerCase();
  var is_iphone = ((agent.indexOf('iphone') != -1));
  var is_ipad = ((agent.indexOf('ipad') != -1));
  var ie_version = getInternetExplorerVersion();
  
  //dragDropGrid();
  
  // Shop sub nav links in a wrapper and slice the LIs into equal columns
  if ($('ul.navDropDown').length) {

    var $shopNavLink = $('#shopNav'), // shop link
        $shopNavDropDownWrapper = $('.navDropDownWrapper'),
        $shopNavDropDown = $('.navDropDown', $shopNavDropDownWrapper).first(), // ul to slice into columns
        height = $shopNavDropDown.height(), // total height
        maxHeight = 400;


    if (height > maxHeight) {
       var nLi = $shopNavDropDown.find('li.navDropDownCategory').length, // number of total lis
           i = 1,
           nColumns = 0,
           tempHeight = 0,
           group ='',
           $tempLi;
      // Looping through every lis      
      while (i <= nLi) {

        // get the next
        $tempLi = $shopNavDropDown.find('li.navDropDownCategory:eq(0)');
        tempHeight += $tempLi.height() + 25;

        // if we have a column
        if (tempHeight > maxHeight) {
          // add the new list to the final markup
          $('<ul/>').addClass('navDropDown').append(group).appendTo($shopNavDropDownWrapper);
          tempHeight = $tempLi.height() + 25;
          group = '';
          nColumns++;
        }
        // Append the list item to the current group

        group += '<li>' + $tempLi.html() + '</li>';
        // Remove the current li from the initial navDropDown

        $tempLi.remove();
        i++;
      }
      // Remove the initial navDropDown

      $shopNavDropDown.remove();
      // if the group has not been appended to the output
      if (group) {
          $('<ul/>').addClass('navDropDown').append(group).appendTo($shopNavDropDownWrapper);
          nColumns++;
      }

      if(ie_version == 6 || ie_version == 7) {
        $shopNavDropDownWrapper.hide().css({'margin-left' : -67});
        if(ie_version == 6) $shopNavDropDownWrapper.css({width : 206 * nColumns});
        
      } else {
        $shopNavDropDownWrapper.hide().css({'margin-left' : 0});
      }


      $shopNavLink.parent().bind('mouseenter', function() {
        $shopNavDropDownWrapper.stop(true, true).fadeIn(250, function() {
          $(this).show();
        });

        $shopNavLink.parent().addClass('active');
        
      }).bind('mouseleave', function() {
        $shopNavDropDownWrapper.stop(true, true).fadeOut(200, function() {
          $(this).hide();
        });
        
        $shopNavLink.parent().removeClass('active');
      });

    }
  }


  // Setup a default popup link binding
  $('a.popupLink').bind('click', function(e) {
    popupWindow($(this).attr('href'), $(this).attr('title').replace(/[^A-z]/ig, ''), 'width=600, height=800, scrollbars');
    e.preventDefault();
  });

  // Assigning behaviour to submit a reset password from the checkout login page
  $('#memberPasswordResetSubmitLink').bind('click', function (e) {
    $('#memberAccountAction').attr('value', 'memberPasswordResetProcess');
    $('#memberLoginForm').attr('action', location.href.replace(/\?.*$/i, ''));	// Replace the query string with nothing
    $('#memberLoginSubmit').click();
    e.preventDefault();
  });

  LovedItem.init();

  $('#productLimit').change(function() {
    $('#productLimitForm').submit();
  });

  if ($('.loved-box ul.gall-holder li').length == 0) {
    $('.loved-box .carousel').hide();
    $('div.carousel a.link-prev, div.carousel a.link-next').hide();
  }

  if ($('#productList li').length > 0) {
    $('#productList li').hover(function() {
      $('.lovedToggle', this).show();
    }, function() {
      if (!$('.lovedToggle', this).hasClass('lovedItem')) {
        $('.lovedToggle', this).hide();
      }
    });
    $('#productList li').each(function() {
      if (!$('.lovedToggle', this).hasClass('lovedItem')) {
        $('.lovedToggle', this).hide();
      }
    });
  }
  $('.lovedToggle').click(function(e) {
    e.preventDefault();
    clickedElement = $(this);
    if ($(clickedElement).hasClass('lovedItem')) {
      //remove from loved list
      $(clickedElement).removeClass('lovedItem');
      var url = 'rest/productLovedCollectionItemRemove/' + $(clickedElement).attr('href');
      var baseTags = document.getElementsByTagName('base');
      // If the url doesn't already contain a full URL then append the base href
      if (url.search(/^http(s)?:\/\//i) < 0 && baseTags != undefined && baseTags.length > 0) {
        url = baseTags[0].href + url;
      }
      $.get(url, function(data, textStatus, xmlHttpRequest) {
        $(clickedElement).hide();
        var items = LovedItem.getItems();
        LovedItem.updateItemCount(items.length);
      });
    } else {
      //add to loved list
      $(clickedElement).addClass('lovedItem');
      var url = 'rest/productLovedCollectionItemAdd/' + $(clickedElement).attr('href');
      var baseTags = document.getElementsByTagName('base');
      // If the url doesn't already contain a full URL then append the base href
      if (url.search(/^http(s)?:\/\//i) < 0 && baseTags != undefined && baseTags.length > 0) {
        url = baseTags[0].href + url;
      }
      $.get(url, function(data, textStatus, xmlHttpRequest) {
        LovedItem.reloadAll();
      });
    }
  });

  if ($('#productNav').length == 1) {
    originalOffset = $('#productNav').offset().top;
    $(window).scroll(function() {
      productNavHeightThreshold = $(window).height() - 107;
      if ($('#productNav').height() < productNavHeightThreshold) {
        if ($(document).scrollTop() > $('#productNav').offset().top) {
          $('#productNav').css({position : 'fixed', 'top' : '0px'});
        } else if ($(document).scrollTop() < originalOffset) {
          $('#productNav').removeAttr('style');
        }
      } else {
        $('#productNav').attr('style', '');
      }
    });
  }

  if ($('#sizingChart').length > 0) {
    $('#sizingChart').click(function(e) {
      e.preventDefault();
      $('body').prepend('<div class="popupOverlay">&nbsp;</div><div class="popupContainer"><div class="popupWrapper"><div class="popupWindow"><a href="#" style="color: #FFFFFF;" id="popupClose">Close</a><div class="popupWindowContent"></div></div></div></div>');
      $.get('sizing-chart.html', function(data) {
        $('.popupWindowContent').html(data);
        showOverlay();
      });
    });
  }

  if ($('#sizingChartProductLink a').length > 0) {
    $('#sizingChartProductLink a').click(function(e) {
      e.preventDefault();
      $('body').prepend('<div class="popupOverlay">&nbsp;</div><div class="popupContainer"><div class="popupWrapper"><div class="popupWindow"><a href="#" style="color: #FFFFFF;" id="popupClose">Close</a><div class="popupWindowContent"></div></div></div></div>');
      $.get('sizing-chart.html', function(data) {
        $('.popupWindowContent').html(data);
        showOverlay();
      });
    });
  }

  if ($('#lovedItemEmail').length > 0) {
    $('#lovedItemEmail').click(function(e) {
      e.preventDefault();
      $('body').prepend('<div class="popupOverlay">&nbsp;</div><div class="popupContainer"><div class="popupWrapper"><div class="popupWindow"><a href="#" style="color: #FFFFFF;" id="popupClose">Close</a><div class="popupWindowContent" style="height: auto;"></div></div></div></div>');
      $.get('email-loved-form.php', function(data) {
        $('.popupWindowContent').html(data);
        showOverlay();
        $('#productLovedShareForm').submit(function() {
          var form = $(this);
          var formData = form.serialize();
          var formUrl = form.attr('action');
          $('#productLovedShareFormErrors').hide();
          $.get(formUrl, formData, function(data, textStatus) {
            if ($('response', data).attr('status') != "success") {
              errorsHTML = '<div class="errors"><p><strong>The following errors occurred:</strong></p><ul>';
              $('error-message', data).each(function() {
                errorsHTML += '<li>' + $(this).text() + '</li>';
              });
              errorsHTML += '</ul></div>';
              $('#productLovedShareFormErrors').show().empty().html(errorsHTML);
            }
            else {
              $('#productLovedShareForm').remove();
              $('.popupBody').append('<strong style="display: block; text-align:center; font-size: 14px; line-height: 20px;color: #000000;">Your loved collection has been successfully shared</strong>');
              setTimeout('closeOverlay();', 2500);
            }
          });
          return false;
        });

      });
    });
  }

  if ($('#memberAccountWrapper').length > 0) {
    $('a.productReturnLink').click(function() {
      $(this).parents('tr').find('input.returnHiddenProduct').show().removeAttr('disabled');
      $(this).parents('form').find('.returnHidden').show();
      $(this).hide();
      return false;
    });
  }


  // Voucher - check balance
  $('#voucherCheckButton').bind('click', function(e) {
    e.preventDefault();
    voucherBalanceRetrieve();
  });

  $('#voucherForm').bind('submit', function(e) {
    e.preventDefault();
    voucherBalanceRetrieve();
  });

  $('#credentialCode').bind('keyup', function(e) {
    voucherInputsUpdate();
  });

  $('#credentialPassword').bind('keyup', function(e) {
    voucherInputsUpdate();
  });

  // On submit of the payment form ensure the voucher card number and pin are copied into the hidden fields in this form
  $('#credit-form').bind('submit', function(e) {
    voucherInputsUpdate();
  });

  updateCartHeader();
});

function dragDropGrid() {
	$('#productList li').css({"clear":"none;"});
	$('#productList > li:nth-child(3n+2)').css({"clear":"both"});
}

function getInternetExplorerVersion() {
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat(RegExp.$1);
  }
  return rv;
}

function popupWindow(url, name, attributes) {
  // Append popup to the URL if it does not already exist
  var queryStringExists = false;
  if (url.match(/\?/)) {
    queryStringExists = true;
  }

  if (queryStringExists) {
    // Only append if we haven't already got the parameter popup defined
    if (!url.match(/(\?|&)popup=/)) {
      url = url + '&popup=true';
    }
  } else {
    url = url + '?popup=true';
  }

  var baseTags = document.getElementsByTagName('base');
  if (baseTags != undefined && baseTags.length > 0) {
    url = baseTags[0].href + url;
  }

  var newWindow = window.open(url, name.replace(/[^A-z]/ig, ''), attributes);
  newWindow.focus();
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function showOverlay() {
  $('.popupOverlay').css({display: 'block'});
  $('.popupContainer').css({display: 'block'});
  totalHeight = $('#wrapper').height();
  $('.popupOverlay, .popupContainer').css({height: totalHeight + 'px'})
  $(window).scrollTo(0, 800);
  $('.popupOverlay').animate({opacity: 0.5}, 300, "swing", function() {
    $('.popupContainer').animate({opacity: 1.0}, 300, "swing", function() {
      $('#popupClose').click(function(e) {
        e.preventDefault();
        closeOverlay();
      });
    });
  });
}

function closeOverlay() {
  $('.popupContainer').animate({opacity: 0.0}, 100, "swing", function() {
    $('.popupOverlay').animate({opacity: 0.0}, 100, "swing", function() {
      $('.popupOverlay').remove();
      $('.popupContainer').remove();
    });
  });
}

function voucherInputsUpdate() {
  $('#hiddenCredentialCode').val($('#credentialCode').val());
  $('#hiddenCredentialPassword').val($('#credentialPassword').val());
}

function voucherBalanceRetrieve() {
  // Hide the credit card message
  $('#voucherValueContainer').html('');

  // Display the loader grahpic
  $('#ajaxLoader').show();

  // Submit the AJAX with credentialCode
  $.ajax({
    type: 'GET',
    url: 'cart/restGiftVoucherBalance',
    data: 'credentialCode=' + $('#credentialCode').val(),
    dataType: 'xml',
    error: voucherBalanceRetrieveError,
    success: voucherBalanceRetrieveSuccess,
    cache: false
  });
}

function voucherBalanceDisplayUpdate(message, balance, poTotalDifference, amountRedeemable) {
  // Hide the AJAX loader
  $('#ajaxLoader').hide();

  // Update the message
  $('#voucherValueContainer').html(message);

  // Update the hidden fields for the voucherAmount and creditCardAmount
  $('#creditCardAmount').val((poTotalDifference <= 0 ? '0.00' : poTotalDifference));
  $('#voucherAmount').val(amountRedeemable);

  // Update the display of how much is to be paid on credit
  $('#creditValueContainer').html((poTotalDifference <= 0 ? '0.00' : poTotalDifference.toFixed(2)));


  if (balance > 0) {
    if (balance > 0 && amountRedeemable <= 0) {
      $('#credentialPassword').attr('disabled', 'disabled');
    } else if (balance > 0 && amountRedeemable > 0 && balance > amountRedeemable) {
      $('#credentialPassword').removeAttr('disabled');
    } else {
      $('#credentialPassword').removeAttr('disabled');
    }
  } else {
    $('#credentialPassword').attr('disabled', 'disabled');
  }

  // If nothing is to be paid my credit card then remove the javascript validation
  if ($.validator != undefined) {
    if (poTotalDifference <= 0) {
      $('.creditCardRequired').removeClass('required');

      $.validator.addClassRules('creditNumber', { });
      $.validator.addClassRules('creditName', { });
      $.validator.addClassRules('creditCSC', { });
    } else {
      $('.creditCardRequired').addClass('required');

      $.validator.addClassRules('creditNumber', {
        creditcard2: function(creditNumberInput) {
          return $('.creditType', $(creditNumberInput).parents('form')).val();
        }
      });

      $.validator.addClassRules('creditName', {
        textOnly:true
      });

      $.validator.addClassRules('creditCSC', { minlength:3, maxlength:3 });
    }
  }
}

function voucherBalanceRetrieveSuccess(data, textStatus) {
  // Check if it was successful or not
  var responseStatus = $('response', data).attr('status');
  var message = '';
  var balance = 0;
  var poTotalDifference = Number($('response', data).attr('purchase-order-total'));
  var amountRedeemable = 0;
  var expiryDate = '';
  var expiryDateFormatted = '';

  if (responseStatus == 'success') {
    // Success - Get the balance
    balance = Number($('response', data).attr('gift-voucher-balance'));
    poTotalDifference = Number($('response', data).attr('purchase-order-total-difference'));
    amountRedeemable = Number($('response', data).attr('gift-voucher-redeemable'));
    expiryDate = $('response', data).attr('expiry-date');

    if (expiryDate != '') {
      // Format the date
      var expiryDateParts = expiryDate.split('-');
      expiryDateFormatted = expiryDateParts[2] + '/' + expiryDateParts[1] + '/' + expiryDateParts[0];
    }

    // Handle the amount redeemable
    if (balance > 0 && amountRedeemable <= 0) {
      message = 'You have $' + balance.toFixed(2) + ' remaining on this gift card. However you must have more than $' + Number($('response', data).attr('redemption-minimum')).toFixed(2) + ' balance to redeem';
    } else if (balance > 0 && amountRedeemable > 0 && balance > amountRedeemable) {
      message = 'You have $' + balance.toFixed(2) + ' remaining on this gift card. However you are only about to redeem $' + amountRedeemable.toFixed(2) + ' in one transaction';
    } else {
      message = 'You have $' + balance.toFixed(2) + ' remaining on this gift card';
    }

    // Add the expiry date
    if (expiryDateFormatted != '') message += '.<br/> Expiry date - ' + expiryDateFormatted;

  } else if (responseStatus == 'failure') {
    // Failure with error message
    message = 'An error occurred: ' + $('response errors error-message', data).text();
  } else {
    // Unknown error
    message = 'An unknown error occurred. Please try again later';

  }
  voucherBalanceDisplayUpdate(message, balance, poTotalDifference, amountRedeemable);
}


function voucherBalanceRetrieveError(XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown will have info
  this; // the options for this ajax request
  voucherBalanceDisplayUpdate();
}

function updateCartHeader() {
  var totalCartProducts = "" + parseInt(readCookie('totalCartProducts'));
  if (totalCartProducts == '' || totalCartProducts == 'null') {
    totalCartProducts = 0;
  }

  if (totalCartProducts > 0) $('.cartProducts span').html('(' + totalCartProducts + ')');
}
