// Load dependend files

if(!$chk(HKM)) {
	var HKM = {};
}

if(!$defined(console)) {
	var console = {};

}

HKM.Shop = new Class({

	options: {
		productPageSelector: '.productPage',
		themePageSelector: '.themePage',
		detailPageSelector: '.detailPage',
		zoomPageSelector: '.zoomPage'
	},
	
	shopContainer: null,
	
	exceptionDisplay: null,
	
	exceptionTextDisplay: null,
	
	productData: null,

	pages: {
		productPage: Class.empty,
		themePage: Class.empty,
		detailPage: Class.empty,
		zoomPage: Class.empty
	},
		
	productService: Class.empty,
	
	currentPage: null,
	
	tellAFriend: null,
	
	currentProductId: null,
	
	initialize: function(target, options) {
				
		this.setOptions(options);
		this.shopContainer = $(target);
		this.setupPages();
		
		
		
		var productRequestOptions = {onData:this.onProductHandler.bind(this), onDataFailed:this.onDataFailesHandler.bind(this)};
		if($defined(HKM.shopConfiguration) && $defined(HKM.shopConfiguration.catalogServiceURL)) {
			productRequestOptions.serviceURL = HKM.shopConfiguration.catalogServiceURL;
		}
		
		this.productService = new HKM.ProductRequest(productRequestOptions);
		
		this.exceptionDisplay = new Element('div');
		this.exceptionDisplay.addClass('exceptionDisplay');
		this.exceptionTextDisplay = new Element('div');
		this.exceptionTextDisplay.injectInside(this.exceptionDisplay);
		
		this.exceptionDisplay.setStyles({
										'display':'none', 
										'position':'absolute',
										'width':this.shopContainer.getSize().size.x-2, 
										'height':80, 
										'left':'0', 
										'top':0,
										'z-index':500,
										'backgroundColor':'#F5F5F5',
										'visibility':'hidden',
										'border-bottom': '1px solid #BD9E56'
										});
		this.exceptionDisplay.injectBefore(this.shopContainer.getFirst());
		
		this.shopContainer.addEvent('mouseleave', this.shopContainerMouseLeaveHandler.bindAsEventListener(this));
	},
	
	wasZooming: false,
	
	shopContainerMouseLeaveHandler: function() {
		if(this.currentPage == this.pages.zoomPage) {
			this.showThemePage();
			this.pages.productPage.enableZoomClickImage();
		}
	},
	
	shopContainerMouseEnterHandler: function() {
		if(this.wasZooming) {
			this.showZoomPage();
			this.wasZooming = false;
		}
	},
	
	setupPages: function() {
		
		var productPageCandidates = $ES(this.options.productPageSelector, this.shopContainer);
		if(productPageCandidates.length > 0) {
			this.pages.productPage = new HKM.ProductPage(productPageCandidates.pop(), {
																						identifier: 'productPage',
																						onDetailButtonClicked: this.showDetailPage.bindAsEventListener(this),
																						onZoomButtonClicked: this.showZoomPage.bindAsEventListener(this),
																						onTellAFriendButtonClicked: this.showTellAFriend.bindAsEventListener(this),
																						onEnlargeButtonClicked: this.showEnlargedImage.bindAsEventListener(this), 
																						onWillClose:this.willCloseHandler.bindAsEventListener(this),
																						onDidClose:this.didCloseHandler.bindAsEventListener(this),
																						delegate: this
																						});
		}
		
		var themePageCandidates = $ES(this.options.themePageSelector, this.shopContainer);
		if(themePageCandidates.length > 0) {
			this.pages.themePage = new HKM.ThemePage(themePageCandidates.pop(), {
																				identifier: 'themePage',
																				onWillClose:this.willCloseHandler.bindAsEventListener(this),
																				onDidClose:this.didCloseHandler.bindAsEventListener(this),
																				delegate: this
																				});
			
			if(this.pages.themePage.options.visibleAtStartUp) {
				this.currentPage = this.pages.themePage;
			}
		}
		
		var detailPageCandidates = $ES(this.options.detailPageSelector, this.shopContainer);
		if(detailPageCandidates.length > 0) {
			
			var detailPageOptions = {
									identifier: 'detailPage', 
									onWillClose:this.willCloseHandler.bindAsEventListener(this),
									onDidClose:this.didCloseHandler.bindAsEventListener(this),
									delegate: this
									};
			
			
			
			if($defined(HKM.shopConfiguration) && $defined(HKM.shopConfiguration.createYourOwnMaxTextLength)) {
				detailPageOptions.createYourOwnMaxCharacter = HKM.shopConfiguration.createYourOwnMaxTextLength;
			}
			if($defined(HKM.shopConfiguration) && $defined(HKM.shopConfiguration.warningFillOutCreateYourOwnText)) {
				detailPageOptions.warningFillOutCreateYourOwnText = HKM.shopConfiguration.warningFillOutCreateYourOwnText;
			}
			
			
			this.pages.detailPage = new HKM.DetailPage(detailPageCandidates.pop(), detailPageOptions);
			if(this.pages.detailPage.options.visibleAtStartUp) {
				this.currentPage = this.pages.detailPage;
			}
		}
		
		var zoomPageCandidates = $ES(this.options.zoomPageSelector, this.shopContainer);
		if(zoomPageCandidates.length > 0) {
			this.pages.zoomPage = new HKM.ZoomPage(zoomPageCandidates.pop(), {
																				identifier: 'zoomPage', 
																				onWillClose:this.willCloseHandler.bindAsEventListener(this),
																				onDidClose:this.didCloseHandler.bindAsEventListener(this),
																				delegate: this
																			});

			if(this.pages.zoomPage.options.visibleAtStartUp) {
				this.currentPage = this.pages.zoomPage;
			}			
		}
		
		// Check if there is initial data. If So. Load into pages
		// Load initial data
		if($chk(HKM.initialProductData)) {
			var initialProductId = HKM.initialProductData.data[0].productId;
			var initialProductLabel = HKM.initialProductData.data[0].displayName;

			this.productData = HKM.initialProductData.data[0];
			this.currentProductId = this.productData.productId;
			
			// Allow prepare
			for(var e in this.pages) {
				this.pages[e].prepareReload(initialProductId, initialProductLabel, false);
			}
			// Set product data
			this.renderProductData(HKM.initialProductData.data[0]);
		}
		
	},
	
	willCloseHandler: function(target) {
		this.quickHideException();
	},
	
	didCloseHandler: function(target) {
		if(target.identifier() == 'detailPage') {
			this.pages.themePage.show();
			this.currentPage = this.pages.themePage;
		} else if(target.identifier() == 'zoomPage') {
			this.pages.productPage.enableZoomClickImage();
		}
	},
	
	showDetailPage: function() {		
		if(this.currentPage.identifier() == 'detailPage') {
			return;
		}
		
		if(this.currentPage !== null) {
			this.currentPage.hide();
		} else {
			this.pages.themePage.hide();
		}
		this.pages.detailPage.show();
		this.currentPage = this.pages.detailPage;
		
	},
	
	showZoomPage: function(targetImage) {

		if(this.currentPage.identifier() !== 'zoomPage') {
			this.currentPage.hide(false);
			this.pages.zoomPage.show();
			this.pages.zoomPage.startZoom((($chk(targetImage)) ? targetImage : this.pages.zoomPage.smallImageTarget));
			this.currentPage = this.pages.zoomPage;
		} else {
			this.showThemePage();
			this.pages.productPage.enableZoomClickImage();
		}		
	},
	
	showThemePage: function() {

		this.currentPage.hide(false);
		this.pages.themePage.show();
		this.currentPage = this.pages.themePage;

	},
	
	showTellAFriend: function(target) {
		
		if(this.tellAFriend === null) {
			
			var tellAFriendOptions = {
									onDidSend: this.sendTellAFriend.bindAsEventListener(this),
									onDidCancel: this.cancelTellAFriend.bindAsEventListener(this)
									}
			
			if($defined(HKM.shopConfiguration) && $defined(HKM.shopConfiguration.fillOutFieldErrorMessage)) {
				tellAFriendOptions.fillOutFieldErrorMessage = HKM.shopConfiguration.fillOutFieldErrorMessage;
			}
			
			
			this.tellAFriend = new HKM.TellAFriend(
												this.shopContainer, 
												$$('.tellAFriendFormContainer').pop(),
												tellAFriendOptions
												);
		}
		this.tellAFriend.startForProduct(this.currentProductId);
	},
	
	sendTellAFriend: function(postData) {

		var tellAFriendRequestOptions = {
										onData: this.tellAfriendRequestSuccess.bindAsEventListener(this),
										onDataFailed: this.tellAfriendRequestFailure.bindAsEventListener(this)
										};
		if($defined(HKM.shopConfiguration) && $defined(HKM.shopConfiguration.tellAFriendServiceURL)) {
			tellAFriendRequestOptions.serviceURL = HKM.shopConfiguration.tellAFriendServiceURL;
		}
		
		var tellAFriendRequestObject = new HKM.TellAFriendRequest(tellAFriendRequestOptions);
		tellAFriendRequestObject.load(postData);
		
	},
	
	cancelTellAFriend: function() {
		if(this.tellAFriend !== null && this.tellAFriend.visible === true) {
			this.tellAFriend.hide();
		}
	},
	
	tellAfriendRequestSuccess: function() {


		this.cancelTellAFriend();
	},
	
	tellAfriendRequestFailure: function(message) {
		
		if(this.tellAFriend !== null && this.tellAFriend.visible === true) {
			this.tellAFriend.requestFailed(message);
		}

	},
	
	showEnlargedImage: function(target) {
		
		if($chk(this.productData) && $chk(this.productData.detailImageUrl)) {
		window.open(
					this.productData.detailImageUrl, 
					"hkmEnlargeWindow",
					"location=no,\
					status=no,\
					scrollbars=yes,\
					resizable=yes,\
					toolbar=no,\
					width=1100,\
					height=600");     
		}
		
	},
	
	displayProduct: function(productId, productLabel, relatedProduct) {
		this.wasZooming = false;
		this.cancelTellAFriend();
		
		this.currentProductId = productId;
		
		// Hide zoom page if needed
		if(this.currentPage.identifier() == 'zoomPage') {
			this.showThemePage();
		}
		
		for(var e in this.pages) {
			this.pages[e].prepareReload(productId, productLabel);
		}
		
		this.productService.load(productId);
		
	},

	onProductHandler: function(productData) {
		this.currentProductId = productData.productId;
		this.renderProductData(productData);
	},

	renderProductData: function(productData) {
		this.cancelTellAFriend();
		for(var e in this.pages) {
			this.productData = productData;
			this.pages[e].reloadData(productData);
		}
	},
	
	displayExceptionColors: ['#48575E', '#FF0000'],
	
	displayException: function(exceptionText, level) {

		var exceptionLevel = ($chk(level) && level <= this.displayExceptionColors.length) ? level : 0;

		this.exceptionDisplay.setStyles({
											'color':this.displayExceptionColors[exceptionLevel], 
											'height':1,
											'display':'block',
											'visibility':'visible'
											});
		if(!window.ie6) {
					this.exceptionDisplay.setStyles({
											'left':this.shopContainer.getPosition().x+1,
											'top':this.shopContainer.getPosition().y+1
										});
		}
		this.exceptionTextDisplay.setText(exceptionText);
		this.exceptionTextDisplay.setStyles({'visibility':'visible', 'display':'block', 'opacity':1});
		
		var onCompleteHandler = this.hideException.bind(this);
		var disappearFX = new Fx.Styles(this.exceptionDisplay, {onComplete:onCompleteHandler.delay(3500)});
		disappearFX.start({'opacity':[this.exceptionDisplay.getStyle('opacity'), 1], 'height':[this.exceptionDisplay.getStyle('height'), 30]});

	},
	
	hideException: function() {
		
		var disappearFX = new Fx.Styles(this.exceptionDisplay);
		disappearFX.start({'opacity':[this.exceptionDisplay.getStyle('opacity'), 0], 'height':[this.exceptionDisplay.getStyle('height'), 0]});
		
	},
	
	quickHideException: function() {
		//this.exceptionTextDisplay.setStyles({'opacity':[1, 0], 'height':[60, 0]});
		this.exceptionTextDisplay.setStyles({'opacity':0, 'height':0});	
	},
	
	onDataFailesHandler: function() {

	}
	

});
HKM.Shop.implement(new Options);
HKM.Shop.implement(new Events);


