var nav , click_clear , MiniBasket, selector, ios;

window.addEvent( 'domready' , function(){
    var mb;
	nav();
	click_clear();
	mb = new MiniBasket( document.getElement('#top_cart a') );
    selector();

    ios();
} );

ios = function(){
    if ( Browser.Platform.ios ) {
        document.getElements('.hideios').setStyle('display' , 'none');
        document.getElements('.showios').setStyle('display' , 'block');
    }
}

selector = function(){
    var switcher = document.getElement('#drop a.site-switch'),
    drop = document.getElements('#drop a.site-switch,#down'),
    down = document.id('down');

    drop.addEvents({
        'mouseenter' : function(){
            down.setStyle('display' , 'block');
            switcher.addClass('hover');
        },
        'mouseleave' : function(){
            down.setStyle('display' , 'none');
            switcher.removeClass('hover');
        }
    });
}

var MiniBasket = new Class({
	// elements
	poporder : undefined,
	minitotal : undefined,
	header : undefined,
	scrolls : undefined,
	ul : undefined,
	link : undefined,
	lis : [],
	// binds
	hide_bind : undefined,
	show_bind : undefined,

	currency : undefined,

	show_count : 2,

	status : '',

	initialize : function(link){
		this.poporder = document.id('pop_order');
		this.minitotal = this.poporder.getElement('div.mini_total p span');
		this.header = document.id('header');
		this.scrolls = this.poporder.getElements('div.scroll button');
		this.ul = this.poporder.getElement('ul');
		this.link = link;

		this.hide_bind = this.hide.bind( this );
		this.show_bind = this.show.bind(this);

		this.link.addEvent( 'click' , this.show_bind );
		// the below event is fired by the add-to-basket functionality, so we set a warning status
		this.poporder.addEvent('show' , ( function(){ this.status = 'Added to your order.'; this.show(); this.status = ''; } ).bind(this) );
		this.poporder.addEvent('hide' , ( function(){ this.hide(); } ).bind(this) );
		this.scrolls.addEvent( 'click' , this.scroll.bind(this) );
	},

	show : function(){
        if (Browser.ie && Browser.version <= 6) {
            document.getElements('select').setStyle('visibility' , 'hidden');
        }
		this.load_products();
		this.show_status();
		$(document.body).addEvent('click' , this.hide_bind);
		this.link.removeEvent('click' , this.show_bind);
		this.link.addEvent('click' , this.hide_bind);
		return false;
	},

	show_status : function(){
		var exist;
		exist = this.poporder.getElement('div.status');
		if ( exist ) exist.dispose();
		if ( this.status != '' ) this.poporder.grab( new Element('div').addClass('status').set('html' , '<p>'+ this.status +'</p>') , 'top' );
	},

	hide : function(event){
        document.getElements('select').setStyle('visibility' , 'visible');
		this.link.removeEvent('click' , this.hide_bind);
		this.link.addEvent('click' , this.show_bind);
		$(document.body).removeEvent('click' , this.hide_bind);
		this.poporder.setStyle('display' , 'none');
		this.unset_header();
		if ( event !== undefined && event.target.get !== undefined && event.target.get('tag') == 'span' ) return false;
	},

	scroll : function(event){
		event.stopPropagation();
		var hide,show,diff,first;
		if ( this.lis.length < this.show_count ) return false;
		if ( event.target.get('rel') == 'up' ) {
			hide = this.last_index();
			show = this.first_li() - 1;
			diff = 0;
			first = show;
		} else {
			hide = this.first_li();
			show = this.next_li();
			diff = 1;
			first = hide;
		}
		if ( first + this.show_count >= this.lis.length || first < 0 ) return false;
		if (this.lis[hide] != undefined) this.lis[hide].addClass('hidden');
		this.lis.each(function(e){e.getElement('div.mini_order').removeClass('last')});
		this.align_lis( first + diff );
		return false;
	},

	last_index : function(){
		var last;
		this.lis.each(function(e,i){
			if ( e.getElement('div.mini_order').hasClass('last') ) last = i;
		});
		return last;
	},

	first_li : function(){
		return this.last_index() - ( this.show_count - 1 );
	},

	next_li : function(){
		return index = this.last_index() + ( this.show_count - 1 );
	},

	hdim : undefined,
	tdim : undefined,

	set_header : function(){
		this.hdim = this.header.getSize();
		this.tdim = document.id('top_cart').getSize();
		this.header.addClass('pop');
		this.header.setStyles({
			'padding-right' : this.tdim.x,
			'width' : this.hdim.x - this.tdim.x
		});
	},

	unset_header : function(){
		this.header.removeClass('pop');
		this.header.setStyles({
			'padding-right' : 0,
			'width' : this.hdim.x
		});
	},

	load_products : function(){
		new Request.JSON({
			'url' : '/basket/load-products.json',
			'onFailure' : (function(x){
				window.location = '/basket';
			}).bind(this),
			'onSuccess' : this.update_basket.bind(this)
		}).send();
	},

	lis_dispose : function(){
		var old_lis;
		old_lis = this.ul.getElements('li');
		if ( old_lis.length > 0 ) {
			old_lis.each(function(e){
				e.dispose();
			});
		}
	},

	update_basket : function( json ){
		/**
		 * do actual first show here so that we don't get a blip when on HTTPS
		 */
		if ( this.poporder.getStyle('display') == 'none' ) {
			this.poporder.setStyle('display' , 'block');
			this.set_header();
		}
		this.lis_dispose();
		this.lis = [];
		this.currency = json.currency;
		json.products.each( this.add_product.bind(this) );
		this.update_totals( json );
		/**
		 * get the height of the first two li elements and make that the ul height, then add .last to the last of the two
		 */
		if ( this.lis.length == 0 ) {
			this.ul.grab( new Element('li').set('html' , '<p>Your basket is empty.</p>') );
			this.ul.setStyles({
				'opacity' : 1,
				'height' : 'auto'
			});
			return false;
		}
		if ( this.lis.length <= this.show_count ) {
			this.scrolls.each( function(e){ e.getParent().addClass('hidden') } );
		} else {
			this.scrolls.each( function(e){ e.getParent().removeClass('hidden') } );
		}
		this.align_lis(0);
		this.ul.set('tween' , {duration: 300}).tween('opacity' , 1);
	},

	align_lis : function(first_offset){
		var lis = this.lis.slice(first_offset,this.show_count + first_offset) , two_high = 0;
		if ( lis.length == 0 ) return false;
		lis.each(function(e){
			e.removeClass('hidden');
			two_high = two_high + e.getSize().y + 30; // + 30 for margin
		});
		lis.getLast().getElement('div.mini_order').addClass('last');
		this.ul.setStyle('height' , two_high - 16); // - 15 because .last has no bottom margin, - 1 because it has no bottom border
	},

	add_product : function( product , line ){
		var li,order,thumb,description,del,name;

		li = new Element('li');
		order = new Element('div').addClass('mini_order');
		thumb = new Element('div').addClass('mini_thumb');
		description = new Element('div').addClass('mini_description');
		del = new Element('div').addClass('mini_delete');

		name = product.size == '' ? product.name : product.name + ' (' + product.size + ')';

		thumb.grab(
			new Element('img' , {
				'src' : product.image,
				'alt' : product.name
			})
		);

		description.grab(
			new Element('p' , {
				'class' : 'price',
				'html' : this.currency + (parseFloat(product.salePrice) > 0 ? product.salePrice : product.price)
			})
		);

		description.grab(
			new Element('p' , {
				'class' : 'title',
				'html' : product.brand
			})
		);


		description.grab(
			new Element('p' , {
				'html' : name
			})
		);

		description.grab(
			new Element('p' , {
				'html' : 'Qty ' + product.qty
			})
		);

		del.grab( new Element('a').set('text', 'X').addEvent('click' , this.remove_product.bind( this , product.link_product_id )) );

		li.grab(order);
		order.grab(thumb);
		order.grab(description);
		order.grab(del);
		this.ul.grab(li);
		this.lis.include(li);
	},

	remove_product : function( id , event ){
		new Request.JSON({
			'url' : '/basket/remove.json/' + id,
			'onFailure' : (function(x){
				window.location = '/basket';
			}).bind(this),
			'onSuccess' : this.update_basket.bind(this)
		}).send();
		return false;
	},

	update_totals : function( json ){
		this.minitotal.set('text' , json.total);
		var bskt,qty;
		bskt = document.getElement('#header span.bskt');
		bskt.set('html' , json.currency + json.total);
		qty = document.getElement('#header span.quantity');
		qty.set('text' , '(' + json.qty.toString() + ')' );
	}
});

