
function Cart() {
	
}
// helper functions

Cart.get_po_box_checkbox_status = function() {
 	var status;
	$('#is_po_box:checked').length > 0 ? status =  1 : status = 0;
	return status;
}

//

Cart.Update_cart_data = function( options ){
	
	try {
		
	
		// post data
		var data = new Object();

		// Collect Quantities
		$('input[name^="quantity_"]').each(function(){
			var attr_name = $(this).attr('name');
			eval('data.' + attr_name + ' = $(this).val();');
		});
		
		// is_po_box?
		 data.is_po_box = Cart.get_po_box_checkbox_status();
		
		// zip code
		 data.zip_code = $('input[name="zip_code"]').val();
		
		//
		// Selected shipping
		//		
		if ( typeof(options.shipping_service) != 'undefined' ) {
			data.shipping_service = options.shipping_service;
		} 
		else {
			data.shipping_service = jQuery('#shipping_select').val();
		}
		
		if( typeof(options) != 'undefined' ) {
			for(key in options) {
				eval('data.' + key + ' = options[key];');
			}
		}
		

		
		$('a.calculate_shipping').html('Recalculate');
		$('#shipping_rate_loading').hide();
		$('#rate_popup').jqmHide();

		$.blockUI({ 
        	message: '<h1>Updating Cart...</h1><img style="display:block; margin-left: auto; margin-right: auto; margin-top: 5px;" src="/images/icons/common/loading-blockui.gif" />',

        	css: {
	            border: 'none', 
	            padding: '15px',
	            top: ($('.cart_container').offset().top + 20) + 'px',
	            left: ($('.cart_container').offset().left + 250) + 'px', 
	            backgroundColor: '#000', 
	            '-webkit-border-radius': '10px', 
	            '-moz-border-radius': '10px', 
	            opacity: .7, 
	            color: '#fff' 
        	} 
       }); 
       
		$.post('/Cart/get-cart-data', data, function(data){
			//
			Cart.Apply_data_array(data);
			
	        $.unblockUI(); 


		}, "json");
	}
	catch(e) {
		alert(e);
	}
}

Cart.Apply_data_array = function(data) {
	// UPDATE RATES
	if(typeof(data.shipping_rates) != 'undefined' && !data.options.bypass_rate_lookup){

		if (data.shipping_rates.length == 0) {
			if(!data.options.shipping_rate_optional && !data.options.ignore_shipping_rate){	
				$('#shipping_rate_loading').hide();
				$('#rate_error').text('There was a problem with your request. Please check your zip.').show();
				return false;
			}
		}
		else {
			$('#shipping_select').html('');
			$('<option/>').attr('value', '').html('- Choose Shipping -').appendTo('#shipping_select');
			
			for( rate_id in data.shipping_rates ) {
				var attrs = new Array();
				service_data = data.shipping_rates[rate_id]; 
				attrs['value'] = rate_id;
				
				if ( service_data.selected ) {
					attrs['selected'] = 'selected';
				}
				
				$('<option/>').attr(attrs).html(service_data.title + " - $" + parseFloat(service_data.cost).toFixed(2)).appendTo('#shipping_select');
				$('#shipping_select').show();
			}
			
		}
	}
	// UPDATE TOTALS
	if(typeof(data.cart.items) != 'undefined') {
        var num_items = 0;
        for ( id in data.cart.items ) {
        	var item = data.cart.items[id];
        	if ( item.qty == 0 ) {
        		jQuery('#cart_row_' + id.toString()).fadeOut();
        	}
        	else {
        		$('#span_item_total_' + id).html(item.total_price);
        		num_items += parseInt(item.qty);
        	}
        }
        
    	$('.badge-cart_quantity').html('(' + data.cart.total.qty + ')');

    	if ( parseInt(num_items) <= 0 ) {
    		$('.cart_container').hide();
    		jQuery('#cart_empty_message').show();
    	}
	}
	
	if(typeof(data.cart.total.price) != 'undefined') {
		$('#cart_total_amount').html(data.cart.total.price);
	}
}

Cart.Add_item_by_id = function( item_id, options ) {
	
       try {

                var request_obj = new BRIJ_Request();
				var data;
				
                request_obj.request_method = 'POST';
                request_obj.request_uri = 'http://www.nativeyewear.com/Cart/Item/Add/' + item_id;
                request_obj.set_result_handler( Cart.Handle_item_add );

				data = Cart.Collect_item_options_by_id( item_id );
                request_obj.set_request_data( data );
                
                try {
                        var result = request_obj.get_function_result();

                }
                catch( e ) {
                        alert( 'BRIJ error: ' + e.message );
               }


        }
        catch(e) {
                alert( e.message );
        }


}

