var strShoppingCartTableTrClass = 'itemlined';
var strShoppingCartTableTrClassUniqueCharacter = 'd';
var strShoppingCartListOfItemIds = getShoppingCartItemIds();
var intShoppingCartTableLastRow = getShoppingCartTableLastRow();

function add_to_cart(item_id, quantity, obj, page, site_id) {

	if (page=='undefined') page='_';
    var qty = '';
    if((page=='')||page=='undefined') page ='_' ;
    var isObj = false;
    if (typeof(quantity) == 'object') {
        isObj = true;
        qty = quantity.val();
        if (qty == '') {
            qty = 1;
            quantity.val(qty);
        }
    } else {
        qty = quantity;
    }
     
	obj.id = 'butAddToCart_'+item_id +'_' + page;
    $(obj).after('<div id="working"> working...</div>');
    $(obj).hide();
            
    if(urltoken == '') {
        urltoken = 'none=none';
    }

    $.ajax({
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=add_shopping_cart_item&item_id=' + item_id  + '&' + urltoken + '&quantity=' + qty,
        type: 'get',
        cache : false,
        async: true,
        success: function(data) {
            var result = $.trim(data); 
            var json = eval("(" + result + ")");
            if (json.STATUS == "OK") {
                
                if (isObj) 
                {
                    if ($(obj).hasClass('button-blue')) 
                    {
                        $('input', obj).val('View cart')
                                .unbind('mouseover')
                                .unbind('mouseout')
                                .unbind('click')
                                .click(function() { location.href = '/cart/'; })
                                .parent().unbind('click').attr('onclick', '');
                    }
                    
                    if ($(obj).hasClass('add_to_cart_compatible_model'))
                    {
                        $(obj).val('View cart')
                                .unbind('mouseover')
                                .unbind('mouseout')
                                .unbind('click')
                                
                                $(obj).attr('onclick', '');
                    }
                    
                    if ($(obj).hasClass('panbtn1')) 
                    {
                          $(obj).unbind('click');
                          $(obj).attr('onclick', '');
                    }
                    
                    if ($(obj).hasClass('add_to_cart_compatible'))
                    {
                        $(obj).unbind('click');
                        $(obj).attr('onclick', '');
                        $(obj).val('');
                    } 
                     
                    quantity.hide();
        
                    if ($(obj).hasClass('button-blue')) { quantity.after('<div id="more_' + item_id +'_' + page + '" class="button-blue button-blue_fix" style="float:none !important; "><input type="button" value="+ Add" onclick="doAddMore(\'' + item_id + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\');" /></div>'); }
                    if ($(obj).hasClass('add_to_cart_compatible_model')){ quantity.after('<div id="more_' + item_id +'_' + page + '" class="button_grey add_more_fix" style="" ><input type="button" value="+ Add" onclick="doAddMore(\'' + item_id + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\');" /></div>'); }
                    if ($(obj).hasClass('panbtn1')) {
                        quantity.after('<input type="button" value="+ Add" class="panbtn3" id="more_' + item_id +'_' + page + '" onclick="doAddMore(\'' + item_id + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\');" />');
                    }
                    if ($(obj).hasClass('add_to_cart_compatible')) 
                    { 
                        if(site_id == 23)
                        {
                            quantity.after('<input type="button" value="Add" class="add_more st_add_more"  id="more_' + item_id +'_' + page + '" onclick="doAddMore(\'' + item_id + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\', 23);" />');
                        }
                        else
                        {
                            quantity.after('<input type="button" value="+ Add" class="add_more" id="more_' + item_id +'_' + page + '" onclick="doAddMore(\'' + item_id + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\');" />');
                        }  
                    }
                }
        
                if ($(obj).hasClass('button-blue')) 
                {
                    $(obj).removeClass('button-blue');
                    $(obj).addClass('button-gray');
                }
                if ($(obj).hasClass('add_to_cart_compatible_model'))
                {
                    $(obj).removeClass('button-blue');
                    $(obj).addClass('button-gray_compatible');
                }
                if ($(obj).hasClass('panbtn1')) 
                {
                    $(obj).removeClass('panbtn1');
                    $(obj).addClass('panbtn2');
                }
                if ($(obj).hasClass('add_to_cart_compatible')) 
                {
                    $(obj).removeClass('add_to_cart_compatible');
                    $(obj).addClass('view_cart_compatible');
                }
                
                get_cart_info('cart-details');
                $('#working').remove();
                $(obj).show();
                if ($(obj).hasClass('panbtn2')) {
                    $(obj).bind('click', function() {location.href = '/cart/'});
                }
                if ($(obj).hasClass('view_cart_compatible')) {
                    $(obj).bind('click', function() {location.href = '/cart/'});
                }
                if ($(obj).hasClass('add_to_cart_compatible_model'))
                {
                    $(obj).bind('click', function() {location.href = '/cart/'});
                }
            } else {
                $('#working').remove();
                $(obj).show();
                alert(json.MESSAGE);
                //quantity.select();
                //quantity.focus();
            }
        }
    });
}

