// JavaScript Sell your Calc Shopping Cart.
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function update_notification() {
    if (document.getElementById('dontshow').checked)
        createCookie('sellyourcalculators_notify',1,365);
    else
        createCookie('sellyourcalculators_notify',0,365);
	jQuery.fancybox.close();
}

function calc_update_picker()
{
	// Get Calc ID number
	var index = document.getElementById('model').selectedIndex;
	var model = document.getElementById('model').options[index].value;

	// Update Calc Name & Photo
	document.getElementById('calc_name').innerHTML = calc[model]['model'];
	document.getElementById('calc_image').src = calc[model]['image'];

	// Update Calc Condition price options
	var condition = ''+
	   '<h4>Select its condition and accessories</h4>'+
          '<div><p>Condition</p>'+
          '<ul>';
      if (calc[model]['poor'] > 0)    condition  += '  <li><a href="#" class="tiplink"><input type="radio" name="condition" id="Poor"  onclick="update_price();" value="'+calc[model]['poor']+'" /><span style="color: #2D3641;"> Poor  </span><strong>?</strong><span class="tooltip">'+calc['poor']+'</span></a></li>';
      if (calc[model]['fair'] > 0)    condition  += '  <li><a href="#" class="tiplink"><input type="radio" name="condition" id="Fair"  onclick="update_price();" value="'+calc[model]['fair']+'" /><span style="color: #2D3641;"> Fair  </span><strong>?</strong><span class="tooltip">'+calc['fair']+'</span></a></li>';
      if (calc[model]['good'] > 0)    condition  += '  <li><a href="#" class="tiplink"><input type="radio" name="condition" id="Good"  onclick="update_price();" value="'+calc[model]['good']+'" /><span style="color: #2D3641;"> Good  </span><strong>?</strong><span class="tooltip">'+calc['good']+'</span></a></li>';
      if (calc[model]['great'] > 0)   condition  += '  <li><a href="#" class="tiplink"><input type="radio" name="condition" id="Great" onclick="update_price();" value="'+calc[model]['great']+'" /><span style="color: #2D3641;"> Great </span><strong>?</strong><span class="tooltip">'+calc['great']+'</span></a></li>';
      if (calc[model]['mint'] > 0)    condition  += '  <li><a href="#" class="tiplink"><input type="radio" name="condition" id="Mint"  onclick="update_price();" value="'+calc[model]['mint']+'" /><span style="color: #2D3641;"> Mint  </span><strong>?</strong><span class="tooltip">'+calc['mint']+'</span></a></li>';
      if (calc[model]['like_new'] > 0) condition += '  <li><a href="#" class="tiplink"><input type="radio" name="condition" id="New-in-box" onclick="update_price();" value="'+calc[model]['like_new']+'" /><span style="color: #2D3641;"> New-in-box </span><strong>?</strong><span class="tooltip newinbox">'+calc['like_new']+'</span></a></li>';
      condition += '</ul></div>';

	// Update Calc Accessory Price Selections
	var accessories = ''+
          '<div><p>Accessories</p>'+
          '<ul>\n';
	for (var i in calc_access ) {
		if (calc[model][calc_access[i]]) {
			accessories += '  <li><input type="checkbox" name="acc" id="'+calc_access[i]+'" onclick="update_price();" value="'+calc[model][calc_access[i]]+'" /> '+calc_access[i]+'</li>\n';
		}
	}
    accessories += '</ul></div>';

	// Update Condition Accessory Display
	document.getElementById('selectcondition').innerHTML = condition + accessories;

	update_price();

	// set height of Shopping Cart
	var model_height = document.getElementById('homemodel').clientHeight;
	document.getElementById('homecart').style.height = model_height-20+"px";
	document.getElementById('cartitems').style.height = model_height-145+"px";

}

// Update Calulator selected and all pricing.
function calc_update()
{
	calc_update_picker();

	document['add_but'].src = 'images/button_addtocart.jpg';
	document.getElementById('add_click').onclick = add_to_cart;

	document.getElementById('unit_cond').value = "";
	document.getElementById('unit_acc').value = "";
}