Cart.Collect_item_options_by_id = function ( id ) {
	
	try {
    
    	var item_options = new Array( 'eyewear_style', 'frame_color', 'lens_color' );
		var cur_id;
    	var j;
    	var data = new Array();
    	var val;
    	
    	for ( j = 0; j < item_options.length; j++ ) {
    		
    		cur_id = 'option_' + item_options[j] + '_' + id;
    		
    		if ( document.getElementById(cur_id) ) {
	    		 val = jQuery('#' + cur_id).val();
	    		if ( val && typeof(val) != 'undefined' ) {
    				data[item_options[j]] = val; 
    			}
    			else {
    				throw new Error('Please select your sunglass');
    			}	
    		}
    	}
    	
    	return data;
    
    }
    catch(e) {
    	throw e;
    }
	
}

Cart.Handle_item_add = function ( result ) {

        try {
             	if ( is_BRIJ_Error(result) ) {
                      	alert( 'An error occurred: ' + result.error_message );
                }
                else {
                    Cart.Increment_badge_quantity(); 
                    jQuery('#added_to_cart_popup').jqmShow();
                }
        }
        catch(e) {
                alert( e.message );
        }

}

Cart.Update_quantities = function( options ) {
	
	try {
		
		var quantities = new Array();
		var inputs = document.getElementsByTagName('input');
		var data = new Array();
		
		for ( var i = 0; i < inputs.length; i ++ ) {
			cur_input = inputs[i];
			if ( cur_input.name.substring(0, "quantity_".length) == 'quantity_' ) {
				data[cur_input.name] = cur_input.value;
			}
		}
		
		var request_obj = new BRIJ_Request();

		request_obj.request_method = 'POST';
        request_obj.request_uri = 'http://www.nativeyewear.com/Cart/UpdateQuantities';
        request_obj.set_result_handler( Cart.Handle_quantity_update );
		request_obj.set_request_data( data );
		

		var result = request_obj.get_function_result();
		
		
		
	}
    catch(e) {
    	alert( e.message );
    }	
}

Cart.Remove_item = function (item_id) {
	
	Cart.Update_cart_data();
	//Cart.Update_quantity( item_id, 0);
	
}

Cart.Update_quantity = function(item_id, quantity) {
	
	try {
		
		cur_input = document.getElementById('textbox_quantity_' + item_id);
		cur_input.value = quantity;		
		Cart.Update_quantities();
		
	}
    catch(e) {
    	alert( e.message );
    }
    
}

Cart.Handle_quantity_update = function( result ) {

        try {
                if ( is_BRIJ_Error(result) ) {
                        alert( 'An error occurred: ' + result.error_message );
                }
                else {
                      
                      var num_items = 0;
                     
                      for ( item_id in result ) {
                      
                    	if ( result[item_id]['qty'] == 0 ) {
                      		
                      		jQuery('#cart_row_' + item_id.toString()).fadeOut();

							/*
                      		span_obj = document.getElementById('span_item_name_' + item_id);
                      		span_obj.style.textDecoration = 'line-through';
                      		
                      		span_obj = document.getElementById('span_price_' + item_id);
                      		span_obj.style.textDecoration = 'line-through';
                      		
                      		if ( span_obj = document.getElementById('span_item_options_' + item_id) ) {
                      			span_obj.style.textDecoration = 'line-through';
                      		}
                      		*/
                      	}
                      	else {
                      		span_obj = document.getElementById('span_item_total_' + item_id);
                      		span_obj.innerHTML = result[item_id]['total_price'];
                      		num_items += parseInt(result[item_id]['qty']);
                      	}
                      	
                      	jQuery('.badge-cart_quantity').html('(' + num_items.toString() + ')');
                      }
                    
                  	if ( parseInt(num_items) <= 0 ) {
                  		jQuery('.cart_container').hide();
                  		jQuery('#cart_empty_message').show();
                  	}
                  	else {

                  		Cart.Refresh_total({ shipping_rate_optional: 1, ignore_tax: 1});
                  	}
                  
                      	
                     
                }
        }
        catch(e) {
                alert( e.message );
        }
	
} 

