$(document).ready(function() {

/***********************************************
***  INITIALISE  *******************************
************************************************/

/* preload */
$("<img>").attr("src", "/images/icons/ico-bullet-dark.gif");

$('html').addClass('jsEnabled');

$('#formSignup, #formContactus').append('<input type="hidden" name="formAuth">');

/***********************************************
***  BUTTON ROLLOVER & PRELOAD  ****************
************************************************/

	// button rollover
	if ($('.imgBtn') != null) {
		$('.imgBtn').hover(function(){
				if(!$(this).is('.disabled'))
					$(this).attr("src", $(this).attr("src").replace(/^(.*?)(?:-hover)?(\..*?)$/i,'$1-hover$2'));
			},
			function(){
					if(!$(this).is('.disabled'))
						$(this).attr("src", $(this).attr("src").replace(/^(.*)-hover(\..*?)$/i, '$1$2'));
				});
	}
	// preload image rollovers
	if ($("img.imgBtn, img[src^='images/buttons/btn'], input[src^='images/buttons/btn']") != null) {
	    $("img.imgBtn, img[src^='images/buttons/btn'], input[src^='images/buttons/btn']").each(function(){
			    $("<img>").attr("src", $(this).attr("src").replace(/(btn-.*)(\..*?)/i, '$1-hover$2'));
		    });
	}

/***********************************************
***  EXTERNAL LINKS  ***************************
************************************************/

	$("a[rel=external]").each(function() {
		$(this).addClass('external');
		$(this).attr({
			title: "Open this page in a new window",
			target: "_blank"
		});
	})




/***********************************************
***  COMPACT FORM (LABEL OVER INPUT)  **********
************************************************/
/*
	$('form.compact input, form.compact select, form.compact textarea').focus(function(){
			$('label[for=' + $(this).attr('id') + ']').hide();
		});
	$('form.compact input, form.compact select, form.compact textarea').each(function(ele){
			if($(this).val().length > 0)
				$('label[for=' + $(this).attr('id') + ']').css({ display: "none" });
		});
	$('form.compact input, form.compact select, form.compact textarea').blur(function(){
			if($(this).val().length == 0)
				$('label[for=' + $(this).attr('id') + ']').show();
		});
	$('form.compact').removeClass('compact');
*/

$(function(){
	$('.compactForm input, .compactForm select, .compactForm textarea').focus(function(){
		//alert('dd');
			$('label[for=' + $(this).attr('id') + ']').hide();
		});
	$('.compactForm input, .compactForm select, .compactForm textarea').each(function(ele){
			if($(this).val().length > 0)
				$('label[for=' + $(this).attr('id') + ']').css({ display: "none" });
		});
	$('.compactForm input, .compactForm select, .compactForm textarea').blur(function(){
			if($(this).val().length == 0)
				$('label[for=' + $(this).attr('id') + ']').show();
		});
	$('.compactForm').removeClass('compactForm');
});


/*********************************************** 
***  PROGRESSIVE ENHANCEMENT  ****************** 
************************************************/

	$('#main .productsGrid h2 a, .productsGrid .thumb').hover(function(){
			$(this).closest('li').addClass('hover')
		},
		function(){
				$(this).closest('li').removeClass('hover')
			});

	
/***********************************************
***  FOOTER SLIDING  ***************************
************************************************/

	$('.footerCategories a').hover(function(){
			$(this).stop().animate({
					paddingLeft: 15,
					backgroundPosition: '5px 3px'
				}, 200);
		},
		function(){
				$(this).stop().animate({
						paddingLeft: 10,
						backgroundPosition: '0 3px'
					}, 200);
			});
		
		
/***********************************************
***  SLIDER HOVERS  ****************************
************************************************/
		
	$('.fullWidthScroll .productViewport a').hover(function(){
			$(this).find('.prodName').stop().animate({ backgroundColor: "#ccc5be" }, 150);
			
		}, function(){
			$(this).find('.prodName').stop().animate({ backgroundColor: "#f6f6f6" }, 150);
	});

/***********************************************
***  FANCYBOX  *********************************
************************************************/

	$('.fancyBox').fancybox({
		'transitionIn'	:	'fade',
		'transitionOut'	:	'fade',
		'speedIn'	:	600, 
		'speedOut'	:	200, 
		'overlayColor'	:	'#000'
	});


/***********************************************
***  CHECKOUT  *********************************
************************************************/
$(".cvcInfo").each(function(){
	var trigger = $(this);
	trigger.tooltip({
			tip: '.cvcTooltip', 
			offset: [-5, -170],
			effect: 'slide',
			lazy: false
		});
});




/***********************************************
***  THUMB GALLERY LOAD / FADE  ****************
************************************************/
		
	/*$('.galleryBlock .thumbs a').click(function(){
			$(this).parent().find('.prodName').animate({ backgroundColor: "#dddddd" }, 150);
			
		}, function(){
			$(this).find('.prodName').animate({ backgroundColor: "#f6f6f6" }, 150);
	});*/


/*********************************************** 
***  ACTIVATE TABS  **************************** 
************************************************/

	// Initialize
	$('.tabContent').addClass('hasJS');
	$('.tabMenu li').geeTabs({
			tabbedContentSelector: '.tabContent > li'
		});
		
	// Fix jumping tabs 
	$(".tabContent").css('min-height', $(".tabContent > li").height())
		
	// Flyout menu
	/*if($.browser.msie){
		$("#mainMenu > li").hover(function(){
				$(this).find(".flyout").css('visibility','visible');
			},
			function(){
					$(this).find(".flyout").css('visibility','hidden')
				});
	} else {*/
		$(".flyout").hide();
		
		var backgroundColor;

		$('#mainMenu > li a').each(function() {
				$(this).data('bgc', $(this).css('backgroundColor'));
			});
		$('#mainMenu > li').hover(function() {
				$(this).find('.flyout').stop(true, true).fadeIn('fast');
				$(this).children('a').stop().each(function() {
						$(this).animate({
								backgroundColor: '#678b00'
							}, 150);
					});
			}, function() {
					$(this).find('.flyout').stop(true, true).fadeOut('fast');
					$(this).children('a').stop().each(function() {
							$(this).animate({
									backgroundColor: $(this).data('bgc')
								}, 150);
						});
				});
		$(window).unload(function(){
				$('.flyout').stop(true, true);
			});	


/***********************************************
***   Subscribe to Newsletter   ****************
************************************************/
	$(function() {
		var qtyAjaxDelay = undefined;
		$('form.newsletterForm').submit(function(){
			var email = $('#email').val();
			var theURL = 'http://thesphereagency.us2.list-manage2.com/subscribe/post-json?subscribe=Subscribe&EMAIL=' + encodeURIComponent(email) + '&u=2ac2cddbf95ed2186aab902f9&id=b2f6b898fd&c=?';
			//alert(theURL);
			if (email == '' || !validate(email)) {
				$('#msgPanel').html('<div class="error">Please enter a valid email.<br/></div>');
				//return false;
			} else {
				if (qtyAjaxDelay !== undefined){clearTimeout(qtyAjaxDelay);}
				qtyAjaxDelay = setTimeout(function(){
					$.ajax({
						type: "GET",
						url:  theURL,
						dataType: 'json',
						data: {},
						success: function(r) {
							if (r.result == "success"){
								$('#msgPanel').html('<div class="success">'+ r.msg +'</div>');
								$('#email').val("");
							} else {
								$('#msgPanel').html('<div class="error">'+ r.msg +'</div>');
							}
						}
					});
				},500);
				
			}
			return false;
		});
	});

	function validate(email) {
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test(email) == false) {
			//alert('Invalid Email Address');
			return false;
		} else {
			return true;
		}
	}


			
		
});


