var applicationName = 'Firebrand';

if (typeof(SwcAdmin) != 'undefined') {
    SwcAdmin.makeFriendlyUrl = function(e) {
        element = Event.element(e);
    }
}

// Configure search
shop.search.defaultText = 'Search';
shop.search.useAutocomplete = false;

// Configuring checkout
shop.checkout.isPaymentRequired = function() {
	return true
}

shop.checkout.termsAccepted = function() {
    if ($('terms').checked) return true;
    shop.display.info('Before submitting the order, you have to agree to the terms & conditions');
    return false;
}

shop.checkout.isCheckoutComplete = function() {
    return (shop.checkout.isGuestEmailAddressValid() && shop.checkout.isDeliveryDataValid() && shop.checkout.isPaymentDataValid() && shop.checkout.termsAccepted());
}

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'), /^(.{0,9}|\d{5}(-\d{4})?)$/, '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'), /^(.{0,9}|\d{5}(-\d{4})?)$/, '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.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 last name');
    // 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 firebrandoptedIn = $$('input:checked[name=SignedUpForFirebrandEmail]').pluck('value').first();
        destinationUrl  = destinationUrl || '/';
        xajax_userRegister($F('register_first_name'), $F('register_last_name'), userName , $F('register_email_address'), $F('register_password'), optedIn, firebrandoptedIn, storeId, destinationUrl);
        tao.analytics.track('/customer/register/');
    } else {
        shop.display.validationWarn();
    }
}

shop.display.notify = function(message) {
    shop.display.getGrowler().growl(message, {header: shop.name, className: 'taoshop-notify', life: 9});
}

shop.checkout.isDeliveryDataValid = function() {
    if ($('delivery_address')) {
        return tao.form.validateElement($('delivery_address'), 'nonzero', 'Please choose a delivery address');
    } else {
        return true;
    }
}