Cart.Refresh_total = function( options ) {

       try {

			  var request_obj = new BRIJ_Request();

              request_obj.request_uri = 'http://www.nativeyewear.com/Cart/GetTotal/';
              
              if ( typeof(options) != 'undefined' ) {
              	
              	request_obj.set_request_data( options );
              	
              	//for( key in options ) {
              	//	request_obj.request_uri += key + '=' + options[key] + '&';
              	//}

              	//if ( typeof(options['ignore_shipping_rate']) != 'undefined' ) {
              	//	request_obj.request_uri += '&ignore_shipping_rate=1';
              	//}

				//alert( request_obj.request_uri );
              }
              
              request_obj.set_result_handler( Cart.Handle_refresh_total );
              request_obj.get_function_result();

        }
        catch(e) {
                alert( e.message );
        }
	
} 

Cart.Handle_refresh_total = function( result ) {

                try {
                        if ( is_BRIJ_Error(result) ) {
                                alert( 'An error occurred: ' + result.error_message );
                        }
                        else {
                              var total_div = document.getElementById('cart_total_amount');
                              
                              //result = Cart.Add_selected_shipping_to_cart_subtotal(result);
                              total_div.innerHTML = result;
                        }
                }
                catch(e) {
                        alert(e.message );
                }
	
} 

Cart.Increment_badge_quantity = function() {

	try { 
	
   		//
    	// TODO: Badge update should come from AJAX instead
        //
        var cur_badge_quantity = jQuery('.badge-cart_quantity').html();
		
		if ( cur_badge_quantity == null ) {
			cur_badge_quantity = 0;
		}
		else {
			cur_badge_quantity = cur_badge_quantity.replace(/[^0-9]/g, '');
		}
                               
        if ( !cur_badge_quantity || isNaN(cur_badge_quantity) ) {
        	cur_badge_quantity = 0;
        }
        else {
        	cur_badge_quantity = parseInt(cur_badge_quantity);
		}

		var new_badge_quantity = cur_badge_quantity + 1;
		var badge_string = '(' + new_badge_quantity.toString() + ')';
		
		jQuery('.badge-cart_quantity').html(badge_string).show();
    }
    catch( e ) {
    	alert( e.message );
    }                           

}


//Cart.Ajax_get_rates = function() { 
//	IS_PO_BOX = get_po_box_checkbox_status();
//	
//	data = {
//			is_po_box: IS_PO_BOX,
//			zip_code: $('input[name="zip_code"]').val()
//		};
//
//	setCookie('preferredZipCode', $('input[name="zip_code"]').val());
//	setCookie('addressIsPOBox', IS_PO_BOX);
//	
//	$.post('http://www.nativeyewear.com/Cart/UpdateRates/', data, 
//			function(rdata) {
//				var rates = new Object();
//				if (rdata.length == 0) {
//					$('#shipping_rate_loading').hide();
//					$('#rate_error').text('There was a problem with your request. Please check your zip.').show();
//					return false;
//				}
//				
//				shipping = $.evalJSON(rdata);
//				SHIPPING_RATES = shipping;
//
//				var options = '<option value="">- Choose Shipping -</option>' + "\n";
//
//				$.each(shipping.rates, function(){
//					options += '<option value="' + this.id + "\">" + this.name + " - $" + parseFloat(this.rate).toFixed(2) + '</option>';
//				});
//				
//
//				
//				$('#shipping_select').html(options).show().parent().parent().css({"width": "240px"});
//				
//				
//				
//				
//				setCookie('preferredShippingService', $('#shipping_select').val());
//				
//				$('a.calculate_shipping').html('Recalculate');
//				$('#shipping_rate_loading').hide();
//				$('#rate_popup').jqmHide();
//				Cart.Refresh_total(
//					{
//						ignore_tax: 1,
//						'shipping_rate_optional': 1,
//						'shipping_service': jQuery('#shipping_select').val(),
//						'zip_code': jQuery('input[name="zip_code"]').val()
//					}
//				);
//			}
//		);
//}


/*
Cart.Add_selected_shipping_to_cart_subtotal = function( subtotal ) {

	try {
		 
		 total_with_shipping = subtotal;
		 
		 if ( typeof(SHIPPING_RATES) != 'undefined' ) {
           	if ( jQuery('#shipping_select').length > 0 ) {
         		if ( typeof(SHIPPING_RATES[jQuery('#shipping_select').val()]) != 'undefined' ) {
                		total_with_shipping = parseFloat(subtotal) + parseFloat(SHIPPING_RATES[jQuery('#shipping_select').val()]);
                }
             }
         }
         
				//a Number Object is needed for use with toFixed in Handle_refresh_total() 
				var num = new Number(total_with_shipping);
        return num;
	}
	catch( e ) {
		alert( e.message );
	}

}
*/