
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/index.cfm?page_id=481',
        data: 'phase=add_shopping_cart_item&theme=ajax&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/index.cfm?page_id=481',
        data: 'phase=get&theme=ajax&response_type=json&' + urltoken,
        type: 'get',
        dataType: "json",
        cache: false,
		async: false,
        success: function(json) {
            $('#'+layer_id).html(json.HTML);

            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];
                $('#checkout_btn').css('color','#000000');
            }

        }
    });
}

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) {

            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/index.cfm?page_id=481',
        data: 'phase=set_shopping_cart_item&theme=ajax&item_id=' + item_id + '&quantity=' + quantity + '&'  + urltoken,
        async: true,
        cache: false,
        success: function(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;
	}

	$("#img_div_" + item_id).hide();
	$("#rotation_div_" + item_id).show();
		
	$.ajax({
        type: "GET",
        dataType: "json",
        url: '/sage/index.cfm?page_id=481',
        data: 'phase=add_shopping_cart_item&theme=ajax&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();
                            $('#item_total_' + item_id).text(dollarFormat(json.ITEM_TOTAL_PRICE));
                            $('#itemquantity-' + item_id).val(json.ITEM_TOTAL_QTY);
                            break;
                        }
                    
                    }

                    $('#shipping_data').val(json.SHIPPING_COST);
                    $('#shipping_cost').html(dollarFormat(json.SHIPPING_COST));
				
				$('#cart-details').html(json.CART_INFO);

				setTimeout(function() { $("#rotation_div_" + item_id).hide(); $("#img_div_" + item_id).show(); }, 200);
				
                    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];
				}
			}

        }
    });
}

var total_items;
var generalTotal;
	
function hideShow(id)
{	
	if ($("#"+id).attr(':visible') == 'true')
	{
		$("#"+id).attr('display','none');
	}
	else
	{
		$("#"+id).attr('display','block');
	}

}

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/index.cfm?page_id=481',
        data: 'phase=remove_shopping_cart_item&theme=ajax&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 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]);
            }
        }
    });
}
