/**
 * Requires prototypejs
 *
 * @author BJ Basanes
 */
 
var GiftCertificateTemplates = {
	DropDownOption : '<option value="#{value}">#{text}</option>'
};
 
var GCItemTemplate = Class.create(Template, {
	initialize: function($super) {
		this.addToCartButtonText = "Add";
		this.addButtonIdPrefix = "add_to_cart_";
		$super('');
	},
	
	initTemplate: function() {
		var newTemplate = '<div class="pgitem_outter_container"><div class="pgitem_inner_container">' +
			'<div class="pgitem_name_container">#{name}</div>' +
			'<div class="pgitem_image_container"><img src="#{iconPath}" alt="#{name}" title="#{imageTitle}" /></div>' +
			'<div class="pgitem_price_container">Price: $#{cost}</div>' +
			'<div class="pgitem_subcategory_navigation_container"></div>' +
			'<div><input type="button" id="' + this.addButtonIdPrefix + '#{id}" name="' + this.addButtonIdPrefix + '#{id}" value="' + this.addToCartButtonText + '" style="cursor: pointer" /></div>' +
			'</div></div>';
				
		this.template = newTemplate;
	},
	
	evaluate: function($super, data) {
		if (this.template == '')
			this.initTemplate();
		
		return $super(data);	
	}
});

var GCPackageTemplate = Class.create(Template, {
	initialize: function($super) {
		this.addToCartButtonText = "Add";
		this.addButtonIdPrefix = "add_to_cart_";
		$super('');
	},
	
	initTemplate: function() {
		var newTemplate = '<div class="pgitem_outter_container"><div class="pgitem_inner_container"><div class="packageContainer">' +
			'<div class="divNameContainer">#{name}</div>' +
			'<div class="packageImageContainer"><img src="#{iconPath}" alt="#{name}" title="#{imageTitle}" /></div>' +
			'<div class="divPriceContainer">Price: $#{cost}</div>' +
			//'<div id="cdebutton" style="cursor: pointer;"><a id="view_package_details_#{id}">View Package Details</a></div>' +			
			'<div class="divButtonContainer"><input type="button" id="' + this.addButtonIdPrefix + '#{id}" name="' + this.addButtonIdPrefix + '#{id}" value="' + this.addToCartButtonText + '" style="cursor: pointer" /></div>' +
			'</div></div></div>';
				
		this.template = newTemplate;
	},
	
	evaluate: function($super, data) {
		if (this.template == '')
			this.initTemplate();
		
		return $super(data);	
	}
});

var GCBadgeTemplate = Class.create(Template, {
	initialize: function($super) {
		this.addToCartButtonText = "Add";
		this.addButtonIdPrefix = "add_to_cart_";
		$super('');
	},
	
	initTemplate: function() {
		var newTemplate = '<div class="pgitem_outter_container"><div class="pgitem_inner_container">' +
			'<div class="pgitem_name_container">#{name}</div>' +
			'<div class="badgeImageContainer"><img src="#{iconPath}" alt="#{name}" title="#{imageTitle}" /></div>' +
			'<div class="divPriceContainer">Price: $#{cost}</div>' +			
			'<div class="divButtonContainer"><input type="button" id="' + this.addButtonIdPrefix + '#{id}" name="' + this.addButtonIdPrefix + '#{id}" value="' + this.addToCartButtonText + '" style="cursor: pointer" /></div>' +
			'</div></div>';
				
		this.template = newTemplate;
	},
	
	evaluate: function($super, data) {
		if (this.template == '')
			this.initTemplate();
		
		return $super(data);	
	}
});

var GCPackageDetailsTemplate = Class.create(Template, {
	
	addToCartButtonText: "Add to Gift Certificate",	
	backToPackageListButtonText: "Back to Package List",
	
	addToCartButtonClickListeners: {},	
	
    initialize: function($super) {
    	
    },
    
    addAddToCartButtonClickListener: function(listener) {
    	
    }
});
 
