/**
QS_BasketController:
   Top level Object that wraps basket related resources 
   and the operations against them.

author: dedmondson
date:   09/01/2009
*/
var MAX_BASKET_LINE_QUANTITY = 20;

// Object Def
function  QS_BasketController(){
 
  // QS_BasketController: Public functions
  return{
    
    // Contructor
    init: function(){
    
      // ajax call to server to get user
      if(sessvars.bookaboo_order == null){
         $.ajax({
           url:'qs_jsonOrderBeans',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'orderId':'.',
            'errorViewName':'qs_jsonStatusError'
           },
           success:function(data){
             if(data.status == 'success'){    
               basketController.setOrder(data.order);
               basketController.refreshMiniBasket();
               basketController.initSpecialShippingRules();
             }
             else{
              sessionController.showErrorOverlay(data.errorMessages);
              
             }
           }
         });    
      }
      else{
        this.refreshMiniBasket();
        this.initSpecialShippingRules();
      }
    }, 

    // renders the MiniBasket with fresh data
    refreshMiniBasket:function(){
      //todo: fix hard coded currency symbol . dedmondson 02/2009
      $('.QS_basketQty').html(this.getOrder().basketQty);
      $('.QS_basketTotal').html("&pound;"+ new Number(this.getOrder().basketTotal).toFixed(2));
    },
    
    initSpecialShippingRules:function(){
	  if ( (new Number(this.getOrder().basketQty).valueOf() == 1) ) {
	   	 $('.QS_singleShipping').show();
	   	 $('.QS_stdShipping').hide();
	   	 $('.QS_stdShipping :radio').removeAttr('checked');
	  } else {
		 $('.QS_stdShipping').show();
	   	 $('.QS_singleShipping').hide();
	   	 $('.QS_singleShipping :radio').removeAttr('checked');
	  }
    },
    
    purge:function(){
     sessvars.bookaboo_order = null;
     sessvars.$.flush();
    },
    
    getOrder:function(){
      return sessvars.bookaboo_order;
    },
    
    setOrder:function(order){
      sessvars.bookaboo_order = order;
      sessvars.$.flush();
    },
    
    getPendingOrders:function(){
      return sessvars.bookaboo_pendingOrders;
    },
    
    setPendingOrders:function(pendingOrders){
      sessvars.bookaboo_pendingOrders = pendingOrders;
      sessvars.$.flush();
    },
    
    getOrderItemInfoForProduct:function(catEntryId){
      var order = this.getOrder();
      if(order != null && order != undefined && order.cashOrderItems != null && order.cashOrderItems != undefined){
        
        if( order.cashOrderItems.length > 0){
         for (var i = 0, item; item = order.cashOrderItems[i]; i++) {
            
            // break and return 1st match
            if(item.itemId == catEntryId){
              var info = new Object();
              info.orderItemId = item.orderItemId;
              info.qty = item.qty;
              return info;
            }
          }
        }
      }
      
      return null;
    },
    
   
    addProduct:function( catEntryId, quantity, successCallback , errorCallback){
    
      
    	
      // Perform an update if we already have this product in the basket.
      var orderItemInfo = this.getOrderItemInfoForProduct(catEntryId);
      if(orderItemInfo != null ){
        var  orderItemId = orderItemInfo.orderItemId;
        var newQuantity = (new Number(quantity) + new Number(orderItemInfo.qty));
        this.updateProduct( orderItemId, newQuantity, successCallback , errorCallback);
       return;  
      }
      
      // do not allow qtys over max 
      if(quantity > MAX_BASKET_LINE_QUANTITY ){
    	  if(confirm('There is a limit of '+MAX_BASKET_LINE_QUANTITY +' of this product available to purchase at one time. Would you like to add '+MAX_BASKET_LINE_QUANTITY+' to your basket?')){ 
    		quantity = MAX_BASKET_LINE_QUANTITY;  
    	  }
    	  else{
    		  return;
    	  }
    	  
      }
  
      $.ajax({
           url:'OrderItemUpdate',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'orderId':'.',
            'catEntryId':catEntryId,
            'quantity': quantity,
            'URL':'qs_jsonOrderBeans',
            'errorViewName':'qs_jsonStatusError'
           },
           success:function(data){
             if(data.status == 'success'){    
               basketController.setOrder(data.order);
               basketController.refreshMiniBasket();
               successCallback(data);
             }
             else{
              errorCallback(data.errorMessages);
             }
           }
         });    
    },
   
    updateOrderShippingAddress:function( orderId, addressId, allowRefresh, successCallback , errorCallback){
    	 
        $.ajax({
            url:'OrderItemUpdate',
            data:{
             'storeId':storeId,
             'catalogId':catalogId,
             'langId':langId,
             'orderId':orderId,
             'calculationUsageId':'-1',
             'calculationUsageId':'-2',
             'addressId':addressId,
             'errorViewName':'qs_jsonStatusError',
             'URL':'OrderCalculate?URL=qs_jsonOrderBeans'
            },
            success:function(data){
              if(data.status == 'success'){    
                successCallback(data,allowRefresh);
              }
              else{
               errorCallback(data.errorMessages);
              }
            }
          });  
     },
    
     
     updateProduct:function( orderItemId, quantity, successCallback , errorCallback){
    	 
    	
    	 
    	     
         // do not allow qtys over max 
         if(quantity > MAX_BASKET_LINE_QUANTITY ){
       	  if(confirm('There is a limit of '+MAX_BASKET_LINE_QUANTITY +' of this product available to purchase at one time. Would you like to change your basket quantity to '+ MAX_BASKET_LINE_QUANTITY +'?')){ 
       		quantity = MAX_BASKET_LINE_QUANTITY;  
       	  }
       	  else{
       		  return;
       	  }
       	  
         }
    	 
    
         $.ajax({
             url:'OrderItemUpdate',
             data:{
              'storeId':storeId,
              'catalogId':catalogId,
              'langId':langId,
              'orderId':'.',
              'orderItemId':orderItemId,
              'quantity': quantity,
              'updatePrices':'1',
              'calculationUsageId':'-1',
              'errorViewName':'qs_jsonStatusError',
              'URL':'qs_jsonOrderBeans'
             },
             success:function(data){
               if(data.status == 'success'){    
                 basketController.setOrder(data.order);
                 basketController.refreshMiniBasket();
                 successCallback(data);
               }
               else{
                errorCallback(data.errorMessages);
               }
             }
           });  
      },

    updateProductAndCalculate:function( orderItemId, quantity, successCallback , errorCallback){
 
       $.ajax({
           url:'OrderItemUpdate',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'orderId':'.',
            'orderItemId':orderItemId,
            'quantity': quantity,
            'updatePrices':'1',
            'calculationUsageId':'-1',
            'errorViewName':'qs_jsonStatusError',
            'URL':'OrderCalculate?URL=qs_jsonOrderBeans'
           },
           success:function(data){
             if(data.status == 'success'){    
               basketController.setOrder(data.order);
               basketController.refreshMiniBasket();
               successCallback(data);
             }
             else{
              errorCallback(data.errorMessages);
             }
           }
         });  
    },
    
    calculateOrder:function( successCallback , errorCallback){
    	 
        $.ajax({
            url:'OrderCalculate',
            data:{
             'storeId':storeId,
             'catalogId':catalogId,
             'langId':langId,
             'orderId':'.',
             'updatePrices':'1',
             'calculationUsageId':'-1',
             'errorViewName':'qs_jsonStatusError',
             'URL':'qs_jsonOrderBeans'
            },
            success:function(data){
              if(data.status == 'success'){    
                basketController.setOrder(data.order);
                basketController.refreshMiniBasket();
                successCallback(data);
              }
              else{
               errorCallback(data.errorMessages);
              }
            }
          });  
     },
    
    
    
    deleteProduct:function( orderItemId, successCallback , errorCallback ){
         $.ajax({
           url:'OrderItemDelete',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'orderId':'.',
            'orderItemId':orderItemId,
            'updatePrices':'1',
            'calculationUsageId':'-1',
            'errorViewName':'qs_jsonStatusError',
            'URL':'OrderCalculate?URL=qs_jsonOrderBeans'
            
           },
           success:function(data){
             if(data.status == 'success'){    
               basketController.setOrder(data.order);
               basketController.refreshMiniBasket();
               successCallback(data);
             }
             else{
              errorCallback(data.errorMessages);
             }
           }
         });    
    },
    
    makePayment:function( orderId,
            policyId,
            cardBrand,
            cardNumber,
            cardHolderName,
            cardExpiryMonth,
            cardExpiryYear,
            verificationNumber,
            cardStartMonth,
            cardStartYear,
            cardIssue,
            notifyShopper,
            notifyOrderSubmitted,
            notify_OrderReceived_EMailSender_recipient,
            city,
            billtoAddressId,
            successCallback , 
            errorCallback ){
            
            
		var referrerId = getCookie( 'Referrer');
		if(referrerId == null){
		var referrerId ='';
		}
		deleteCookie('Referrer');                 
		            
		$.ajax({
			url:'OrderPrepare',
			data:{
			'storeId':storeId,
			'catalogId':catalogId,
			'langId':langId,
			'orderId':orderId,
			'policyId':policyId,
			'cardBrand':cardBrand,
			'cardNumber':cardNumber,
			'cardHolderName':cardHolderName,
			'cardExpiryMonth':cardExpiryMonth,
			'cardExpiryYear':cardExpiryYear,
			'cardStartMonth':cardStartMonth,
			'cardStartYear':cardStartYear,
			'cardIssue':cardIssue,
			'creditCardPolicyNumber':policyId,
			'city':city,
			'billtoAddressId':billtoAddressId,
			'referrerId':referrerId,
			'verificationNumber':verificationNumber,
			'notifyOrderSubmitted':notifyOrderSubmitted,
			'notify_OrderReceived_EMailSender_recipient':notify_OrderReceived_EMailSender_recipient,
			'notifyShopper':notifyShopper,
			'errorViewName':'qs_jsonStatusError',
			'URL':'OrderProcess?URL=qs_jsonStatusSuccess'
			
		},
		success:function(data){
		if(data.status == 'success'){  
		 basketController.purge();// clear out the old order  
		 successCallback(data,orderId);
		}
		else{
		errorCallback(data.errorMessages);
		}
		}
		});    
},
    
    redeemBookPoints:function( orderItemId ){
        alert('TODO');
    },
    
    undoBookPoints:function( orderItemId ){
       alert('TODO');
    },
    
    
    removeAllFromWishList:function(  successCallback , errorCallback ){
        $.ajax({
            url:'InterestItemDelete',
            data:{
             'storeId':storeId,
             'catalogId':catalogId,
             'langId':langId,
             'listId':'.',
             'catEntryId':'*',
             'errorViewName':'qs_jsonStatusError',
             'URL':'qs_jsonStatusSuccess'
             
            },
            success:function(data){
              if(data.status == 'success'){  
                successCallback(data);
              }
              else{
               errorCallback(data.errorMessages);
              }
            }
          });  
     },
     
     removeFromWishList:function( catEntryId, successCallback , errorCallback ){
         $.ajax({
             url:'InterestItemDelete',
             data:{
              'storeId':storeId,
              'catalogId':catalogId,
              'langId':langId,
              'listId':'.',
              'catEntryId':catEntryId,
              'errorViewName':'qs_jsonStatusError',
              'URL':'qs_jsonStatusSuccess'
              
             },
             success:function(data){
               if(data.status == 'success'){ 
                 successCallback(data);
               }
               else{
                errorCallback(data.errorMessages);
               }
             }
           });  
      },
      
      moveToBasketFromWishList:function( catEntryId, successCallback , errorCallback  ){
          $.ajax({
               url:'OrderItemAdd',
               data:{
                'storeId':storeId,
                'catalogId':catalogId,
                'langId':langId,
                'catEntryId':catEntryId,
                'quantity':'1',
                'orderId':'.',
                'updatePrices':'1',
                'calculationUsageId':'-1',
                'errorViewName':'qs_jsonStatusError',
                'URL':'InterestItemDelete?URL=qs_jsonOrderBeans'
                
               },
               success:function(data){
                 if(data.status == 'success'){    
                   basketController.setOrder(data.order);
                   basketController.refreshMiniBasket();
                   successCallback(data);
                 }
                 else{
                  errorCallback(data.errorMessages);
                 }
               }
             });    
        },
    
    addToWishList:function( catEntryId, successCallback , errorCallback ){
       $.ajax({
           url:'InterestItemAdd',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'listId':'.',
            'catEntryId':catEntryId,
            'errorViewName':'qs_jsonStatusError',
            'URL':'qs_jsonOrderBeans'
            
           },
           success:function(data){
             if(data.status == 'success'){ 
               basketController.setOrder(data.order);
               basketController.refreshMiniBasket();   
               successCallback(data);
             }
             else{
              errorCallback(data.errorMessages);
             }
           }
         });  
    },
    
    moveToWishList:function( catEntryId, orderItemId, successCallback , errorCallback  ){
      $.ajax({
           url:'OrderItemDelete',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'orderId':'.',
            'listId':'.',
            'catEntryId':catEntryId,
            'orderItemId':orderItemId,
            'updatePrices':'1',
            'calculationUsageId':'-1',
            'errorViewName':'qs_jsonStatusError',
            'URL':'OrderCalculate?URL=InterestItemAdd?URL=qs_jsonOrderBeans'
            
           },
           success:function(data){
             if(data.status == 'success'){    
               basketController.setOrder(data.order);
               basketController.refreshMiniBasket();
               successCallback(data);
             }
             else{
              errorCallback(data.errorMessages);
             }
           }
         });    
    },
    
    sendWishList:function( listId, senderName,sender, recipientName ,recipient, message, successCallback, errorCallback ){
      
      
      
      $.ajax({
           url:'InterestItemListMessage',
           data:{
            'storeId':storeId,
            'catalogId':catalogId,
            'langId':langId,
            'listId':listId,
            'sender_name':senderName,
            'sender':sender,
            'recipient_name':recipientName,
            'recipient':recipient,
            'message':message,
            'SendCopy':'0',
            'errorViewName':'qs_jsonStatusError',
            'URL':'qs_jsonStatusSuccess'
           },
           success:function(data){
             if(data.status == 'success'){    
               successCallback(data,recipientName);
             }
             else{
              errorCallback(data.errorMessages);
             }
           }
         });  
         
    },
    
      
     
    submitPromoCode:function( orderId, promoCode, successCallback, errorCallback ){
    	
    	 $.ajax({
             url:'PromotionCodeManage',
             data:{
              'storeId':storeId,
              'catalogId':catalogId,
              'langId':langId,
              'orderId':orderId,
              'taskType':'A',
              'promoCode':promoCode,
              'calculationUsageId':'-1',
              'errorViewName':'qs_jsonStatusError',
              'URL':'OrderCalculate?URL=qs_jsonOrderBeans'
              
             },
             success:function(data){
               if(data.status == 'success'){    
                 basketController.setOrder(data.order);
                 basketController.refreshMiniBasket();
                 successCallback(data);
               }
               else{
                errorCallback(data.errorMessages);
               }
             }
           });    
      
    },
    
    sendToAFriend:function( title,
    		                author,
    		                ourPrice,
    		                rrp,
    		                save,
    		                urlInEmail,
    		                thumbnail,
    		                fromname, 
    		                toname, 
    		                fromemail, 
    		                toemail, 
    		                emailMessage, 
    		                sendMeACopy,
    		                successCallback, 
    		                errorCallback){
    	$.ajax({
    		url:'ItemInfoNotification',
    		data:{
              'storeId':storeId,
              'catalogId':catalogId,
              'langId':langId,
              'intro':'Send to a Friend',
              'msgType':'NotifyItemInfoEmailFormat',
              'title':title,
              'author':author,
              'ourPrice':ourPrice,
              'rrp':rrp,
              'save':save,
              'urlInEmail':urlInEmail,
              'thumbnail':thumbnail,
	          'fromname':fromname, 
              'toname':toname, 
              'fromemail':fromemail, 
              'toemail':toemail, 
              'emailMessage':emailMessage, 
              'sendMeACopy':sendMeACopy,
              'errorViewName':'qs_jsonStatusError',
              'URL':'qs_jsonStatusSuccess'
    		},
    		success:function(data) {
                if(data.status == 'success'){    
                    successCallback(data);
                  }
                  else{
                   errorCallback(data.errorMessages);
                  }
    		}
    	  }
    			
    	);
    },
     
    postReview:function( productIds,
    		             productId,
    		             itemName,
    		             itemMaker,
    		             productFeature,
    		             reviewStatusRef,
    		             reviewTypeRef,
    		             rating,
    		             foreName,
    		             emailAddress,
    		             reviewTitle,
    		             reviewText,
 		                 successCallback, 
		                 errorCallback){
    	$.ajax( {
    		url:'ManageBookReview',
    		data: {
              'storeId':storeId,
              'catalogId':catalogId,
              'langId':langId,
              'categoryId':categoryId,
              'updateReviewBody':'true',
              'updateReviewProductLink':'true',
              'redirecturl':'qs_jsonStatusSuccess',
              'productIds':productIds,
              'productId':productId,
              'itemName':itemName,
              'itemMaker':itemMaker,
              'productFeature':productFeature,
              'reviewStatusRef':reviewStatusRef,
              'reviewTypeRef':reviewTypeRef,
              'rating':rating,
              'foreName':foreName,
              'surname':'',
              'email':emailAddress,
              'field3':reviewTitle,
              'reviewText':reviewText
    		},
    		success:function(data) {
                if(data.status == 'success'){    
                    successCallback(data);
                  }
                  else{
                   errorCallback(data.errorMessages);
                  }
    		}
    	});
    },
    
    subscribe:function( listName,
    		            title,
    		            firstName,
    					lastName,
    					subscribeEmailAddress,
    					setting,				// 1 - subscribe, 0 - unsubscribe
    					successCallback,
    					errorCallback) {
    	$.ajax({
    		url:'LyrisMemberUpdateCmd',
    		data:{
              'storeId':storeId,
              'catalogId':catalogId,
              'langId':langId,
              'Title':title,
              'Firstname':firstName,
              'Lastname':lastName,
              'name': (title ? title + " " : "") + firstName + " " + lastName,
              'email':subscribeEmailAddress,
              'list':listName,
              'confirm':'one',
              'showconfirm':'F',
              'errorViewName':'qs_jsonStatusError',
              'URL':'qs_jsonStatusSuccess',
              'mailinginclude':setting,
              'demographics':'mailinginclude'
    	    },
    	    success:function(data) {
    	    	if(data.status == 'success') {
    	    		successCallback(data);
    	    	} else {
    	    		errorCallback(data.errorMessages);
    	    	}
    	    }
    	});

    }

  }
}