debugMode=false;




function initDOM() {

	//$('form').css('border','1px solid red').each(function() { alert($(this).attr('id')) });


	$('#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') });


	$('h1.flashHeading').flash({
    src: 'gbbusters3a.swf',
    width: 980,
    height: 130
	});

	$('.definitionLink').css({cursor: 'help'}).hover(function() { showBallGrade($(this)) }, function() {  $('#ballGradeBubble').hide()  });



	$('body').append('<div id="ballGradeBubble"><div></div></div>');
	
	
	
	//oldURI = $('#menuContactUs a').attr('href');
	
	$('#menuContactUs a').bind('click',function() { showSlider('contact'); return false; });
	
		$('#askAQuestionButton a, #faqsLink, .bulkBallsLink').bind('click',function() { showSlider('askAQuestion'); return false; });


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

	
	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');
		
	}
	
	
	//setupCartButtons();
	
	

}

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

function initWindow() {
	
	
	
}

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) {
	
	//alert(which);
	//return false;
	
	
	//debug(sliderOut);
	
	
	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);

window.onload = initWindow;




/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function(){
	
var $$;

/**
 * 
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 * 
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 * 
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
	height: 240,
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+encodeURIComponent(this[key])+'&';
	return s.replace(/&$/, '');		
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String 
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it 
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more 
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<embed ' + String(htmlOptions) + '/>';		
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}
	
})();



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>');
		
		}
			
	}
	
}
