var FranchiseFormController = {
  /**
   * Initializes the instance.
   * 
   */
  init: function()
  {
  },

  runSwitch: function(el) {
	  if(el.getAttribute('type')=='radio' && !el.checked) return;
	  var cmd=JSON.decode('{'+el.getAttribute('switch')+'}');
	
	  var switchEls=Array();
	  if(cmd['id']) {
	    var switchEl=$(cmd['id']);
	    if(switchEl) switchEls.push(switchEl);
	  }
	  else if(cmd['class']) {
      switchEls=$$('.'+cmd['class']);
	  }
	  else {
		  return;
	  }
	  for(var i=0; i<switchEls.length; i++) {
			var switchEl=switchEls[i];
	    switch(cmd['do']) {
		    case 'show':
		      switchEl.show();
		      break;
		    case 'hide':
		      switchEl.hide();
		      break;
	    }
	  }
  },
  
	setupEvents: function() {
		//Headings foldout
		var elements=$$('input');
		//var classRegex=/categoryHeading/;
		for(i=0; i<elements.length; i++) {
			//if(!classRegex.test(elements[i].className))
			//  continue;
			if(!elements[i].getAttribute('switch'))
			  continue;
			elements[i].addEvent('click',function(e) { 	var evt = new Event(e); this.runSwitch(evt.target); }.bind(this));
			//this.runSwitch(elements[i]); //Run once now incase the browser remembered form values
		}
	}
	//   /**
	//    * Ajax callback for updatePurchaseTotals
	//    * 
	//    * @param {Object} ..
	//    */
	//   updatePurchaseTotalsCallback: function(purchaseTotals)
	//   {
	//     fields=Array('purchase_subtotal_price','shipping_price','purchase_total_price'); //'purchase_weight',
	// 
	//     for(var i=0; i<fields.length; i++) {
	//     var field=fields[i];
	//     $(field).update(this.priceFormat(purchaseTotals[field]));
	//   }
	//   $('purchase_subtotal_price_2').update(this.priceFormat(purchaseTotals['purchase_subtotal_price']));
	// 
	//     //Walk through all the products in the form, key off the qty fields to discover the idproducts displayed in the form
	//   purchaseProductQtyEls=this.getPurchaseProductQtyEls();
	//   for(var i=0; i<purchaseProductQtyEls.length; i++)
	//   {
	//       idproduct=this.idproductFromQtyEl(purchaseProductQtyEls[i]);
	//       if(idproduct==false)
	//         continue;
	//       $('purchase_products_'+idproduct+'_subtotal_price_display').update( this.priceFormat( purchaseTotals['purchase_products'][idproduct]['subtotal_price'] ) );
	//       //weight display is disabled
	//       //$('purchase_products_'+idproduct+'_subtotal_weight_display').update( this.priceFormat( purchaseTotals['purchase_products'][idproduct]['subtotal_weight'] ) );
	//   }
	//   	
	//   },
	// 
	//   idproductFromQtyEl: function (el)
	//   {
	//   //Regex out the idproduct from the element's id attribute
	//     var bits=/purchase_products_([0-9]+)_qty/.exec(el.id);
	//     if(!bits)
	//      return false;
	//     return bits[1];	
	//   },
	//   
	//   priceFormat: function(price)
	//   {
	//     return safeParseFloat(price).toFixed(2);
	//   },
	// 
	// 
	//   /**
	//    * Calls updatePurchaseTotals after 2 seconds to avoid ajax call while still typing
	//    */
	//   lastPendingUpdateID: false,
	//   updatePurchaseTotalsDelayed: function()
	//   {
	//   if(this.lastPendingUpdateID!==false)
	//     window.clearTimeout(this.lastPendingUpdateID);
	//   this.blankTotals();
	//     this.lastPendingUpdateID=this.updatePurchaseTotals.bind(this).delay(1);
	//   },
	// 
	//   blankTotals: function()
	//   {
	//     fields=Array('purchase_subtotal_price','purchase_subtotal_price_2','shipping_price','purchase_total_price'); //'purchase_weight',
	//     filler='-';
	//     for(var i=0; i<fields.length; i++) {
	//     var field=fields[i];
	//       $(field).update(filler);
	//   }
	// 
	//     //Walk through all the products in the form, key off the qty fields to discover the idproducts displayed in the form
	//   purchaseProductQtyEls=this.getPurchaseProductQtyEls();
	//   for(var i=0; i<purchaseProductQtyEls.length; i++)
	//   {
	//       idproduct=this.idproductFromQtyEl(purchaseProductQtyEls[i]);
	//       if(idproduct==false)
	//         continue;
	// 
	//       $('purchase_products_'+idproduct+'_subtotal_price_display').update(filler);
	//       //$('purchase_products_'+idproduct+'_subtotal_weight_display').update(filler);
	//   }
	//   	
	//   },
	// 
	// 
	//   getPurchaseProductQtyEls: function() {
	//   if(this.purchaseProductQtyEls===false) {
	//     this.purchaseProductQtyEls=$$('.productQty');
	//   }
	//   return this.purchaseProductQtyEls;
	//   },
	//   
	//   /**
	//    * Show/hide payment method dependent fields.
	//    */
	// 
	//   paymentMethodChanged: function()
	//   {
	//   ccRows=$$('tr.ccDetailsRow');
	//   ccShow=($('payment_method').value=='Credit Card online');
	// 
	//   for(i=0; i<ccRows.length; i++) {
	// 	  if(ccShow)
	// 	    ccRows[i].show();
	// 	  else
	// 	    ccRows[i].hide();
	//   }
	// 
	//   ccPhoneRows=$$('tr.ccPhoneRow');
	//   ccPhoneShow=($('payment_method').value=='Credit Card by phone');
	// 
	//   for(i=0; i<ccPhoneRows.length; i++) {
	// 	  if(ccPhoneShow)
	// 	    ccPhoneRows[i].show();
	// 	  else
	// 	    ccPhoneRows[i].hide();
	//   }
	//   },
	// 
	//   toggleCategoryShown: function(nameEl) {
	//   var detailsEl=nameEl.up('a').next('div.productsListWrapper');
	//   var arrowOut=nameEl.down('img.arrow-fold-out');
	//   var arrowIn=nameEl.down('img.arrow-fold-in');
	//   if(detailsEl.visible()) {
	// 	  new Effect.BlindUp(detailsEl,{duration: '0.5'});
	// 	  arrowOut.show();
	// 	  arrowIn.hide();
	// 	}
	// 	else {
	// 	  new Effect.BlindDown(detailsEl,{duration: '0.5'});
	// 	  arrowOut.hide();
	// 	  arrowIn.show();
	//     }
	//   },
	// 
	// setupEvents: function() {
	// 	
	//   var matches=/#([0-9a-zA-Z_]+)$/.exec(window.location.href);
	// 	if(matches!==null) {
	// 		var linkedCategoryHeading=$('name-'+matches[1])
	// 		if(linkedCategoryHeading) {
	// 			this.toggleCategoryShown(linkedCategoryHeading);
	// 		}
	// 	}
	// 	
	// 	//Headings foldout
	// 	var elements=$('content').getElementsByTagName('h2');
	// 	var classRegex=/categoryHeading/;
	// 	for(i=0; i<elements.length; i++) {
	// 		if(!classRegex.test(elements[i].className))
	// 		  continue;
	// 		Element.observe(elements[i],'click',function(evnt) { this.toggleCategoryShown(evnt.findElement('h2')); }.bind(this));
	// 	}	
	// 	
	// 	//Flash added product if one exists
	// 	this.itemAddedFlash();
	// 	
	// 	//Update prices
	// 	PurchaseController.updatePurchaseTotals();
	// 	
	// 	//Qty changes
	// 	$$('.productQty').each(function(el,i) {
	// 	  el.observe('click', function() { this.select() });
	// 	  el.observe('keyup', function() { PurchaseController.updatePurchaseTotalsDelayed() } );
	// 	});
	// 	
	// 	//Other changes
	// 	$('iddelivery_service').observe('change', function() { PurchaseController.updatePurchaseTotals() });
	// 	$('payment_method').observe('change', function() { PurchaseController.paymentMethodChanged() });
	// 	
	// },
	// 
	// itemAddedFlash: function() {
	// 	var el=$('item-added-flash');
	// 	if(el) {
	// 	  new Effect.Highlight(el);
	// 	}
	// },
	// 
	//   //Prototypejs Form.serialize() was too slow in IE6 - replaced with this from http://dev.rubyonrails.org/ticket/10453	
	// fastSerialize: function(form, options) {
	//   return PurchaseController._fastSerializeElements($(form).getElementsByTagName('*'), options);
	// },
	// 
	// _fastSerializeElements: function(elements, options) {
	//   if (typeof options != 'object') options = { hash: !!options };
	//   else if (Object.isUndefined(options.hash)) options.hash = true;
	//   var key, value, submitted = false, submit = options.submit;
	// 
	//   var result = {};
	//   for(var i=0, size=elements.length; i <size; i++)
	//   {
	//     var element = elements[i];
	//     var name = element.name;
	//     if (!name)
	//       continue;
	//     if (Form.Element.Serializers[element.tagName.toLowerCase()])
	//     {
	//       if (!element.disabled) {
	//         key = name, value = Form.Element.Serializers[element.tagName.toLowerCase()](element);
	//         if (value != null && (element.type != 'submit' || (!submitted && submit !== false && (!submit || key == submit) && (submitted = true)))) {
	//           if (key in result) {
	//             // a key is already present; construct an array of values
	//             if (!Object.isArray(result[key])) result[key] = [result[key]];
	//               result[key].push(value);
	//           }
	//           else result[key] = value;
	//         }
	//       }
	//     }
	//   }
	//   return options.hash ? result : Object.toQueryString(result);
	// }
 
}


//Setup event handlers for the purchase page once the document loaded
// Event.observe(window, 'load', function() {
// 	FranchiseFormController.setupEvents();
// 	FranchiseFormController.paymentMethodChanged();
// });
window.addEvent('load',function() {
	//implement show / hide
	Element.implement({
		//implement show
		show: function() {
			this.setStyle('display','');
		},
		//implement hide
		hide: function() {
			this.setStyle('display','none');
		}
	});
	
  FranchiseFormController.setupEvents();
});

