var strShoppingCartTableTrClass = 'itemlined';
var strShoppingCartTableTrClassUniqueCharacter = 'd';
var strShoppingCartListOfItemIds = getShoppingCartItemIds();
var intShoppingCartTableLastRow = getShoppingCartTableLastRow();

function add_to_cart(item_id, price, quantity, obj, page, site_id) { 
	//alert(item_id + ' ' + price + ' ' + quantity.attr('id') + ' ' + obj);
	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;

    if (price > 0.01) {
        $(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&item_id=' + item_id + '&price=' + price + '&' + urltoken + '&quantity=' + qty + '&rnd=' + Math.random(),
            type: 'get',
            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 + '\', \'' + price + '\', \'' + 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 + '\', \'' + price + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\');" /></div>'); }
						if ($(obj).hasClass('panbtn1')) 
						{ 	/*<!---NOTE:
								----DO NOT REMOVE THE FOLLOWING CODE
								---- reason: WE do not sell for now compatible items on ST	
							if(site_id == 23) 
							{
								quantity.after('<input type="button" value="Add" class="panbtn3 st_panbtn3" id="more_' + item_id +'_' + page + '" onclick="doAddMore(\'' + item_id + '\', \'' + price + '\', \'' + quantity.attr('id') + '\', \'' + obj.id + '\', \'' + page +'\', 23);" />');
							}
							else
							{*/
								quantity.after('<input type="button" value="+ Add" class="panbtn3" id="more_' + item_id +'_' + page + '" onclick="doAddMore(\'' + item_id + '\', \'' + price + '\', \'' + 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 + '\', \'' + price + '\', \'' + 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 + '\', \'' + price + '\', \'' + 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, price, 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() { add_to_cart(item_id, price, $('#' + 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, price, $('#' + 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, price, $('#' + 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')
                //.parent().unbind('click').click(function() { add_to_cart(item_id, price, $('#' + obj_id), this, page); });
                $(obj_btn).unbind('click').click(function() { add_to_cart(item_id, price, $('#' + 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 update_cart(item_id, price, quantity, obj_id) {

	if(urltoken == '') {urltoken = 'none=none';}
/*	
	var shipping_cost_extended = 0.00
	var base_shipping_cost = 6.99
	var shipping_multiplier	= .70
	
	var shipping_cost_extended = shipping_cost_extended + (shipping_weight * quantity * shipping_multiplier);
	
	var shipping_cost = shipping_cost_extended + base_shipping_cost;
	
	alert ('New Shipping Cost:' + shipping_cost);
*/
	quantity_obj = $("#"+obj_id)[0];
	
	if (quantity == '') {
		countTotalPrice();
		return true;
	}

	if (isNaN(quantity) || quantity < 1) {
		quantity = 1;// : quantity = quantity;
		quantity_obj.value = 1;
	}

	if (typeof(item_quantity) == 'object' && item_quantity.length > 0) { //an array of item quantities of shopping cart is initialized
		if (item_quantity[item_id] == quantity) {
			countTotalPrice();
			return true; //if changed quantity remains the same, we don't need to go next
		}
	}
	
    if (price > 0.01) {
        $.ajax({
            url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
            data: 'fv_action=update&item_id=' + item_id + '&price=' + price + '&quantity=' + quantity + '&'  + urltoken + '&rnd=' + Math.random(),
            type: 'get',
			async: false,
            success: function(data) {
				var result = $.trim(data); 
				var json = eval("(" + result + ")");
				if (json.STATUS == "OK") {
					this_result = true;
					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] = quantity;
					}
					//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];
					}
				}
            }
        });
	}
	
}

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 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;
					        }
					    });						      		 		
        		   }		        			        			        	
        }
    });
}		