shop.user.saveProfile = function() {
    var validName = tao.form.validateElement($('profile_first_name'), 'required', 'Please enter a first name');
    validName &= tao.form.validateElement($('profile_last_name'), 'required', 'Please enter a surname');
    //User names are optional for taoshop instances
    var validUserName = true;
    var userName = "";
    var storeId = 0;
    
    if ($('profile_user_name')) {
        validUserName = tao.form.validateElement($('profile_user_name'), 'required', 'Please enter a user name');
        userName = $F('profile_user_name');
    }
    if ($('profile_store_id')) {
        storeId = $F('profile_store_id');
    }
    var validEmailAddress =tao.form.validateElement($('profile_email_address'), 'emailAddress', 'Please enter a valid email address');
    var validForm = (validName && validUserName && validEmailAddress);
    if (validForm) {
        xajax_saveUserProfile(xajax.getFormValues('profile_form'));
    } else {
        shop.display.validationWarn();
    }
}



    //////////////////////////////
    // PAYPAL SPECIFIC OVERIDES //
    //////////////////////////////

    shop.checkout.isPayPal = function()
    {
        var isPayPal = false;
        if ('paypal' == shop.checkout.getPaymentMethod()) {
            isPayPal = true;
        }
        return isPayPal;
    };

    shop.checkout.getPaymentMethod = function()
    {
        var paymentMethod = false;
        $('card_selection_container').select('input[name="payment_method"]').each(function(ele){
                if (true === ele.checked) {
                    paymentMethod = ele.value;
                }
        });
        return paymentMethod;
    };

    //overrides normal hasPaymentMethodBeenSelected
    shop.checkout.hasPaymentMethodBeenSelected = function()
    {
        var hasPaymentMethodBeenSelected = false;
        if (true == shop.checkout.isPayPal()) {
            hasPaymentMethodBeenSelected = true;
        } else {
            var isBankcardSelected = (shop.checkout.isExistingBankcardSelected() || shop.checkout.isNewBankcardSelected());
            hasPaymentMethodBeenSelected = (isBankcardSelected || shop.checkout.isGiftcardSelected());
        }
        return hasPaymentMethodBeenSelected;
    };

    //overrides normal isPaymentDataValid
    shop.checkout.isPaymentDataValid = function()
    {
        var isPaymentDataValid = false;
        if (false == shop.checkout.isPayPal()) {
            isPaymentDataValid = tao.form.validateElement($('billing_address'), 'nonzero', 'Please choose a billing address');
        } else {
            isPaymentDataValid = true; //no billing address required
        }
        return isPaymentDataValid;
    };

    //overide standard getOrderDataSubmission
    shop.checkout.getOrderDataForSubmission = function() {
        var orderData = new Hash();
        if ($('delivery_address')) {
            orderData.set('deliveryAddressId', $F('delivery_address'));
        }

        if (false == shop.checkout.isPayPal()) {
            orderData.set('isPayPal', 0);
            if (shop.checkout.isPaymentRequired()) {
                orderData.set('billingAddressId', $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 (shop.checkout.isGiftcardSelected()) {
                   orderData.set('giftcard', {giftcardId: $F('giftcard_id'), allocation: $F('giftcard_allocation')}); 
                }
            }
        } else {
            orderData.set('isPayPal', 1);
            if (shop.checkout.isPaymentRequired()) {
                if (shop.checkout.isGiftcardSelected()) {
                   orderData.set('giftcard', {giftcardId: $F('giftcard_id'), allocation: $F('giftcard_allocation')}); 
                }
            }
        }
        return orderData;
    };

    shop.checkout.onPaymentMethodChange = function()
    {
        if (true == shop.checkout.isPayPal()) {
            //hide billing details and show billing details not required
            $('billing_address_selector').hide();
            $('billing_address_paypal').show();
        } else {
            //hide billing details not required and show billing details
            $('billing_address_paypal').hide();
            $('billing_address_selector').show();
        }
    };

    shop.checkout.onCardChange = function()
    {
        $('payment_method_card').checked = true;
        shop.checkout.onPaymentMethodChange();
    };

    //////////////////////////////////
    // END PAYPAL SPECIFIC OVERIDES //
    //////////////////////////////////

var firebrand = {
	init: function() {
        this.stockreport.init();
		this.price.init();
	},
    stockreport: {
        init: function() {
            var options = {
                icon: '/images/calendar.png',
                dateFormat: 'dd/MM/yyyy',
                timePicker: true,
                timePickerAdjacent: true,
                use24hrs: true,
                locale: 'en_GB'
            };
            //new Control.DatePicker('startdate', options);
            //new Control.DatePicker('enddate', options);
        }
    },
    price: {
        init: function() {
			var conversionRate = tao.cookie.get('currency_conversion_rate');
			var currencySymbol = tao.cookie.get('currency_conversion_symbol');
			if (currencySymbol == '¬') currencySymbol = '&euro;';
			if (conversionRate && currencySymbol) {
				firebrand.price.showEquivalentPrices(conversionRate, currencySymbol);
				$$('#currency_select option[value='+conversionRate+']').first().setAttribute('selected', 'selected');
			}
		},
 	    switchCurrency: function() {
			var conversionRate = parseFloat($F('currency_select'));
			var selectedOption = $$('#currency_select option').find(function(ele){return !!ele.selected});
			var currencySymbol = selectedOption.innerHTML.match(/\((.*)\)/).last();
			firebrand.price.showEquivalentPrices(conversionRate, currencySymbol);
			tao.cookie.set('currency_conversion_rate', conversionRate);
			tao.cookie.set('currency_conversion_symbol', currencySymbol.unescapeHTML());
			if (conversionRate != 1) {
				shop.display.info('Note that currencies other than GBP sterling are displayed for illustration only.  All transactions occur in British pounds');
			}
		},
		showEquivalentPrices: function(conversionRate, currencySymbol) {
			$$('.price_holder').each(function(ele){
				firebrand.price.showEquivalentPrice(ele, conversionRate, currencySymbol);
			});
            $$('p.product-price').each(function(ele){
                firebrand.price.showPriceHint(ele, conversionRate, currencySymbol);
            });
		},
	    showEquivalentPrice: function(ele, conversionRate, currencySymbol) {
			var priceInSterling = $(ele).next('span').innerHTML;
			var convertedPrice = firebrand.price.convert(priceInSterling, conversionRate);
			ele.update(currencySymbol+convertedPrice.toFixed(2));
		},
		showPriceHint: function(ele, conversionRate, currencySymbol) {
			firebrand.price.removePriceHint(ele);
			if (conversionRate == 1) return;
			var priceInSterling = ele.innerHTML.match(/[\d,.]+/).first();
            var convertedPrice = firebrand.price.convert(priceInSterling, conversionRate);
			var hintEle = new Element('span', {'class': 'price-hint'});
			var hintHtml = ' ('+currencySymbol+convertedPrice.toFixed(2)+')';
			ele.insert({bottom: hintEle.update(hintHtml)});
		},
		removePriceHint: function(ele) {
			ele.select('.price-hint').invoke('remove');
		},
        convert: function(price, conversionRate) {
			if (typeof price == 'string') {
				price = parseFloat(price.replace(/,/g, ''));
			}
			return price * conversionRate;
		}
	},
    cs: {
    	getOrderNumber: function() {
    		return parseFloat($F('order_number'));
    	},
	    updateOrderTotal: function() {
	        var newOrderTotal = firebrand.cs.getOrderSubtotal() + firebrand.cs.getOrderDeliveryCharge();
	        $('customer_services_total').update(newOrderTotal.toFixed(2));
	    },
	    getOrderSubtotal: function() {
	        return parseFloat($('customer_services_subtotal').innerHTML.gsub(/[^\d.]/, ''));
	    },
	    getOrderDeliveryCharge: function() {
	        return parseFloat($F('customer_services_delivery'));
	    },
	    getOrderTotal: function() {
	        return parseFloat($('customer_services_total').innerHTML.gsub(/[^\d.]/, ''));
	    },
		takePayment: function(orderNumber) {
	    	xajax_takePayment(orderNumber, firebrand.cs.getOrderTotal());  
	    },
	    applyRefund: function() {
	    	var type = $$('input[name=refund_type]').find(function(ele){return ele.checked}).getValue()
	    	switch (type) {
	    	case 'WholeOrder':
	    		xajax_refundOrder(firebrand.cs.getOrderNumber(), firebrand.cs.getRefundReason());
	    		break;
			case 'SelectedItems':
				xajax_refundSelectedItems(firebrand.cs.getOrderNumber(), firebrand.cs.getSelectedBatchProductIds(), firebrand.cs.getRefundReason());    		
				break;
			case 'CustomAmount':
				xajax_refundCustomAmount(firebrand.cs.getOrderNumber(), parseFloat($F('refund_custom_amount')), firebrand.cs.getRefundReason());  
				break;
			default: 
				Swc.Error('Please choose a refund type');
	    	}
	    },
	    getSelectedBatchProductIds: function() {
	    	return $$('.batch_product').collect(function(ele){if (ele.checked) return ele.identify().match(/\d+/).first()}).compact()
	    },
	    getRefundReason: function() {
	    	return $F('refund_reason');
	    }
    }
}

document.observe('dom:loaded', function(){
	firebrand.init();
})

function windowSize() {
	  var myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myHeight = document.body.clientHeight;
	  }
	  $$('div.page_wrapper').invoke("setStyle", {minHeight: myHeight+'px'});
	}

HtmlContentEditor    = {
    mode: "specific_textareas",
    plugins: "spellchecker,media",
    theme: "advanced",
    theme_advanced_toolbar_location: "top",
    theme_advanced_buttons1: "bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist",
    theme_advanced_buttons2: "forecolor,image,code,anchor,html,link,unlink",
    theme_advanced_buttons3: "",
    convert_urls: false,
    theme_advanced_statusbar_location: "bottom",
    theme_advanced_path: false,
    theme_advanced_resize_horizontal: false,
    theme_advanced_resizing: true,
    cleanup_on_startup: true,
    apply_source_formatting: true,
    extended_valid_elements: "object[width|height],param[name|value],embed[src|type|wmode|width|height|allowfullscreen]",
    width: "100%",
    spellchecker_rpc_url: "js/common/tiny_mce/plugins/spellchecker/rpc.php"
};
Tiny.addConfig('HtmlContent', HtmlContentEditor);
