window.DOL = window.DOL || {};

/* Beigin: Slidesshow */
DOL.Navigation = function (){
	
	var settings = {};
	var view = {};
	
	var defaults = {
		triggerEvent: 'click',
		loopingInterval: 10,
		duration: 500,
		debug: false
	};
	
	function setView() {
		if (settings.debug) console.log('Setting views');
		view = {};
		view.navBar = $(settings.navBar);
		view.items = view.navBar.find('.item');
		view.viewStack = $('#' + view.navBar.attr('dataProvider'));
		view.views = view.viewStack.find('.view');

		for (var i = 0; i < view.items.length; i++){
			view.items[i].index = i;
			$(view.items[i]).text(
				$(view.views[i]).attr('viewTitle')
			);
		}
	};
	
	function setEventListeners() {
		if (settings.debug) console.log('Setting Event Listeners');
		settings.triggerEvent = view.navBar.attr('triggerEvent') || settings.triggerEvent;
		settings.loopingInterval = view.viewStack.attr('loopingInterval') || settings.loopingInterval;
		settings.duration = parseInt(view.viewStack.attr('duration') || settings.duration);

		for (var i = 0; i < view.items.length; i++){
			$(view.items[i]).bind(settings.triggerEvent, function(event){
				$(this).blur();
				switchTo(this.index);
				clearTimeout(view.timer);
				return false;
			});
		}

		for (var i = 0; i < view.views.length; i++){
			$(view.views[i]).bind(settings.triggerEvent, function(event){
				$(this).blur();
				clearTimeout(view.timer);
				return false;
			});
			
			$(view.views[i]).bind('mouseout', function(event){
				$(this).blur();
				startLooping();
				return false;
			});
		}
	};
	
	function switchTo(index) {
		if (view.currentIndex || view.currentIndex === 0) {
			if (view.currentIndex == index) return;
			$(view.views[view.currentIndex]).fadeOut(settings.duration);
			$(view.items[view.currentIndex]).removeClass('active');
		};
		
		$(view.items[index]).addClass('active');
		$(view.views[index]).fadeIn(settings.duration);
		view.currentIndex = index;
		startLooping();
	};
	
	function startLooping() {
		clearTimeout(view.timer);
		if (! (settings.loopingInterval && settings.loopingInterval > 0)) return; 
		view.timer = setTimeout(function(){
			switchTo(getNextIndex());
		}, settings.loopingInterval)	
	};
	
	function getNextIndex() {
		var len = view.views.length;
		var nextViewIndex = (view.currentIndex + 1) % len;
		return nextViewIndex
	};
	
	function getPreviousIndex() {
		var len = view.views.length;
		var previousViewIndex = (view.currentIndex - 1 + len) % len;
		return previousViewIndex
	};
	
	return {
		init: function(options){
			settings = $.extend({}, defaults, options);
			setView();
			setEventListeners();
			if ($(view.navBar).length > 0) switchTo(0);
		}
	}
}();
/* End: Slideshow */


/* Begin: lightbox */
DOL.PopupContainer = {
		
	create: function () {
	
		var view = {};
		var options;

		function initialize(opts) {
			options = opts || {};
			setView();
		}

		function setView() {
			view.wrapper = (options.view.wrapper.clone().removeClass('popupContainer'));
			view.wrapper.appendTo($("body"));
			view.wrapper.find('.content').append(options.view.content);
			view.wrapper.addClass(options.view.className);
			view.lbtClose = view.wrapper.find('.lbtClose');
			
			view.lbtClose.click(function() {
				view.wrapper.hide();
				if (options.onClose != undefined) options.onClose();
			});
		}

		return {

			open: function() {
				view.wrapper.show();
			},
			
			close: function() {
				view.wrapper.hide();
			},
			
			reset: function() {
				$.extend(options, opts);
			},
			
			init: function(opts) {
				initialize(opts);
				return this;
			}
		
		}
	}
	
}