HKM.shopVars = {
	'shopContainerSelector': 'hkmAjaxShopContainer',
	mainController: Class.empty,
	currentProductId: null,
	basketRequest: null,
	scroller: null,
	shopInfoTips: null
}

HKM.initializeHKMShop = function() {
	
	var shopCandidates = $$('.'+HKM.shopVars.shopContainerSelector);
	for(var i=0;i<shopCandidates.length;i++) {
		HKM.shopVars.mainShopController = new HKM.Shop(shopCandidates[i]);
	}
	
	HKM.shopVars.shopInfoTips = new Tips('.infoLabel', {'x': 16, 'y': 16});
}

HKM.displayShopProduct = function(productId, productLabel, relatedProduct) {
	
	var windowScroll = new Fx.Scroll(window);
	windowScroll.toTop();
	
	
	if(HKM.shopVars.currentProductId !== productId) {
		HKM.shopVars.mainShopController.displayProduct(productId, productLabel, relatedProduct);
	}
	HKM.shopVars.currentProductId = productId;
	return false;
}

HKM.addToBasket = function(productId, variantId, quantity, createYourOwnString, onCompleteHandler, onFailureHandler, color, size) {

	if(HKM.shopVars.basketRequest !== null) {
		//HKM.shopVars.basketRequest.stop();
		HKM.shopVars.basketRequest = null;
	}
	
	var basketRequestOptions = {onData:onCompleteHandler, onDataFailed:onFailureHandler};
	if($defined(HKM.shopConfiguration) && $defined(HKM.shopConfiguration.basketServiceURL)) {
		basketRequestOptions.serviceURL = HKM.shopConfiguration.basketServiceURL;
		basketRequestOptions.onData = HKM.addToBasketResultHandler.bindAsEventListener(window, onCompleteHandler)
	}
	
	HKM.shopVars.basketRequest = new HKM.BasketRequest(basketRequestOptions);

	var requestData = {
						"productId":productId,
						"variantId":variantId,
						"quantity":quantity.toInt()
						};
						
	if($chk(createYourOwnString)) {
		requestData.personalPrint = createYourOwnString;
	}

	HKM.shopVars.basketRequest.load(requestData);

}

HKM.addToBasketResultHandler = function(data, originalHandler) {

	if($chk(originalHandler)) {
	   	originalHandler();
	}
	
	if($chk(data.productCount)) {
		HKM.updatePageBasket(data.productCount.toString());
	}
	
}

window.addEvent('domready', HKM.initializeHKMShop);
