debugMode=false;




function initDOM() {

	$('body').addClass('javascript');
    
    // Check out to see if they are in the right place!
    
    var showModal = $.cookie('showLocaleModal') != 'false' && l10n != false;
    
    if (showModal) {
        
        
        
        $('body').append('<div id="modal" style="display: none;" /><div id="loading" style="display: none;" /><div id="overlay" style="display: none;" />');
    
        $modal = $('#modal');

        $overlay = $('#overlay');

		$loading = $('#loading');

		$modal.html('<p><img src="templates/Original1_B2B/images/layout/logo.png" alt="GBB" /></p><p>It looks like you are from <strong>' + l10n.userLong + '</strong> but you are on <strong>Golfball Busters ' + l10n.siteLong + '</strong>!</p><p>Would you like to go to <a href="' + l10n.userUrl + '"> GolfBall Busters ' + l10n.userLong + '</a> instead?</p><button type="button">No thanks</button> ');
		
		$loading.fadeIn(500);
		$overlay.show();
		$modal.fadeIn(500, function() { $loading.hide(); });
		
		$(document).click(function() {
		
		  $modal.hide();
		  $overlay.fadeOut(500);
		  
		  $.cookie('showLocaleModal', false, { expires: 14 });
		
		});

    
    };
    
    $('#header-specials').fadeIn(500).find('ul').jcarousel({
        auto: 2,
        scroll: 1,
        wrap: 'last',
        initCallback: function(carousel) {
        
        // Pause autoscrolling if the user moves with the cursor over the clip.
            carousel.clip.hover(function() {
                carousel.stopAuto();
            }, function() {
                carousel.startAuto();
            });

        
        }
    
    });
    
	if ( ! $('body').hasClass('logged-in')) {
	
		var loginButton = $('#user #login-link');
		
		loginButton.click(function(event) {
			event.preventDefault();
			$('#login').slideToggle(500, function() {
			
				if ( ! $(this).is(':hidden')) {
					var emailInput = $('#input-login-email');
					if (emailInput.val() === '') {
						emailInput.focus();
					};
				
				};
			
			});
		
		});	
	};
	
	var specialsButton = $('#menuSpecials');
	
	setInterval(function() {
		specialsButton.toggleClass('tag');
	}, 1000);
	
	
	

	$('#home-buttons').prepend('<li id="friend" style="cursor: pointer; ">Introduce a Friend</li>');

	$('#certFormContent form').bind('submit',function() {return checkForm('certForm');  });


	$('#sliderOverlay').hide();

	$('.formPanel').hide();


	//doGiftCertsPage();

	//$('#paymentBlock input[value=paypal]').attr('checked','checked');

	setupSlideMenu();
	$('a[rel*=external]').each(function() { $(this).bind('click',{href: $(this).attr('href') }, newWindow).attr('title','Link opens in a new window') });

	
	
	$('#menuContactUs a').bind('click',function() { showSlider('contact'); return false; });
	
	$('#faq, #faqsLink, #freight').bind('click',function() { showSlider('askAQuestion'); return false; });


	$('#friend').bind('click',function() { showSlider('tellAFriend'); return false; });

	
	var preload  = [];
	
	preload[0] = new Image;
	
	preload[0].src='templates/Original1_B2B/images/layout/alexpix.jpg';
	
	//highlightRows();
	
	if ($('.tellAFriendOpen').length) {
		
			showSlider('tellAFriend');
		
	}
	
	if ($('body.ask-a-question').length) {
		
			showSlider('askAQuestion');
		
	}
	
	
	
	$("#ball-gradings a, #customer-videos-list a").click(function(event) {
			$.fancybox({
					'padding'		: 0,
					'autoScale'		: false,
					'transitionIn'	: 'none',
					'transitionOut'	: 'none',
					'title'			: $(this).attr('title'),
					'width'		    : 680,
					'height'		: 495,
					'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
					'type'			: 'swf',
					'swf'			: {
					   	 'wmode'		: 'transparent',
						'allowfullscreen'	: 'true'
					}
				});
		
			event.preventDefault();
		});

	
	

}



function setupCartButtons() {

	$('.addToCart').bind('click', function() {
	
		thisName = $(this).attr('name');
	
		$('.addToCart:not(.addToCart[name=' + thisName + '])').css('border','2px solid red');
	
	
	
	})


}


//############################################