function doAddMore(item_id, obj_id, obj_btn_id, page, site_id) {
    obj = $('#' + obj_id);
    obj.show();
    obj_btn = $('#' + obj_btn_id);
    $('#more_' + item_id+'_'+page).remove(); 
	if ($(obj_btn).hasClass('panbtn2')) {
		$(obj_btn).removeClass('panbtn2');
        $(obj_btn).addClass('panbtn1');
                
        $(obj_btn).unbind('click')
        $(obj_btn).unbind('click').click(function() {
        	$('.paninput').hide();        	       	
        	add_to_cart(item_id, $('#' + obj_id), this, page, site_id);        	 
        });
                
	}
	if ($(obj_btn).hasClass('button-gray')) {
		$(obj_btn).removeClass('button-gray');
        $(obj_btn).addClass('button-blue');
		 $('input', obj_btn).val('Added')
                       .mouseover(function() { this.value = '+ Add'; })
                       .mouseout(function() { this.value = 'Added'; })
                .unbind('click')
                .parent().unbind('click').click(function() { add_to_cart(item_id, $('#' + obj_id), this, page, site_id); });
	}
	if ($(obj_btn).hasClass('view_cart_compatible')) {
		$(obj_btn).removeClass('view_cart_compatible');
		$(obj_btn).addClass('add_to_cart_compatible');
		$(obj_btn).unbind('click')
        $(obj_btn).unbind('click').click(function() { add_to_cart(item_id, $('#' + obj_id), this, page, site_id); });
        $(obj_btn).val('Add to Cart');
	}
	if ($(obj_btn).hasClass('button-gray_compatible')) {
		$(obj_btn).removeClass('button-gray_compatible');
        //$(obj_btn).addClass('button-blue');
		 $(obj_btn).val('Added')
                       .mouseover(function() { this.value = '+ Add'; })
                       .mouseout(function() { this.value = 'Added'; })
                .unbind('click')
                $(obj_btn).unbind('click').click(function() { add_to_cart(item_id, $('#' + obj_id), this, page, site_id); });
	}
}

function get_cart_info(layer_id, page_id) {
	if(urltoken == '') {urltoken = 'none=none';}
    $.ajax({
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=get' + '&' + urltoken + '&rnd=' + Math.random(),
        type: 'get',
		async: false,
        success: function(data) {
            $('#'+layer_id).html($.trim(data.replace(/(<link([^>]+)>)/ig, '')));

	    if($('#'+layer_id).length){
		cart_items_qty = $('#'+layer_id).html();
		cart_items_qty = cart_items_qty.split('(')[1];
		cart_items_qty = cart_items_qty.split(' ')[0];
		
/*		if (cart_items_qty == '0'){
			$('#checkout_btn').css('color','#888888');
			$('#checkout_btn').unbind('click');
			$('#checkout_btn').click(function(){
				alert("Your shopping cart is empty, please add something to it in order to proceed to checkout page");
			});
			
		}
		else{	
			$('#checkout_btn').css('color','#000000');
			$('#checkout_btn').unbind('click');
			$('#checkout_btn').click(function(){
				location.href='/checkout/';
			});			
			
		}*/
			$('#checkout_btn').css('color','#000000');
/*			$('#checkout_btn').unbind('click');
			$('#checkout_btn').click(function(){	
				if (page_id == 481)
					location.href='/checkout/';
				else 
					location.href='/cart/';
			});*/		
		
		
	    }
        }
    });
}

