var BASE_URL = "http://www.bubbletreehouse.ie/";
function toggleMenuIE(el,id)
{var uls=el.parentNode.getElementsByTagName("ul");for(var eid in uls){e=$(eid);if(e!=null){if(e.id==id&&!e.visible()){Effect.BlindDown(e,{duration:0.5});}
else{Effect.BlindUp(e,{duration:0.5});}}}}


function toggleMenu(el,id)
{
    el.parentNode.select("ul").each(function(e) {
		if(e.id==id&&!e.visible()){Effect.BlindDown(e,{duration:0.5});}
else{Effect.BlindUp(e,{duration:0.5});}}
	);
}
var PatternSelector = Class.create (
	{
		initialize: function(element, productid) {
			this.element = $(element);
			this.productid = productid;
            this.images = new Array();
            this.width;
            this.imagesJson = null;
            this.currentImageIndex = null;
            this.selectedIndex = null;
			var initPatterns = this.initPatterns.bind(this);
			var req = new Ajax.Request('http://www.bubbletreehouse.ie/ajax/initpattern',{ parameters:{productid:this.productid}, onComplete:initPatterns, evalScripts:true})
		},
		initPatterns: function(request){
			this.imagesJson = request.responseJSON;
            this.currentImageIndex = 0;
            this.width  = this.imagesJson[0].width;
           this.renderPicker();
		},
        renderPicker: function() {
        var idx = this.currentImageIndex;
        this.element.innerHTML='';
            var container = document.createElement('div');
            var inputField = document.createElement('input');
            inputField.type='hidden';
            inputField.name='pattern_id';
            inputField.value=this.imagesJson[this.currentImageIndex].id; 
            
            var totalwidth = parseInt(this.imagesJson[idx].width)+30;
            container.style.width = totalwidth + "px";
            container.style.height = parseInt(parseInt(this.imagesJson[idx].height)+23) + "px";
            container.style.position = 'absolute';
            container.style.margin = "0 0px 0 0";
            
            var leftHandle = document.createElement('div');
            leftHandle.style.position="absolute";
            leftHandle.style.left ="0px";
            leftHandle.style.top = parseInt(parseInt(this.imagesJson[idx].height) / 2 - 9) + "px";
            leftHandle.style.overflow = 'hidden';

            leftHandle.style.width = "15px";
            leftHandle.style.height = "18px";
            leftHandle.innerHTML = "&nbsp;";
            leftHandle.className = "previous";

            leftHandle.style.textAlign='center';
            leftHandle.onclick = new Function("patternChooser.slideToPreviousImage();return false");
            //leftHandle.setAttribute('onclick',"patternChooser.slideToPreviousImage();return false");
            
            
            var rightHandle = document.createElement('div');
            rightHandle.style.position="absolute";
            rightHandle.style.right="0";
            rightHandle.style.top = parseInt(parseInt(this.imagesJson[idx].height) / 2 - 9) + "px";
            rightHandle.style.overflow = 'hidden';

            rightHandle.style.width = "15px";
            rightHandle.style.height = "18px";
            rightHandle.innerHTML = "&nbsp;";
            rightHandle.className = "next";
            rightHandle.style.textAlign='center';
            rightHandle.onclick = new Function("patternChooser.slideToNextImage();");
          
            var titleLabel = document.createElement('div');
            titleLabel.innerHTML = this.imagesJson[this.currentImageIndex].title;
//            titleLabel.style.width = totalwidth + 'px';
            titleLabel.style.textAlign = 'center';
            titleLabel.style.position = 'absolute';
            titleLabel.style.bottom = "10px";
            titleLabel.style.height = "13px";
            titleLabel.style.fontSize='11px';
            
            
            var summaryLabel = document.createElement('div');
            summaryLabel.innerHTML = parseInt(this.currentImageIndex+1)+'/'+this.imagesJson.length;
            //summaryLabel.style.width = totalwidth + 'px';
            summaryLabel.style.textAlign = 'center';
            summaryLabel.style.position = 'absolute';
            summaryLabel.style.bottom = "0";
            summaryLabel.style.height = "10px";
            summaryLabel.style.fontSize='9px';
            
            var mainView = document.createElement('div');
            mainView.style.height = this.imagesJson[idx].height+"px";
            mainView.style.width = this.imagesJson[idx].width + "px";
            var offWidth = parseInt(this.imagesJson[idx].width) + 35 ;
            mainView.className = "mainView";
            mainView.style.position = "absolute";
            mainView.style.left = "15px";
            mainView.style.overflow='hidden';
            
            var contentView = document.createElement('div');
            contentView.id='contentViewSliding';
            contentView.className = "contentView";
            
            
            var prevImage = this.makeImageFromJson((this.currentImageIndex == 0 ? this.imagesJson[this.imagesJson.length - 1] : this.imagesJson[this.currentImageIndex - 1] ));
            var currentImage = this.makeImageFromJson(this.imagesJson[this.currentImageIndex]);
            //currentImage.setAttribute('ondblclick','alert("double click !")');
            var cHeight = currentImage.height;
             var cWidth= currentImage.width;
           
            var nextImage = this.makeImageFromJson((this.currentImageIndex >= this.imagesJson.length-1 ? this.imagesJson[0] : this.imagesJson[this.currentImageIndex + 1] ));
           // alert(prevImage.src +',' + currentImage.src + "," + nextImage.src);
            contentView.style.height = currentImage.height+"px";
            contentView.style.width = parseInt(prevImage.width+currentImage.width+nextImage.width+1)+"px";
            contentView.style.position = "absolute";
            contentView.style.left = - 1 * prevImage.width +"px";
            var lbLink = document.createElement("a");
            lbLink.setAttribute ('href','http://www.bubbletreehouse.ie/media/' + this.imagesJson[this.currentImageIndex].filePath);
           lbLink.setAttribute("rel","lightbox");
            lbLink.appendChild(currentImage);
            //if ie
           if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion <= "7" )
           		container.style.right = offWidth +"px";
                        summaryLabel.style.width = totalwidth+"px";
						titleLabel.style.width =  totalwidth+"px";
            			titleLabel.style.right = "0px";
             			summaryLabel.style.right = "0px";
           
            contentView.appendChild(prevImage);
            contentView.appendChild(lbLink);
            contentView.appendChild(nextImage);
            mainView.appendChild(contentView);
            container.appendChild(mainView);
            container.appendChild(inputField);
            container.appendChild(leftHandle);
            container.appendChild(rightHandle);
            container.appendChild(titleLabel);
            container.appendChild(summaryLabel);
            
            
            this.element.appendChild(container);
            this.element.style.height = parseInt(parseInt(cHeight)+23)+"px";
            this.element.style.width = totalwidth+"px";
            this.element.style.margin = "5px 0 5px 0";

          
        },
        makeImageFromJson: function(obj) {
            var image = document.createElement('img');
            image.src = 'http://www.bubbletreehouse.ie/media/' + obj.filePath;
            image.height =  obj.height;
            image.width = obj.width;
            image.title = obj.title;
            return image;
        },
        slideToPreviousImage: function() {
           var eff = new Effect.Move('contentViewSliding', { y: 0, x: this.width, duration:0.3, mode: 'relative', afterFinish:function(){patternChooser.previousImage(); }});
            return false;
        },
        previousImage: function() {
            this.currentImageIndex = this.currentImageIndex - 1 < 0 ? this.imagesJson.length - 1 : this.currentImageIndex - 1;
            this.renderPicker();
            return true;
        },
        slideToNextImage: function() {
           var eff = new Effect.Move('contentViewSliding', { y: 0, x: - this.width, duration:0.3, mode: 'relative', afterFinish:function(){patternChooser.nextImage();
}});
            return false;
        },
        nextImage: function() {
            this.currentImageIndex = this.currentImageIndex + 1 == this.imagesJson.length ? 0 : this.currentImageIndex + 1;
            this.renderPicker();
        },
        select: function() {
            this.selectedIndex = this.currentImageIndex;
        } 
	});