DOL.Confirmation = function () {

	var view = {};
	var options;

	function initialize(opts) {
		options = opts || {};
		setView();
		setEventListeners();
	}

	function setView() {
		view.wrapper = $('#confirmation');
		view.title = view.wrapper.find('.title');
		view.details = view.wrapper.find('.details');
		view.btnYes = view.wrapper.find('.btnYes');
		view.btnNo = view.wrapper.find('.btnNo');

		view.popup = DOL.PopupContainer.create().init({
			'view' : {
				'wrapper': $('.popupContainer'),
				'className': 'confirmationWindow',
				'content': view.wrapper 
			}
		});
		view.wrapper.show();
	}

	function setEventListeners() {
		view.btnYes.click(function() {
			//close(); (comment out for farleyco)
			options.onYes();
		});
		view.btnNo.click(function() {
			close();
			options.onNo();
		});
	}

	function open() {
		view.popup.open();
		view.btnYes.focus();
	}

	function close() {
		view.popup.close();
	}

	return {

		confirm: function(opts) {
			view.title.text(opts.title);
			view.details.html(opts.details);
			view.btnYes.text(opts.yes);
			view.btnNo.text(opts.no);
			options.onYes = opts.onYes;
			options.onNo = opts.onNo;
			open();
		},

		close: function () {
			close();
		},
		
		init: function(opts) {
			initialize(opts);
			return this;
		}
	}
}();


DOL.Alert = function () {

	var view = {};
	var options;

	function initialize(opts) {
		options = opts || {};
		setView();
		setEventListeners();
	}

	function setView() {
		view.wrapper = $('#alert');
		view.title = view.wrapper.find('.title');
		view.details = view.wrapper.find('.details');
		view.btnOK = view.wrapper.find('.btnOK');

		view.popup = DOL.PopupContainer.create().init({
			'view': {
				'wrapper': $('.popupContainer'),
				'className': 'alertWindow',
				'content': view.wrapper
			}
		});
		view.wrapper.show();
	}

	function setEventListeners() {

		view.btnOK.click(function() {
			close();
			options.onOK();
		});
		
	} 

	function open() {
		view.popup.open();
		view.btnOK.focus();
	}

	function close() {
		view.popup.close();
	}

	return {
		
		alert: function(opts) {
			view.title.text(opts.title);
			view.details.html(opts.details);
			view.btnOK.text(opts.ok);
			options.onOK = opts.onOK;
			open();
		},

		init: function(opts) {
			initialize(opts);
			return this;
		} 
	}
}();


DOL.Notification = function () {

	var view = {};
	var options;

	function initialize(opts) {
		options = opts || {};
		setView();
	}

	function setView() {
		view.wrapper = $('#notification');
		view.title = view.wrapper.find('.title');
		view.details = view.wrapper.find('.details');

		view.popup = DOL.PopupContainer.create().init({
			'view': {
				'wrapper': $('.popupContainer'),
				'className': 'notificationWindow',
				'content': view.wrapper
			},
			'onClose': function() {
				options.onClose();
			}
		});
		view.wrapper.show();
	}

	return {

		open: function(opts) {
			view.title.text(opts.title);
			view.details.html(opts.details);
			options.onClose = opts.onClose;
			view.popup.open();
		},

		close: function() {
			view.popup.close();
		},

		init: function(opts) {
			initialize(opts);
			return this;
		}
	}
}();

/* End: lightbox */


