/* BOURNE */

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}

function buildElement(type,html_attributes,classes,contents) {
	// Build an HTML element with attributes
	new_element = document.createElement(type);
	if (typeof(html_attributes) != 'undefined') {
		$H(html_attributes).each(function(el) {
				new_element.setAttribute(el.key,el.value);
		});
	}
	if (classes && typeof(classes) != 'undefined') {
		$A(classes).each(function(theclass) {new_element.className = new_element.className + ' '+theclass; });
		new_element.className = new_element.className.trim();
	}
	switch (typeof(contents)) {
		case 'string': new_element.appendChild(document.createTextNode(contents)); break;
		case 'undefined': break;
		default: new_element.appendChild(contents);
	}

	return $(new_element);
}

var BourneApp = {
	init: function() {
		$$('.lola-button').each(function(el) {
			BourneApp.capThis(el);
		});
	},
	capThis : function(el) {
		var temp;
		if (el.tagName == 'INPUT') {
			var classes = el.className;
			classes = classes.split(' ') || [];
			var newa = buildElement('a',{'href':'#'},classes);
			var newspan = buildElement('span',{},[],el.value || el.title);
			newa.appendChild(newspan);
			var ref = el.parentNode.insertBefore(newa,el);
			ref.observe('click',function(e) {el.click(e); e.stop();});
			
			el.style.display = 'none';
		} else {
			if (el.getElementsByTagName('span').length == 0) {
				temp = el.innerHTML;
				el.innerHTML = '';
				span = document.createElement('span');
				span.innerHTML = temp;
				el.appendChild(span);
			}
		}
	}
}

document.observe('dom:loaded',function() { BourneApp.init(); });

var StoneFilter = {
    'more' : null,
    'less' : null,
    'init': function() {
	// If there is a stones list. And it's got more than 5 items then hide all but 5 and 
	// Make a More link.
	var stones = $$('#filter-stones ol li');
	if ( stones.length > 9 ) {
	    stones.each( function( s, i ) { s.rev = i >= 5 ? true : false; if ( i >= 5 ) { $(s).setStyle( { 'display' : 'none' } ) } } );
	    StoneFilter.more = Builder.node( 'div', { 'class' : 'more-link' }, 'More Stones' );
	    StoneFilter.less = Builder.node( 'div', { 'class' : 'more-link', 'style' : 'display:none' }, 'Less Stones' );
	    $('filter-stones').appendChild( StoneFilter.more );
	    $('filter-stones').appendChild( StoneFilter.less );
	    $(StoneFilter.more).observe( 'click', StoneFilter.revealStones );
	    $(StoneFilter.less).observe( 'click', StoneFilter.hideStones );
	}
    },
    'revealStones' : function() { 
	Effect.Queues.get('stones').invoke('cancel');
	$$('#filter-stones ol li').each( function(s) { 
		if ( s.rev ) { Effect.BlindDown( s, { 'queue' : { 'position': 'end', 'scope' : 'stones' }, 'duration' : 0.05 } ) } } 
	    );
	Effect.Fade( StoneFilter.more, { 'queue' : { 'position' : 'front', 'scope': 'stones' }, 'duration' : 0.5 } );
	Effect.Appear( StoneFilter.less, { 'queue' : { 'position' : 'end', 'scope': 'stones' }, 'duration' : 0.5 } );
    },
    'hideStones' : function() { 
	Effect.Queues.get('stones').invoke('cancel');
	$$('#filter-stones ol li').each( function(s) { 
		if ( s.rev ) { Effect.BlindUp( s, { 'queue' : { 'position': 'front', 'scope' : 'stones' }, 'duration' : 0.05 } ) } } 
	    );
	Effect.Fade( StoneFilter.less, { 'queue' : { 'position' : 'front', 'scope': 'stones' }, 'duration' : 0.5 } );
	Effect.Appear( StoneFilter.more, { 'queue' : { 'position' : 'end', 'scope': 'stones' }, 'duration' : 0.5 } );
    }   
   
   };

document.observe('dom:loaded', StoneFilter.init );

$j(function() {
	$j('input#newsletter').focus(function() {
		if($j(this).val() == 'Enter email address') {
			$j(this).val('');
		}
	});
	
	$j('input#newsletter').blur(function() {
		if($j(this).val() == '') {
			$j(this).val('Enter email address');
		}
	});

});

