if (typeof trolleycards == "undefined" || !trolleycards) {
    var trolleycards = {};
}

Event.observe(window, 'load', function() {
	productModal = new trolleycards.product();
	$$('.product-name a, a.product-image').each(function(i) {
		i.observe('click', productModal.showWindow.bindAsEventListener(productModal, i));
		i.href = 'javascript:;';
	});
});
		
document.observe('lightview:opened', function(event) {
	var artistModalLink = $('product-modal-artist');
	if (artistModalLink) {
		artistModalLink.observe('click',
			artistModal.showWindow.bindAsEventListener(artistModal, $('product-modal-artist'))
		);
	}
});

document.observe('lightview:hidden', function(event) {
	var artistModalLink = $('product-modal-artist');
	if (artistModalLink) {
		artistModalLink.stopObserving('click');
	}
	screenManager.restorePageTitle();
	$$('.lv_Loading').invoke('show'); // http://www.nickstakenburg.com/forum/comments.php?DiscussionID=1423/
});

trolleycards.product = Class.create({	
	initialize: function() {
		this.template = $('product-modal').innerHTML;
		this.zoomedIn = false;
		this.draggable = null;
		this.currProductId = null;
		
		document.observe('lightview:opened', this.onOpen.bindAsEventListener(this));
		document.observe('lightview:hidden', this.onClose.bindAsEventListener(this));
	},
	
	onOpen: function () {
		if($('product-modal').visible()) {
			this.zoomOut();
		}
	},
	
	onClose: function () {
		var artistModalLink = $('product-modal-artist');
		if (artistModalLink) {
			artistModalLink.stopObserving('click');
		}
	},
	
	resetWindow: function () {
		if($('product-modal').visible()) {
			$('product-modal').hide();
			screenManager.restorePageTitle();
		}
	},
	
	showWindow: function () {
		var elem = $A(arguments)[1];
		this.currProductId = isNaN(elem) ? elem.getAttribute('product') : elem;		
		var product = productData[this.currProductId];
		
		//if there is no data for the product, bail now
		if(product == undefined) { 
			Lightview.hide();
			return;	
		} else {
			this.resetWindow();
		}
		
		//create template to replace data
		var html = new Template(this.template).evaluate(product);
		$('product-modal').update(html);
		
		//manually replace link
		$('product-modal-link').href = product.url;
		$('product-modal-artist').setAttribute('artist', product.artist_id);
		
		//manually replace small images
		var imgs = $$('#product-modal .modal-gallery .small img');
		var types = new Array('image', 'image_message', 'image_giftcard', 'image_envelope');
		for(var i=0; i<4; i++) {
			imgs[i].src = eval('product.' + types[i] + '.thumbnail');
			imgs[i].observe('click', this.swapImage.bindAsEventListener(this, imgs[i]));
		}
		
		//manaully replace large image
		var imgLg = $('product-modal-image');
		imgLg.src = product.image.large;
		imgLg.className = 'image';
		
		//set up zoom control button
		var zoom = $$('#product-modal .modal-gallery .zoom')[0];
		zoom.stopObserving('click');
		zoom.observe('click', this.zoomToggle.bindAsEventListener(this));
		
		//next and previous buttons
		var ids = this.getNextPrevious(this.currProductId);		
		$('product-modal-previous').stopObserving('click').observe('click', this.showWindow.bindAsEventListener(this, ids[0]));
		$('product-modal-next').stopObserving('click').observe('click', this.showWindow.bindAsEventListener(this, ids[1]));
				
		screenManager.appendToPageTitle(product.name);
		screenManager.trackPageview(product.url.replace('.html', '.modal'));
		/**
		 * Adding a width & height here prevents an IE error.  Since autosize is true, these
		 * options are ignored anyway.
		 */
		Lightview.show({ href: 'product-modal', rel: 'inline', options: {autosize: true, width: 200, height: 200} });
	},
	
	swapImage: function() {
		$('product-modal-image').className = $A(arguments)[1].className;
		this.zoomOut();
	},
	
	zoomOut: function() {
		var imgLg = $('product-modal-image');
		var zoom = $$('#product-modal .modal-gallery .zoom')[0];
		zoom.style.backgroundPosition = '0px 0px';
		if(this.draggable) this.draggable.destroy();
		
		imgLg.src = productData[this.currProductId][imgLg.className]['large'];
		imgLg.style.cursor = 'auto';
		imgLg.style.left = 0;
		imgLg.style.top = 0;
		
		this.zoomedIn = false;
	},
	
	zoomIn: function() {
		var imgLg = $('product-modal-image');
		var zoom = $$('#product-modal .modal-gallery .zoom')[0];

		imgLg.src = productData[this.currProductId][imgLg.className]['full'];

		var panelWidth = 345;
		var panelHeight = 345;
		var imgWidth=900;
		var imgHeight=900;
		var left = (imgWidth-panelWidth)/2;
		var top = (imgHeight-panelHeight)/2;

		imgLg.setStyle({left: "-"+left+"px", top: "-"+top+"px"});
		imgLg.style.cursor = 'move';		
		zoom.style.backgroundPosition = '0px -15px';
		
		this.draggable = new Draggable(imgLg, {
            starteffect:false,
            reverteffect:false,
            endeffect:false,
            snap:this.contain.bind(this)
        });
		
		this.zoomedIn = true;
	},
	
	zoomToggle: function() {
		this.zoomedIn ? this.zoomOut() : this.zoomIn();
	},

    contain: function (x,y,draggable) {
		var imgLg = $('product-modal-image');
        var dim = Element.getDimensions(draggable.element);

        var xMin = 0, xMax = imgLg.parentNode.getWidth()-dim.width;
        var yMin = 0, yMax = imgLg.parentNode.getHeight()-dim.height;

        x = x>xMin ? xMin : x;
        x = x<xMax ? xMax : x;
        y = y>yMin ? yMin : y;
        y = y<yMax ? yMax : y;

        this.imageX = x;
        this.imageY = y;

        imgLg.style.left = this.imageX+'px';
        imgLg.style.top = this.imageY+'px';

        return [x,y];
    },
    
    getNextPrevious: function(current) {
    	var next, previous, first, last, found;
		for(var i in productData) {
			if(!first) first = i;
			if(found && !next) next = i;
			if(current == i) found = true;
			if(!found) previous = i;
			last = i;
		}
		if(!next) next = first;
		if(!previous) previous = last;
		return [previous, next];
    }
	
});