/* Begin: Form Validation */
DOL._Form = (function() {
	return {
		create: function(form) {
			
			var validators = [];
			var view = {};
			var isValidForm = true;
		
			function initialize(opts) {
				options = opts || {};
				setView();
				setEventListeners();
			}
			
			function setView() {
				view.form = $('#' + form);
				view.inputs = view.form.find('input, textarea, select');
				//view.inputs = view.form.find('input[type=text], input[type=password], textarea, select');
				view.selects = view.form.find('select');
				//view.chkboxes = view.form.find('input[type=checkbox], input[type=radio]');
			}
			
			function setEventListeners() {
				view.inputs.each(function(i, input) {
					$(input).bind('keyup', function (e) {
						validate(e.target);
					});
				});
				
				view.inputs.each(function(i, input) {
					$(input).bind('blur', function (e) {
						validate(e.target);
					});
				});
				
				view.selects.each(function(i, input) {
					$(input).bind('change', function (e) {
						validate(e.target);
					});
				});
				/*
				view.chkboxes.each(function(i, input) {
					$(input).bind('click', function (e) {
						validateChkbox(e.target);
					});
				});
				*/
                view.form.bind('submit', function () {
                    validateAll();
                    if (isValidForm && options.onSubmit) {
						options.onSubmit(form);
						isValidForm = false;
					}
                    return isValidForm;
                });
			}
			
			function validateAll() {
				isValidForm = true;
				view.inputs.each(function(i, input) {
					validate($(input));
				});
				/*
				view.chkboxes.each(function(i, input) {
					validateChkbox($(input));
				});*/
			}
			
			function validate(target) {
				
				$.each(validators, function(i, item) {
					if ($(target).attr('name') !== item[0]) return;
					
					var value = $(target).val();
					if (value == null || undefined ) value = '';
					
					var validation = $(target).siblings('.validation');
					
					if(! item[1](value)) {
						isValidForm = false;
						validation.text(item[2]);
					} else {
						var text = validation.text().replace(item[2], '');
						validation.text(text); 
					}
					
					if ($.trim(validation.text()).length > 0) validation.show();
					else validation.hide();
					
				})
			}
			
			function validateChkbox(target) {
				
				$.each(validators, function(i, item) {
					
					var name = $(target).attr('name');
					if (name !== item[0]) return;
					var value = [];
					
					var chkboxes = $(view.form).find('input[name=' + name + ']:checked');
					chkboxes.each(function(i, input) {
						value.push($(input).val());
					});
					if (value.length == 1) value = value[0];
					var validation = $(target).siblings('.validation');
					if(! item[1](value)) {
						isValidForm = false;
						validation.text(item[2]);
					} else {
						var text = validation.text().replace(item[2], '');
						validation.text(text); 
					}
					
					if (validation.text().trim().length > 0) validation.show();
					else validation.hide();
					
				})
			}
			
			return {
				
				addValidator: function(v) {
					validators.push(v);
					return this;
				},
				
				addValidators: function(vs) {
					$.merge(validators, vs);
					return this;
				},
			
				init: function(opts) {
					initialize(opts);
					return this;
				}
			}
		}
	}
})();


DOL.Validator = (function () {
	return {
		isNotBlank: function (value) {
			return !! $.trim(value.toString()).length;
		},
		
		isValidEmailFormat: function (value) {
            return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/.test($.trim(value.toString())) || $.trim(value.toString()).length == 0;
		},
		
        hasNoWhiteSpace: function (value) {
            return ! ( /\s/.test(value.toString()) && $.trim(value.toString()).length !== 0 );
        },
        
        isGoodPassword: function (value) {
            return $.trim(value.toString()).length >= 6 || $.trim(value.toString()).length == 0;
        },
        
        //12 to 16 digits
        isValidCreditcard: function (value) {
            return /^[0-9]{12,16}$/.test($.trim(value.toString())) || $.trim(value.toString()).length == 0;
        },
        
        
        isValidPhonenumber: function (value) {
			//7 to 10 digits
            // return /^[0-9]{7,10}$/.test($.trim(value.toString())) || $.trim(value.toString()).length == 0;
			//7, 10 or 11 digits with or without hyphens
            return /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/.test($.trim(value.toString())) || $.trim(value.toString()).length == 0;

        },
        
        //no comma seperator, dot for decimal seperator, 0 to 2 digits after dot
        isValidPrice: function (value) {
            return /^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.][0-9]{0,2})?(?:\\.[0-9]{0,2})?|(?:\\.[0-9]{3})*)$/.test($.trim(value.toString())) || $.trim(value.toString()).length == 0;
        },
        
        //positive integer
        isPositiveInteger: function (value) {
            return /^[0-9]{*}$/.test($.trim(value.toString())) || $.trim(value.toString()).length == 0;
        }
        
	}
})();
/* End: Form Validation */


