﻿$.ajaxSetup ({
  cache: false
});

$(function(){

  isIeOld = ( $.browser.msie && $.browser.version < 8.0 );

  $( '#cart' ).scrollFollow( { 
    speed: 300,
    offset: 40,
    container: 'rightColumnBg'
  } );

  $("#bookSubCategoryList .bookSummary:even").css( {"background-color": "#dbd1bc" } );
  $("#bookSubCategoryList .bookSummary:odd").css( {"background-color": "#ffffff" } );
  
  if( $("#middleColumn .content .section .paging").length > 0 ){ 
    $("#middleColumn .content .section .paging").each( function(){
      var actualWidth = 0;
      $(this).find('li').each( function(){
        var liWidth = $(this).width() + 4;
        actualWidth += liWidth;
      });
      actualWidth += 4;
      $(this).css( 'width', actualWidth + "px" );
    });
  }

  $("#subnavigation").hide();
  
  setupCartQuantityChangers();
  
  setupCartAddSubtract();
  
  setupDropDownNavigation();
  
  setupLeftNavigation();

  setupShippingBillingPage();
  
  setupSignupPage();
});

function setupSignupPage(){
  if( $("#signUp form").length > 0 ){
    $("#signUp form table td #ShippingSameAsBilling").click( function(){
      $("#shippingAddressFormPart").toggle();
    });
    
    if ( $("#signUp form table td #ShippingSameAsBilling").attr('checked') ){
      $("#shippingAddressFormPart").hide();
    }
  }
}

function getRandomNumber(){
  var result = Math.floor( Math.random(5) * 1000001 );
  return result;
}

//Prevents caching
function getAjaxUrlNumber(){
  return "?" + getRandomNumber();
}

function setupShippingBillingPage(){
  if( $("#ShippingAddressForm").length > 0 ){
    $("#ShippingAddressForm table").hide( );
    
    $("#alternateShipping").click( function(){ 
      if( $("#ShippingAddressForm table").is(":visible")){
        $("#ShippingAddressForm table").slideUp( "fast" );
      } else {
        $("#ShippingAddressForm table").fadeIn();
      }
    });
  }
  
  if( $("#confirmAddress .error" ).length > 0 ){
    $("#alternateShipping").click();
  }
}

function setupCartAddSubtract(){
  $("body").find(".cartSubtract").each( function(){
    $(this).click( function(){
      var $currentQuantityHolder = $(this).parent().find(".currentQuantity");
      var value = $currentQuantityHolder.attr('value');
      if( ( value * 1 ) != 0 ){
        var newValue = (value * 1) - 1;
        $currentQuantityHolder.attr('value', newValue );
      }
      var webjectId = $(this).parent().attr("class");
      var actionString = "/Cart/Subtract/" + 
                       webjectId.replace("-","!") + getAjaxUrlNumber();
                       
      
      setContentReviewTableHtml( $(this) );
                       
      $.get( actionString, function(response){
        $("#cart .table").html(response);
        
        if( !cartHasItems() || isIeOld ){
          location.reload();
        }
        
        setupCartQuantityChangers();
      });
      
      return;
    });
  });
  
  $("body").find(".cartAdd").each( function(){
    $(this).click( function(){
    
      var $currentQuantityHolder = $(this).parent().find(".currentQuantity");
      var value = $currentQuantityHolder.attr('value');
      var newValue = (value * 1) + 1;
      $currentQuantityHolder.attr('value', newValue );
      var webjectId = $(this).parent().attr("class");
      var actionString = "/Cart/Add/" + webjectId.replace("-","!") + getAjaxUrlNumber();
      
      setContentReviewTableHtml( $(this) );
      
      if( !cartHasItems() || isIeOld ){
        $.post( actionString, function(data){
          location.reload();
        });
        return;
      }
                       
      $.get( actionString, function(response){
        $("#cart .table").html(response);
        setupCartQuantityChangers();
      });
      return;
    });
  });
}

function setContentReviewTableHtml( $object ){
  var parent = $object.parent().parent().parent().parent();
  
  if ( $("#reviewOrder").length > 0 ){
    var quantity = parent.find( '.currentQuantity' ).attr('value');
    if( quantity == "0" ){
      parent.remove();
      updateTotals( parent.parent() );
      return;
    }
    var yourPrice = parent.find( '.itemYourPrice' ).html();
    var rrp = parent.find( '.itemRRP' ).html();
    
    var newTotalRRP = quantity * rrp;
    var newYourPrice = quantity * yourPrice;
    
    parent.find( '.itemRRPTotal' ).html( padCurrencyNumber(newTotalRRP) );
    parent.find( '.itemYourPriceTotal' ).html( padCurrencyNumber( newYourPrice ));
    
    updateTotals( parent.parent() );
  }
}

