/**
 * Nestle Professional Notepad
 * Using XML source, allow dragging and dropping of products into virtual notepad.
 * Developed by David Shanley <david.shanley@europe.mccann.com>
 *  
 *  depends on mootools.
 * @author David Shanley
 */
var Notepad = {
	init: function() {
		this.products = new Array();
		this.notepadDrop = $('notepad');
		
		
		this.firstdrop = true; 
		
		/* add event to notepad download button */
		var submitPDF = this.submitToPDFGenerator.bind(this);
		$('notepadbottom').addEvent('click',submitPDF);
	},
	enableProducts: function() {
		
		this.fxobj = new Fx.Tween($('notepad'));
		
		/* bind notepad function */
		var addProductToPad = this.addProductToPad.bind(this);
		var fxobj = this.fxobj;
		
		$$('.productthumb_bar_drag').each(function(item){
			
 			/* for every thumbnail add an event */
			item.addEvent('mousedown', function(e) {
				e = new Event(e).stop();
				/* get the id of the product */
				var prodId = this.getAttribute('productthumb_bar_drag_id');
 				var productImage = this.getParent().getParent().getChildren('img');
			
				/* clone the dragger */	
				var cloneDrag = this.clone()
					.setStyles(this.getCoordinates()) // this returns an object with left/top/bottom/right, so its perfect
					.setStyles({'opacity': 0.8, 'position': 'absolute'})
					.addClass('productthumb_bar_dragger');
					cloneDrag.set('text','Please drag');
					cloneDrag.inject(document.body);
				
				/* clone the image */
				var cloneImage = productImage.clone()
					.setStyles({ 'top': this.getCoordinates().top + 20, 'left': this.getCoordinates().left, 'border': '2px dotted #7c141d'}) // this returns an object with left/top/bottom/right, so its perfect
					.setStyles({'opacity': 0.8, 'position': 'absolute'});
					cloneImage.setProperty('name',productImage.getProperty('id'));
					cloneImage.inject(document.body);
				
				
				var droppables = new Array();
				droppables[0] = $('notepad');
				droppables[1] = '.droppable';
				
				/* initialize the dragger */
				var drag = new Drag.Move(cloneDrag, {
					droppables: '.droppable',
					snap: 0,
					onDrag: function() {
						/* move the image every step... make it look like it's fluid */
						cloneImage.setStyles({ 'top': cloneDrag.getCoordinates().top +20, 'left': cloneDrag.getCoordinates().left, 'border': '2px dotted #7c141d' })
					},
					onEnter: function() {
						fxobj.set('background-color','#801624');
					},
					onLeave: function() {
						fxobj.start('background-color','#f4f1ea');
					},
					onDrop: function(element, droppable){
       					if (!droppable) {
							//Products.loadProduct(clone.getAttribute('prod_id'));
        					/* remove from the DOM */
							cloneImage.dispose();
							cloneDrag.dispose();
							fxobj.start('background-color','#f4f1ea');
						
						} else{ 
					 		addProductToPad(cloneImage.clone());
							fxobj.start('background-color','#f4f1ea');
							cloneImage.dispose();
							cloneDrag.dispose();
						}
    				},
					onComplete: function() {
						fxobj.start('background-color','#f4f1ea');
					}
				}); // this returns the dragged element
 				
 				drag.start(e); // start the event manual
				
			});
 	
		});
	},
	addProductToPad: function(product) {
		
		/* add products to pad */
		this.products[this.products.length] = product;
		
		/* empty the notepad if its the first drop */
		if(this.firstdrop == true) {
			this.notepadDrop.empty();
			this.firstdrop = false;
		}
		
		var prodName =  product.getProperty('name');
		prodName = prodName.toString().trim();
		
		/* add product into the notepad */
		var holdingBox = new Element('div',{ 'class': 'holdingbox'});
		var holdingText = new Element('textarea',{ 'class': 'holdingtext','name' : prodName});
		var holdingTitle = new Element('p', { 'class': 'holdingtitle'});
		var removeLink = new Element('span',{ 'class':'notepad_remove' });
		removeLink.set('text','remove from notepad');
		var removeProduct = this.removeProductFromNotepad.bind(this);
		removeLink.addEvent('click',function(){
			removeProduct(prodName);
		});
		
		//alert(product.getProperty('name'))
		/* create a new image */
		var productImage = new Element('img', { 'src' : product.getProperty('src'), 'alt' : product.getProperty('alt'),'name' : prodName, 'class':'prodImg'});
		productImage.addClass('droppable');
		productImage.injectInside(holdingBox);
		holdingTitle.set('text', product.getProperty('alt'));
		holdingText.set('text','Add some notes about your product....');
		holdingBox.injectInside(this.notepadDrop);
		holdingTitle.injectInside(this.notepadDrop);
		holdingText.injectInside(this.notepadDrop);
		removeLink.injectInside(this.notepadDrop);
			
		
	},
	
	removeProductFromNotepad: function(id) {
			
		var products = this.notepadDrop.getElements('img');
		var notes = this.notepadDrop.getElements('textarea');
		var box = this.notepadDrop.getElements('div');
		var para = this.notepadDrop.getElements('p');
		var remove = this.notepadDrop.getElements('span');
		
		for (var x = 0; x < products.length; x++) {
			var pid = products[x].getProperty('name');
			if(pid == id) {
				/* remove */
				products[x].dispose();
				notes[x].dispose();
				box[x].dispose();
				para[x].dispose();
				remove[x].dispose();
			}
		}
		
			
		
	},
	
	submitToPDFGenerator: function() {
		var notes ="";
		var dataArray = new Array();
		
		var products = this.notepadDrop.getElements('img');
		var notes = this.notepadDrop.getElements('textarea');
		
		/* loop through the elements and build objects */
		for(var x = 0; x < products.length; x++) {
			var id = products[x].getProperty('name');
			id = id.clean().substring(8); // strip off the 'product_'
			var notesData = notes[x].value;
			var product = {
							'id': parseInt(id),
							'notes' : notesData.clean()
						  };
			dataArray[dataArray.length] = product;
			
		}
		
		var productArray = new Array();
		
		var productObj = { 'products' : dataArray};
		
		/* prepare array as JSON string */
		var formPayload = JSON.encode(productObj);
		
		/* AJAX won't work here, so we need to create a form... and submit it! */
		var form = new Element('form', { 'method' : 'post', 'action' : '/npro/pdfgen.go'});
		var hidden = new Element('input', { 'type' : 'hidden', 'name' : 'products', 'id' : 'products', 'value' : formPayload });
		hidden.injectInside(form);
		form.injectInside(document.body);
		form.submit();
		
		/* send the form! */
		//	var pdfRequest = new Request({url: 'http://localhost:8000/npro/pdfgen',method: 'post'}).send("products="+formPayload);
		
	}
}
