// NailsInc specific JS file
var applicationName = 'nails inc';
var ColourSelector = {
    
    // collection object
    collection: {
    
        items: new Array(),
        limit: 10,
        lastError: false,
    
        add: function (item) {
            if (ColourSelector.collection.items.length == ColourSelector.collection.limit) return false;
            ColourSelector.collection.items.push(item);
            return ColourSelector.collection.items.length;
        },

        isItemInCollection: function (item) {
            return false;   // workaround to allow duplicate items in collection
            index = ColourSelector.collection.items.indexOf(item);
            if (index != -1) {
                return true;
            } else {
                return false;
            }
        },
        
        removeByIndex: function (index) {
            if (!ColourSelector.collection.items[index]) return false;
            ColourSelector.collection.items.splice(index, 1);
            return ColourSelector.collection.items.length;
        },
        
        remove: function (item) {
            if (!ColourSelector.collection.isItemInCollection(item)) return false;
            ColourSelector.collection.items = ColourSelector.collection.items.without(item);
            return ColourSelector.collection.items.length;
        },
        
        reset: function () {
            ColourSelector.collection.items = ColourSelector.collection.items.clear();
        }
    
    },
    
    addToBasket: function () {
        ColourSelector.collection.items.each(function (productId) {
            shop.basket.addQuietly(productId);
        });
        
        ColourSelector.collection.reset();
        ColourSelector.resetCollectionBoxes();
        
        shop.display.notify('Your collection has been added to basket');
    },
        
    addToCollection: function (productId) { 

        // check if exists
        if (ColourSelector.collection.isItemInCollection(productId)) {
            boxId = 'CollectionBox' + (ColourSelector.collection.items.indexOf(productId) + 1);
            new Effect.Pulsate(boxId, { pulses: 2 });
            return false;
        }
        
        // add to collection
        result = ColourSelector.collection.add(productId);
        if (result === false) {
            shop.display.warn('Maximum number of items in collection has been reached');
            return false;
        } else {
            shop.display.notify('Added to collection');
        }
        
        // display on page
        ColourSelector.displayCollectionBox(result, productId);
        ColourSelector.displayBasketButton();
    },
    
    displayBasketButton: function () {
        if ((ColourSelector.collection.items.length >= 3 && ColourSelector.collection.items.length <= 5) || 
             ColourSelector.collection.items.length == 10) {
            $('CollectionAddToBasket').show();
        } else {
            $('CollectionAddToBasket').hide();
        }
    },
    
    displayCollectionBox: function (boxIndex, productId) {
        boxId = 'CollectionBox' + boxIndex;
        productBoxId = 'ProductBox' + productId;
        $(boxId).innerHTML  = $(productBoxId).innerHTML;
        $(boxId).title      = 'Click to remove from your collection ' + productId;
        $(boxId).setStyle({cursor: 'pointer'});
    },
    
    removeFromCollection: function (index) {
        
        result = ColourSelector.collection.removeByIndex(index);
        if (result === false) return false;
        
        shop.display.notify('Removed from collection');
        
        ColourSelector.resetCollectionBoxes();
        
    },
    
    resetCollectionBoxes: function () {
        
        // clear all boxes
        for (var boxIndex = 1; boxIndex <= ColourSelector.collection.limit; ++boxIndex) {
            boxId = 'CollectionBox' + boxIndex;
            $(boxId).innerHTML = '';
            $(boxId).title = '';
            $(boxId).setStyle({cursor: 'default'});
        }

        // populate boxes with remaining items
        for (var boxIndex = 1; boxIndex <= ColourSelector.collection.limit; ++boxIndex) {
            item = ColourSelector.collection.items[boxIndex-1];
            if (item > 0) {
                ColourSelector.displayCollectionBox(boxIndex, item);
            }
        }
        
        ColourSelector.displayBasketButton();
    },
    
    selectProduct: function (ProductId) { 
        xajax_selectProduct(ProductId); 
    }

}