function findChild (element, nodeName)
{
	var child;
	for (child = element.firstChild; child != null; child = child.nextSibling)
	{
		if (child.nodeName == nodeName)
			return child;
	}

	return null;
}

howmuch = document.createElement('div');
howmuch.id = "how_much_bb";
howmuch.className = "help-bb";
howmuch.style.display="none";
howmuch.innerHTML = "Click here to find out how to calculate how much you need";
if(howmuch.addEventListener)
	howmuch.addEventListener('click',function(){new HelpArticle('1')},true);
else
	howmuch.onclick = function(){new HelpArticle('1')};


var HelpArticle = Class.create({
	initialize:function(id) {
		this.content = '';
		this.id = id;
		if(this.id=='') {alert('Error while retrieving the Help Article'); return}
		this.articleJson = null
		var container = document.body;
		var curtain = document.createElement('div');
		curtain.id = 'overlayHA';
		curtain.className = 'overlayHA';
		curtain.style.display = 'none';
		curtain.style.height = document.body.offsetHeight+"px";
		
		container.appendChild(curtain);
		var initArticle = this.initArticle.bind(this);
		var eff = new Effect.Appear('overlayHA', { from: 0, to: 0.75, duration:0.3, afterFinish:initArticle});
	},
	initArticle: function(){
		var renderArticle = this.renderArticle.bind(this);
		var req = new Ajax.Request('http://www.bubbletreehouse.ie/ajax/getHelpArticle',{ parameters:{articleid:this.id}, onComplete:renderArticle, evalScripts:true})
	},
	renderArticle: function(request) {
		//draw a curtain
		
		if(request.responseJSON.error == "Y") {alert('Error while retrieving the Help Article'); return}
		this.articleJson = request.responseJSON.article;
		//render the box
		var articleWrapper = document.createElement('div');
		articleWrapper.className='articleWrapper';
		articleWrapper.id = 'articleWrapper';
		articleWrapper.style.display='none';
		articleWrapper.style.width='100%';	
		articleWrapper.style.top = document.body.scrollTop + "px";
		var articleEl = document.createElement('div');
		articleEl.className = "articleInside";
		
		var articleTitle = document.createElement('div');
		articleTitle.className = 'HA-title';
		var articleContent = document.createElement('div');
		articleContent.className = 'HA-content';
		var articleCloseContainer = document.createElement('div');
		articleCloseContainer.style.padding="2px";
		articleCloseContainer.style.height="24px";		
		
		var articleCloseButton = document.createElement('div');
		articleCloseButton.className = 'add_to_basket_button';
		articleCloseButton.style.float='right';
		
		articleCloseButton.style.paddingTop = '2px';
		articleCloseButton.style.height='18px';
		articleCloseButton.style.paddingBottom = 0;
		articleCloseButton.style.marginTop="3px";
		articleCloseButton.style.marginBottom="3px";
		
		articleCloseButton.innerHTML = "Close";
		articleCloseContainer.appendChild(articleCloseButton);
		
		
		articleContent.innerHTML = this.articleJson.content;
		articleTitle.innerHTML = this.articleJson.title;
		
		
		articleEl.appendChild(articleTitle);
		articleEl.appendChild(articleContent);
		articleEl.appendChild(articleCloseContainer);
		
		articleWrapper.appendChild(articleEl);
		document.body.appendChild(articleWrapper);
		
		//create event listeners
		if(articleCloseButton.addEventListener) {
			articleCloseButton.addEventListener('click',function() { Effect.SlideUp('articleWrapper',{afterFinish:function() { $('articleWrapper').remove();new Effect.Appear('overlayHA', { from: 0.75, to: 0, duration:0.3,onComplete:$('overlayHA').remove()}) } })},true);
			$('overlayHA').addEventListener('click',function() { Effect.SlideUp('articleWrapper',{afterFinish:function() { new Effect.Appear('overlayHA', { from: 0.75, to: 0, duration:0.3,onComplete:$('overlayHA').remove()}) } })},true);
		}
		else {
			articleCloseButton.onclick=function() { Effect.SlideUp('articleWrapper',{afterFinish:function() { $('articleWrapper').remove();new Effect.Appear('overlayHA', { from: 0.75, to: 0, duration:0.3,onComplete:$('overlayHA').remove()}) } })};
			$('overlayHA').onclick=function() { Effect.SlideUp('articleWrapper',{afterFinish:function() { new Effect.Appear('overlayHA', { from: 0.75, to: 0, duration:0.3,onComplete:$('overlayHA').remove()}) } })};

		}
		
		// slide it down
		Effect.SlideDown('articleWrapper');
	}
});