DOL.SearchBox = function() {
	var settings = {};
	var view = {};
	
	function initilize(options) {
		settings = $.extend({}, settings, options);
		setView();
		setEventListeners();
	}
	
	function setView() {
		view.searchField = $('#search_field');
		view.label = $(view.searchField).find('label');
		view.input = $(view.searchField).find('#search_input');
		if ($.trim($(view.input).val()).length == 0)$(view.label).show();
	};
	
	function setEventListeners() {
		$(view.input).focus(function () {
			$(view.label).hide();
		});
		$(view.input).blur(function () {
			if ($.trim($(this).val()).length == 0)$(view.label).show();
		});
		$(view.input).keyup(function () {
			$(view.label).hide();
		});
	};
	
	return {
		init: function(options) {
			initilize(options);
		}
	}
}()

window.com = window.com || {};
com.principle = com.principle || {};
com.principle.aacstore = com.principle.accstore || {};

com.principle.aacstore.Validator = (function () {
	return {
		specifiedPriceType: function (value) {
			if ((!! $('#nonmember_price_on_details').attr('checked')) || (!! $('#member_price_on_details').attr('checked')) ) return true;
			else return false;
		},
		specifiedSize: function (value) {
			return(! ( $.trim($('#size_on_details').val()) == ''));
		},
		specifiedQty: function (value) {
			var val = $.trim($('#qty_on_details').val());
			var minQty = $.trim($('#qty_on_details').attr('data-min-qty'));
			var maxQty = $.trim($('#qty_on_details').attr('data-max-qty'));
			val = parseInt(val, 10);
			return ( val >= minQty && val <= maxQty );
		}
	}
})();


com.principle.aacstore.AddToCart = {
		
	create: function () {
	
		var view = {};
		var options;

		function initialize (opts) {
			options = opts || {};
			setView();
			setEventListeners();
		}

		function setView () {
			view.wrapper = options.wrapper;
			view.btnAdd = $(view.wrapper).find('.add');
		}
		
		function setEventListeners () {
			$(view.btnAdd).click(function () {
				
				view.name             = $(this).attr('data-name');
				view.productGroupCode = $(this).attr('data-product-group-cd');
				view.colour           = $(this).attr('data-colour');
				view.yesBtn           = $(this).attr('data-yes-btn');
				view.noBtn            = $(this).attr('data-no-btn');
				
				$.get('product-details-part.html?item=' + view.productGroupCode + '&colour=' + view.colour, function (d) {
					view.html = d;
					DOL.Confirmation.confirm({
						title: view.name,
						details: $(view.html).find('#form_order_on_details_overlay'),
						yes: view.yesBtn,
						no: view.noBtn,
						onYes: function () {
							addProduct();
						},
						onNo: function () {}
					});
					//setWidgets();
				})
			});
		}
		
		/*
		function setWidgets () {
			$('#form_order_on_details_overlay').submit(function () {
				alert('here');
				return false;
			});
			
			DOL._Form.create('form_order_on_details_overlay').init({
				'onSubmit': function () {
					addProduct();
				}
			}).addValidators([
				['size_cd', DOL.Validator.isNotBlank, 'Required'],
				['qty'    , DOL.Validator.isNotBlank, 'Required']
			]);
		}
		*/
		
		function addProduct () {
			$.ajax({
				url: $('#form_order_on_details_overlay').attr('action'),
				type : "POST",
				data: {
					product_group_cd: $('#form_order_on_details_overlay').find('input[name=product_group_cd]').val(),
					colour_cd: $('#form_order_on_details_overlay').find('input[name=colour_cd]').val(),
					qty: $('#form_order_on_details_overlay').find('input[name=qty]').val(),
					size_cd: $('#form_order_on_details_overlay').find('input[name=size_cd]').val()
				},
				dataType: 'json',
				success: function (data) {
					
					if ( !!data && !!data.success) {
						DOL.Confirmation.close();
						DOL.Notification.open({
							title: view.name + ' has been added',
							details: $(view.html).find('#addProductSucceed')
						});
						$('#addProductSucceed .link.shopping-cart').click(function () {
							window.location.href = 'shopping-cart.php';
						});
						$('#addProductSucceed .link.continue').click(function () {
							DOL.Notification.close();
						})
					}
				},
				error: function(xmlhttp,error_msg){
					alert("error: "+error_msg);
				}
			});
		}
		
		return {
			init: function(opts) {
				initialize(opts);
				return this;
			}
		}
	}
}



$(function () {
	DOL.Confirmation.init();
	DOL.Notification.init();
});