$j(function() {
    
	$j('input#search').focus(function() {
		if($j(this).val() == 'i\'m looking for...') {
			$j(this).val('');
		}
	});
	
	$j('input#search').blur(function() {
		if($j(this).val() == '') {
			$j(this).val('i\'m looking for...');
		}
	});

});

$j(function() {
    
	$j('input#coupon_code').focus(function() {
		if($j(this).val() == 'Enter promotional code') {
			$j(this).val('');
		}
	});
	
	$j('input#coupon_code').blur(function() {
		if($j(this).val() == '') {
			$j(this).val('Enter promotional code');
		}
	});
	
	$j('input#giftcard_code').focus(function() {
		if($j(this).val() == 'Enter gift voucher code') {
			$j(this).val('');
		}
	});
	
	$j('input#giftcard_code').blur(function() {
		if($j(this).val() == '') {
			$j(this).val('Enter gift voucher code');
		}
	});

});


var CheckoutDrop = {
    isOpen: false,
    div: null,
    lnk: null,
    count:0,
    show_cart:false,
    
    init: function() {
	// Checkout disabled
	if ( $('inline-basket')) {
	    this.lnk = $('inline-basket');
	    this.lnk.observe('mouseover',this.show.bind(this));
	    document.observe('click',this.hide.bind(this));
	    this.insert();
	}
	if ( $('product_addtocart_form') ) {
	    // Override the standard add to cart form to post to an AJAX one.
	    this.form = $('product_addtocart_form');
	    this.form.submit = function(t) { return function() { t.addCart(); } }(this); 
	    this.form.observe('submit',function(e){ Event.stop(e); return false; });
	    $('product_addtocart_form').select('input[type=submit]').each( function(t){ t.observe( 'click',function(e){ Event.stop(e); return false; } ) } );
	}
    },
    addCart: function() {
	var url = this.form.action.replace( /checkout/, 'ajax' );
	new Effect.ScrollTo( 'header' );
	this.message( 'Putting in Bag' );
	this.show( null, true );
	new Ajax.Request( url, { 
		    onSuccess : this.updated.bind(this), 
		    parameters : this.form.serialize(),
		    method : 'post'
		    });
    },
    insert: function() {
	this.div = buildElement('div',{'id':'checkout-popup'});
	this.div = $$('.page')[0].appendChild(this.div);
	this.message( 'Loading' );
	this.update();
    },
    update: function() {
	new Ajax.Request('/ajax/cart',{onSuccess:this.load.bind(this)});
    },
    makeCart: function(data) {
	this.div.innerHTML = '';

	this.count = data.itemCount; 
	var table = Builder.node('tbody');

	for ( var i = 0; i < data.items.length; i++ ) {
	    var item = data.items[i];
	    
	    var row = Builder.node('tr',{ 'className' : item.is_giftwrap ? 'giftWrap' : 'normal' },
				   [
				    Builder.node('td',{'className': 'cpopup-img', 'rowspan' : '2'},
						 [
						  Builder.node('img',{'src':item.imgUrl})
						  ])
				    ]);
	
	    row.insert(Builder.node('td').insert(item.name));
	    row.insert(Builder.node('td',{'className':'cpopup-price'}).insert(item.price));
	    table.insert(row);

	    item.options.push( 'Qty: ' + item.qty );
	    var str =  item.options.join( '<br/>' );
	    	
	    var cell = Builder.node( 'td', { 'colspan' : '2' } );
	    cell.innerHTML = str; 
	    table.insert( Builder.node( 'tr', { 'className' : 'details ' + (  item.is_giftwrap ? 'giftWrap' : 'normal' ) }, cell ) );
	}
	
	this.div.className = data.loggedIn ? 'logged-in' : '';
	this.div.insert( Builder.node( 'div', { 'className':'cpopup-header'}, 
			  Builder.node( 'div', {}, [ 
						    Builder.node( 'a', { 'href' : '/checkout/cart' }, [ 'Shopping Bag ', Builder.node( 'span', {}, [
									     Builder.node( 'span', { 'className' : 'text-button' }, [ '(' + this.count + ')' ] )
									     ,  ' item' + ( this.count != 1 ? 's' : '' ) ] ) ] ) ] ) ) );

	this.div.insert(
			Builder.node('div',{'className':'checkout-popup-section'},Builder.node('table',{},[table]))
			);
	    
	var rows = [];

	if ( data.hasDiscount || ( data.shipping && this.count > 1 ) ) {
	    rows.push( Builder.node('tr',{},
				    [
				     Builder.node('th',{},['Sub Total']),
				     Builder.node('td',{'className':'cpopup-price'}).insert(data.subTotal)
				     ]) );
	}
	if ( data.hasDiscount ) {
	    rows.push( Builder.node('tr',{},
				    [
				     Builder.node('th',{},['Discount']),
				     Builder.node('td',{'className':'cpopup-price'}).insert(data.discount)
				     ]) );
	} 
	if ( data.shipping ) {
	    rows.push( Builder.node('tr',{},
				    [
				     Builder.node('th',{},['Shipping']),
				     Builder.node('td',{'className':'cpopup-price'}).insert(data.shipping)
				     ]) );
	}

	rows.push (  Builder.node('tr',{'className':'checkout-popup-total'},
				  [
				   Builder.node('th',{},['Total']),
				   Builder.node('td',{'className':'cpopup-price'}).insert(data.total)
				   ]));

	this.div.insert( Builder.node('div',{'className':'checkout-popup-section checkout-popup-total-section'}, [
			  Builder.node('table',{},[ Builder.node('tbody',{}, rows ) ] ) ] ) );
	    
	    
	this.div.insert(Builder.node('div',{'id':'checkout-popup-buttons'},[
									    //Builder.node('a',{'href':'/checkout/cart','className':'lola-button'},['View Bag']),
									    Builder.node('a',{'href':'/checkout/cart','className':'lola-button popup-checkout-button'},['Go to my bag'])
									    ]));
	    
	$('checkout-popup-buttons').select('a').each(BourneApp.capThis);
	var test = this.div.innerHTML;
	this.div.innerHTML = test;
	this.oldCart = this.div.innerHTML;
    },

    message: function(message) {
	this.div.innerHTML = '';
	var counter = Builder.node( 'div',{}, '' );
	counter.innerHTML = $(this.lnk).innerHTML;
	this.div.insert( Builder.node( 'div', { 'className':'cpopup-header'}, [ counter ] ) );
	this.div.insert( Builder.node('div',{'class':'message'},[message]) );
    },

    updateLink : function() {
	$(this.lnk).innerHTML = '';
	$(this.lnk).insert( 'Shopping Bag ' );
	$(this.lnk).insert( Builder.node( 'span', {}, [
									  Builder.node( 'span', { 'className' : 'text-button' }, [ '(' + this.count + ')' ] )
									  ,  ' item' + ( this.count != 1 ? 's' : '' ) ] ) );
    },

    load : function(r) {
	var data = r.responseText.evalJSON();
	if (data.items == null || data.items.length == 0) {
	    this.count = 0;
	    this.message( 'Your shopping bag is empty' );
	    this.oldCart = this.div.innerHTML;
	} else {
	    this.makeCart(data);
	}
    },
    updateCart : function(r) {
	var data = r.responseText.evalJSON();
	this.makeCart(data);
	this.updateLink();
	setTimeout( function(t) { return function() { t.hide() } }(this), 2000 );
    },
    updated: function(r) {
	var data = r.responseText.evalJSON();
	if ( data.failed ) {
	    // Something failed.... need a message.
	    this.message( data.message );
	    setTimeout( function(t) { return function() { t.hide(true) } }(this), 2000 );
	} else {
	    new Ajax.Request('/ajax/cart/', {onSuccess:this.updateCart.bind(this)} );
	} 
    },
    show: function(e,message) {
	message = message ? message : false;
	if ( message || this.count > 0 ) {
	    if (this.div.style.display != 'block') {
		this.div.style.display = 'block';
		this.lnk.addClassName('basket-open');
		this.show_cart = true;
		setTimeout( function(t) { return function() { t.show_cart = false } }(this), 1000 );
	    }
	}
    },
    hide: function(revert) {
	if (this.div.style.display != 'none' && this.show_cart == false) {
	    func = revert  ? 
	              function() { this.div.innerHTML = this.oldCart; this.lnk.removeClassName('basket-open'); }.bind(this) : 
   	              function() { this.lnk.removeClassName('basket-open'); }.bind(this);
	    new Effect.Fade(this.div,{duration:0.3,afterFinish:func});
	}
    }
    
}

//document.observe('dom:loaded',function() { CheckoutDrop.init(); });
	