var CollectionBrowser = Class.create({
	initialize:function(container, collections) {
		this.container = container;
		this.id = this.container.id;
		this.collections = collections;
		this.loadingImage = new Image();
		this.loadingImage.src = '../interface/images/loading-bubbles.gif';
		this.loaded = 0;
		this.imagePaths = [];
		this.images = [];
		this.render();
		this.startLoading();
		this.shownImage = 0;	
	},
	startLoading: function() {
		for(var i=0; i< this.collections.length; i++ ) {
			var collection = this.collections[i];
			this.imagePaths.push(collection.image);
			var im = new Image();
			im.onload = this.onloadImage;
			im.browserObj = this;
			im.src = collection.image;
			im.height='350';
			im.width='350';
			this.images.push(im);
		}
		
	},
	onloadImage:function() {
		this.browserObj.loaded ++;
		this.browserObj.onComplete();
	},
	onComplete: function() {
		if(this.loaded == this.collections.length) {
			this.assignPictures();
		}
	},
	onMyMouseOver: function() {
		$(this.id+"_products").style.display='block';
	},
	onMyMouseOut: function() {
		$(this.id+"_products").style.display='none';
	},
	render: function() {
		// viewport
		var mViewport = document.createElement('div');
		var that = this;
		
		mViewport.id = this.id+"_viewport";
		mViewport.className = "collection-browser-viewport";
		var onTClick = this.onTClick.bind(this);
		var onMyMouseOver = this.onMyMouseOver.bind(this);
		var onMyMouseOut = this.onMyMouseOut.bind(this);
		if(mViewport.addEventListener) {
			mViewport.addEventListener('mouseover', onMyMouseOver,true);
			mViewport.addEventListener('click',onTClick,true);
		}
		else {
				mViewport.onmouseover = onMyMouseOver;
				mViewport.onclick = onTClick;	
		}

		// image containers
		this.strip = document.createElement('div');
		this.strip.id = this.id+"_strip";
		this.strip.className = "collection-browser-strip";
		this.strip.style.width = this.collections.length * 350 + "px";
		
		for (var i=0; i<this.collections.length ; i++) {
			var imageContainer = document.createElement('div');
			imageContainer.className = "collection-browser-image-container";
			/*imageContainer.style.float='left';*/
			imageContainer.style.position='absolute';
			imageContainer.style.left=parseInt( i * 350 )+'px';			
			imageContainer.id = this.id+ "_image_"+i;
			loadingImage = new Image();
			loadingImage.src = this.loadingImage.src;
			imageContainer.appendChild(loadingImage);
			this.strip.appendChild(imageContainer);
		}
		
		mViewport.appendChild(this.strip);
		this.container.appendChild(mViewport);
		
		// title 
		var titleEl = document.createElement('div');
		titleEl.id = this.id+"_title";
		titleEl.className = "collection-browser-title";
		titleEl.innerHTML = this.collections[0].title;
		if(titleEl.addEventListener)
			titleEl.addEventListener('click',onTClick,true);
		else 
			titleEl.onclick = onTClick;
		this.container.appendChild(titleEl);

		// productInfo
		var productInfoDimmer = document.createElement('div');
		productInfoDimmer.className = "collection-browser-viewport";
		productInfoDimmer.style.backgroundColor='rgb(255,255,255)';
		productInfoDimmer.style.opacity='0.6';
		productInfoDimmer.style.position='absolute';
		
		
		var productInfo = document.createElement('div');
		productInfo.id = this.id+"_products";
		productInfo.className = "collection-browser-viewport";
		productInfo.group = "prodinfo";
		productInfo.style.position='absolute';
		productInfo.style.display='none';
		productInfo.style.textAlign='center';
		productInfo.style.color='black';
		productInfo.style.cursor='pointer';
		if(productInfo.addEventListener) 
			productInfo.addEventListener('mouseout',function(e){$(that.id+'_products').style.display='none'},true);
		else
			productInfo.onmouseout = onMyMouseOut;
		productInfo.appendChild(productInfoDimmer);
		productInfo.innerHTML += "<span id='product_detail_"+this.id+"' style='font-size:14px;position:relative;top:150px'><b>" + this.collections[0].products + "</b> Products available in this collection</span>";
		mViewport.appendChild(productInfo);
		
		
		//navigation marker
		
		var navCont = document.createElement('div');
		navCont.className = "collection-browser-nav";
		
		for (var i=0; i<this.collections.length ; i++) {
			var navPoint = document.createElement('div');
			navPoint.className = 'collection-browser-nav-point';
			if(i==0) navPoint.style.backgroundPosition='-14px 0';
			navCont.appendChild(navPoint);
		}

		this.container.appendChild(navCont);
		if(this.collections.length >1 ) {
			// handle right
			var handleRight = document.createElement('div');
			handleRight.className = 'collection-browser-handle-right';
			var scrollRight = this.scrollRight.bind(this);
			if(handleRight.addEventListener)
				handleRight.addEventListener('click',scrollRight,true);
			else
				handleRight.onclick = scrollRight;
			this.container.appendChild(handleRight);
			// handle left
			var handleLeft = document.createElement('div');
			handleLeft.className = 'collection-browser-handle-left';
			var scrollLeft = this.scrollLeft.bind(this);
			if(handleLeft.addEventListener)
				handleLeft.addEventListener('click',scrollLeft,true);
			else
				handleLeft.onclick = scrollLeft;
			this.container.appendChild(handleLeft);
		}
		
	},
	assignPictures: function() {
		for (var i=0; i<this.collections.length ; i++) {
			$(this.id+ "_image_"+i).innerHTML='';
			$(this.id+ "_image_"+i).appendChild(this.images[i]);
		}
	},
	scrollRight: function() {
		var nextImgIndex = this.shownImage + 1;
		if (nextImgIndex == this.collections.length) nextImgIndex = 0 ;
		this.shownImage = nextImgIndex;
		var newPos = nextImgIndex * 350 ;
		var afterMove = this.afterMove.bind(this);
		var eff = new Effect.Move(this.strip, { y: 0, x: - newPos , duration:0.3, mode: 'absolute', afterFinish:afterMove});
       	return false;
	},
	scrollLeft: function() {
		var nextImgIndex = this.shownImage - 1;
		if (nextImgIndex == -1) nextImgIndex = this.collections.length-1 ;
		this.shownImage = nextImgIndex;
		var newPos = nextImgIndex * 350 ;
		var afterMove = this.afterMove.bind(this);
		var eff = new Effect.Move(this.strip, { y: 0, x: - newPos , duration:0.3, mode: 'absolute', afterFinish:afterMove});
       	return false;
	},
	onTClick: function() {
		window.location = 'http://www.bubbletreehouse.ie/collections/'+ this.collections[this.shownImage].urlKey;
	},
	afterMove: function() {
		$(this.id+"_title").innerHTML = this.collections[this.shownImage].title;
		$('product_detail_'+this.id).innerHTML = "<b>" + this.collections[this.shownImage].products + "</b> Products available in this collection";
		
	}
	
});

