/**
 * Pod1 Catalog
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 *
 * @category   Pod1
 * @package    Pod1_Catalog
 * @copyright  Copyright (c) 2009 Pod1 (http://www.pod1.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

if(typeof PodCatalog == 'undefined') {
    var PodCatalog = {};
}

/**************************** Configurabale Options **************************/
PodCatalog.ConfigOptions = Class.create();
PodCatalog.ConfigOptions.prototype = {

	initialize: function(template, uppercase) {
		this.template 	= new Template(template);
		this.uppercase 	= uppercase;
		$$('.super-attribute-select').each(this.initAttribute.bind(this));
    },
    
    initAttribute: function(attribute) {
		this.setLabel(attribute);
		$(attribute).observe('change', this.optionChange.bindAsEventListener(this));
    },
    
    optionChange: function(event) {
    	$$('.super-attribute-select').each(this.setLabel.bind(this));
    },
    
    setLabel: function(attribute) {
    	var option = attribute.options[0];
    	if($(option)) {
    		var attributeId	= attribute.identify().replace('attribute', '');
    		var label		= $('label'+attributeId);
    		if(label) {
    			var template = this.template.evaluate({label: label.innerHTML}).stripTags();
    			$(option).update((true === this.uppercase ? template.toUpperCase() : template));
    			if($(label).visible()) {
    				$(label).hide();
    			}
    		}
    	}
    }
}

/**************************** Catalog Media **************************/
PodCatalog.Media = Class.create(PodCore, {
	
	initialize: function() {
		this.loadEvent	= 'media:load';
		this.loader 	= new Element('p', {className: 'loader'});
		this.loader.update('Loading').hide();
	},
	
	showLoader: function(event) {
		if(this.loader) { this.loader.show() }
	},
	
	hideLoader: function(event) {
		if(this.loader) { this.loader.hide() }
	},
	
	removeLoader: function(event) {
		if(this.loader) { this.loader.remove() }
	}
});

/**************************** Catalog Thumbnail Gallery **************************/
PodCatalog.ThumbnailGallery = Class.create(PodCatalog.Media, {

	initialize: function($super, image, thumb, preview) {
		$super();
		this.image 		= $(image);
		this.preview 	= $(preview);
		this.thumbs		= $$('.'+thumb);
		this.image.up().insert({before: this.loader});
		this.loaderHandler 	= this.hideLoader.bindAsEventListener(this);
		this.thumbHandler	= this.load.bindAsEventListener(this);
		this.zoomHandler	= this.resetZoom.bindAsEventListener(this);
		this.showHandler	= this.show.bindAsEventListener(this);
		if(this.thumbs) {
			this.thumbs.each(this.addThumb.bind(this));
		}
		Event.observe(this.image, 'load', this.loaderHandler);
		Event.observe(this.image, 'load', this.zoomHandler);
		Event.observe(this.image, 'load', this.showHandler);
		this.addToGarbage(this, 'thumb-gallery', 'media');
		this.image.show();
    },
  	
    addThumb: function(thumb) {
    	if($(thumb)) {
			Event.observe($(thumb), 'click', this.thumbHandler);
		}
    },
       
    load: function(event) {
    	event.stop();
		var element = Event.findElement(event, 'a');
		if(element && this.image.src != element.href) {
			this.showLoader(null);
			this.image.hide();
			this.image.src = element.href;
			if(this.preview) {
				var container = element.next();
				if(container && container.hasClassName('preview')) {
					this.preview.src = container.href;
				}
			}
		}
    },
    
    show: function(event) {
    	this.image.show();
    },
    
    resetZoom: function() {
		if(typeof(product_zoom) != 'undefined' && product_zoom.imageEl == this.image) {
			product_zoom.scale(0);
			product_zoom.slider.value = 0;
			product_zoom.slider.setValue(0);
		}
    },
    
    // Cleanup
	destroy: function($super) {
  		$super();
  		Event.stopObserving(this.image, 'load', this.loaderHandler);
  		Event.stopObserving(this.image, 'load', this.zoomHandler);
  		Event.stopObserving(this.image, 'load', this.showHandler);
  		Event.stopObserving(this.image, 'load', this.loadHandler);
  		if(this.thumbs) {
			this.thumbs.each(function(thumb) {
				Event.stopObserving(thumb, 'click', this.thumbHandler);
			});
		}
  	}
});