var GiftCertificateCart = Class.create({
	
	initialize: function(tableId, rootUrl) {
		this.tableId = tableId;
		this.totalRowId = "row_cart_total";
		this.totalAmountId = "cart_total";
		this.cartItemRowPrefix = "cart_item_";
		this.addPackageButtonIdPrefix = "package_";
		this.removePackageButtonIdPrefix = "remove_package_";
		
		/*if (rootUrl === undefined)
			rootUrl = "http://dev.cartoondollemporium.com/~bjbasanes/";*/
		
		this.ajaxUrl =  rootUrl + "/cdeprofile/ajax_functions/ajax_gift_certificate.html";
		
		this.loaderImageUrl = rootUrl + "/cdeprofile/images/ajax-loader-bigflower-blue-white.gif";
	},
	
	test: function() {
		//console.log('test');
	},
	
	addPackage: function (packageId, eventDispatcherElement) {
		var params = {
			add_package: packageId			
		};
		
		new Ajax.Request(this.ajaxUrl, {
			method: "post",
			parameters: params,
			evalJSON: "force",
			onCreate: function(event) {
				if (eventDispatcherElement != undefined)
					this.showHideLoaderImage(true, eventDispatcherElement);
			}.bind(this),
			onComplete: function(event) {
				if (eventDispatcherElement != undefined)
					this.showHideLoaderImage(false, eventDispatcherElement);
			}.bind(this),
			onSuccess: function(event) {
				var response = event.responseJSON;
				if (response.action != "item_updated")
					return;
				
				this.addCartTableRow(response);
				/*var updatedPackageRow = $(this.cartItemRowPrefix + response.package_id);
				if (updatedPackageRow) {
					Element.replace(updatedPackageRow, response.html);
					//this.initRemovePackageButtonClickhandler(this.removePackageButtonIdPrefix + response.package_id);
				} else {
					$(this.totalRowId).insert({before: response.html});
					this.initRemovePackageButtonClickhandler(this.removePackageButtonIdPrefix + response.package_id);
					//$(this.tableId).insert({bottom: response.html});
				}*/
				
				if (response.cart_total !== undefined)
					this.updateTotal(response.cart_total);
				
				this.test();		
			}.bind(this)
		});
	},
	
	initAddPackageButtonClickHandler: function(buttonId) {
		// element must be a button
		//alert("initAddPackageButtonClickHandler" + buttonId); 
		//var element = $(buttonId);
		//alert(element.id);
		Event.observe($(buttonId), "click", this.onAddPackageButtonClick.bind(this));
	},
	
	addOnClickRefreshDispatcher: function(element) {
		element.observe("click", this.onRefreshItemsButtonClick.bind(this));
	},
	
	onRefreshItemsButtonClick: function(event) {
		event.stop();
		this.refreshItemList();
	},
	
	onAddPackageButtonClick: function(event) {
		var packageId = event.target.id;
		//alert("onAddPackageButtonClick" + packageId);
		packageId = packageId.substring(this.addPackageButtonIdPrefix.length);
		
		this.addPackage(packageId, event.target);
		
		//console.log(packageId);
	},
	
	updateTotal: function(total) {
		$(this.totalAmountId).update("$" + total);
	},
	
	initRemovePackageButtonClickhandler: function(buttonId) {
		Event.observe($(buttonId), "click", this.onRemovePackageButtonClick.bind(this));
	},
	
	onRemovePackageButtonClick: function(event) {
		var packageId = event.target.id;
		packageId = packageId.substring(this.removePackageButtonIdPrefix.length);
		this.removePackage(packageId, event.target);
	},
	
	removePackage: function(packageId, eventDispatcherElement) {
		var params = {
			remove_package: packageId			
		};
		
		new Ajax.Request(this.ajaxUrl, {
			method: "post",
			parameters: params,
			evalJSON: "force",
			onCreate: function(event) {
				if (eventDispatcherElement != undefined)
					this.showHideLoaderImage(true, eventDispatcherElement);
			}.bind(this),
			onComplete: function(event) {
				if (eventDispatcherElement != undefined)
					this.showHideLoaderImage(false, eventDispatcherElement);
			}.bind(this),
			onSuccess: function(event) {
				var response = event.responseJSON;
				if (response.action != "item_removed")
					return;
				
				this.removeCartTableRow(response);
					
				/*var updatedPackageRow = $(this.cartItemRowPrefix + response.package_id);
				if (updatedPackageRow) {
					updatedPackageRow.remove();
				}*/
				
				if (response.cart_total !== undefined)
					this.updateTotal(response.cart_total);
				
				this.test();		
			}.bind(this)
		});
	},
	
	refreshItemList: function(eventDispatcherElement) {
		//alert("refreshItemList");
		var params = { get_cart_items: 1,
			nocache: new Date().toString() };
		
		new Ajax.Request(this.ajaxUrl, {
			method: "get",
			parameters: params,
			evalJSON: "force",
			onCreate: function(event) {
				if (eventDispatcherElement != undefined)
					this.showHideLoaderImage(true, eventDispatcherElement);
					
				// remove all items first
				var tableRows = $$("#" + this.tableId + " tr");				
				for (var i = 0; i < tableRows.length; i++) {
					var row = tableRows[i];					
					if (row.id.substring(0, this.cartItemRowPrefix.length) == this.cartItemRowPrefix) {
						row.remove();
					}
				}	
				
			}.bind(this),
			onComplete: function(event) {
				if (eventDispatcherElement != undefined)
					this.showHideLoaderImage(false, eventDispatcherElement);
			}.bind(this),
			onSuccess: function(event) {				
				//alert(event.responseText);
				if (event.responseJSON.action != "refresh")
					return;
				
				// re-add all items				
				var items = event.responseJSON.items;
				for (var i = 0; i < items.length; i++) {
					var item = items[i];
					//this.removeCartTableRow(item);
					this.addCartTableRow(item);
				}
				
				if (event.responseJSON.cart_total != undefined)
					this.updateTotal(event.responseJSON.cart_total);
				
				//console.log("success: get_cart_items");
				//console.log(event.responseText);
			}.bind(this)
		});
	},
	
	addCartTableRow: function(item) {
		var updatedPackageRow = $(this.cartItemRowPrefix + item.package_id);
		if (updatedPackageRow) {
			Element.replace(updatedPackageRow, item.html);			
			this.initRemovePackageButtonClickhandler(this.removePackageButtonIdPrefix + item.package_id);
		} else {
			$(this.totalRowId).insert({before: item.html});
			this.initRemovePackageButtonClickhandler(this.removePackageButtonIdPrefix + item.package_id);			
		}
	},
	
	removeCartTableRow: function(item) {
		var updatedPackageRow = $(this.cartItemRowPrefix + item.package_id);
		if (updatedPackageRow) {
			updatedPackageRow.remove();
		}
	},
	
	/**
	 * Shows/hides loader image and hides/shows the corresponding element. This is used as a generic function
	 * for switching between loader images and buttons. If $show variable pertains to the loader image.
	 */
	showHideLoaderImage: function(show, element) {
		var loader = $(element.id + "_loader");
		if (loader == null) {
			var loaderHTML = '<img src="' + this.loaderImageUrl + '" id="' + (element.id + "_loader") + '" />';
			element.insert({after: loaderHTML});
			loader = $(element.id + "_loader");
		}
		
		if (show) {
			element.hide();
			loader.show();
		} else {
			loader.hide();
			element.show();
		}
	}
});