function clone(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed (twice)
    for(var key in obj)
        temp[key] = clone(obj[key]);

    return temp;
}
Event.observe(window, 'load', function() {
        if($('add-to-basket')){
                $('add-to-basket').observe('click', function(event){
                        event.stopPropagation();
                       new Ajax.Request(BASE_URL+'basket/additemdirect/'+$('add-to-basket').getAttribute('name')+'/0/0/1/'+$('add-to-basket').getAttribute('price')+'/ooak',
							{onCreate:function() {myBasket.empty()} ,onSuccess:function(response){updateBasketNumber(response.responseJSON)} });
                });
        }
});
function updateBasketNumber(json) {
	myBasket.render(json.items,json.added);
	$('basket-count').innerHTML = "("+ json.itemCount +")";//(json.itemCount);
};

var BasketViewer = Class.create({
		initialize: function() {

		},
		empty:function(){
			this.curtain = document.createElement('div');
			this.curtain.className = "curtain";
			this.curtain.id = "curtain";
			document.body.appendChild(this.curtain);
		},
		render:function(basketJson,added){
			this.basket = document.createElement('div');
			this.basket.className = "basket";
			this.basket.style.left = ($('curtain').getWidth() - 600 ) / 2 + "px";
			$('curtain').appendChild(this.basket);
			var total = 0;
			var content = "<h3>My Basket</h3>" +
			"<table width='100%' cellspacing=4 cellpadding=3><tr><th>Description</th><th width='20%'>Quantity</th><th>Price</th></tr>";
			for(var i=0 ; i < basketJson.length ; i++) {
				content += "<tr><td><b>"+basketJson[i].name+"</b></td><td align=right>"+basketJson[i].quantity+"</td><td  align=right>&#8364;"+(basketJson[i].price * basketJson[i].quantity)+"</td></tr>";
				total += basketJson[i].price * basketJson[i].quantity;
			}
			content += "<tr><td colspan=3 >&nbsp;</td></tr>";
			content += "<tr><td colspan=2 align=left><b>Estimated Total (Shipping not included)</b> </td><td  align=right>&#8364;"+total+"</td></tr>";
			content += "<tr><td colspan=3 >&nbsp;</td></tr>";
			content += "<tr><td colspan=3 align=right><input type='button' onclick='window.location.href=\""+BASE_URL+"basket\"' value='Open My Basket'> <input type='button' onclick='myBasket.close()' value='Close'></td></tr>";
			
			content += "</table>";
			this.basket.innerHTML = content;
			if(!added) {
				alert("This item is unique and can only be added once to your basket !");
			}
		},
		close: function() {
			this.curtain.remove();
		}
		
});
var myBasket = new BasketViewer();

