// Modify form error display
(function(t){
    var oldFn = t.form.displayError;
    t.form.displayError = function(ele, message, className) {
        if (t.form.isErrorElementCreated(ele)) {
            ele.next().update(message);
        } else {
            ele.insert({after: new Element('div', {'class': tao.form.errorClass}).update(message)});
        }
    };
})(tao);


// Modify taoshop object
(function(taoshop){
	taoshop.basket.addCallbackProduct = function(json) {
		// Pass transparently for now.
		xajax_addCallbackProductToBasket(json);
    };
    // Checkout modifications
    taoshop.checkout.isSdmCheckout = function() {
        return !!$('recipient_id');
    };
    taoshop.checkout.isDeliveryDataValid = function() {
    	if (taoshop.checkout.isSdmCheckout()) {
            var ids = taoshop.checkout.getRecipientAddressIds();
            if (ids.length == 0) {
                shop.display.error("Please select/add some recipients");
                return false;
            } else {
                var tandc =  taoshop.checkout.getTandC();
                if (tandc == null) {
                    xajax_selectTandC();
                    return false;
                }
            }
        } else {
            return taoshop.checkout.isDeliveryAddressFormValid();
        }
        return true;
    };
    taoshop.checkout.isDeliveryAddressFormValid = function() {
        $('da_postcode').setValue($F('da_postcode').toUpperCase())
        var isFormValid = true;
        isFormValid &= tao.form.validateElement($('da_last_name'), 'required', 'Please enter a last name');
        isFormValid &= tao.form.validateElement($('da_outlet_name'), 'required', 'Please enter the outlet name');
        isFormValid &= tao.form.validateElement($('da_phone'), 'required', 'Please enter the contact mobile number');
        isFormValid &= tao.form.validateElement($('da_line1'), 'required', 'Please enter the first line of your address');
        isFormValid &= tao.form.validateElement($('da_line3'), 'required', 'Please enter a town or city');
        isFormValid &= tao.form.validateElement($('da_postcode'), 'required', 'Please enter a valid post/zip code');
        isFormValid &= tao.form.validateElement($('tandc'), 'nonzero', 'Please accept Terms and Conditions');
        return !!isFormValid;
    };
    taoshop.checkout.isBankcardDataValid = function() {
        $('card_number').setValue($F('card_number').gsub(/\D/, ''));
        var isFormValid = true;
        isFormValid &= tao.form.validateElement($('card_holder_name'), 'required', 'Please enter the card holder name');
        isFormValid &= tao.form.validateElement($('card_number'), 'cardNumber', 'Please enter a valid card number');
        isFormValid &= tao.form.validateElement($('security_number'), 'securityNumber', 'Please enter a valid security number');
        isFormValid &= tao.form.validateElement($('start_year'), taoshop.checkout.validateStartDate, 'Please choose a start date');

        // Also check billing address if using bankcard
        isFormValid &= tao.form.validateElement($('ba_line1'), 'required', 'Please enter the first line of your address');
        isFormValid &= tao.form.validateElement($('ba_line3'), 'required', 'Please enter a town or city');
        isFormValid &= tao.form.validateElement($('ba_postcode'), 'required', 'Please enter a valid post/zip code');

        return !!isFormValid;
    };
    taoshop.checkout.isPaymentDataValid = function() {
        // Check for cheque/CC inputs
        if ($$('input[name=PaymentMethod]').length > 0) {
            return taoshop.checkout.isChequeSelected() ? true : taoshop.checkout.isBankcardDataValid();
        }
        return true;
    };
    taoshop.checkout.isCheckoutComplete = function() {
        // Check Portman checkbox
        if ($('portman_group') && $F('portman_group') != 'on') {
            shop.display.error("Please check the checkbox to indicate that you have read the Portman Group Code");
            return false;
        }
        return taoshop.checkout.isDeliveryDataValid() && taoshop.checkout.isPaymentDataValid(); 
    };
    taoshop.checkout.getPaymentMethod = function() {
        var checkedEle = $$('input[name=PaymentMethod]').find(function(ele){return !!ele.checked});
        return checkedEle ? checkedEle.getValue() : null;
    };
    taoshop.checkout.isChequeSelected = function() {
        return taoshop.checkout.getPaymentMethod() == 'Cheque';
    };
    taoshop.checkout.getRecipientAddressIds = function() {
        return $$('.recipient-button').collect(function(ele){return ele.identify().gsub(/\D/, '')});
    };
    taoshop.checkout.getTandC = function() {
        return $('tandc').getValue();
    };    
    taoshop.checkout.getOrderDataForSubmission = function() {
        var orderData = new Hash();

        // Determine if this is a SDM checkout or a normal one
        if ($('recipient_id')) {
            orderData.set('deliveryAddressIds', taoshop.checkout.getRecipientAddressIds());
        } else {
            var deliveryAddress = new Hash({
                'title': $F('da_title'),
                'firstName': $F('da_first_name'),
                'lastName': $F('da_last_name'),
                'outletname': $F('da_outlet_name'),
                'line1': $F('da_line1'),
                'line2': $F('da_line2'),
                'line3': $F('da_line3'),
                'county': $F('da_county'),
                'postcode': $F('da_postcode'),
                'phone': $F('da_phone')
            });
            orderData.set('deliveryAddress', deliveryAddress);
        }
        orderData.set('deliveryMethod', taoshop.checkout.getDeliveryMethod());

        // Payment info
        if ($('card_holder_name') && $F('card_holder_name').length > 0) {
            var bankcard = new Hash({
                'type': '',
                'name': $F('card_holder_name'),
                'number': $F('card_number').gsub(/\D/, ''),
                'securityNumber': $F('security_number').gsub(/\D/, ''),
                'expiryDate': $F('expiry_month')+'/'+$F('expiry_year')
            });
            if (!$F('start_month').empty() || !$F('start_year').empty()) { 
                bankcard.set('start_date', $F('start_month')+'/'+$F('start_year'));
            }
            orderData.set('bankcard', bankcard);

            // Billing info
            var billingAddress = new Hash({
                'line1' : $F('ba_line1'),
                'line2' : $F('ba_line2'),
                'line3' : $F('ba_line3'),
                'postcode' : $F('ba_postcode')
            });
            orderData.set('billingAddress', billingAddress);
        }
        if (taoshop.checkout.isChequeSelected()) {
            orderData.set('payByCheque', true);
        }

        return orderData;
    };
    // SDM checkout
    taoshop.checkout.addSdmRecipientAddress = function() {
        var isFormValid = taoshop.checkout.isDeliveryAddressFormValid();
        if (isFormValid) {
            var deliveryAddress = new Hash({
                'title': $F('da_title'),
                'firstName': $F('da_first_name'),
                'lastName': $F('da_last_name'),
                'outletname': $F('da_outlet_name'),
                'line1': $F('da_line1'),
                'line2': $F('da_line2'),
                'line3': $F('da_line3'),
                'postcode': $F('da_postcode'),
                'phone': $F('da_phone'),
                'saveinaddressbook': $F('save-in-address-book')
            });
            xajax_addSdmRecipientAddress(Object.toJSON(deliveryAddress));
        } else {
              xajax_selectTandC();
        }
    };
    taoshop.checkout.handleCheque = function(action) {
    	if (action == undefined) {
    		$('chequeTo').toggle('slide');
    	} else if (action == 'show') {
    		$('chequeTo').show();
    	} else {
    		$('chequeTo').hide();
    	}
    		
    };
    // Modify basket
    taoshop.basket.add = function(productId) {
        var submission = {
            'productId': productId
        }
        if ($('personalised_text') && $F('personalised_text').length > 0) {
            submission['PersonalisedMessage'] = $F('personalised_text');
        }
        xajax_addProductToBasket(Object.toJSON(submission));
    };
    // Customer services
    taoshop.cserv = {};
    taoshop.cserv.saveProduct = function() {
    	var isFormValid = true;
        isFormValid &= tao.form.validateElement($('product-code'), 'required', 'Please enter a product code');
        isFormValid &= tao.form.validateElement($('product-title'), 'required', 'Please enter a product title');
        if (!isFormValid) return false;
    };
    taoshop.cserv.saveVariantProduct = function() {
    	var isFormValid = true;
        isFormValid &= tao.form.validateElement($('product-code'), /^\w+\/[LM]-[0-9SMLX]+(-[NY])?$/, 'Please enter a product code in the right format');
        if (!isFormValid) return false;
    };
    // Voucher admin
    taoshop.voucher = {};
    taoshop.voucher.initEditForm = function() {
        $j( "#StartDate" ).datepicker({dateFormat: 'yy-mm-dd'});
        $j( "#EndDate" ).datepicker({dateFormat: 'yy-mm-dd'});
    }
})(shop);

