﻿$(function(){
  var cartContents = $( ".cart-contents" ).length > 0;
  var cartDetails =  $( ".cart-details" ).length > 0;
  
  if( cartContents ) {
    $( ".cart-contents input[type='submit']" ).hide();
    $( ".cart-contents .quantity a" ).hide();
    
    $( ".cart-contents .quantity" ).each(function(){
      var productId = $( this ).attr( "data-product-id" );
      var quantityControl = '<a href="javascript:void(0);" id="{productId}-{control}" title="{control}" class="quantity-control {control}">{text}</a>';
      var increaseControl = quantityControl.replace( /{text}/g, "+" ).replace( /{productId}/g, productId ).replace( /{control}/g, "increase" );
      var decreaseControl = quantityControl.replace( /{text}/g, "−" ).replace( /{productId}/g, productId ).replace( /{control}/g, "decrease" );
      var removeControl = quantityControl.replace( /{text}/g, "X" ).replace( /{productId}/g, productId ).replace( /{control}/g, "remove" );
      var controls = '<label for="' + productId + '-quantity" class="quantity-controls">' + increaseControl + '<span class="separator">/</span>' + decreaseControl + " " + removeControl + '</label>';

      $( "#" + productId + "-form" ).append( controls );
      
      AddControlClick( productId, "increase", "IncrementQuantity" );
      AddControlClick( productId, "decrease", "DecrementQuantity" );
      AddControlClick( productId, "remove", "Remove" );

      $( "#" + productId + "-quantity" ).change(function(){  
        var url = "/Shopping/JsonSetQuantity/" + productId + "/" + $( this ).val();
        $.ajax({
          url: url,
          cache: false,
          dataType: "json",
          success: UpdateCart
        });
      });     

      function AddControlClick( productId, controlType, action ) {
        $( "#" + productId + "-" + controlType ).click(function(){
          $.ajax({
            url: "/Shopping/Json" + action + "/" + productId,
            cache: false,
            dataType: "json",
            success: UpdateCart
          });
        });    
      }
      
      function UpdateCart( data ) {
        if( data.total == "$0.00" ) window.location.reload();
        if( parseFloat( data.weight ) > 10 ) {
          $( "#message" ).html( "Total weight exceeds 10kg, please remove some items to continue" );
          $( "#weight" ).addClass( "overweight" );
          $( ".checkout-action" ).addClass( "overweight" );
          $( ".checkout-action a" ).each(function(){
            $( this ).attr( "href", "javascript:void(0);" );
          });
        } else {
          $( "#message" ).html( "" );
          $( "#weight" ).removeClass( "overweight" );
          $( ".checkout-action" ).removeClass( "overweight" );
          $( ".checkout-action a" ).each(function(){
            $( this ).attr( "href",  $( this ).attr( "data-href" ) );
          });
        }
        if( data.quantity < 1 ) {
          $( "#" + data.id + "-cart-content-item" ).remove();
        } else {
          var currentQuantity = $( "#" + data.id + "-quantity" ).val();
          if( data.quantity != currentQuantity ) {
            $( "#" + data.id + "-weight" ).html( data.weightSubtotal );
            $( "#" + data.id + "-quantity" ).val( data.quantity );
          }
          $( "#" + data.id + "-subtotal" ).html( data.subtotal );
        }
        $( "#weight" ).html( data.weight );
        $( "#total" ).html( data.total );
      }
      
      $( "#" + productId + "-quantity" ).change();
    });
  }
  
  if( cartDetails ) {
    function FormSubmitOptions() {
      return {
        dataType: 'json',
        success: UpdateDetails,
        url: "/Shopping/DetailsJsonResult"
      }
    }    
    
    $( "input[name='PaymentType']" ).change(function(){
      $( '.paymentMethod' ).hide();
      if( $( this ).attr( 'checked' ) ) {
        $( "#paymentMethod" + $( this ).attr( 'value' ) ).show();
      } 
    });
  
    $( ".required" ).change(function(){
      $( ".cart-details" ).ajaxSubmit( FormSubmitOptions() );
    });
    
    function GetKeys( obj ) {
      var keys = [];
      for( var propertyName in obj ) {
        keys.push( obj[ propertyName ].name );
      }
      return keys;
    }
  
    function UpdateDetails( data ) {
      if ( data.Supported != null ){
        $( "#ShippingMethod input" ).removeAttr( 'disabled', 'disabled' );
        if ( data.Supported.length == 1 ){
          var supportedId = data.Supported[ 0 ];
          $( "#ShippingMethod input" ).attr( 'disabled', 'disabled' );
          $( "#ShippingMethod input" ).removeAttr( 'checked' );
          $( "#ShippingMethod #" + supportedId ).removeAttr( 'disabled' );
          $( "#ShippingMethod #" + supportedId ).attr( 'checked', 'checked' );
        }
      }      

      var valid = false;
      
      $( ".required" ).removeClass( "invalid" );
      if( data.ErrorFields.length > 0 ) {
        $( "#message" ).show();
        $( "#message" ).html( data.Message );
        for( var i in data.ErrorFields ) {
          var formField = data.ErrorFields[ i ];
          $( "#" + formField ).addClass( "invalid" );
        }
      } else {
        $( "#message" ).hide();
        valid = true;
      }
      
      $.each( data.OrderSummary, function( key, value ) {
        $( "#" + key ).html( value );
      });
      
      
      if( valid ) {
        $( "input[type='submit']" ).removeAttr( 'disabled' );
      } else {
        $( "input[type='submit']" ).attr( 'disabled', 'disabled' );
      }
    }
    
    $( "input[name='PaymentType']" ).change();
  }
});