if (typeof jQuery != "undefined") {
	var $j = jQuery.noConflict();
}

var applicationName = 'Borders AU';
var growlerOptions = {location: 'tc'};
var synopsisOptions = {showDimmer: true};

var swcOptions = {disableInputListeners:true};
// Fix same page anchors 
function fixAnchors() {
	var arr = $$('a[href^="#"]');
	for (i=0; i<arr.length; i++) {
  		arr[i].observe('click',function(event){
			var a=Event.element(event).readAttribute('href');
			a = a.slice(1);
			$$('a[name='+a+']')[0].scrollTo();
			Event.stop(event);
		});
	}
}


function addNewTimeField(value, id){
	if(value == '8'){
		$('holiday_'+id).style.display = 'block';
	}else{
		$('holiday_'+id).style.display = 'none';
	}
}


//////////////////////////////
// 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({
        '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();
		$('submit_order_button').setValue('submit order');
	} else {
		//hide billing details not required and show billing details
		$('billing_address_paypal').hide();
		$('billing_address_selector').show();
		$('submit_order_button').setValue('submit order');
	}
};

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

shop.checkout.allocateGiftCardAmount = function(cardNumber, amount)
{
	if (amount > 0) {
		$('payment_method_paypal').disable();
		$('payment_method_card').checked = true;
		$('paypal_message').show();
	} else {
		$('payment_method_paypal').enable();
		$('paypal_message').hide();
	}
	xajax_updatePaymentBreakdown(cardNumber, amount);
};
shop.checkout.getOrderTotal = function()
{
    var orderTotal = $('order_totals_container').select('td.total').first().innerHTML.match(/(\d+\,?\d+)+|\d+.\d+/).first().replace(',','');
    return parseFloat(orderTotal);
}

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


///////////////////////////
// REGISTRATION OVERIDES //
///////////////////////////

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');
        if(($F('register_mobile_number') != '') || ($F('SignedUpForSMS') == 'Yes'))
        {
       	 	var validMobileNumber = tao.form.validateElement($('register_mobile_number'), 'mobileNumber', 'Please enter a valid mobile number for SMS newsletter');
        }else{
        	tao.form.removeError($('register_mobile_number'));
       	 	var validMobileNumber = true;
        }
        var validForm = (validName && validUserName && validEmailAddress && validPassword && validMobileNumber);
        if (validForm) {
            var optedIn = $$('input:checked[name=SignedUpForEmail]').pluck('value').first();
            var SMSoptedIn = $$('input:checked[name=SignedUpForSMS]').pluck('value').first();
            destinationUrl  = destinationUrl || '/';
            xajax_userRegister($F('register_first_name'), $F('register_last_name'), userName , $F('register_email_address'), $F('register_password'), optedIn, $F('register_mobile_number'), SMSoptedIn, storeId, destinationUrl);
            tao.analytics.track('/customer/register/');
        } else {
            shop.display.validationWarn();
        }
 };

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');
     if(($F('profile_mobile_number') != '') || ($F('SignedUpForSMS') != null))
     {
    	 var validMobileNumber = tao.form.validateElement($('profile_mobile_number'), 'mobileNumber', 'Please enter a valid mobile number');
     }else{
    	 var validMobileNumber = true;
     }
     
     var validForm = (validName && validUserName && validEmailAddress && validMobileNumber);
     if (validForm) {
         xajax_saveUserProfile(xajax.getFormValues('profile_form'));
     } else {
     	shop.display.validationWarn();
     }

};

//////////////////////////////////
// END OF REGISTRATION OVERIDES //
//////////////////////////////////

document.observe('dom:loaded', function(){
	fixAnchors();
	$$('.hover_link').each(function(e){
			e.observe('click', function(evt){
				$$('.hover_sublinks').each(function(e){e.style.display='none';});
				elm = Event.element(evt);
				var target = $$('#'+elm.ancestors()[0].identify()+' .hover_sublinks')[0];
				Effect.toggle(target, 'blind', {duration:.25});
    		});										
		}
	);
});


// Override product synopsis popups

shop.synopsis.init = function() {
        // $$('img.product_image').invoke('return false');
};


//Carousel Init
function loadCarousel(id, numItems) {
	$j('#' + id).jcarousel({
		visible: numItems
	});
}