/***********************************************
**  ROTATING TILES HOMEPAGE  *******************
************************************************/



/*
var imgPath = '/images/banners/';
var imgFile = new Array('home-hero-banner1.jpg', 'home-hero-banner2.jpg', 'home-hero-banner3.jpg');
var imgAlt = new Array('', '', '');
var x = 0;
var intTimeout = null;

function rotateBanner()
{
	var displayImg = $('#displayImage');
	var transitionImg = $('#transitionImage');
	if(transitionImg.is(':animated'))
		return;

	var newImg = $('<img />');
	newImg.load(function() {
			$('.bannerIcons li.activeBtn').removeClass('activeBtn');
			$('.bannerIcons li:eq(' + x + ')').addClass('activeBtn');
			$('.popups').css({ 'opacity': '1.0' }).stop().animate({ 
					'opacity': '0' 
				}, 400);
			transitionImg.attr({
					src: $(this).attr('src'),
					alt: $(this).attr('alt')
				});
			var loadedImg = $(this);
			transitionImg.stop().fadeIn(800, function() {
					displayImg.attr({
							src: loadedImg.attr('src'),
							alt: loadedImg.attr('alt')
						});
					transitionImg.hide();

					if(intTimeout)
						clearTimeout(intTimeout);
					intTimeout = setTimeout('rotateBanner();', 4500);
				});
		});
	x = x +1 > imgFile.length -1 ? 0 : x +1;
	newImg.attr({
			src: imgPath + imgFile[x],
			alt: imgAlt[x]
		}).data('loadingInt', x);
}

var loadingInt = 0;

$(function() {
	$('#transitionImage').hide();

	intTimeout = setTimeout('rotateBanner();',4500);

});

*/