// Update Current Item Price
function update_price()
{
	var price = 0;
	var cond = document.your_calc.condition;
	var acc = document.your_calc.acc;

	disable_options = false;
	for (var i = 0; i < cond.length; i++) {
		if (cond[i].checked) {
			if (cond[i].id == 'New-in-box') {
				disable_options = true;
			}
			if (cond[i].value != '') {
				price = parseFloat(cond[i].value);
			}
		}
	}

    if (acc.length != undefined) {
        for (i = 0; i < acc.length; i++) {
                if (disable_options) {
                    acc[i].checked = false;
                    acc[i].disabled = true;
                } else {
                    acc[i].disabled = false;
                }
                if (acc[i].checked) {
                    if (acc[i].value != '') {
                        price += parseFloat(acc[i].value);
                    }
                }
        }
    } else {
        if (acc.checked && acc.value != '')
            price += parseFloat(acc.value);
    }

	document.getElementById('pay').innerHTML = '$'+price;
}


function init_cart()
{
	var param = new Array();
	param['mode'] = 'init_cart';
	new Ajax.Request ( 'classes/ajax_item.php',
					   {method: 'post',
					     parameters: param,
					     onComplete: function(transport){
						  var json = transport.responseJSON;

							document.getElementById('total_items').innerHTML = "Total Items: "+json.count;
							document.getElementById('cartitems').innerHTML = json.cart;
							document.getElementById('total_price').innerHTML = '$'+json.total;

							//document.getElementById('last_id').value = json.id;

						}
					   } );

	document.getElementById('unit_cond').value = "";
	document.getElementById('unit_acc').value = "";

	// set height of Shopping Cart
	var model_height = document.getElementById('homemodel').clientHeight;
	document.getElementById('homecart').style.height = model_height-20+"px";
	document.getElementById('cartitems').style.height = model_height-145+"px";

}


function clear_cart()
{
	var param = new Array();
	param['mode'] = 'clear_cart';
	new Ajax.Request ( 'classes/ajax_item.php',
					   {method: 'post',
					     parameters: param,
					     onComplete: function(transport){
						  var json = transport.responseJSON;

							document.getElementById('total_items').innerHTML = "Total Items: 0";
							document.getElementById('cartitems').innerHTML = "&nbsp;";
							document.getElementById('total_price').innerHTML = '$0';

							//document.getElementById('last_id').value = json.id;

						}
					   } );
	document.getElementById('unit_cond').value = "";
	document.getElementById('unit_acc').value = "";

}

// Add to Shopping Cart
// Update Shopping cart pricing
// Create Transaction in DB.
function add_to_cart()
{
	// Get Calculator Options and Validate.
	var cond = document.your_calc.condition;
	var acc = document.your_calc.acc;

	var cond_selected = false;
	for (var i = 0; i < cond.length; i++) {
		if (cond[i].checked) {
			cond_selected = true;
			if (cond[i].value != '') {
				var condition = cond[i].id+' : $'+cond[i].value;
				var est_payment = parseFloat(cond[i].value);
				document.getElementById('unit_cond').value = cond[i].id;
				break;
			}
		}
	}

	if (!cond_selected) {
		alert("Please select the condition of your calculator!");
		return;
	}

	var accessories = '';
    if (acc.length != undefined) {
        for (i = 0; i < acc.length; i++) {
            if (acc[i].checked) {
                if (acc[i].value != '') {
                    if (accessories.length > 0) {accessories += ', ';}
                    accessories += acc[i].id+' : $'+acc[i].value;
                    est_payment += parseFloat(acc[i].value);
                }
            }
        }
    } else {
        if (acc.checked && acc.value != '') {
            accessories = acc.id+' : $'+acc.value;
            est_payment += parseFloat(acc.value);
        }
    }
	document.getElementById('unit_acc').value = accessories;
//alert("accessories "+accessories);

	// Update Total Items
	var total_items = document.getElementById('total_items').innerHTML;
	var parts = total_items.split(":");

	num = parseInt(parts[1]) + 1;
	document.getElementById('total_items').innerHTML = "Total Items: "+num;

	// Get the Cart details
	var cart = document.getElementById('cartitems').innerHTML;

	// Get Calc ID number
	var index = document.getElementById('model').selectedIndex;
	var model = document.getElementById('model').options[index].value;

	// Save values in shopping cart form.
	var pay = document.getElementById('pay').innerHTML;
	document.getElementById('unit_total').value = pay.substr(1);
	var total_price = document.getElementById('total_price').innerHTML;
	var total = parseFloat(pay.substr(1))+parseFloat(total_price.substr(1));
	document.getElementById('total_price').innerHTML = '$'+total;

	// Update the database
	var param = new Array();
	param['mode'] = 'add';
	param['calc_id'] = model;
	param['condition'] = condition;
	param['accessories'] = accessories;
	param['est_payment'] = est_payment;
	param['total_est_payment'] = document.getElementById('total_price').innerHTML;

	new Ajax.Request ( 'classes/ajax_item.php',
					   {method: 'post',
					     parameters: param,
					     onComplete: function(transport){
							var json = transport.responseJSON;

							document.getElementById('cartitems').innerHTML = json.cart;
							document.getElementById('last_id').value = json.id;
                            document.getElementById('total_price').innerHTML = '$'+json.total;

                            var notify = readCookie('sellyourcalculators_notify');
                            if (notify == null || notify != 1) {
                                jQuery("#notify").trigger('click');
                            }
						}
					   } );

	document['add_but'].src = 'images/button_addanother.png';
	//document.getElementById('add_click').onclick = update_cart;

}