/****
Once DOM is loaded, searches for inputs with the class 'focus', then extends onfocus and onblur as follows:

If a textfield or textarea has a default value, this function will clear the input on focus,
and restore the value if focus is lost and the input has an empty value.

If the default value is 'Password' it will destroy the text input and replace it with a 
Password input with the same id, classes and parent node, and will restore if focus is lost and value is empty

****/
var inputs = {
	init : function() {
		inputs.attachFocus($$("input.focus"));
	},
	attachFocus : function(sfEls){
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onfocus=function() {inputs.txtInputOnFocus(this,this.defaultValue);}
		}
	},
	txtInputOnFocus : function(txtInput,str){
		if(txtInput.hasFocus){return;}
		txtInput.hasFocus=true;
		if(str=='Password'&&txtInput.value==str){
			txtInput=inputs.swapInputType(txtInput,str);
		}
		if(txtInput.value==str)txtInput.value='';
		txtInput.className+=" hasfocus";
		txtInput.onblur = function(){
			if(txtInput.value==''){
				if(txtInput.type=='password')txtInput=inputs.swapInputType(txtInput,str);
				txtInput.value=str;
			}
			$(txtInput).removeClassName("hasfocus");
			txtInput.hasFocus=false;
		}
	},
	swapInputType : function(txtInput,str){
		var newInput = document.createElement('input');
		if(txtInput.type=='password')newInput.type='text';
		else newInput.type='password';
		newInput.name = txtInput.name;
		newInput.value = txtInput.value;
		newInput.id = txtInput.id;
		newInput.className = txtInput.className;
		objParent=txtInput.parentNode;
		objParent.replaceChild(newInput,txtInput);
		newInput.onfocus = function (){inputs.txtInputOnFocus(newInput,str)};
		newInput.hasFocus=false;
		window.newInput = newInput;
		newInput.onblur = function(){
			if(newInput.value==''){
				if(newInput.type=='password')newInput=inputs.swapInputType(newInput,str);
				newInput.value=str;
			}
			newInput.hasFocus=false;
		}
		setTimeout("newInput.hasFocus=true;newInput.focus();",1);
		return newInput;
	}
}
document.observe("dom:loaded", inputs.init);

var nailsinc = {
	checkout: {
		init: function() {
		},
		getPointsAllocation: function() {
			return $('points-allocation') ? parseFloat($F('points-allocation')) : 0.00;
		},
		arePointsUsed: function() {
			return nailsinc.checkout.getPointsAllocation() > 0;
		},
		isGiftWrappingRequested: function() {
			return !!$('gift_wrapped').checked;
		},
		handleGiftSelect: function() {
			if (nailsinc.checkout.isGiftWrappingRequested()) {
				$('gift_wrap_additions').show();
			} else {
				$('gift_wrap_additions').hide();
			}
		},
		getShippingTotal: function() {
			var shippingTotal = $('order_totals_container').select('td.shipping_total').first().innerHTML.match(/\d+.\d+/).first();
        	return parseFloat(shippingTotal);
		},
		getProductsTotal: function() {
			var productsTotal = $('order_summary').select('td.products_total').first().innerHTML.match(/\d+.\d+/).first();
        	return parseFloat(productsTotal);
		},
		isBankcardRequired: function() {
			return nailsinc.checkout.getShippingTotal() > 0;
		},
		getRequestedPointsAllocation: function() {
			return parseFloat($F('points-allocation'));
		},
		getAllowedPointsAllocation: function() {
			var requestedPointsAllocation = nailsinc.checkout.getRequestedPointsAllocation();
			if (nailsinc.checkout.getProductsTotal() < requestedPointsAllocation) {
				return nailsinc.checkout.getProductsTotal();
			}
			return requestedPointsAllocation;
		}
	}
}

shop.user.register = function(destinationUrl) {
    var validName = tao.form.validateElement($('register_first_name'), 'required', 'Please enter a first name');
    validName &= tao.form.validateElement($('register_last_name'), 'required', 'Please enter a surname');
    // User names are optional for taoshop instances
    var userName = "";
    var validUserName = true;
    var storeId = 0;
    
    if ($('register_user_name')) {
        validUserName = tao.form.validateElement($('register_user_name'), 'required', 'Please enter a user name');
        userName = $F('register_user_name');
    }
    if ($('register_store_id')) {
        storeId = $F('register_store_id');
    }
    var validEmailAddress = tao.form.validateElement($('register_email_address'), 'emailAddress', 'Please enter a valid email address');
    validEmailAddress &= tao.form.validateElement($('register_confirm_email_address'), function(){return $F('register_email_address') == $F('register_confirm_email_address');}, 'Please ensure your confirmation email address matches your main address');
    var validPassword = tao.form.validateElement($('register_password'), 'password', 'Please choose a password of 6 characters or more');
    if (true == validPassword) validPassword &= tao.form.validateElement($('register_password'), function(password){return !['password', 'password123'].member(password)}, 'This password is too obvious - please choose another');
    validPassword &= tao.form.validateElement($('register_confirm_password'), function(){return $F('register_password') == $F('register_confirm_password');}, 'Please ensure your confirmation password matches your main password');
    var validForm = (validName && validUserName && validEmailAddress && validPassword);
    if (validForm) {
        var optedIn = $$('input:checked[name=SignedUpForEmail]').pluck('value').first();
        var addVip = $$('input:checked[name=AddVipMembership]').pluck('value').first();
        destinationUrl  = destinationUrl || '/';
        xajax_userRegister($F('register_first_name'), $F('register_last_name'), userName , $F('register_email_address'), $F('register_password'), optedIn, addVip, $F('date_of_birth'), destinationUrl);
        tao.analytics.track('/customer/register/');
    } else {
        shop.display.validationWarn();
    }
}