function clear_cart() {
	if(urltoken == '') {urltoken = 'none=none';}
    $.ajax({
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=clear' + '&' + urltoken + '&rnd=' + Math.random(),
        type: 'get',
        success: function(data) {
            get_cart_info('cart-details');
        }
    });
}

function doCalcTax(address_id) {

    if (address_id == '') return false; //shipping address not selected yet

    $.ajax({
        url: '/sage/index.cfm',
        dataType: "json",
        cache: false,
        async: false,
        data: 'page_id=487&phase=get_tax&theme=ajax&safari=true&address_id=' + address_id,
        type: 'GET',
        beforeSend: function() {
            $('#tax_data').html('<div class="loading">&nbsp;</div>');
            $('#general-total-price').html('<div class="loading">&nbsp;</div>');
        },
        success: function(json) {
//$.dump(json);
            switch (json.STATUS) {

                case 'OK': {
                    $('#tax_data').text(dollarFormat(json.TAX_RATE));
                    $('#general-total-price').text(dollarFormat(json.SUBTOTAL_PRICE + json.ORDER_FEE + json.TAX_RATE + json.SHIPPING_COST));
                    break;
                }

                case 'ERR': {

                    switch (json.CODE) {

                        default: { }

                    }

                }

            }

        }
    });
} 