$j(window).load(function() {
	$j('.packshot img').each(function(index, ele) {
		var heightDelta = 165 - $j(ele).height();
		if (heightDelta > 0) {
			var heightOffset = Math.floor(heightDelta/2);
			// Check to avoid strange Safari issue where the issue gets 
			// moved to far down.
			if (heightOffset > 0 && heightOffset < 70) {
				$j(ele).parent().css('padding-top', heightDelta/2);
			}
		}
	})
})


var profiles = {
	moveRight: function() 
	{ 
		$j('#pageProfilePermissionsLHS   option:selected').remove().appendTo('#pageProfilePermissionsRHS');
	},

	moveLeft: function() 
	{ 
		$j('#pageProfilePermissionsRHS   option:selected').remove().appendTo('#pageProfilePermissionsLHS');
	},

	save: function()
	{
		var status = $j('input:radio[name=status]:checked').val();
		
		if (status == null) {
            shop.display.error("Please specify whether you want to include or exclude your chosen profiles from this page");
            return;
        }

		$j("#pageProfilePermissionsRHS *").attr("selected", "selected");
		var RHSItems= []; 
		$j('#pageProfilePermissionsRHS option:selected').each(function(i, item){ 
			RHSItems[i] = $j(item).val(); 
		});

		xajax_savePageProfiles(RHSItems, status);
		$j("#pageProfilePermissionsRHS *").attr("selected", "");
	},

	search: function()
	{
		$j("#pageProfilePermissionsRHS *").attr("selected", "selected");
		var RHSItems= []; 
		$j('#pageProfilePermissionsRHS option:selected').each(function(i, item){ 
			RHSItems[i] = $j(item).val(); 
		});

		$j("#pageProfilePermissionsLHS *").attr("selected", "selected");
		var LHSItems= []; 
		$j('#pageProfilePermissionsLHS option:selected').each(function(i, item){ 
			LHSItems[i] = $j(item).val(); 
		});

		xajax_searchAddPageProfileList($('addPageProfilesSearch').value, LHSItems, RHSItems);
		
		$j("#pageProfilePermissionsLHS *").attr("selected", "");
		$j("#pageProfilePermissionsRHS *").attr("selected", "");
		
	},
	
	clear: function() 
	{ 
		xajax_clearProfiles();
	}
};