// Checkout alterations
shop.user.saveDeliveryAddress = function() {
    var validName = tao.form.validateElement($('da_first_name'), 'required', 'Please enter a first name');
    validName &= tao.form.validateElement($('da_last_name'), 'required', 'Please enter a last name');
    var validLine1  = tao.form.validateElement($('da_line1'), 'required', 'Please enter the first line of your address');
    var validCode = tao.form.validateElement($('da_postcode'), 'required', 'Please enter a valid post/zip code');
    var validForm = (validName && validLine1 && validCode);
    if (validForm) {
        xajax_saveDeliveryAddress(xajax.getFormValues('delivery_address_form'))
    } else {
    	shop.display.validationWarn();
    }
}
shop.user.saveBillingAddress = function() {
    var validName = tao.form.validateElement($('ba_first_name'), 'required', 'Please enter a first name');
    validName &= tao.form.validateElement($('ba_last_name'), 'required', 'Please enter a last name');
    var validLine1  = tao.form.validateElement($('ba_line1'), 'required', 'Please enter the first line of your address');
    var validCode   = tao.form.validateElement($('ba_postcode'), 'required', 'Please enter a valid post/zip code');
    var validForm   = (validName && validLine1 && validCode);
    if (validForm) {
        xajax_saveBillingAddress(xajax.getFormValues('billing_address_form'))
    } else {
    	shop.display.validationWarn();
    }
}
shop.checkout.getOrderDataForSubmission = function() {
    var orderData = new Hash();
    if ($('delivery_address')) orderData.set('deliveryAddressId', parseInt($F('delivery_address')));
    
    var deliveryMethod = shop.checkout.getDeliveryMethod();
    if (deliveryMethod) {
        orderData.set('deliveryMethod', deliveryMethod);
    }
    
    if (shop.checkout.isPaymentRequired()) {
    	orderData.set('billingAddressId', parseInt($F('billing_address')));
    	if (shop.checkout.isExistingBankcardSelected()) {
            orderData.set('existingbankcard', {bankcardId: $F('bankcard')});
        } else if (shop.checkout.isNewBankcardSelected()) {
            orderData.set('newbankcard', shop.checkout.newbankcard);
        }
        if (nailsinc.checkout.arePointsUsed()) {
            orderData.set('pointsAccountAllocation', nailsinc.checkout.getAllowedPointsAllocation()); 
        }
        if (nailsinc.checkout.isGiftWrappingRequested()) {
        	orderData.set('giftWrapping', true);
        	orderData.set('giftMessage', $F('gift_message'));
        }
    }
    return orderData;
}
shop.checkout.getOrderTotal = function() {
	var orderTotal = $('order_totals_container').select('td.total').last().innerHTML.match(/\d+.\d+/).first();
	return parseFloat(orderTotal);
}

shop.checkout.disableSubmitButton = function() {
    if (!$("submit_order_button")) return;
    $("submit_order_button").disable();
    $("submit_order_button").hide();
    $("submission_message").show();
}

shop.checkout.enableSubmitButton = function() {
    if (!$("submit_order_button")) return;
    $("submit_order_button").show();
    $("submit_order_button").enable();
    $("submission_message").hide();
}

shop.checkout.getDeliveryMethod = function() {
    return $F('DeliveryOption');
}

try {
    document.observe('dom:loaded', nailsinc.checkout.init);
} catch (error) {
    tao.debug(error.name+': '+error.message);
}