dojo.require("dojo.fx");
dojo.require("dojo.fx.easing");
var lupiui = {
    basketstate : 'hidden',
    basketContents : [],
    dirty : true,
    showBasket : function (){
        if (this.basketstate == 'hidden') {
            dojo.fx.wipeIn({
                node     : "basket",
                duration : 500,
                easing   : dojo.fx.easing.circOut
              }).play();
              lupiui.basketstate = 'showing';
              if (this.dirty) 
            	  this.refreshBasket();  
              
        } else {
            dojo.fx.wipeOut({
                node     : "basket",
                duration : 500,
                easing   : dojo.fx.easing.circOut
            }).play();
            this.basketstate = 'hidden';
        }
    },
    basketItem : function(item) {
    	if (lupiui.basketstate == 'hidden') {
    		//prevent double loading
	    	lupiui.showBasket();
    	}
    	this.dirty = true;
    	dojo.destroy('emptyMsg');
    	basket = dojo.byId('basketContents');
    	
    	var xhrArgs = {
    	    url          : '/store/basket-item?format=json',
    	    content      : {id : item},
	    	handleAs     : 'json',
	    	preventCache : true,
	    	load : function(response, ioArgs) {
    		    var newItem = response.item;
    		    if (dojo.byId('qty-item-' + escape(newItem.id))) {
    		    	dojo.byId('qty-item-' + escape(newItem.id)).innerHTML = newItem.quantity;
    		    	return;
    		    }
    		    		
	    		itemContainer = lupiui.getNewBasketItemNode(newItem);
	        	dojo.style(itemContainer, 'display', 'none');
	        	dojo.style(itemContainer, 'height', '0px');
	        	dojo.style(itemContainer, 'opacity', '0');
	        	dojo.place(itemContainer, basket, 'first');
	        	setTimeout('lupiui.animateItemIn(itemContainer)',500);
           	    dojo.destroy('emptyMsg');
    	    },
    	    error :function(respoinse, ioArgs) {
    	    	this.showBasket();
    	    	lupi.alert(response);
    	    }
    	}
    	dojo.xhrPost(xhrArgs);
    	
    },
    animateItemIn : function(node) {
    	dojo.fx.combine([
    	dojo.fx.wipeIn({node: node, duration:500}),
    	dojo.fadeIn({node: node, duration:500})
    	]).play();
    },
    refreshBasket : function() {
    	var xhrArgs = {
    	    url          : '/store/show-basket',
    	    content      : {format : 'json'},
    	    handleAs     : 'json',
    	    preventCache : true,
    	    load : function(response, ioArgs) {
    	    	if (dojo.byId('throbber')) {
    	    		dojo.fx.combine([
    	    		    dojo.fadeOut({node: 'throbber', duration:500}),
    	    		    dojo.fx.wipeOut({node: 'throbber', duration:500})
    	    		]).play();
    	    		lupiui.fillBasket(response);
    	    	} else {
    	    		lupiui.fillBasket(response);
    	    	}
    	    	lupiui.dirty = false;
    	    },
    	    error : function (response, ioArgs) {
    	    	alert(response);
    	    }
    	}
    	dojo.xhrGet(xhrArgs);
    },
    fillBasket : function(bucket) {
    	basket = dojo.byId('basketContents');
    	if (bucket.items.length < 1) {
    		var text = dojo.create('p', {id        : 'emptyMsg',
    			                         innerHTML : 'Your basket is currently empty',
    			                         style     : 'margin-left:5px;'});
    		dojo.place(text, basket, 'first');
    	} else {
	    	for (i in bucket.items) {
	    		var node = lupiui.getNewBasketItemNode(bucket.items[i]);
	        	dojo.style(node, 'display', 'none');
	        	dojo.style(node, 'height', '0px');
	        	dojo.style(node, 'opacity', '0');
	    		dojo.place(node, basket , 'last');
	    		this.animateItemIn(node);
	    	}
    	}
    },
    getNewBasketItemNode : function (args) {
    	var node = dojo.create('div');
    	node.id = 'item-' + args.id;
    	dojo.attr(node, 'class', 'basketItem clearfix');
    	var thumb = dojo.create('img', {src : args.thumbnail});
    	var name = dojo.create('h2', {innerHTML : args.name});
    	var id = dojo.create('p', {innerHTML : args.id + ' QTY:<span id="qty-' 
    		            + escape(node.id) + '">' + args.quantity + '</span>'});
    	dojo.place(id,     node, 'first');
    	dojo.place(name,   node, 'first');    	
    	dojo.place(thumb,  node, 'first');
    	
    	return node;
    },
    insertAddress : function (where) {
    	dojo.require('dijit.form.RadioButton');
    	lupiui.addressdialog = new dijit.Dialog({
    		title       : 'Choose Address',
            href        : '/member/address-select',
            parseOnLoad : true,
            preload     : true,
            draggable   : false,
            execute : function(arguments){lupiui.updateAddress(where, arguments['address'])},
    	    onContentError: function (error){alert('error' + dojo.toJson(error, true))}
    	});
    	lupiui.addressdialog.connect(lupiui.addressdialog, 'hide', function() {
            setTimeout("lupiui.addressdialog.destroyRecursive(true)", 500);
        });
    	lupiui.addressdialog.show();
    	return false;
    },
    updateAddress : function(where, data) {
    	var attribs = dojo.fromJson(data);
    	dojo.byId(where + '-address1').value = attribs.addr1;
    	if (attribs.addr2) {
    		dojo.byId(where + '-address2').value = attribs.addr2;
    	}
    	dojo.byId(where + '-town').value = attribs.town;
    	dojo.byId(where + '-county').value = attribs.county;
    	dojo.byId(where + '-postcode').value = attribs.postCode;
    	if (attribs.savename) {
    		dojo.byId(where + '-savename').value = attribs.savename;
    	}
    	var ship = dojo.byId('shippingalso');
    	if (ship && where == 'billing') {
    		if (ship.checked == true) {
    			lupiui.updateAddress('shipping', data);
    		}
    	}
    },
    enableShippingFields : function( state ) {
    	var toggle = new dojo.fx.Toggler({
    		node : 'shippingFields'
    	});
    	if (!state) {
    		toggle.show();
    	}else {
    		toggle.hide();
    	}
    	
    
    },
    editAddress : function ( id ) {
    	var callback = function (address) {
    		delete address.save;
    		address.id = id;
    		var xhrArgs = { 
    				url     : '/member/do.edit.address',
    				content : address,
    				handleAs: 'json',
    				handle  : function(response, ioArgs) {
    			                  if (response.state == 'ok') {
    			                	  lupiui.updateAddressList();
    			                  } else {
    			                	  lupi.alert('Server Response: ',response.message);
    						      }
    		                   }
    		}
    		dojo.xhrPost(xhrArgs);
    	}
    	idstr = '?id='+id;
    	if (null == id) {
    		idstr = '';
    	}
    	lupi.dialog('Edit Address', '/member/edit.address' + idstr, callback);
    },
    deleteAddress : function ( id ) {
    	var message = 'Are you sure you wish to delete this address?<br/>' +
    	              'This operation cannot be undone' + 
    	              '<button dojoType="dijit.form.Button" onclick="lupi.myWarning.hide();' +
    	              'lupiui.doDeleteAddress(\'' + id + '\');">Ok</button>' +
    	              '<button dojoType="dijit.form.Button" onclick="lupi.myWarning.hide()">Cancel</button>';	     
    	lupi.warning(message);
    },
    doDeleteAddress : function ( subject ) {
    	var xhrArgs = {
    	    url     : '/member/drop-address',
    	    content  : {id : subject},
    	    handleAs : 'json',
    	    load     : function (response, ioArgs) {
    	    	 	       if (response.state == 'ok') {
    	    	 	    	   lupiui.updateAddressList();
    	    	 	       } else {
    	    	 	    	   lupi.alert('Unable to delete record', response.message);
    	    	 	       }
    	               },
    	    error    : function (response, ioArgs) {
    	            	   lupi.alert('Unable to delete record', 'Could not negotiate with the server');
    	               }
    	}
    	dojo.xhrPost(xhrArgs);
    },
    updateAddressList : function () {
        var list = dojo.byId('addresslist');
        dojo.fx.wipeOut({
        	node: list, 
        	duration:300, 
        	onEnd : function () {
	        	var xhrArgs = {
	            		url: '/member/address-list?format=json', 
	            		handleAs:'json', 
	            		load : function(resp, ioArgs){lupiui.populateAddressList(resp.addresses);},
	            		error : function(resp, ioArgs){lupi.alert('Something bad happened',dojo.toJson(resp));}
	            };
	            dojo.xhrPost(xhrArgs);
        	}
        }).play();
    },
    populateAddressList : function (items) {
    	list = dojo.byId('addresslist');
    	dojo.empty(list);
    	var i = 0;
    	dojo.forEach(items, function(d) {
    		var item = dojo.create('li');
    		item.className = 'odd';
    		if (0 == i % 2) {
    		    item.className = 'even';	
    		}     		
    		var text = dojo.create('span');
    		text.className = 'adlisttext';
    		text.innerHTML = d.name;
    		var controls = dojo.create('span');
    		controls.className = 'adlistcontrols';
    		var editimg = dojo.create('img');
    		editimg.src = '/images/admin/icons/page_white_edit.png';
    		var delimg = dojo.create('img');
    		delimg.src = '/images/admin/icons/page_white_delete.png';

    		dojo.connect(delimg, 'onclick', function(){lupiui.deleteAddress(d.id)});
    		dojo.connect(editimg, 'onclick', function(){lupiui.editAddress(d.id)});
    		
    		dojo.place(text, item, 'first');
    		dojo.place(controls, item, 'last');
    		dojo.place(editimg, controls, 'first');
    		dojo.place(delimg,  controls, 'last');
    		dojo.place(item, list, 'last');
    		i++;
    	});
    	setTimeout(
    		'dojo.fx.wipeIn({node: \'addresslist\', duration: 300}).play();',
    		400);
    }
}
