// notes for use:

// this adds callbacks to the add to cart and complete checkout forms to link smc products
// to plugin builder items.

// for this to work in multiple browsers (cough *ie6*) some attention needs to be paid to the 
// following details:

// updates are needed to template-checkout_payment.html and the product template (usually details) to 
// add item to cart - see examples from other site that uses...

// make sure forms have ids: add_product_to_cart_form, complete_checkout_form
// make sure forms have submit buttons with ids: add_to_cart_btn, complete_checkout_btn
// make sure forms have onsubmit event that always returns false so form doesn't submit normally (problem with ie6)
// make sure forms have an action tag

// TODO: be nice at the end to display the final page instead of in a popup...

DEBUG_PRODUCT_LINK = false;

function isInteger(s) {
	return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function add_product_to_plugin(product_id, shopping_id) {
	if (DEBUG_PRODUCT_LINK) {
		console.debug ('add_product_to_plugin running xhr');
		//console.dir(dijit.byId('add_product_to_cart_form').getValues());
	}

	// change the action of the form to plugin builder now so can save the plugin builder parts. 
	action_save = dojo.byId('add_product_to_cart_form').action;
	dojo.byId('add_product_to_cart_form').action = '/pb/plugin/plugin.php';

	dojo.xhrPost({
		form: dojo.byId('add_product_to_cart_form'),
		handleAs: "json",
		handle: function (response, ioArgs) {
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Link XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				if (DEBUG_PRODUCT_LINK) console.dir(response);
				if (response.data == 'ok') {
					if (DEBUG_PRODUCT_LINK) alert ('callback ok!  Redirecting...');
					// redirect em
					window.location = action_save;
				}
				else {
					SMC_Dialog.titleNode.innerHTML = 'Error!';
					SMC_Dialog.setContent('Plugin Builder Link XHR Unexpected response: ' + response.stack);
					SMC_Dialog.show();
				}
			}
			dojo.byId('add_product_to_cart_form').action = action_save;
			
			return response;
		},
		timeout: 100000
	});
}

function link_add_to_cart_to_plugin_builder() {
	// submit the form via XHR so when done we can get the product/shopping cart ids for the plugin builder item
	if (DEBUG_PRODUCT_LINK) console.debug ('link_add_to_cart_to_plugin_builder running xhr');
	
	formNode = dojo.byId('add_product_to_cart_form');

	if (formNode == null) {
		alert ("Error!  form tag needs an id of: add_product_to_cart_form");
		return false;
	}
	 
	SMC_Dialog.titleNode.innerHTML = 'Please Wait';
	SMC_Dialog.setContent('Adding your Item to your Shopping Cart...');
	SMC_Dialog.show();
	
	dojo.xhrPost({
		form: formNode,
		handleAs: "json",
		content: {"xhr_return_shopping_id": 1},
		handle: function (response, ioArgs) {
			if (DEBUG_PRODUCT_LINK) console.dir(response);
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Link XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				if (isInteger(response.product_id)) {
					// set the value for the associated product field
					if (DEBUG_PRODUCT_LINK) console.log ("setting: " + response.product_field + " to " + response.product_id);
					if (response.product_field != '') {
						dojo.byId(response.product_field).value = response.product_id
					}
					if (response.product_details_field != '') {
						dojo.byId(response.product_details_field).value = response.product_detail_id
					}
					if (response.shopping_field != '') {
						dojo.byId(response.shopping_field).value = response.shopping_id
					}
					// run second callback to link product/cart id to plugin builder item.
					add_product_to_plugin(response.product_id, response.shopping_id);
				}
				else {
					SMC_Dialog.titleNode.innerHTML = 'Error!';
					SMC_Dialog.setContent('Plugin Builder Link XHR Unexpected response: ' + response);
					SMC_Dialog.show();
				}
			}
			
			//return false;
			return response;
		},
		timeout: 100000
	});
}

function show_final_payment_form() {
	// TODO: this doesn't work unfortunately - the order totals are incorrect cause 
	// we're skipping step 4...

	// note: if you try to re-enable this again need to add case 5 into smc catalog/checkout/default.php
	// to call only paymentFinal-i.php
	
	if (DEBUG_PRODUCT_LINK) console.debug ('show_final_payment_form running xhr');
	
	// resubmit the form changing the step to 5 to display the final payment form. 
	if (DEBUG_PRODUCT_LINK) console.dir(dojo.byId('complete_order_form'));
	dojo.byId('complete_order_form').step.value = 5;

	dojo.xhrPost({
		form: dojo.byId('complete_order_form'),
		handleAs: "text",
		handle: function (response, ioArgs) {
			if (DEBUG_PRODUCT_LINK) console.log(response);
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Link XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				// note: this won't parse any script tags
				window.document.body.innerHTML = response;
			}
			return response;
		},
		timeout: 100000
	});
}

function link_order_to_plugin_items(order_id, line_items, response_html) {
	if (DEBUG_PRODUCT_LINK) console.debug ('link_order_to_plugin_items running xhr');
	
	dojo.xhrPost({
		url: "/pb/callbacks/dojo_link_smc_order_line_items.php",
		content: {'order_id': order_id, 'line_items': line_items},
		handleAs: "json",
		handle: function (response, ioArgs) {
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Link XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				if (DEBUG_PRODUCT_LINK) console.dir(response);
				if (response.data == 'ok') {
					//show_final_payment_form();
					//window.document.body.innerHTML = decodeURI(response_html);
					//window.location = dojo.byId('complete_order_form').action;
					SMC_Dialog.domNode.style.width = '550px';
					SMC_Dialog.titleNode.innerHTML = 'Order Complete!';
					SMC_Dialog.setContent(response_html);
					SMC_Dialog.show();
					dojo.connect(dijit.byId('SMC_Dialog'), 'hide', function () { window.location = '/'; });
				}
				else {
					SMC_Dialog.titleNode.innerHTML = 'Error!';
					SMC_Dialog.setContent('Plugin Builder Link XHR Unexpected response: ' + response.stack);
					SMC_Dialog.show();
				}
			}			
			return response;
		},
		timeout: 100000
	});
}

