// Using jquery get all a tags with class of termsConditionsLink and add an on click to popup window
$(document).ready(init);
function init() {
    $('a.popupLink').bind('click', function(e) { popupWindow($(this).attr('href'), $(this).attr('title').replace(/[^A-z]/ig, ''),'width=760, height=730, scrollbars'); e.preventDefault(); });
	$('a.deliveryLink').bind('click', function(e) { popupWindow($(this).attr('href'), 'DeliveryPricing','width=760, height=495, scrollbars'); e.preventDefault(); });
	$('a.errorOverlayClose').bind('click', function(e) { $('.errorOverlay').hide(); e.preventDefault(); });
	$('a.thumbnailLink').hover(function() { $('.overlayTitle', this).fadeIn(300); }, function() { $('.overlayTitle', this).fadeOut(200); });
	
	// Assing behaviour to submit a reset password from the checkout login pag
	$('#checkoutMemberPasswordResetSubmitLink').bind('click', function (e) { $('#checkoutLoginForm').attr('action', 'checkout-login-member-password-reset'); $('#checkoutLoginSubmit').click(); e.preventDefault(); });
	
	$('#cardMessage').bind('keyup', function(e) {
		limitCharacters(this, '#remainingCharactersInfo', 200);
	});
	
	limitCharacters('#cardMessage', '#remainingCharactersInfo', 200);
	
	replaceSubmit();
}

function limitCharacters(element, elementDisplay, characterLimit) {
	// Check the message length
	var remaining = characterLimit;
	var limitExceeded = false;
	if($(element).val() != undefined) {
		if($(element).val().length > characterLimit) {
			// Display message and restrict value of input/textarea
			$(element).val($(element).val().substring(0, characterLimit));
			limitExceeded = true;
		}
		
		remainingCharacters = characterLimit - $(element).val().length;
		
		var remainingCharactersMessage = remainingCharacters + ' characters remaining';
		if(remainingCharacters == 1) remainingCharactersMessage = remainingCharacters + ' character remaining';
		$(elementDisplay).html(remainingCharactersMessage);
		
		if(limitExceeded) alert('Maximum of ' + characterLimit + ' characters allowed');
	}
}


/**
 * popup a new window
 */
function popupWindow(url, name, attributes){
	var newWindow = window.open(url, name, attributes);
	newWindow.focus();
}

function attachPrint(selectedElement) {
	$(selectedElement).bind('click', function(event) {
			event.preventDefault();
			window.print();
		});
}

function replaceSubmit() {
    var inputElement;
    $(':submit').each(function(index) {
            inputElementId = this.id;
            $(this).after('<a href="#" id="' + this.id + 'Link" class="submitLink">' + $(this).val() + '</a>').hide();
            $('#' + this.id + 'Link').bind('click', function (event) { event.preventDefault(); $('#' + this.id.replace(/Link$/, '')).trigger('click'); });
        }
    );
}

function trim(value) {
    return value.replace(/^\s+|\s+$/g, '');
}

/**
 * Case insensitive version of contains
 */
jQuery.extend(jQuery.expr[':'], {
    Contains :
    "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
}); 