function doSetShoppingCartItem(item_id, quantity, page) {

	if (urltoken == '') {
        urltoken = 'none=none';
    }

	if (isNaN(quantity) || quantity == '' || quantity < 1) {
		quantity = 1;
	}

    $.ajax({
        type: "GET",
        dataType: "json",
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=set_shopping_cart_item&item_id=' + item_id + '&quantity=' + quantity + '&'  + urltoken,
        async: true,
        cache: false,
        success: function(json) {
//$.dump(json);
            switch (json.STATUS) {

                case 'OK': {

                    switch (page) {

                        case 'cart': {
                            order_fee = 0.00;
                            $('#item_total_' + item_id).html(dollarFormat(json.ITEM_TOTAL_PRICE));
                            $('#itemquantity-' + item_id).val(json.ITEM_TOTAL_QTY);
                            $('#subtotal-price').text(dollarFormat(json.SUBTOTAL_PRICE));

                            if (json.SUBTOTAL_PRICE < json.ORDER_FEE_UNDER) {
                                $('#order-fee').show();
                                $('#fee-diff').text(dollarFormat(json.ORDER_FEE_UNDER - json.SUBTOTAL_PRICE));
                                order_fee = json.ORDER_FEE;
                            } else {
                                $('#order-fee').hide();
                            }

                            $('#general-total-price').text(dollarFormat(json.SUBTOTAL_PRICE + json.SHIPPING_COST + order_fee));
                            get_cart_info('cart-details');
                            break;
                        }
                    
                        case 'checkout': {
                            order_fee = 0.00;
                            $('#sc-price-'+item_id).text(dollarFormat(json.ITEM_TOTAL_PRICE));
                            $('#sc-qty-'+item_id).val(json.ITEM_TOTAL_QTY);
                            $('#quant'+item_id).html(json.ITEM_TOTAL_QTY);
                            $('#total'+item_id).html(dollarFormat(json.ITEM_TOTAL_PRICE))
                            $('#shipping_data').val(json.SHIPPING_COST);
                            $('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
                            $('#sc-total').text(dollarFormat(json.SUBTOTAL_PRICE));
                            $('#subtotal-price').text(dollarFormat(json.SUBTOTAL_PRICE));

                            if (json.SUBTOTAL_PRICE < json.ORDER_FEE_UNDER) {
                                $('#order-fee').show();
                                $('#fee-diff').text(dollarFormat(json.ORDER_FEE_UNDER - json.SUBTOTAL_PRICE));
                                $('#order-fee-value').text(dollarFormat(json.ORDER_FEE));
                                order_fee = json.ORDER_FEE;
                            } else {
                                $('#order-fee').hide();
                            }

                            //countTotalPrice();
                            $('#general-total-price').text(dollarFormat(json.SUBTOTAL_PRICE + order_fee+ json.SHIPPING_COST));
                            doCalcTax($('#address_shipping_id').val());
                            break;
                        }
                    
                        default: {
                            get_cart_info('cart-details');
                        }

                    }

                    $('#shipping_data').val(json.SHIPPING_COST);
                    $('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
                    break;
                }

                case 'ERR': {

                    switch (json.CODE) {

                        default: {
                            alert(json.MESSAGE);
                        }

                    }

                }

            }

        }
    });
}

function doAddShoppingCartItem(item_id, quantity, page) {

	if (urltoken == '') {
        urltoken = 'none=none';
    }

	if (isNaN(quantity) || quantity == '' || quantity < 1) {
		quantity = 1;
	}

    $.ajax({
        type: "GET",
        dataType: "json",
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=add_shopping_cart_item&item_id=' + item_id + '&quantity=' + quantity + '&page=' + page + '&'  + urltoken,
        async: true,
        cache: false,
        success: function(json) {

            switch (json.STATUS) {

                case 'OK': {

                    switch (page) {

                        case 'cart': {
                            order_fee = 0.00;

                            if (typeof(json.item_html_row) !== 'undefined' && json.item_html_row.length > 0) {
                                $('.shooping_cart_empty').hide();
                                $('#shopping_cart_table tbody').append(json.item_html_row)
                                tb_init('a.thickbox, area.thickbox, input.thickbox');
                            }

                            $('#subtotal-price').text(dollarFormat(json.SUBTOTAL_PRICE));

                            if (json.SUBTOTAL_PRICE < json.ORDER_FEE_UNDER) {
                                $('#order-fee').show();
                                $('#fee-diff').text(dollarFormat(json.ORDER_FEE_UNDER - json.SUBTOTAL_PRICE));
                                order_fee = json.ORDER_FEE;
                            } else {
                                $('#order-fee').hide();
                            }

                            $('#general-total-price').text(dollarFormat(json.SUBTOTAL_PRICE + json.SHIPPING_COST + order_fee));
                            $('#shooping_cart_empty_row').hide();
                            $('#shooping_cart_empty_row_delimiter').hide();
                            //check_zip($('#zip_code_').val());
                            $('#item_total_' + item_id).text(dollarFormat(json.ITEM_TOTAL_PRICE));
                            $('#itemquantity-' + item_id).val(json.ITEM_TOTAL_QTY);
                            break;
                        }
                    
                        default: {
                        }

                    }

                    get_cart_info('cart-details');
                    $('#shipping_data').val(json.SHIPPING_COST);
                    $('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
                    break;
                }

                case 'ERR': {

                    switch (json.CODE) {

                        default: { }

                    }

                }

            }

        }
    });
}

function remove_from_cart(item_id) {
	if(urltoken == '') {urltoken = 'none=none';}
    $.ajax({
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=remove&item_id=' + item_id + '&' + urltoken + '&rnd=' + Math.random(),
        type: 'get',
		async: false,
        success: function(data) {
			var result = $.trim(data); 
			var json = eval("(" + result + ")");

			if (json.STATUS == "OK") {
				orderfee = json.RESULT;
				get_cart_info('cart-details');
				//check_zip($('#zip_code_').val());
				if (typeof(item_quantity) == 'object' && item_quantity.length > 0) { //an array of item quantities of shopping cart
					item_quantity[item_id] = 0;
				}
				//countShippingWeight(shipping_cost);
				$('#shipping_data').val(json.SHIPPING_COST);
				$('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
				countTotalPrice();
				//ChangeShippingWeight(shipping_cost);
			} else {
				alert(json.MESSAGE);
				if (typeof(item_quantity) == 'object' && item_quantity.length > 0) { //an array of item quantities of shopping cart
					quantity_obj.value = item_quantity[item_id];
				}
			}
/*
			orderfee = data;
			countTotalPrice();
            get_cart_info('cart-details');
*/
        }
    });
}

var total_items;
var generalTotal;
	
function hideShow(id)
{	
	if ($("#"+id).attr(':visible') == 'true')
	{
		$("#"+id).attr('display','none');
	}
	else
	{
		$("#"+id).attr('display','block');
	}

}	
/*
	function countShippingWeight(sh_cost){
	//alert ('New Shipping Cost bla bla:' + sh_cost);
	var shipping_cost = parseFloat(sh_cost);
		$('#shipping_data').val(sh_cost);
		$('#shipping_cost').html(dollarFormat(shipping_cost));
	}
*/


function listFind(strList, strValue, strDelimeter) {
	strList += ''; // cheap way to convert to a string
	if(!strDelimeter) { strDelimeter = ','; }
	var intResult = 0;
	var arListToArray = strList.split(strDelimeter);
	for (var i = 0; i < arListToArray.length; i++) {
		if (arListToArray[i] == strValue) {
			intResult = i + 1;
			break;
		}
	}
	return intResult;
}	

function listLast(strList, strDelimeter) {
	strList += ''; // cheap way to convert to a string
	if(!strDelimeter) { strDelimeter = ','; }		
	strList = strList.split(strDelimeter);
	return strList[strList.length - 1];
}

function listGetAt(strList, intPosition, strDelimeter) {
	strList += ''; // cheap way to convert to a string
	if(!strDelimeter) { strDelimeter = ','; }
	return strList.split(strDelimeter)[intPosition - 1];
}

function listDeleteAt(strList, intPosition, strDelimeter) {
	strList += ''; // cheap way to convert to a string
	if(!strDelimeter) { strDelimeter = ','; }
	var i, intPosInList;
	var posInArray = intPosition - 1;
	var strThisD = '';
	var strReturn = '';
	for(i = 0; i < strList.split(strDelimeter).length; i++) {
		if (i != posInArray) {
			intPosInList = i + 1;
			if (strReturn.length) {
				strThisD = strDelimeter;
			}
			strReturn += strThisD + listGetAt(strList, intPosInList, strDelimeter);
		}
	}
	return strReturn;
}


function deleteItemFromCart(pos, item_id)
{
	$.ajax({
		type: 'GET',
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=is_already_items_on_cart&pos='+pos+'&item_id='+item_id+'&delete=true&theme=ajax&safari=true&rnd='+Math.random()       
    });
}


function getItemIdByRow(row) {		
	return listLast($('#item-landing-page-link' + row).attr('href').split('/'));		
}

function getRowByItemId(item_id) {		
	var str = $('a.item-landing-page-link[@href*='+item_id+']').attr('id');		
	var pos = str.indexOf('k');
	return str.substr(pos+1);		
}

function doRemoveShoppingCartItem(item_id, page) {

	if ( ! confirm("Are you sure?") ) {
        return false;
    }

    if(urltoken == '') {
        urltoken = 'none=none';
    }

    $.ajax({
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=remove_shopping_cart_item&item_id=' + item_id + '&' + urltoken,
        type: 'GET',
        dataType: "json",
        cache : false,
		async: true,
        success: function(json) {

            switch (json.STATUS) {

                case 'OK': {

                    switch (page) {

                        case 'cart': {
                            order_fee = 0.00;

                            if ( json.TOTAL_QTY == 0) {
                                $('#shopping_cart_table tbody').html('');
                                $('#shooping_cart_empty_row').show();
                                $('#shooping_cart_empty_row_delimiter').show();
                            } else {
                                $('#itemline'+item_id).remove();
                                $('#itemlined'+item_id).remove();
                            }

                            $('#subtotal-price').text(dollarFormat(json.SUBTOTAL_PRICE));

                            if (json.SUBTOTAL_PRICE < json.ORDER_FEE_UNDER) {
                                $('#order-fee').show();
                                $('#fee-diff').text(dollarFormat(json.ORDER_FEE_UNDER - json.SUBTOTAL_PRICE));
                                order_fee = json.ORDER_FEE;
                            } else {
                                $('#order-fee').hide();
                            }

                            $('#general-total-price').text(dollarFormat(json.SUBTOTAL_PRICE + json.SHIPPING_COST + order_fee));
                            break;
                        }

                        case 'checkout': {
                            order_fee = 0.00;
                            $('#itemline'+item_id).remove();
                            $('#confirm-'+item_id).remove();
                            $('#confirmline-'+item_id).remove();
                            $('#subtotal-price').text(dollarFormat(json.SUBTOTAL_PRICE));
                            $('#sc-total').text(dollarFormat(json.SUBTOTAL_PRICE));

                            if (json.SUBTOTAL_PRICE < json.ORDER_FEE_UNDER) {
                                $('#order-fee').show();
                                $('#fee-diff').text(dollarFormat(json.ORDER_FEE_UNDER - json.SUBTOTAL_PRICE));
                                order_fee = json.ORDER_FEE;
                            } else {
                                $('#order-fee').hide();
                            }

                            $('#general-total-price').text(dollarFormat(json.SUBTOTAL_PRICE + json.SHIPPING_COST + order_fee));
                            doCalcTax($('#address_shipping_id').val());
                            break;
                        }
                    
                        default: {
                        }

                    }

                    get_cart_info('cart-details');
                    $('#shipping_data').val(json.SHIPPING_COST);
                    $('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
                    break;
                }

                case 'ERR': {

                    switch (json.CODE) {

                        default: { }

                    }

                }

            }

        }
    });
}

function removeItem(i)
{
	if(confirm("Are you sure?"))
	{			
		var intItemId = getItemIdByRow(i); 
		deleteItemFromCart(i, intItemId);
		strShoppingCartListOfItemIds = listDeleteAt(strShoppingCartListOfItemIds, i);
		
		$("tr").remove("#itemline"+i);
		$("tr").remove("#itemlined"+i);
		//countTotalPrice();
		if (!$('.lp-tbl-items-info').length){
			$('#shopping_cart_table .lp-tbl-items-header').after('<tr class="shooping_cart_empty"><td colspan="9" align="center"><div style="padding:10px 0 10px 0;">Your cart is currently empty, please use search to find what you are looking for and add here. </div></td></tr>');											
			$('#zip_code_field').attr("readonly","true");
			$('#zip_code_field').val('');
			$('#tax_price').html('$0.00');
		}else{
			check_zip($('#zip_code_').val());
		}

		return true;
	}
	return false;
}

function getShoppingCartItemIds() {				
	var strTrId = '';
	var intTrRows = 0;
	var arTrRows = new Array();
	
	var strAllItemLandigPageLinks = '';
	var strItemId = '';
	var arItemId = new Array();
	
	var arTmp = new Array();
	var strReturn = '';

	var intPositionOfTrClassUniqueCharacter = strShoppingCartTableTrClass.indexOf(strShoppingCartTableTrClassUniqueCharacter);
			
	$.each($('.' + strShoppingCartTableTrClass), function(i) {
		 strTrId = $(this).attr('id');
		 intTrRows = strTrId.substr(intPositionOfTrClassUniqueCharacter + 1);	
		 arTrRows.push(intTrRows);				
	});
	//console.log(arTrRows);
	
	$.each($('a.item-landing-page-link[@href*=/]'), function(i) {
		strAllItemLandigPageLinks = $(this).attr('href');
		strItemId = listLast(strAllItemLandigPageLinks.split('/'));
		arItemId.push(strItemId);			
	});
	//console.log(arItemId);
	
	for (var i = 0; i < arTrRows.length; i++) {
		arTmp[arTrRows[i]] = arItemId[i];			
	}	
	strReturn = arTmp.join(',');
	strReturn = strReturn.substr(1);
	//console.log(strReturn);
	
	return strReturn;			
}

function getShoppingCartTableLastRow() {		
	var strLastTrClassName = '';				
	if (!$('.lp-tbl-items-info').length) {
		var intTrLastRow = 0;
	} else { 		
		var intPositionOfTrClassUniqueCharacter = strShoppingCartTableTrClass.indexOf(strShoppingCartTableTrClassUniqueCharacter);
					
		strLastTrClassName = $('table#shopping_cart_table tr.' + strShoppingCartTableTrClass + ':last').attr('id');
		intTrLastRow = strLastTrClassName.substr(intPositionOfTrClassUniqueCharacter + 1);				
		//console.log('last row = ' + intTrLastRow);			
	}	
	return intTrLastRow;
}
	

function addItemToBasket(item_id, item_price, item_qty, row) {
	$.ajax({
		type: 'GET',
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: {fv_action: 'is_already_items_on_cart', item_id: item_id, theme: 'ajax', safari: 'true', rnd: Math.random()},	
		beforeSend: function() {
						$('#add_btn_' + item_id).hide();
						$('#rotation_div_' + item_id).html('<table cellpadding="0" cellspacing="0"><tr><td>Adding&nbsp;</td><td><img src="/sage/themes/tonermax/images/bigrotation2.gif" border="0" /></td></tr><table>');
				},
		complete: function() {
						$('#add_btn_' + item_id).show();
						$('#rotation_div_' + item_id).html('');
				},
        success: function(data) {	        			
        		 	if (data == 'TRUE') {
						var current_row = getRowByItemId(item_id);																
						var html_id = 'itemquantity-' + current_row;						
						add_to_cart(item_id, item_price, 1, html_id, 'mlp');			
						var current_qty = $('#'+html_id).val();
						var new_qty = parseInt(current_qty) + 1;
						$('#'+html_id).attr('value', new_qty);						 		
						countTotalPrice();
        		 	} else {	    	        		 			 			  	        		 		      			        		 								 
        		 		$.ajax({
							type: 'GET',
					        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
					        data: {item_id: item_id, row: row, item_price: item_price, item_qty: item_qty, fv_action: 'add_to_basket', theme: 'ajax', safari: 'true', rnd: Math.random()},	        
					        success: function(data) {							        							        	 	
					        	nextRow = parseInt(row) + 1;        
					        	obj = 'itemquantity-' + nextRow;			            
					           	add_to_cart(item_id, item_price, 1, obj, 'mlp');
					        	if (row != 0) {							           									           								           								           		           					           		
						           	$('tr#itemlined' + row).after(data);
					        	} else {						        		
					        		$('.shooping_cart_empty').remove();
					        		$('.lp-tbl-items-header').after(data);
					        	}						        								           			           							           			           		           	
					            countTotalPrice();
					            strShoppingCartListOfItemIds += ','+item_id;
					        }
					    });						      		 		
        		   }		        			        			        	
        }
    });
}

function update_sc(item_id, quantity) {

    if (isNaN(quantity) || quantity < 1) {
        quantity = 1;// : quantity = quantity;
        $("#sc-qty-" + item_id).val('1');
    }

    $.ajax({
        url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
        data: 'fv_action=update&item_id=' + item_id + '&quantity=' + quantity +  '&safari=true&rnd=' + Math.random(),
        type: 'GET',
        dataType: "json",
        cache : false,
		async: true,
        success: function(json) {

            if (json.STATUS == "OK") {
                orderfee = json.result;
                $('#sc-price-'+item_id).html(dollarFormat(price*quantity));
                $('#sc-qty-'+item_id).val(quantity);
                $('#quant'+item_id).html(quantity);
                $('#total'+item_id).html(dollarFormat(price*quantity))
                $('#shipping_data').val(json.SHIPPING_COST);
                $('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
                countTotalPrice();
                item_quantity[item_id] = quantity;
            } else {
                alert(json.MESSAGE);
                $("#sc-qty-" + item_id).val(item_quantity[item_id]);
            }
        }
    });
}