function link_create_order_to_plugin_builder () {
	// submit the form via XHR so when done we can get the order/line item ids for the items in our cart
	if (DEBUG_PRODUCT_LINK) console.debug ('link_create_order_to_plugin_builder running xhr');
	
	formNode = dojo.byId('complete_order_form');

	if (formNode == null) {
		alert ("Error!  form tag needs an id of: complete_order_form");
		return false;
	}
	
	SMC_Dialog.titleNode.innerHTML = 'Please Wait';
	SMC_Dialog.setContent('Saving your Order...');
	SMC_Dialog.show();
	
	if (DEBUG_PRODUCT_LINK) console.dir(formNode);
	
	dojo.xhrPost({
		form: formNode,
		handleAs: "json",
		content: {"xhr_return_order_and_line_item_id": 1},
		handle: function (response, ioArgs) {
			if (DEBUG_PRODUCT_LINK) console.dir(response);
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Link XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				console.log(response);
				if (response.cc_error) {
					SMC_Dialog.domNode.style.width = '550px';
					SMC_Dialog.titleNode.innerHTML = 'Processing Error!';
					SMC_Dialog.setContent(response.html);
					SMC_Dialog.show();
				}
				else if (isInteger(response.order_id)) {
					// run second callback to link order/lineitem to plugin builder item.
					link_order_to_plugin_items(response.order_id, response.line_items, response.html);
				}
				else {
					SMC_Dialog.titleNode.innerHTML = 'Error!';
					SMC_Dialog.setContent('Plugin Builder Link XHR Unexpected response: ' + response);
					SMC_Dialog.show();
				}
			}
			
			//return false;
			return response;
		},
		timeout: 100000
	});
}

function get_cart_option_content(shopping_id, item_id, plugin_id, content_node, template) {
	URL = "/pb/plugin/plugin.php" +
			"?commtypeid=" + plugin_id + 
			"&template=" + template + 
			"&item_id=" + item_id;
	
	dojo.xhrGet({
		handleAs: "text",
		url: URL,
		handle: function (response, ioArgs) {
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Fetch Id XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				//console.debug(response);
				if (response.toLowerCase().indexOf('error') == -1) {
					//alert ('callback ok!');
					dojo.byId(content_node + shopping_id).innerHTML = response;
				}
				else {
					SMC_Dialog.titleNode.innerHTML = 'Error!';
					SMC_Dialog.setContent('Plugin Builder Fetch Id XHR Unexpected response: ' + response);
					SMC_Dialog.show();
				}
			}
			
			return response;
		},
		timeout: 100000
	});
}

function show_cart_line_item_product_info(shopping_id, plugin_id, content_node, template) {
	// run a callback to get the actual item id based on the order/line item ids
	
	URL = "/pb/callbacks/dojo_get_order_line_item_id.php" + 
			"?shopping_id=" + shopping_id + 
			"&commtypeid=" + plugin_id;
	
	//console.debug ('show_cart_line_item_product_info running xhr - url: ' + URL);
	
	dojo.xhrGet({
		handleAs: "json",
		url: URL,
		handle: function (response, ioArgs) {
			if ((response.error) || (typeof response == "Error")) {
				SMC_Dialog.titleNode.innerHTML = 'Error!';
				SMC_Dialog.setContent('Plugin Builder Fetch Id XHR Error: ' + response.error);
				SMC_Dialog.show();
			}
			else {
				//console.dir(response);
					if (isInteger(response.data)) {
					//alert ('callback ok!');
					get_cart_option_content(shopping_id, response.data, plugin_id, content_node, template)
				}
				else {
					SMC_Dialog.titleNode.innerHTML = 'Error!';
					SMC_Dialog.setContent('Plugin Builder Fetch Id XHR Unexpected response: ' + response.data);
					SMC_Dialog.show();
				}
			}
			
			return response;
		},
		timeout: 100000
	});
}

dojo.addOnLoad(function () {
	// attempt to connect to either the add to cart button or the complete checkout button - these 
	// buttons need to have ids (not in the default templates) that match these in order for this to work

	btn = dojo.byId('add_to_cart_btn');
	if (btn != null) {
 		// this nastiness causes double submits in ie6 so connect on clicking the add to cart button instead.
		//dojo.connect(dojo.byId('add_product_to_cart_form'), 'onsubmit', link_add_to_cart_to_plugin_builder);
		dojo.connect(dojo.byId('add_to_cart_btn'), 'onclick', link_add_to_cart_to_plugin_builder);
		if (DEBUG_PRODUCT_LINK) console.debug('link_add_to_cart_to_plugin_builder connect');
		dojo.byId('add_to_cart_btn').style.display = '';
	} 

	btn = dojo.byId('complete_checkout_btn');
	if (btn != null) {
		dojo.connect(dojo.byId('complete_checkout_btn'), 'onclick', link_create_order_to_plugin_builder);
		if (DEBUG_PRODUCT_LINK) console.debug('link_create_order_to_plugin_builder connect');
		dojo.byId('complete_checkout_btn').style.display = '';
	}
});