var PackagesList = Class.create({
	
	emptyListNotification: null,
	
	initialize: function(rootUrl) {
		this.itemsListContainerId = "pg_container"; 
		this.itemsListLoadingViewContainerId = "pg_loading";
		this.packageDetailListContainerId = "pg_package_detail_list_container";
		
		this.categoryDropdownId = "packages_category"; // <select> for main categories (item types)
		this.subCategoryDropdownId = "packages_sub_category"; // <select> for sub categories (item subcats)
		this.sortDropdownId = "packages_sort"; // <select> for sorting options
		this.pageDropdownId = "packages_page"; // <select> for page
		
		this.groupItemsButtonId = "package_group_items";
		this.groupPackagesButtonId = "package_group_packages";
		this.groupBadgesButtonId = "package_group_badges";
		
		this.emptyListNotification = $("empty_list_notification");
		
		this.itemTemplate = null;
		this.badgeTemplate = null;
		this.packageTemplate = null;
		
		this.group = PackagesList.PackageGroup.Items;
		
		if (rootUrl === undefined)
			this.rootUrl = "http://www.cartoondollemporium.com/";
		else
			this.rootUrl = rootUrl;
			
		this.ajaxUrl =  this.rootUrl + "/cdeprofile/ajax_functions/ajax_gift_certificate.html";
	},
	
	/**
	 * Should be called on dom ready to attach to dropdown and other events
	 */
	initEventsListener: function() {
		$(this.categoryDropdownId).observe("change", this.onCategoryDropdownChange.bind(this));
		$(this.subCategoryDropdownId).observe("change", this.onSubCategoryDropdownChange.bind(this));
		$(this.sortDropdownId).observe("change", this.onSortDropdownChange.bind(this));
		$(this.pageDropdownId).observe("change", this.onPageDropdownChange.bind(this));
		
		$(this.groupItemsButtonId).observe("click", this.onGroupItemsButtonClick.bind(this));
		$(this.groupPackagesButtonId).observe("click", this.onGroupPackagesButtonClick.bind(this));
		$(this.groupBadgesButtonId).observe("click", this.onGroupBadgesButtonClick.bind(this));
	},
	
	/**
	 * Refreshes the package list based on the value of the dropdowns (categories, subcats, sort, etc)
	 */
	refreshList: function(group) {
		//console.log("RefreshList :: " + group);
		if (group === undefined) 
			group = this.group;		
			
		var params = { "package_list" : group,
			"category" : $(this.categoryDropdownId).value,
			"sub_category" : $(this.subCategoryDropdownId).value,
			"page": $(this.pageDropdownId).value,
			"sort": $(this.sortDropdownId).value
			};
			
		//console.log(params);
		
		new Ajax.Request(this.ajaxUrl, {
			method: "get",
			parameters: params,
			evalJSON: "force",
			onCreate: function(event) {
				this.updateItemList(null);
				$(this.itemsListContainerId).hide();
				$(this.itemsListLoadingViewContainerId).show();
				this.emptyListNotification.hide();
			}.bind(this),
			onComplete: function(event) {
				$(this.itemsListLoadingViewContainerId).hide();
				$(this.itemsListContainerId).show();	
				if ($(this.itemsListContainerId).childElements().length == 0)
				    this.emptyListNotification.show();
			}.bind(this),
			onSuccess: function(event) {
				var response = event.responseJSON;				
				
				if (response == null)
					response = { };
				
				this.updateCategoryDropdown(response.categoryList, response.info.category);
				this.updateSubCategoryDropdown(response.subCategoryList, response.info.subCategory);
				this.updatePageDropdown(response.info.total_pages, response.info.page);
				
				if (this.group == PackagesList.PackageGroup.Packages) {
					//this.updatePageDropdown(response.info.total_pages, response.info.page);
					this.updateItemList(response.list, this.packageTemplate);
				} else if (this.group == PackagesList.PackageGroup.Badges) {
					//this.updatePageDropdown(response.info.total_badge_count, response.info.page);
					this.updateItemList(response.list, this.badgeTemplate);
				} else {
					
					this.updateItemList(response.list, this.itemTemplate);
				}
					
			}.bind(this)
		});
		
	},
	
	updateItemList: function(list, template) {
		var newContent = "";
		
		if (list != null) {
			var itemsCount = list.length;
			for (var i = 0; i < itemsCount; i++) {
				var item = list[i];
				var itemData = item;
				/*var itemData = {
					id: item.id,
					name: item.name,
					price: item.cost,
					imageurl: item.iconPath
				};*/
				
				var description = item.descriptiopn; // wrong spelling is from ecom_control.inc I think
				if (description !== undefined && description.length > 0)
					itemData.imageTitle = "header=[Item Description] body=[" + description + "] fade=[on] fadespeed=[0.1]";
				
				if (template != null)
					newContent += template.evaluate(itemData);
			}
		}
		
		$(this.itemsListContainerId).update(newContent);
		
		if (list != null && template != null) {
			for (var i = 0; i < itemsCount; i++) {
				var buttonId = template.addButtonIdPrefix + list[i].id;
				$(buttonId).observe("click", this.onItemButtonClick.bind(this));
			}		
		}
	},
	
	onItemButtonClick: function(event) {
		if (this.itemAddButtonClickListeners == undefined)
			return;
			
		var listenersCount = this.itemAddButtonClickListeners.length;
		for (var i = 0; i < listenersCount; i++) {
			this.itemAddButtonClickListeners[i](event);
		}
		//console.log(event.target.id);
	},
	
	addItemAddButtonClickListener: function(listener) {
		if (this.itemAddButtonClickListeners === undefined)
			this.itemAddButtonClickListeners = [];
		
		this.itemAddButtonClickListeners.push(listener);
	},
	
	updateCategoryDropdown: function(categoryList, selectedCategoryValue) {
		var newContent = this.createDropdownOptionsHTML(categoryList, true);
		
		$(this.categoryDropdownId).update(newContent);
		if (selectedCategoryValue !== undefined)
			$(this.categoryDropdownId).value = selectedCategoryValue;
	},
	
	updateSubCategoryDropdown: function(itemList, selectedValue) {
		var newContent = this.createDropdownOptionsHTML(itemList, true);
		
		$(this.subCategoryDropdownId).update(newContent);
		if (selectedValue !== undefined)
			$(this.subCategoryDropdownId).value = selectedValue;
	},
	
	updatePageDropdown: function(pageCount, currentPage) {
		var list = [];
		
		for (var i = 1; i <= pageCount; i++) {
			list.push({ value: i, name: i });
		}
		
		var newContent = this.createDropdownOptionsHTML(list, false);
		$(this.pageDropdownId).update(newContent);
		if (currentPage !== undefined)
			$(this.pageDropdownId).value = currentPage;
	},
	
	createDropdownOptionsHTML: function(itemList, addAllOption) {
		var dropdownTemplate = new Template(GiftCertificateTemplates.DropDownOption);				
		
		var newContent = "";
		
		if (addAllOption) {
			var optionAll = { value: "all", text: "All" };			
			newContent += dropdownTemplate.evaluate(optionAll);
		}
		
		if (itemList !== undefined) {
			var itemsCount = itemList.length;
			for (var i = 0; i < itemsCount; i++) {
				var item = itemList[i];
				newContent += dropdownTemplate.evaluate({ value: item.value, text: item.name });			
			}
		}
		
		return newContent;
	},
	
	onCategoryDropdownChange: function(event) {
		this.refreshList();
		//console.log("onCategoryDropdownChange");
	},
	
	onSubCategoryDropdownChange: function(event) {
		this.refreshList();
		//console.log("onSubCategoryDropdownChange");
	},
	
	onSortDropdownChange: function(event) {
		this.refreshList();
		//console.log("onSortDropdownChange");
	},
	
	onPageDropdownChange: function(event) {
		this.refreshList();
		//console.log("onPageDropdownChange");
	},
	
	onGroupItemsButtonClick: function(event) {
		event.stop();
		var newGroup = PackagesList.PackageGroup.Items;
		if (this.group != newGroup) {
			this.resetGroupRelatedControls();
			this.group = newGroup;
		}
		this.refreshList();
	},
	
	onGroupPackagesButtonClick: function(event) {
		event.stop();
		var newGroup = PackagesList.PackageGroup.Packages;
		if (this.group != newGroup) {
			this.resetGroupRelatedControls();
			this.group = newGroup;
		}
		this.refreshList();
	},
	
	onGroupBadgesButtonClick: function(event) {
		event.stop();
		var newGroup = PackagesList.PackageGroup.Badges;
		if (this.group != newGroup) {
			this.resetGroupRelatedControls();
			this.group = newGroup;
		}
		this.refreshList();
	},
	
	/**
	 * Reset controls (categories dropdowns, subcats, paging, etc)   
	 */
	resetGroupRelatedControls: function() {
		$(this.categoryDropdownId).value = "all";
		$(this.subCategoryDropdownId).value = "all";
		$(this.sortDropdownId).value = "newest";
		$(this.pageDropdownId).value = "1";
	}
	
});

