// DOM Ready Extension for Prototype

Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);
    
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
	},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) { 
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
        
        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});

// End DOM Ready Extension for Prototype
/**********************************************************************************/


var NYBG = function(){
	
	return {		

		/* -- BEGIN: quickPurchase ------------------------------------------ */
		quickPurchase : function() {
			var CONFIG = {
				form_id : "orderform",
				target_div : "result",
				response_msg_class : "none",
				loading_message : "<span class=\"load\">One moment...<\/span>",
				temp_productid : 0,
				temp_cat: 0,
				
				// Ajax XML response nodes
				xml_root_node : "response",
				xml_productid_node : "productid",
				xml_productcode_node : "productcode",
				xml_product_node : "product",
				xml_list_price_node : "list_price",
				xml_descr_node : "descr",
				xml_options_node : "options",
				xml_recipients_node : "recipients",
				xml_avail_node : "avail", 
				xml_product_type_node : "product_type",
				xml_price_node : "price",
				xml_category_id_node : "category_id",
				xml_web_path_node : "web_path",
				xml_image_path_node : "image_path",
				xml_main_class_node : "main_class",

				error_parsing_response : "There was a parsing error.",
				error_connection : "There was a connection error."
			};
			return {
				init : function() {

					// Check to see if we need to attach event handlers to the current document.
					if ($('usesQuickPurchase')) {
						// Hurray, lets handle data from the DOM.
						$A($('main').getElementsByTagName('form')).each(function(e){
							Event.observe(e.id, "submit", function(e){
								// Cancel the form submission
								Event.stop(e);
								// JavaScript must be enabled. Let's change the action attribute
								// to submit the form data via Ajax.
								Event.element(e).setAttribute("action", "include/quickPurchase.php");
								// Send the Ajax request
								NYBG.quickPurchase.sendReq(Event.element(e));							
							}.bind(this), false);
						});
					}
					return false;
				}, // END: init()

				sendReq : function(this_form) {

					// FIXME: cheap hack for "validation"
					var params = Form.serialize(this_form);

					// Create an ajax request
					var ajax_vote_request = new Ajax.Request(this_form.action, {
						method: "post",
						parameters: params,
						
						onLoading: function() {
							// First, disable the form to prevent any more clicks.
							Form.disable(this_form);
							$(this_form.id).innerHTML = "";
							var result_html = "";
							// Show an interim status message while the response is being processing
							$(this_form.id).innerHTML = CONFIG["loading_message"];
						}.bind(this),
						
						onSuccess: function(req) {

							var result_html = "";
								// this is potentially risky stuff
							try {
								// response is coming back as XML
								var root_node = req.responseXML.getElementsByTagName(CONFIG["xml_root_node"])[0];
								var r_productid = root_node.getElementsByTagName(CONFIG["xml_productid_node"])[0].firstChild.nodeValue;
								var r_productcode = root_node.getElementsByTagName(CONFIG["xml_productcode_node"])[0].firstChild.nodeValue;
								var r_product = root_node.getElementsByTagName(CONFIG["xml_product_node"])[0].firstChild.nodeValue;
								var r_list_price = root_node.getElementsByTagName(CONFIG["xml_list_price_node"])[0].firstChild.nodeValue;
								var r_descr = root_node.getElementsByTagName(CONFIG["xml_descr_node"])[0].firstChild.nodeValue;
								var r_options = root_node.getElementsByTagName(CONFIG["xml_options_node"])[0].firstChild.nodeValue;
								var r_recipients = root_node.getElementsByTagName(CONFIG["xml_recipients_node"])[0].firstChild.nodeValue;
								var r_avail = root_node.getElementsByTagName(CONFIG["xml_avail_node"])[0].firstChild.nodeValue;
								var r_product_type = root_node.getElementsByTagName(CONFIG["xml_product_type_node"])[0].firstChild.nodeValue;
								var r_price = root_node.getElementsByTagName(CONFIG["xml_price_node"])[0].firstChild.nodeValue;
								var r_category_id = root_node.getElementsByTagName(CONFIG["xml_category_id_node"])[0].firstChild.nodeValue;
								var r_image_path = root_node.getElementsByTagName(CONFIG["xml_image_path_node"])[0].firstChild.nodeValue;
								var r_web_path = root_node.getElementsByTagName(CONFIG["xml_web_path_node"])[0].firstChild.nodeValue;
								var r_main_class = root_node.getElementsByTagName(CONFIG["xml_main_class_node"])[0].firstChild.nodeValue;	

								var id = this_form.id.match(/(\d+)/)[1];

								result_html = '<div class=\"quick_win\" id=\"quick_win\">';
								result_html+= '<h6><span>Quick Purchase</span>';
								result_html+= '<a href=\"#\" onclick=\"$(\'result' + id + '\').innerHTML = \'\'; return false;\">';
								result_html+= 'X | Close</a></h6>';
								result_html+= '<div>'+r_descr;
								result_html+= '<p class=\"member\"><strong>Members Save 10%</strong><br /><br /><a href=\"'+r_web_path+'/membership.php\">Join Today!</a></p>';	
								result_html+= '</div><form id=\"orderform\" action=\"cart.php?mode=add\" method=\"post\" name=\"orderform\">';
								result_html+= '<input type=\"hidden\" value=\"add\" name=\"mode\" />';
								result_html+= '<input type=\"hidden\" value=\"'+r_productid+'\" name=\"productid\" />';
								result_html+= '<input type=\"hidden\" value=\"'+r_productcode+'\" name=\"sku\" />';
								result_html+= '<input type=\"hidden\" value=\"'+r_category_id+'\" name=\"cat\" />';
								result_html+= '<input type=\"hidden\" value=\"1\" name=\"page\" />';
								result_html+= '<fieldset id=\"quantity\" >';
								// We still need to do a form validation to make sure a quantity was entered.								
								result_html+= '<p><label for=\"amount\">Quantity</label> <input id=\"product_avail\" name=\"amount\" value=\"1\" size=\"2\" maxlength=\"3\" class=\"Required Number\"></p>';
								result_html+= "<p>"+r_options+"</p>";
								result_html+= "<p>"+r_recipients+"</p>";
								result_html+= '<p><input type=\"image\" src=\"images/'+r_image_path+'/but_add-to-cart.gif\" alt=\"Add To Cart\" /></p>';
								result_html+= '</fieldset></form>';
								result_html+= '<script type=\"text/javascript\">var v = new Validation(\'orderform\')\;</script></div>';
	
							} catch(e) {
								result_html = CONFIG["error_parsing_response"] + "<br/>" + e;
							}
							// Take the results show the quickPurchase form.
							this._showResponse(result_html, r_productid, r_category_id, r_main_class);
							}.bind(this),
							
						onFailure: function() {
							this._showResponse(CONFIG["error_connection"]);
						}.bind(this),
						
						onComplete: function() {
							var isSearch = $('search_results');
							if(isSearch)
								html = "<input type=\"image\" src=\"images/but_search_trans.gif\" name=\"submit\" value=\"Quick Purchase\" />";
							else
								html = "<input type=\"image\" src=\"images/but_trans.gif\" name=\"submit\" value=\"Quick Purchase\" />";
							//html = "<input type=\"image\" src=\"images/but_trans.gif\" value=\"Quick Purchase\" name=\"submit\" />";
							html+= "<input type=\"hidden\" value=\""+CONFIG["temp_productid"]+"\" name=\"productid\"/>";
							html+= "<input type=\"hidden\" value=\""+CONFIG["temp_cat"]+"\" name=\"cat\"/>";
							html+= "<input type=\"hidden\" value=\"1\" name=\"page\"/>";
							html+= "<input type=\"hidden\" value=\"1\" name=\"amount\"/>";
							html+= "<input type=\"hidden\" value=\"add\" name=\"mode\"/>";
							$(this_form.id).innerHTML = html;

							var id = this_form.id.match(/(\d+)/)[1];

							this._mouseHandler =  this.mouseHandler.bindAsEventListener(this, id);

							// Set up the mouse click handler.
							Event.observe(document, 'click', this._mouseHandler, false);
						}.bind(this)
						
					}); // END: new Ajax.Request
					return false;
					
				}, // END: sendReq()
				
				formHandler : function(e) {
					// Cancel the form submission
					Event.stop(e);
					// Send the Ajax request.			
					this.sendReq(Event.element(e));
				},
				
				mouseHandler : function(e, id) {
					var result_node_id = 'result' + id;
					if (!Event.element(e).up("#" + result_node_id)) {
						Event.stopObserving(document, 'click', this._mouseHandler);
						$(result_node_id).innerHTML = "";
					}
				},
												
				// return the result in HTML; private
				_showResponse : function(html, pid, cat, main) {
					CONFIG["temp_productid"] = pid;
					CONFIG["temp_cat"] = cat;
					CONFIG["temp_main"] = main;
					$((CONFIG["target_div"]+pid)).innerHTML = "<p class=\"" + CONFIG["response_msg_class"] + "\">" + html + "</p>";
				} // END: _showResponse()
				
			}
			
		}() // END: quickPurchase
		
	}; // END: return
	
}(); // END: NYBG namespace

// Initialize the form submission event observer.
Event.onDOMReady(function(){
	NYBG.quickPurchase.init();
});