nav = function(){
	document.getElements('#menu li.top').addEvents({
		'mouseenter' : function(){
			var ul = this.getElement( '.wrapper' );
			if (ul) {
				ul.setStyle('display' , 'block').setStyle('z-index',9999).setStyle('position' , 'absolute');
				document.id('navigation').setStyles({
					'position' : 'relative',
					'z-index' : 9998
				});
                if ( !Browser.ie ) return true;
                document.id('main').getElements('select').each(function(e){
                    e.setStyle('opacity' , 0);
                });
			}
		},

		'mouseleave' : function(){
			var ul = this.getElement( '.wrapper' );
			if (ul) {
                ul.setStyle('display' , 'none');
				document.id('navigation').setStyles({
					'z-index' : 1
				});
                if ( !Browser.ie ) return true;
                document.id('main').getElements('select').each(function(e){
                    e.setStyle('opacity' , 1);
                });
            }
		}
	});
}

click_clear = function(){
	var inputs;
	inputs = document.getElements( 'input.click-clear , textarea.click-clear' ).click_clear();
}

Element.implement({
	default_value : '',
	return_default_on : [''],

	click_clear : function(){
		this.default_value = this.get('value');
		this.return_default_on.push(this.default_value);

		this.addEvents({
			'blur' : this.check_return,
			'focus' : this.do_clear
		});
		return this;
	},

	check_return : function( e ){
		var return_default = false;
		this.return_default_on.each(function( e ){
			if ( this.get('value') == e ) return_default = true;
		} , this );
		if ( return_default == true ) this.set( 'value' , this.default_value );
	},

	do_clear : function( e ){
		this.set( 'value' , '' );
	}
});