/**
 * Packages Group enum
 */
PackagesList.PackageGroup = {
	Items : 1,
	Packages : 2,
	Badges : 3
}; 

/**
 * Custom validator (this can be moved to a standalone js file to be more reusable)
 */
var CDEValidator = Class.create({
	currentValidator: null,
	
	initialize: function() {
		
	},
	
	setValidatorEnabledStatus: function(validator, enable) {
		validator = this.setCurrentValidator(validator);		
		if (validator == null)
			return null;
			
		if (enable)
			validator.enable();
		else
			validator.disable();
			
		return this;
	},
	
	setCurrentValidator: function(validator) {
		if (validator == null)
			return this.currentValidator;
			
		this.currentValidator = validator;
		return validator;
	},
	
	addRequiredFieldValidator: function(validator) {
		validator = this.setCurrentValidator(validator);		
		if (validator == null)
			return null;		
		
		validator.add(Validate.Presence, {failureMessage: "Required"});
		validator.add(Validate.Custom, {against: CDEValidator.notEmptyString, failureMessage: "Required"});
		return this;
	},
	addEmailValidator: function(validator) {
		validator = this.setCurrentValidator(validator);		
		if (validator == null)
			return null;	
			
		validator.add(Validate.Email, {failureMessage: "Must be a valid email address"});
		return this;
	},
	addDateFormatISO8601Validator: function(validator) {
		validator = this.setCurrentValidator(validator);		
		if (validator == null)
			return null;
			
		validator.add(Validate.Format, {pattern: /(19|20)[0-9]{2}-(0|1)[0-9]-[0-3][0-9]/, failureMessage: "Date format should be yyyy-mm-dd"});
		//validator.add(Validate.Format, {pattern: /([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/, failureMessage: "Date format should be yyyy-mm-dd"});
			
		return this;
	}
});