/***********************************************
***  CHECKOUT  ******************
************************************************/

$(function(){

	var fldArr = ['memDelFirstname', 'memDelLastname', 'memDelCompany', 'memDelAddress', 'memDelSuburb', 'memDelPostcode'];

	/* create account checkbox */
	$('#createAccount').click(function(){
		if (this.checked){
			$('fieldset.orderForm1').show();
		}else{
			$('fieldset.orderForm1').hide();				
		}
	})


	/* same as billing key sync */
		$('#sameAsBilling').click(function(){
				if($(this).is(':checked')){
					$(this).closest('fieldset').find('ol:first input[type="text"], ol:first select').attr('disabled', 'disabled');
					$('#memDelFirstname').val($('#memFirstname').val());
					$('#memDelLastname').val($('#memLastname').val());
					$('#memDelCompany').val($('#memCompany').val());
					$('#memDelAddress').val($('#memBillAddress').val());
					$('#memDelSuburb').val($('#memBillSuburb').val());
					changeSelectedValue('#memDelState', $('#memBillState').val());
					$('#memDelPostcode').val($('#memBillPostcode').val());
					for (var i =0; i<fldArr.length; i++){
						//checkLabel(fldArr[i]);
					}
				}else{
					$(this).closest('fieldset').find('ol:first input[type="text"], ol:first select').removeAttr('disabled');
				}
			});

		$('#sameAsBilling:checked').each(function(){
			if($(this).is(':checked')){
				$(this).closest('fieldset').find('ol:first input[type="text"], ol:first select').attr('disabled', 'disabled');
				$('#memDelFirstname').val($('#memFirstname').val());
				$('#memDelLastname').val($('#memLastname').val());
				$('#memDelCompany').val($('#memCompany').val());
				$('#memDelAddress').val($('#memBillAddress').val());
				$('#memDelSuburb').val($('#memBillSuburb').val());
				changeSelectedValue('#memDelState', $('#memBillState').val());
				$('#memDelPostcode').val($('#memBillPostcode').val());
			}
		});
	/* END - same as billing key sync */


		function registerShippingSync(bI, sI){
			$('#' + bI).keyup(function(){
				if($('#sameAsBilling').is(':checked')) {
					var id = this.id;
					$('#' + sI).val($(this).val());
					//checkLabel(sI);
				}
				if (this.id == 'memBillPostcode' && $('#sameAsBilling').is(':checked')  || this.id == 'memDelPostcode'){
					// do ajax call
					//refreshShipping();
				}
			});

			$('#' + bI).change(function(){
				if($('#sameAsBilling').is(':checked')) {
					changeSelectedValue('#' + sI, $(this).val()) 
				}
			});
		}		

		/*function checkLabel(sI){
			if($('#' + sI).val().length == 0){
				$('label[for=' + sI + ']').show();
			}else{
				$('label[for=' + sI + ']').hide();
			}
		}*/

		if ($('input#sameAsBilling:enabled').length > 0){
			registerShippingSync('memFirstname', 'memDelFirstname');
			registerShippingSync('memLastname', 'memDelLastname');
			registerShippingSync('memCompany', 'memDelCompany');
			registerShippingSync('memBillAddress', 'memDelAddress');
			registerShippingSync('memBillSuburb', 'memDelSuburb');
			registerShippingSync('memBillState', 'memDelState');
			registerShippingSync('memBillPostcode', 'memDelPostcode');
			for (var i =0; i<fldArr.length; i++){
				//checkLabel(fldArr[i]);
			}
		}

		/* Only allow numbers in qty input */
		$('input[name^="qty"]').keypress(function(e){
			var a = e.which;
			if(((a >= 32 && a <= 126) || a === 128 || (a >= 130 && a <= 140) || a === 142 || (a >= 145 && a <= 156) || (a >= 158 && a <= 255)) && isNaN(String.fromCharCode(a)))
				return false;
		});
})

// Added by B.X 20/07/2010
// Changes the selected value of a select box
function changeSelectedValue(selector, value) {
	$(selector).val(value);
	$(selector + '_input').toggleClass('selectLabel',(value==''))
						.val($(selector + ' option:selected').text());
	$(selector + '_container li.selected').removeClass('selected');
	$(selector + '_input_' + value).addClass('selected');
}

var timesSubmitted = 0;
function submitPayment(){
	if (timesSubmitted == 0){
		$("a").click(function(){ 
			return false; 
		});
		//$('#btnProcess').html('<p>Processing Credit Card Transaction.  Please be patient.<img src="/images/ajax/ajax-loader-2.gif" alt="loading" /></p>')
		
		$('#checkoutForm').submit();
		timesSubmitted ++;
	}else{
		alert("Payment has already been submitted, please be patient");
	}
}