function updateTotals( $object ){
  //Update freight totals
  var totalQuantity = 0;
  var freightTotal = "$3.50";
  var singleFreight = true;
  
  $object.parent().find( '.currentQuantity' ).each( 
    function(){
      totalQuantity = totalQuantity + $(this).attr('value');
    }
  );
  
  if( totalQuantity > 1 ){
    freightTotal = "$6.00";
    singleFreight = false;
  }
  
  $object.parent().find( '.freightTotal' ).html( freightTotal );
  
  var totalPrice = 0.0;
  
  //Update your total
  $object.parent().find( '.itemYourPriceTotal' ).each(
    function(){
      totalPrice += parseFloat( $(this).html() );
    }
  );
  
  if( singleFreight ){
    totalPrice += 3.5;
  } else{
    totalPrice += 6;
  }
  
  $object.parent().find( '.yourPriceTotal' ).html( "$" + padCurrencyNumber( totalPrice ) );
}

function padCurrencyNumber( number ){
  number = number + "";
  var splitNum = number.split('.');
  if( splitNum.length > 1 ){
    var paddedNumber = splitNum[1];
    if( paddedNumber.length == 2 ){
      return number;
    }
    if( paddedNumber.length == 1 ){
      return splitNum[0] + "." + splitNum[1] + "0";
    }
  }
  return number + ".00";
}

function setupDropDownNavigation(){
  $("#navigation ul li .dropDownNavigation").hover(
    function(){
      $(this).parent().find("a:first").addClass("hover");
    },
    function(){
      $(this).parent().find("a:first").removeClass("hover");
    }
  );
}

function cartHasItems(){
  var totalQuantity = 0;
  $('#cart').find( '.currentQuantity' ).each( 
    function(){
      totalQuantity = totalQuantity + $(this).attr('value');
    }
  );
  
  if( totalQuantity == 0 ){
    return false;
  }
  
  return true;
}

function setupLeftNavigation(){
  $("#leftCategoryNavigation .category ul.subCategories").hide();
  
  $("#leftCategoryNavigation .category").find("h3").each( function(){
    $(this).css( { "margin-bottom": "-1px" } );
    if( $(this).find("span").attr("class") == "current" ){
      $(this).parent().find(".subCategories").show();
    }    
    $(this).click( function(){
      var $subCategoryToShow = $(this).parent().find(".subCategories");
      if(  !$subCategoryToShow.is(':visible') ){
        $subCategoryToShow.slideDown("normal");
        $(this).find("span").addClass('current');
        
        if( $(this).find("img").length > 0 ){
          var src = $(this).find("img").attr('src');
          var newSrc = src.replace('expand','collapse');
          var newTitle = $(this).attr('title').replace("expand", "collapse");
          $(this).find("img").attr('src', newSrc);
          $(this).attr('title',newTitle);
          $(this).find('img').attr('title','Collapse Category');
        }
        
        return;
      }
      $subCategoryToShow.slideUp("normal");
      $(this).find("span").removeClass('current');
      var src = $(this).find("img").attr('src');
      var newSrc = src.replace('collapse','expand');
      var newTitle = $(this).attr('title').replace("collapse","expand");
      $(this).find("img").attr('src', newSrc);
      $(this).attr('title',newTitle);
      $(this).find('img').attr('title','Expand Category');
    });
    $(this).hover( function(){
      $(this).css( { "cursor": "pointer" } );
    }, function( ){
      $(this).css({ "cursor": "default" });
    });
  });
}

function setupCartQuantityChangers(){

  $(".currentQuantity").each( function( ){
  
    $(this).unbind("change");
    $(this).unbind("keypress");
    
    $(this).change( function(){
      var value = $(this).val();
      
      var webjectId = $(this).parent().attr("class");
      
      if( $("#bookSubCategoryList ." + webjectId + " .currentQuantity") != null ){
        if( $("#bookSubCategoryList ." + webjectId + " .currentQuantity").attr('value') != value ){
          $("#bookSubCategoryList ." + webjectId + " .currentQuantity").attr('value', value);
        }
      }

      var actionString = "/Cart/SetQuantity/" + webjectId.replace("-","!") + "/" + value + getAjaxUrlNumber();
      
      if( isIeOld ){
        $.post( actionString, function(data){
          location.reload();
        });
        return;
      }

      $.get( actionString, function(response){
       $("#cart .table").html(response);
       setupCartQuantityChangers();
      });
    });
  
    $(this).keypress(function (event){
      if ( event.which == 13 ){
        event.preventDefault();
      
        var value = $(this).val();
      
        var webjectId = $(this).parent().attr("class");
    
        if( $("#bookSubCategoryList ." + webjectId + " .currentQuantity") != null ){
          if( $("#bookSubCategoryList ." + webjectId + " .currentQuantity").attr('value') != value ){
            $("#bookSubCategoryList ." + webjectId + " .currentQuantity").attr('value', value);
          }
        }

        var actionString = "/Cart/SetQuantity/" + webjectId.replace("-","!") + "/" + value + getAjaxUrlNumber();
      
        if( isIeOld ){
          $.post( actionString, function(data){
            location.reload();
          });
          return false;
        }

        $.get( actionString, function(response){
         $("#cart .table").html(response);
         setupCartQuantityChangers();
         return false;
        });
        
        return false;
      }
    });
  });
}