CDEValidator.notEmptyString = function(value, args) {
	return !value.strip().empty();		
};
CDEValidator.DateFormatISO8601 = "yyyy-MM-dd";

/**
 * Manages gift certificate infos form
 */
var GiftCertificateInfo = Class.create({
	
	buyerNameControl: null,
	buyerEmailControl: null,
	deliveryOptionControls: { // not to be confused with this.deliveryOptionsControls (sorry, no time to refactor yet)
		sendToRecipient: {
			recipientName: null,
			recipientEmail: null
		},
		sendToRecipientOnDate: {
			deliveryDate: null,
			recipientName: null,
			recipientEmail: null
		}
	},
	//messageToRecipientContainer: null,
	
	initialize: function() {
		this.buyerNameControl = $("buyer_details_name");
		this.buyerEmailControl = $("buyer_details_email");
		this.deliveryOptionControls.sendToRecipient.recipientName = $("do_details_2_name");
		this.deliveryOptionControls.sendToRecipient.recipientEmail = $("do_details_2_email");
		this.deliveryOptionControls.sendToRecipientOnDate.deliveryDate = $("do_details_3_date");
		this.deliveryOptionControls.sendToRecipientOnDate.recipientName = $("do_details_3_name");
		this.deliveryOptionControls.sendToRecipientOnDate.recipientEmail = $("do_details_3_email");
		
		//this.messageToRecipientContainer = $("gc_message");
		this.deliveryOptionsControls = [
			{
				deliveryOptionId: GiftCertificateInfo.DeliveryOption.SendToBuyer,  
				name: "sendToBuyer",
				button: "gc_delivery_option_1",
				showMessageToRecipientInput: false
			},
			{
				deliveryOptionId: GiftCertificateInfo.DeliveryOption.SendToRecipient,
				name: "sendToRecipient",
				button: "gc_delivery_option_2",
				detailsContainer: "do_details_2",
				showMessageToRecipientInput: true
			},
			{
				deliveryOptionId: GiftCertificateInfo.DeliveryOption.SendToRecipientOnDate,
				name: "sendToRecipientOnDate",
				button: "gc_delivery_option_3",
				detailsContainer: "do_details_3",
				showMessageToRecipientInput: true
			}
		];		
	},
	
	initEventListeners: function() {
		for (var i = 0; i < this.deliveryOptionsControls.length; i++) {
			var controls = this.deliveryOptionsControls[i];
			$(controls.button).observe("click", this.onDeliveryOptionButtonClick.bind(this));
		}
	},
	
	validators: {
		buyerName: null,
		buyerEmail: null,
		deliveryOption: { 
			sendToRecipient: {
				recipientName: null,
				recipientEmail: null
			},
			sendToRecipientOnDate: {
				deliveryDate: null,
				recipientName: null,
				recipientEmail: null
			}
		},
		messageToRecipient: null
	},
	
	initValidators: function() {
		var cdeValidator = new CDEValidator();
		this.validators.buyerName = new LiveValidation(this.buyerNameControl, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.buyerName);
		this.validators.buyerEmail = new LiveValidation(this.buyerEmailControl, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.buyerEmail).addEmailValidator();
		
		this.validators.deliveryOption.sendToRecipient.recipientName = new LiveValidation(this.deliveryOptionControls.sendToRecipient.recipientName, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.deliveryOption.sendToRecipient.recipientName);
		this.validators.deliveryOption.sendToRecipient.recipientEmail = new LiveValidation(this.deliveryOptionControls.sendToRecipient.recipientEmail, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.deliveryOption.sendToRecipient.recipientEmail).addEmailValidator();
		
		this.validators.deliveryOption.sendToRecipientOnDate.recipientName = new LiveValidation(this.deliveryOptionControls.sendToRecipientOnDate.recipientName, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.deliveryOption.sendToRecipientOnDate.recipientName);
		this.validators.deliveryOption.sendToRecipientOnDate.recipientEmail = new LiveValidation(this.deliveryOptionControls.sendToRecipientOnDate.recipientEmail, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.deliveryOption.sendToRecipientOnDate.recipientEmail).addEmailValidator();
		this.validators.deliveryOption.sendToRecipientOnDate.deliveryDate = new LiveValidation(this.deliveryOptionControls.sendToRecipientOnDate.deliveryDate, {validMessage: ""});
		cdeValidator.addRequiredFieldValidator(this.validators.deliveryOption.sendToRecipientOnDate.deliveryDate).addDateFormatISO8601Validator();	
		
		//this.validators.deliveryOption.sendToRecipient.recipientName = new LiveValidation(this.deliveryOptionControls.sendToRecipient.recipientName, {validMessage: ""});
		//this.validators.buyerEmail.add(Validate.Presence, {failureMessage: "Required"});
		//this.validators.buyerEmail.add(Validate.Custom, {against: Validator.notEmptyString, failureMessage: "Required"});
		
		//console.log(Validate.Presence(this.buyerNameControl.value));
	},
	
	onDeliveryOptionChange: function(deliveryOption) {
		// check if validators have been initialized
		if (this.validators.buyerName == null)
			return;
			
		var cdeValidator = new CDEValidator();
		//var sendToBuyer = (deliveryOption == GiftCertificateInfo.DeliveryOption.SendToBuyer);
		var sendToRecipient  = (deliveryOption == GiftCertificateInfo.DeliveryOption.SendToRecipient);
		var sendToRecipientOnDate = (deliveryOption == GiftCertificateInfo.DeliveryOption.SendToRecipientOnDate)
		
		cdeValidator.setValidatorEnabledStatus(this.validators.deliveryOption.sendToRecipient.recipientName, sendToRecipient);
		cdeValidator.setValidatorEnabledStatus(this.validators.deliveryOption.sendToRecipient.recipientEmail, sendToRecipient);
		cdeValidator.setValidatorEnabledStatus(this.validators.deliveryOption.sendToRecipientOnDate.deliveryDate, sendToRecipientOnDate);
		cdeValidator.setValidatorEnabledStatus(this.validators.deliveryOption.sendToRecipientOnDate.recipientName, sendToRecipientOnDate);
		cdeValidator.setValidatorEnabledStatus(this.validators.deliveryOption.sendToRecipientOnDate.recipientEmail, sendToRecipientOnDate);		
	},
	
	onDeliveryOptionButtonClick: function(event) {		
		for (var i = 0; i < this.deliveryOptionsControls.length; i++) {			
			var controls = this.deliveryOptionsControls[i];			
			if (event.target.id == controls.button) {
				if (controls.detailsContainer != undefined)
					$(controls.detailsContainer).show();					
					
				/*if (controls.showMessageToRecipientInput) {
					if (!this.messageToRecipientContainer.visible())
						this.messageToRecipientContainer.show();
						
				} else {
					this.messageToRecipientContainer.hide();
				}*/
					
				this.onDeliveryOptionChange(controls.deliveryOptionId);
			} else {				
				if (controls.detailsContainer != undefined)					
					$(controls.detailsContainer).hide();
			}
		}
		
	}
});

GiftCertificateInfo.DeliveryOption = {
	SendToBuyer : 1,
	SendToRecipient : 2,
	SendToRecipientOnDate : 3
};