function replaceOneChar(s,c,n){
	var re = "";
	for(var i = 0; i< s.length; i++) {
		if (i == n) {
			re += c;
		} else {
			re += s.charAt(i);
		}
	}
	return re;
}

function validate_cart()
{
	var total_price = parseFloat(document.getElementById('total_price').innerHTML.substr(1));
	var edit_price = parseFloat(document.getElementById('pay').innerHTML.substr(1));
	var unit_total = parseFloat(document.getElementById('unit_total').value);

	// Zero items in cart
	if (total_price == 0) {
		alert('Please add items to your sales cart and try again!');
		return false;
	}


	if (edit_price != 0) {
		// Test Condition Same.
		// Get Calculator Options and Validate.
		var cond = document.your_calc.condition;
		var acc = document.your_calc.acc;
		var unit_cond = document.getElementById('unit_cond').value;
		var unit_acc = document.getElementById('unit_acc').value;

		var condition;
		for (var i = 0; i < cond.length; i++) {
			if (cond[i].checked) {
				if (cond[i].value != '') {
					condition = cond[i].id;
					break;
				}
			}
		}

    	var accessories = '';
        if (acc.length != undefined) {
            for (i = 0; i < acc.length; i++) {
                if (acc[i].checked) {
                    if (acc[i].value != '') {
                        if (accessories.length > 0) {accessories += ', ';}
                        accessories += acc[i].id+' : $'+acc[i].value;
                    }
                }
            }
        } else {
            if (acc.checked && acc.value != '')
                accessories = acc.id+' : $'+acc.value;
        }
		if (unit_total != edit_price || condition != unit_cond || accessories != unit_acc) {
			jQuery.fancybox({'href':'#poplink'});
			return false;
		}
	}
	return true;
}

function delete_from_cart(id)
{
	if (id == document.getElementById('last_id').value) {
		document['add_but'].src = 'images/button_addtocart.jpg';
		document.getElementById('add_click').onclick = add_to_cart;
	}

	// Update Total Items
	var total_items = document.getElementById('total_items').innerHTML;
	var parts = total_items.split(":");
	num = parseInt(parts[1]) - 1;
	document.getElementById('total_items').innerHTML = "Total Items: "+num;

	// Update Database...
	var param = new Array();
	param['mode'] = 'delete';
	param['id'] = id;
	new Ajax.Request ( 'classes/ajax_item.php',
					   {method: 'post',
					     parameters: param,
					     onComplete: function(transport){
						  var json = transport.responseJSON;

						// Update Shopping Cart
						document.getElementById('cartitems').innerHTML = json.cart;
						document.getElementById('total_price').innerHTML = '$'+json.total;

						if (json.total == 0) {
							//document.getElementById('model').selectedIndex = 0;
							document.getElementById('model').options[0].selected = true;
							calc_update();
						}
						}
					   } );
}