/**************************** Catalog Options Gallery **************************/
PodCatalog.OptionGallery = Class.create(PodCatalog.Media, {

	initialize: function($super, product, container, url, allowed, evalWindowLoad) {
		$super();
		this.product		= product;
		this.url 			= url;
		this.container 		= $(container);
		this.allowed		= allowed;
		this.evalWindowLoad = evalWindowLoad;
		this.zoomHandler	= this.initZoom.bindAsEventListener(this);
		this.attributes		= [];
		this.container.insert({before: this.loader});
		if($$('.super-attribute-select')) {
			$$('.super-attribute-select').each(this.addAttribute.bind(this));
		}
	},
	
	// We need to destroy the draggable object inside the product
	// zoom instance. For now we have this hard coded instance
	// name which is used in the default Magento theme. It would
	// be nice to pull this dynamically to eliminate this dependency
	getZoom: function() {
		return typeof product_zoom !== 'undefined' ? product_zoom : false;
	},
	
	getZoomImage: function() {
		if(!this.image) {
			this.image = 'image';
			if(this.getZoom()) {
				this.image = this.getZoom().imageEl.identify();
			}
		}
		return this.image;
	},
	
	addAttribute: function(attribute) {
		if($(attribute) && this.isAllowed(attribute)) {
			$(attribute).observe('change', this.load.bindAsEventListener(this));
			this.attributes.push($(attribute));
		}
    },
    
    isAllowed: function(attribute) {
    	if($(attribute)) {
    		var id = $(attribute).identify().replace('attribute', '');
    		for(var i=0; i<this.allowed.length; i++) {
    			if(id==this.allowed[i]) {
    				return true;
    			}
    		}
    	}
    	return false;
    },
    
    display: function(transport) {
    	if(transport.responseText){
    		if(this.getZoom() && this.getZoom().draggable) {
				this.addToGarbage(this.getZoom().draggable, 'zoom-draggable', 'media');
			}
    		this.cleanGarbage('media');
    		var output = transport.responseText;
    		if(true === this.evalWindowLoad) {
    			output = this.evalWindowLoadScripts(output);
    		}
    		this.container.innerHTML = output;
    		Event.observe($(this.getZoomImage()), 'load', this.zoomHandler);
    	}
    },
    
    initZoom: function(event) {
    	Event.stopObserving(Event.element(event), 'load', this.zoomHandler);
    	Event.fire(this.container, this.loadEvent, null, false);
    },
    
    getVariation: function() {
    	var variation = {};
    	for(var i=0; i<this.attributes.length; i++) {
    		var attribute = this.attributes[i];
    		if(attribute && attribute.value) {
    			var id 		= attribute.identify().replace('attribute', '');
				var value 	= attribute.value;
				if(id && value) {
					variation[id] = value;
				}
    		}
    	}
    	return variation;
    },
 
    load: function(event) {
		var element = Event.element(event);
		if(this.product){
			var aRequest = new Ajax.Request(this.url, {
		   		method: 		'post',
		   		evalJS:			false,
				parameters: 	{isAjax: 1, variation: Object.toJSON(this.getVariation()), product: this.product},
				onCreate: 		this.showLoader.bindAsEventListener(this),
	  			onComplete: 	this.hideLoader.bindAsEventListener(this),
	  			onSuccess:		this.display.bindAsEventListener(this),
	  			on403: 			this.redirect.bindAsEventListener(this)
			});
		}
    }
});


/**************************** DYNAMIC CART **************************/
PodCatalog.DynamicCart = Class.create(PodCatalog.Media, {

	initialize: function($super, container, bag) {
		$super();
    	this.container 	= $$(container)[0];
    	this.bag		= bag;
    	this.loader.removeClassName('loader').addClassName('cart-loader');
    	this.content = new Element('div', {id: 'dynamic-cart'});
    	this.container.insert({top: this.content});
    	this.content.insert({before: this.loader});
    },
    
    getForm: function(form) {
    	if('string' == typeof(form)) {
    		form = new VarienForm(form);
    	}
    	return form;
    },
        
    addForm: function(form, url) {
    	form.submit = this.add.bind(this, this.getForm(form), url);
    },
    
    add: function(form, url) {
		if(this.content) {
			form = this.getForm(form);
			if(!form.validator.validate()) {
				return;
			}
			var aRequest = new Ajax.Request(url, {
		   		method: 		'post',
				parameters: 	Form.serialize(form.form.identify()),
				onCreate: 		this.showLoader.bindAsEventListener(this),
	  			onComplete: 	this.hideLoader.bindAsEventListener(this),
	  			onSuccess:		this.display.bindAsEventListener(this),
	  			on403: 			this.redirect.bindAsEventListener(this)
			});
			this.content.hide();
		}
    },
    
    updateBag: function() {
    	if(this.bag) {
    		this.bag.update();
    	}
    	// If this is in an iFrame then we need to 
    	// update the bag in the parent object
    	else if(window.parent && typeof(window.parent.dynamicBag) !== 'undefined') {
    		window.parent.dynamicBag.update();
    	}
    },
    
    display: function(transport) {
    	if(transport.responseText){
    		this.content.update(transport.responseText)
    		this.content.blindDown({duration: 0.5});
    		this.updateBag();
    	}
    }
});