$j(function() {
	$j('a.hide-details-link').live('click', function() {
		$j(this).parent().slideUp();
		$j(this).parents('.promotion_details').find('.show-details-link').show();
	});
	
	$j('a.show-details-link').live('click', function() {
		$j(this).parent().find('.more_details').slideDown();
		$j(this).hide();
	});

	$j('a.category_show_link').live('click', function() {
		$j(this).parent().next().slideDown('slow'); 
		$j(this).next().show(); 
		$j(this).hide();
	});
	
	$j('a.category_hide_link').live('click', function() {
		$j(this).parent().next().slideUp('fast'); 
		$j(this).prev().show(); 
		$j(this).hide();
	});

	$j('#show-all-details').live('click', function() {
		$j(this).parent().parent().find('.promo-categories').slideDown('slow'); 
		$j(this).parent().parent().find('.category_show_link').hide();
		$j(this).parent().parent().find('.category_hide_link').show();
	});
	
	$j('#hide-all-details').live('click', function() {
		$j(this).parent().parent().find('.promo-categories').slideUp('fast'); 
		$j(this).parent().parent().find('.category_hide_link').hide();
		$j(this).parent().parent().find('.category_show_link').show();
	});

});

//jQuery FED
$j(document).ready(function() {
	/* Navigation */
	  $j('.dropdown').parent().addClass('subtab');
	  $j(function () {
		    $j('#cb-nav-content .dropdown').each(function () {
		      $j(this).parent().eq(0).hoverIntent({
		      timeout: 100,
		      over: function () {
		        var current = $j('.dropdown:eq(0)', this);
		        current.slideDown(150);
		        current.parent().addClass('hover');
		      },
		      out: function () {
		        var current = $j('.dropdown:eq(0)', this);
		        current.fadeOut(250);
		        current.parent().removeClass('hover');
		      }
		    });
		  });
		});
	  
	  /* S2S Navigation */
	  $j(function () {
		  if ($j('#s2s-navigation')) {
		    $j('#s2s-navigation li:not(.selected) h3').each(function () {
		      $j(this).eq(0).hoverIntent({
		      timeout: 100,
		      over: function () {
		        $j(this).addClass('hover');
		      },
		      out: function () {
		        $j(this).removeClass('hover');
		      }
		    });
		  });
		  }
		});


	
	if(location.pathname == '/') {
		$j("#cb-site-wrapper").attr("class", "home_page");
	}
	if(location.pathname == '/planner/') {
		$j("#cb-site-wrapper").attr("class", "planner_home_page");
	}

	/* Add list formatting */
	$j(".two-columns li:odd").addClass("alt");
	$j(".level1 li:first-child").addClass("first");
	$j(".facets li:first-child").addClass("first");

});