var certType='';
function doGiftCertsPage() {

	$('#giftPageBlock li a').hide();
	
	$('#giftPageBlock li:not(:last)').bind('click',function() {
															certType = $(this).attr('id')
															
															if (certType!='') { 
																
																$('#giftPageBlock li').css('borderBottom','none')
															}
															
															$(this).css('borderBottom','3px solid red')

															
															});
	
	$('#giftPageBlock li:last').bind('click',function() {
													  
													
															if (certType=='') {
																
																alert('Please click a gift voucher denomination to the left.');	
															} else {
																
																
																$('#form' + certType + ' button').click();	
															}
															
															});
}

//############################################

var previousSlider;
var sliderOut=false;
function showSlider(which) {

	
	
	debug(previousSlider);
	
	
	if (which!=previousSlider || !sliderOut) {
	
		
		
		if (sliderOut) {
			
		
			hideSlider();
			
		
		
		}
			
		
		setTimeout(function() {
		
		
				
			$('#' + previousSlider +'Content').css('display','none');
			
			$('#' + which + 'Content form').bind('submit',function() { return checkForm(which) });
		
			
			
			$('#sliderOverlay form input[type=text], #sliderOverlay form textarea').removeClass('inputError');
			
				$('#' + which + 'Content p.instructions').removeClass('error').addClass('information').text('All fields are required.');	

	
	
	
			
			
			$('#' + which + 'Content').show();
			$('.closeWindowLink').css({cursor: 'pointer'}).bind('click',hideSlider)
			previousSlider=which;
	
		
		
		
		
		if (!sliderOut) {
			$('#sliderOverlay').show().animate({left: '50%'},1000);
			sliderOut = true;
	
		}
		
								 }, 1000);
		
	
	}
	
	
	return false;
	
}

//####################################################################################

function hideSlider() {
	
	
	$('#sliderOverlay').animate({left: '-1000px'}, 500, function() { $(this).hide(); sliderOut=false; } );
	
}

//####################################################################################


function isset(varname){
 // return(typeof(window[varname])!='undefined');
  
  if (varname!=undefined) 
  { return true} else {
		return false;  
  }
}





//####################################################################################

function searchArray(ArrayObj, SearchFor){
  var Found = false;
  for (var i = 0; i < ArrayObj.length; i++){
    if (ArrayObj[i] == SearchFor){
      return true;
      var Found = true;
      break;
    }
    else if ((i == (ArrayObj.length - 1)) && (!Found)){
      if (ArrayObj[i] != SearchFor){
        return false;
      }
    }
  }
}

//####################################################################################