function update_cart()
{
	// Get Calculator Options and Validate.
	var cond = document.your_calc.condition;
	var acc = document.your_calc.acc;

	var cond_selected = false;
	var condition, est_payment;
	for (var i = 0; i < cond.length; i++) {
		if (cond[i].checked) {
			cond_selected = true;
			if (cond[i].value != '') {
				condition = cond[i].id+' : $'+cond[i].value;
				est_payment = parseFloat(cond[i].value);
				document.getElementById('unit_cond').value = cond[i].id;
				break;
			}
		}
	}

	var accessories = '';
    if (acc.length != undefined) {
        for (i = 0; i < acc.length; i++) {
            if (acc[i].checked) {
                if (acc[i].value != '') {
                    if (accessories.length > 0) {accessories += ', ';}
                    accessories += acc[i].id+' : $'+acc[i].value;
                    est_payment += parseFloat(acc[i].value);
                }
            }
        }
    } else {
        if (acc.checked && acc.value != '') {
            accessories = acc.id+' : $'+acc.value;
            est_payment = parseFloat(acc.value);
        }
    }
	document.getElementById('unit_acc').value = accessories;
//alert("accessories "+accessories);

	// Get Calc ID number
	var index = document.getElementById('model').selectedIndex;
	var model = document.getElementById('model').options[index].value;

	// Updated Price of the item.
	var pay = document.getElementById('pay').innerHTML;
	var est_payment = parseFloat(pay.substr(1));
	document.getElementById('unit_total').value = pay.substr(1);

	// Update the database
	var param = new Array();
	param['mode'] = 'update';
	param['calc_id'] = model;
	param['condition'] = condition;
	param['accessories'] = accessories;
	param['est_payment'] = est_payment;
	param['id'] = document.getElementById('last_id').value;
	new Ajax.Request ( 'classes/ajax_item.php',
					   {method: 'post',
					     parameters: param,
					     onComplete: function(transport){
							  var json = transport.responseJSON;

						// Update Shopping Cart
						document.getElementById('cartitems').innerHTML = json.cart;
						document.getElementById('total_price').innerHTML = '$'+json.total;

						}
					   } );
}

function warning_update()
{
	update_cart();
	jQuery.fancybox.close();
}

function warning_cancel()
{
	calc_update();
	jQuery.fancybox.close();
}

function view_delete_warning(id)
{
	document.getElementById('delete_id').value = id;
	jQuery.fancybox({'href':'#delpoplink'})
}

function warning_delete()
{
	id = document.getElementById('delete_id').value;
	delete_from_cart(id);
	jQuery.fancybox.close();
}

function edit_item(id)
{
	var param = new Array();
	param['mode'] = 'get_item';
	param['id'] = id;
	new Ajax.Request ( 'classes/ajax_item.php',
					   {method: 'post',
					     parameters: param,
					     onComplete: function(transport){
						  var json = transport.responseJSON;

						// Set the calulator selection
						var model = document.getElementById('model');
						for (var i=0; i<model.options.length; i++) {
							if (model.options[i].text == json.model)
								model.options[i].selected = true;
						}

						// Update select image and prices.
						calc_update_picker();

						var cond = document.your_calc.condition;
						var acc = document.your_calc.acc;

						// Update Condition
						for (i = 0; i < cond.length; i++) {
							if (cond[i].id.toLowerCase() == json.condition.toLowerCase()) {
								cond[i].checked = true;
							} else {
								cond[i].checked = false;
							}
						}

						// Update Accessories
                        if (acc.length != undefined) {
                            for (j in acc) {  // 1st clear Acessories.
                                acc[j].checked = false;
                            }
                            var acc_name="";  // Then set selected Accessories
                            for (i = 1; i <= json.total_acc; i++) {
                                acc_name = json.acc[i];
                                for (j in acc) {
                                    // not working in IE - alert("acc_name = "+acc_name+" <> acc[j].id = "+acc[j].id);
                                    if ( acc_name == acc[j].id ) {
                                        acc[j].checked = true;
                                    }
                                }
                            }
                        } else {
                            var acc_name="";  // Then set selected Accessories
                            for (i = 1; i <= json.total_acc; i++) {
                                acc_name = json.acc[i];
                                if ( acc_name == acc.id ) {
                                    acc.checked = true;
                                }
                            }
                        }

						document.getElementById('unit_total').value = json.unit_total;
						document.getElementById('unit_cond').value = json.condition;
						document.getElementById('unit_acc').value = json.accessories;

						update_price();

						}
					   } );

	document.getElementById('last_id').value = id;
	document['add_but'].src = 'images/button_updatecart.jpg';
	document.getElementById('add_click').onclick = update_cart;

}
