$(document).ready(function() {

    if($('#cartShippingPromo').length) {
	$('#promotionCodeCode').focus(function() {
	   $(this).select();
	});
	$('#promoCodeFormWrapper a').removeAttr('onclick').click(function(e) {
	    e.preventDefault();
	    $('#promoCodeFormWrapper #redeem').click();
	});
    }

    $('.giftFormList #message').each(function() {
		$(this).keyup(function() {
			var charLength = $(this).val().length;
			$(this).next('span.messageCount').html(charLength + ' of 60 characters used');
			if($(this).val().length > 60) {
				$(this).next('span.messageCount').html('<strong>You may only have up to 60 characters.</strong>');
			}
		});	
	});
    
    $('.voucherFormError').hide();
    
    /*
    $('#voucherPurchaseForm').submit(function() {
        if (parseInt($('#voucherValues').val()) > 19 && parseInt($('#voucherValues').val()) < 201) {
            $('.voucherFormError').hide();
            var voucherUrl = '/cart/add/GiftVoucher/GV-' + parseInt($('#voucherValues').val());
            
            var baseTags = document.getElementsByTagName('base');
			if(baseTags != undefined && baseTags.length > 0) {
				voucherUrl = baseTags[0].href + voucherUrl;
			}
			
        	if (voucherUrl) {
        		window.location = voucherUrl;
        	} 
        } else {
    		$('.voucherFormError').show();
    		return false;    		
        }
        return false;
    });
    */
    
    $('#voucherCheckBalanceForm').submit(function() {
        $('#voucherCheckBalanceFormErrors').hide();
        $.get('index.php?do=restGiftVoucherBalance', $(this).serialize(), function(data) {
            if ($('response', data).attr('status') == 'success') {
                $('#voucherCheckBalanceFormResult').show().html('<h3>Your voucher <br />has $'+$('response', data).attr('gift-voucher-balance')+' <br />available.</h3>');
                $('#voucherCheckBalanceForm, .checkGCLink').hide();
            } else {
                $('#voucherCheckBalanceForm h3').hide();
                $('#voucherCheckBalanceFormErrors').show().html('<h3>'+$('error-message', data).text()+'</h3>');
            }
        });
        
        return false;
    });
    $('.stockistInfo').hide();
    
	$('.country').bind("click", function(){
		$('.stockistInfo').hide();
		$(this).siblings(".stockistInfo").toggle();
	});
		
	$('.country p').hover(function (){
		$(this).css({'text-decoration' : 'underline'});
	}, function () {
		$(this).css({'text-decoration' : 'none'});
	});
	
	var totalCartProducts = ""+readCookie('totalCartProducts');
	//if (totalCartProducts == '' || totalCartProducts == 'null' || totalCartProducts == 0) {
		//$('#pageHeader .cartItems').html('<a style="text-decoration:underline;" href="au/collection">Go Shopping</a>');	
	//} else {
		$('#pageHeader .cartItems').html('<span class="cartItemCount">'+totalCartProducts+'</span> item(s) in <a style="text-decoration:underline;" href="cart">Shopping Bag</a>');
	//}
	
});

function getInternetExplorerVersion() {
	var rv = -1;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
		rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

function init() {
    $('a.popupLink').bind('click', function(e) {popupWindow($(this).attr('href'), $(this).attr('title').replace(/[^A-z]/ig, ''),'width=550, height=400, scrollbars');e.preventDefault();});
}

function popupWindow(url, name, attributes){
	// Append popup to the URL if it does not already exist
	var queryStringExists = false;
	if(url.match(/\?/)) {
		queryStringExists = true;
	}
	
	if(queryStringExists) {
		// Only append if we haven't already got the parameter popup defined
		if(!url.match(/(\?|&)popup=/)) {
			url = url + '&popup=true';
		}
	} else {
		url = url + '?popup=true';
	}

	if(!url.match('http://')) {
	    var baseTags = document.getElementsByTagName('base');
	    if(baseTags != undefined && baseTags.length > 0) {
		    url = baseTags[0].href + url;
	    }
	}
	
	var newWindow = window.open(url, name.replace(/[^A-z]/ig, ''), attributes);
	newWindow.focus();
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
    	var c = ca[i];
    	while (c.charAt(0)==' ') c = c.substring(1,c.length);
    	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function highlight(field) {
    field.focus();
	field.select();
}