function checkForm(which) {
	//alert(which);
	
	
	var formElements = new Array();
	
	switch (which) {
		
		case 'askAQuestion':
		
			var requiredFields = new Array('name','email','question', 'spam');
			
		
		break;
		
		case 'contact':
		
			var requiredFields = new Array('name','email','enquiry', 'spam');
			
		
		break;
		
		case 'tellAFriend':
		
			var requiredFields = new Array('name','email','friends-email','friends-name');
			
		
		break;
		
		case 'certForm':
		
			var requiredFields = new Array('name','email');
			//alert('this far');
		
		break;
	
	}
	
	
	



	$('#' + which  +'Content form input[type=text], #' + which  +'Content form textarea').each(function() { 
																							
																							formElements[$(this).attr('name')] = $(this).val(); 
																																				 
																																				 //alert($(this).attr('name') + ' = ' +$(this).val();) 
																																				 
																																				 });
	
	
	
	
	var nameRegex = /^[a-z-'\s]{2,}$/i;
	
	var phoneRegex = /[\+ 0-9-\s\(\)]{6,}/i;
	
	var emailRegex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i ;
	
	var postcodeRegex = /[0-9]{4,6}/i;
	
	var placeNameRegex = /^[a-z-'\s]{2,}$/i;
	
	var postalAddressRegex = /[a-z-'\s0-9,]{3,}$/i;
	
	

		if (isset(formElements['name']) && !formElements['name'].match(nameRegex) && (searchArray(requiredFields,'name')) ) {
			
			showError("Please enter the full name.",which);
			highlightError('name',which);
			
			return false;
		}
		
		
		else if (isset(formElements['friends-name']) && !formElements['friends-name'].match(nameRegex) && (searchArray(requiredFields,'friends-name')) ) {
			
			showError("Please enter your friend's full name.",which);
			highlightError('friends-name',which);
			
			return false;
		}
		
	

		
		else if (isset(formElements['email']) && !formElements['email'].match(emailRegex) && (searchArray(requiredFields,'email'))) {
			showError("Please enter a valid email address.",which); 
			highlightError('email',which);
			return false;
		}
		
		else if (isset(formElements['friends-email']) && !formElements['friends-email'].match(emailRegex) && (searchArray(requiredFields,'friends-email'))) {
			showError("Please enter your friend's valid email address.",which); 
			highlightError('efriends-mail',which);
			return false;
		}
	
	
	

			
		 else if (isset(formElements['enquiry']) && formElements['enquiry']=='' && (searchArray(requiredFields,'enquiry'))) {
			showError("Please enter an enquiry.",which); 
			highlightError('enquiry',which);		
			return false;
		}
		
			 else if (isset(formElements['spam']) && formElements['spam']=='' && (searchArray(requiredFields,'spam'))) {
			showError("Please answer the question.",which); 
			highlightError('spam',which);		
			return false;
		}
	
	
		 else if (isset(formElements['question']) && formElements['question']=='' && (searchArray(requiredFields,'question'))) {
			showError("Please ask a question.",which); 
			highlightError('question',which);		
			return false;
		}
	

	
		 else if (isset(formElements['phone']) && !formElements['phone'].match(phoneRegex) && (searchArray(requiredFields,'phone')) ) {
			
			showError("Please enter a valid phone number.",which);
			highlightError('phone',which);
					
			return false;
		}
		
		 else if (isset(formElements['postal-address']) && !formElements['postal-address'].match(postalAddressRegex) && (searchArray(requiredFields,'postal-address')) ) {
			
			showError("Please enter a valid postal address.",which);
			highlightError('postal-address',which);
					
			return false;
		}
	

		
		
		 else if (isset(formElements['city']) && !formElements['city'].match(placeNameRegex) && (searchArray(requiredFields,'city')) ) {
			
			showError("Please enter a valid city.",which);
			highlightError('city',which);
					
			return false;
		}
		
	 	else if (isset(formElements['state']) && !formElements['state'].match(placeNameRegex) && (searchArray(requiredFields,'state')) ) {
			
			showError("Please enter a valid state.",which);
			highlightError('state',which);
					
			return false;
		}
	
	 else if (isset(formElements['postcode']) && !formElements['postcode'].match(postcodeRegex) && (searchArray(requiredFields,'postcode')) ) {
			
			showError("Please enter a valid postcode.",which);
			highlightError('postcode',which);
					
			return false;
		}
	


	return true; // passed all regex
	
	
	
}

//####################################################################################


function showError(text,which) {
	
	$('#' + which + 'Content p.instructions').removeClass('information').addClass('error').text(text);	
}

//####################################################################################


function highlightError(elementName,which) {
	
	
	$('#' + which + 'Content form [name=' + elementName + ']:visible').addClass('inputError').focus();
	
}





//############################################

function highlightRows() {
	$('.showHover').css('cursor','pointer').bind('click',function() {
										  
										  
										 // alert('d');
										  
										  $(this).children('ul').children('li').children('input[type=radio]').attr('checked','checked');
										  
										  
										  });
	
	
}



//############################################


function showBallGrade(object) {
	
	text = object.next('p').text();
	
	
	
	left = object.offset().left-$('#ballGradeBubble').width();
	
	top = object.offset().top - 40;
	
	$('#ballGradeBubble div').text(text);
	
	$('#ballGradeBubble').css({ left: left + 'px', top: top + 'px' }).fadeIn(500);
	
	
}


//############################################


function setupSlideMenu() {
	
	$('.subMenu').hide();
	$('.categoryName').css({cursor: 'pointer'}).bind('click',function() { showSlideMenuItem($(this)) });
	
}

//#####################################

var activatedMenu;
function showSlideMenuItem(object) {
	
	objectId = $(object).attr('id');
	
	
	if (activatedMenu!=objectId) {
	
		$('#'+activatedMenu).next().slideUp(250);
		
		
		$(object).next().slideDown(250);
	
		activatedMenu=objectId;
		
		
	}
	
}

//############################################


function newWindow(event) {
	href = event.data.href;
	var blankWindow = window.open(href, '_blank');
	blankWindow.focus();	
	return false;
	
}





$(document).ready(initDOM);




var debugPrinted=false;
function debug(text) {
	
	if (debugMode==true) {
		try{
			console.log(text);
		}
		catch(error){
			
			if (debugPrinted==false) {
			
				$('body').prepend('<div id="debugBox" style="position:absolute;padding:10px;left:0px;top:0px;display:block;width:auto;height:auto;font-size:1.2em;background-color:#000;color:#fff;z-index: 999;filter: alpha(opacity=80); filter: progid:DXImageTransform.Microsoft.Alpha(opacity=80); -moz-opacity: 0.80; opacity:0.8;"><h2>DEBUG BOX</h2></div>');
				debugPrinted=true;
				
				} 
			
			$('#debugBox').append('<p style="border-bottom:1px solid white;padding-bottom: 5px; padding-top: 5px">'+text+'</p>');
		
		}
			
	}
	
}


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