/**************************** DYNAMIC BAG **************************/
PodCatalog.DynamicBag = Class.create(PodCatalog.Media, {

	initialize: function($super, bag, template, url) {
		$super();
    	this.bag		= $$(bag)[0];
    	this.template  	= template;
    	this.url		= url;
    },
    
	update: function() {
		if(this.bag) {
    		var aRequest = new Ajax.Request(this.url, {
		   		method: 	'post',
	  			onSuccess:	this.display.bindAsEventListener(this)
			});
    	}
    },
    
    display: function(transport) {
    	var response 		= this.evalTransport(transport);
    	this.bag.innerHTML 	= this.template.evaluate({count: response.count});
    }
});

/**************************** Product Videos **************************/
PodCatalog.Video = Class.create();
PodCatalog.Video.prototype = {
	initialize: function(template, mainimage, videoContainer, galleryItem, templateParams, autoPlay, zoomContainer, videoImage, button) {
		this.template = template;
		this.videoImageUrl = videoImage;
		this.gallerySelector = galleryItem;
		this.galleryItems = $$(this.gallerySelector);
		this.templateArgs = templateParams;
		this.videoContainer = videoContainer;
		this.button = $(button);
		this.mainImage = $(mainimage);
		this.zoom = $$(zoomContainer).first();
		this.createFlashEventHandler = this.createFlashEvent.bind(this);
		if(this.button){
			this.button.observe('click', this.createFlashEventHandler);
		}
		this.galleryItems.each(this.setupGalleryThumbnails.bind(this));
		this.defaultTemplateArgs();
		if(autoPlay && this.videoItem){
			if(this.mainImage.complete){
				this.createFlash(element);
			} else {
				this.mainImage.observe('load', this.createFlashEventHandler);
			}
		}
	},
	defaultTemplateArgs: function() {
	    if(!this.templateArgs.width){
	      //  this.templateArgs.width = this.mainImage.getWidth();
		    this.templateArgs.width = '420px';
	    }
	    if(!this.templateArgs.height){
	      //  this.templateArgs.height = this.mainImage.getHeight();
		  	this.templateArgs.height = '600px';
	    }
	},
	setupGalleryThumbnails: function(element) {
		element.stopObserving('click');
		if(element.href == this.videoImageUrl && !this.button){
			this.videoItem = element;
			element.observe('click', this.createFlashEvent.bind(this));
		} else {
			element.observe('click', this.galleryImage.bind(this));
		}
	},
	createFlashEvent: function(event) {
		event.stop();
		this.createFlash(event.findElement(this.gallerySelector));
		this.hideZoom();
	},
	createFlash: function(element) {
		if(element != this.videoItem){
			element = this.videoItem;
			this.mainImage.stopObserving('load', this.createFlashEventHandler);
		}
		if(!this.button){
			this.mainImage.src = element.href;
		}
		this.removeVideo();
		this.evaluatedTemplate = this.template.evaluate(this.templateArgs);
		this.mainImage.hide();
		this.mainImage.insert({before:this.evaluatedTemplate});
	},
	galleryImage: function(event) {
		event.stop();
		console.log(this);
		this.removeVideo();
		this.mainImage.show();
		this.mainImage.src = event.findElement(this.gallerySelector).href;
		this.showZoom();
	},
	removeVideo: function() {
		if($(this.videoContainer))
		{
			$(this.videoContainer).remove();
		}
	},
	showZoom: function(){
		if(this.zoom){
			this.zoom.show();
		}
	},
	hideZoom: function(){
		if(this.zoom){
			this.zoom.hide();
		}
	}
}
