var autoScrollDest = ''		//auto scroll to this content id
var currentContent = ''		//currently displayed content id

var subMenuItem = ''		//sub content to display
var currentSubMenuItem = ''  //currently displayed sub content
var finCount = 0;
var clickSub = false
var isMainSliding = false
var isSubSliding = false

var isGalleryMainSliding = false
var setMainNavActive = true;  //if arive from a direct link ie main=xxxx&sub=yyyy

$(function () {
	
    $('a', '#mainLogo').click(function (e) {
    	if(isSubSliding == false && isMainSliding == false){
			var id = $(this).attr('homeId')
			var mainMenu = $('#'+id,'#mainNav')
			var subMenus = $(mainMenu).find('ul')
			
			if(subMenus.length > 0 && clickSub == false){
				subMenuItem = $(this).attr('rel')
			}
	
			clickSub = false
			scrollGoUp($(this).attr("link"))
			//window.location.replace($(this).attr("href"))
		}
    	e.preventDefault();
    });
     
    $('#mainNav ul li').click(function (e) {

		if(isSubSliding == false && isMainSliding == false){
		
			if($(this).hasClass('main') == false){ //sub menu items
				var menuMain = $(this).parent().parent()
				//var href = $("a", menuMain).attr("href")

				//href = href.substr(1, href.length-2)
				
				subMenuItem = $('a',this).attr('rel');

				clickSub = true
				e.preventDefault();
			}else{
				
				var subMenus = $(this).find('ul')
				
				if(subMenus.length > 0 && clickSub == false){
					subMenuItem = $(this).attr('rel')
				}

				clickSub = false
				scrollGoUp($("a", this).attr("link"))
				//window.location.replace($("a", this).attr("href"))
				
			}
        }
        e.preventDefault();
    });
    
	

    $.Window = $(window);
    $.Scroll = ($.browser.mozilla || $.browser.msie) ? $("html") : $("body");
    $.Mobile = ($("body").hasClass("webkit-mobile") || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))), $.Unsupported = $("body").hasClass("unsupported-browser");
    
    $(".section").initScroll()
    
    
});

function content(main, sub){

	if(isSubSliding == false && isMainSliding == false){
		subMenuItem = sub;
		
		scrollGoUp(main)
	}
}

//scroll up/down when click on menu item!!
function scrollGoUp(a) {

	//debug1('scrollGoUp()', {'a':a} ,{'subMenuItem':subMenuItem},{'currentSubMenuItem':currentSubMenuItem})
	
	a = a.substr(0,a.length-1) //adding '-' to end of href on click and then removing it stops page jumping to section breifly before doing the scroll!!
    target = $(a);
    autoScrollDest = a.substr(1) //remove # from start
    
    isMainSliding = true
    
    finCount = 0;
    if(target.offset().top != $(window).scrollTop()){
		$("html, body").animate({
			scrollTop: target.offset().top
		}, 1000, "swing", function () {
			autoScrollDest = '';
			finCount ++;
			isMainSliding = false
			
			if(finCount == 1) displaySubContent()
		})
    }else{
    	displaySubContent()
    	autoScrollDest = '';
    	isMainSliding = false
    }
    
}(function (a) {
    a.Events = {
        SECTION_ENTER: "sectionEnter",
        SCROLL_TO: "scrollTo",
        SCROLL: "windowScroll",
        SCROLL_ENTER: "windowScrollEnter",
        SCROLL_LEAVE: "windwScrollLeave"
    }
})(jQuery);


(function (a) {
	
    a.fn.initScroll = function (c) {
    	
        var b = {};
        if (c) {
            a.extend(b, c)
        }
        this.each(function () { //per section
            var section = a(this);
            var sectionID = section.attr("id");

            section['all']()
			
        })
    }
})(jQuery);


(function (a) {
	
    a.fn.parallax = function (c) {
    	
        var b = {
            threshold: -100,
            offset_scroll: 6,
            offset_intertia: 0.15  //0.15
        };
        
        if (c) {
            a.extend(b, c)
        }
        
        this.each(function () {
            var f = a(this),
            
            e = f.attr("id");
            b.threshold = 0;
           
            if (a.Mobile || a.Unsupported) {
            
                f.css({backgroundAttachment: "scroll"})
                
            } else {
            
                a.Window.bind("scroll", function (g) {
                
                    if (a.inview(f, {threshold: b.threshold})) {
                    	
                    	var doEnter = false
                    	var browserMiddle = $(window).height()/2
                    	
                    	if(a.distanceFromTop(f) > 0){ //bottom up
                    		doEnter = a.distancefromfold(f, {threshold: 0}) >  browserMiddle//200
                    	}else{
                    		doEnter = f.height() + a.distanceFromTop(f)  > browserMiddle //Math.abs(a.distanceFromTop(f)) < 900
                    	}
                    	
                        if (!f.hasClass("_active") && doEnter) {
                        
                        	
                            f.addClass("_active");
                            
                            if (c.is_nav) {
                                a("body").triggerHandler(a.Events.SECTION_ENTER, e)
                            }
                            
                            f.triggerHandler(a.Events.SCROLL_ENTER)
                        }
                        
                        if (f.hasClass("_active") && !doEnter) {
                        
                            f.removeClass("_active");
                            f.triggerHandler(a.Events.SCROLL_LEAVE)
                            
                        }
                        
                        updateBackgroundPos();
                        f.triggerHandler(a.Events.SCROLL, a.distancefromfold(f, {threshold: b.threshold}) - b.threshold)
                        
                    } else {
                        if (f.hasClass("_active")) {
                        
                            f.removeClass("_active");
                            f.triggerHandler(a.Events.SCROLL_LEAVE)
                            
                        }
                    }
                })
            }
            
            //sets the y offset of the background image
            function updateBackgroundPos() {
                var h = "50% ";
                var g = h + (a.distanceFromTop(f)* b.offset_intertia) + "px";
                
                
               	f.css({backgroundPosition: g})
            }
            
        });
        return this
    };
    
     a.fn.all = function () {

        this.each(function () { //only one
       		    	
            var g = a(this),
                d = g.find("header"),
                c = -200;

            g.parallax({
                threshold: c,
                is_nav: true
            }).bind(a.Events.SCROLL, scroll).bind(a.Events.SCROLL_ENTER, scrollEnter).bind(a.Events.SCROLL_LEAVE, scrollLeave);

			//backgroung image paralax - doesn't actually achieve anything!!!
            function scroll(i, j) {
                var h = "0 " + ((480 - j / 3) + 200) + "px"
            }
            
            //menu item hilited
            function scrollEnter(h) {
            	var menuItem = $(this).attr("rel")
            	var contentID = $(this).attr("id")
            	var menuListItem = $("#"+menuItem)
            	var subMenus = $(menuListItem).find('ul')
            	var subNav = $('#subNav')
            	var menu =  a("#"+menuItem)
                
                if(setMainNavActive == true){
                	menu.addClass("current")
                	menu.stop(true,true).animate({backgroundColor: '#4B4B4B'}, 400,'linear',function(){
					});
				}
				
				
                
                if(subMenus.length > 0){
                	if(autoScrollDest == '' || autoScrollDest == contentID){
                		currentSubMenuItem = $('.sub:visible',$(this)).attr('id');
                		setupSubNav(subMenus)
                	}
                	if(currentSubMenuItem == undefined) currentSubMenuItem = ''

                }else{
                	currentSubMenuItem = ''

                	if ($.browser.msie && parseInt($.browser.version)<9){
                		subNav.hide();
                	}else{
                		subNav.stop(true,true).fadeTo(300,0);
                	}
                }
                
                if(setMainNavActive == true){
                	currentContent = contentID
                }
                Cufon.refresh()
                
                setMainNavActive = true
                //debug1('scrollEnter(h)',currentContent)
            }
            
            //menu item normal
            function scrollLeave(h) {
            	var menuItem = $(this).attr("rel")
            	var menu =  a("#"+menuItem)
            	
            	menu.removeClass("current")
            	
            	 menu.stop(true,true).animate({backgroundColor: '#000000'}, 400,'linear',function(){
                });
                
                Cufon.refresh()
            }
        });
        return this
    };
    
    
    
})(jQuery);

(function (a) {

	a.distanceFromTop = function(b){
		return b.offset().top - a(window).scrollTop()
	}
	
    a.distancefromfold = function (b, d) {

        if (d.container === undefined || d.container === window) {
            var c = a(window).height() + a(window).scrollTop() //this one  a(window).height() = browser height,    a(window).scrollTop() = scroll position
        } else {
            var c = a(d.container).offset().top + a(d.container).height()
        }
        
        //d.threshold = 0
        //b.offset().top = 0/1130/2260/3390 ie content position
        return (c + d.threshold) - b.offset().top  
    };
    
    a.belowthefold = function (b, d) {
        if (d.container === undefined || d.container === window) {
            var c = a(window).height() + a(window).scrollTop()
        } else {
            var c = a(d.container).offset().top + a(d.container).height()
        }
        return c <= b.offset().top - d.threshold
    };
    
    a.rightoffold = function (b, d) {
        if (d.container === undefined || d.container === window) {
            var c = a(window).width() + a(window).scrollLeft()
        } else {
            var c = a(d.container).offset().left + a(d.container).width()
        }
        return c <= b.offset().left - d.threshold
    };
    
    a.abovethetop = function (b, d) {
        if (d.container === undefined || d.container === window) {
            var c = a(window).scrollTop()
        } else {
            var c = a(d.container).offset().top
        }
        return c >= b.offset().top + d.threshold + b.height()
    };
    
    a.leftofbegin = function (b, d) {
        if (d.container === undefined || d.container === window) {
            var c = a(window).scrollLeft()
        } else {
            var c = a(d.container).offset().left
        }
        return c >= b.offset().left + d.threshold + b.width()
    };
    
    a.inview = function (b, c) {
        return (a.abovethetop(b, c) != true && a.belowthefold(b, c) != true)
    };
    
    a.extend(a.expr[":"], {
        "below-the-fold": "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold": "!$.belowthefold(a, {threshold : 0, container: window})",
        "right-of-fold": "$.rightoffold(a, {threshold : 0, container: window})",
        "left-of-fold": "!$.rightoffold(a, {threshold : 0, container: window})"
    })
    
    
    
})(jQuery);




//**********************************************************
// Displays the sub content. 
// Sliding left/right as required
//**********************************************************
function displaySubContent(){
	var contentDiv = $('#'+currentContent);
	
	var menuItem = contentDiv.attr("rel")
    var menuListItem = $("#"+menuItem)
    var subMenus = $(menuListItem).find('ul')
    
    //debug1('displaySubContent() first',{currentSubMenuItem:currentSubMenuItem},{subMenuItem:subMenuItem},{subMenusLength:subMenus.length},{currentContent:currentContent})
    
    if(subMenus.length > 0){
        currentSubMenuItem = $('.sub:visible',contentDiv).attr('id');
    }
    if(currentSubMenuItem == undefined){
    	currentSubMenuItem = ''
    	//debug1('displaySubContent() undefined');
    }

	//debug1('displaySubContent() second',{currentSubMenuItem:currentSubMenuItem},{subMenuItem:subMenuItem},{subMenusLength:subMenus.length})
	
	//need all this crap above cause in IE!!!!!!! the scrollEnter(h) function above is called after this function is called and therefore currentSubMenuItem not set!!!
	
	var trackingPath = ''
	if(currentSubMenuItem == ''){
		trackingPath = currentContent
	}else{
		trackingPath = subMenuItem
	}

	if(trackingPath.substr(trackingPath.length-1) == '_'){
		trackingPath = trackingPath.substr(0,trackingPath.length-1)
	}
	
	_gaq.push(['_trackPageview', trackingPath])
	//_gaq.push(['_trackPageview']);

	
	if(currentSubMenuItem != '' && subMenuItem != '' && currentSubMenuItem != subMenuItem){
		var currentSubContent = $('#'+currentSubMenuItem)
		var newSubContent = $('#'+subMenuItem)
		var currNum = currentSubContent.attr('rel')
		var newNum = newSubContent.attr('rel')
		
		var backImage = $('.backgroundImage',newSubContent)
		var newStartX
		
		if(newNum > currNum){
			newStartX = -$(window).width()
		}else{
			newStartX = $(window).width()
		}
		
		
		currentSubContent.animate({
			left: newStartX
		}, 1000, "swing", function () {
			currentSubContent.hide()
		})
		
		newSubContent.css({left: -newStartX + "px"})
		newSubContent.show()
		backImage.show();
		
		//these two lines if content background image is 50% 0
		backImage.css({left:-(($('img',backImage).width() - $(window).width())/2) + 'px'})
		backImage.css({width:'auto'})
		
		isSubSliding = true
		newSubContent.animate({
			left: 0
		}, 1000, "swing", function () {
			currentSubMenuItem = subMenuItem
			contentDiv.css('background-image', 'url('+$('img',backImage).attr('src')+')');
			backImage.hide();
			backImage.css({width:'100%'})
			isSubSliding = false
		})
		
		
		var mainNav = $('li[class*="current"]','#mainNav')
		var mainNavSub = $('li[class*="current"]',mainNav)
		var mainNavSubNew = $('a[rel="'+subMenuItem+'"]',mainNav).parent()
		
		var subNav = $('#subNav')
		var subNavCurr = $('a[rel="'+currentSubMenuItem+'"]',subNav).parent()
		var subNavNew = $('a[rel="'+subMenuItem+'"]',subNav).parent()
		
		mainNavSub.removeClass("current");
		mainNavSubNew.addClass("current");
		
		mainNavSub.stop(true,true).animate({backgroundColor: '#78797c'}, 1000,'linear',function(){
		});
		
		mainNavSubNew.stop(true,true).animate({backgroundColor: '#4b4b4b'}, 1000,'linear',function(){
		});
		
		subNavCurr.removeClass("current");
		subNavNew.addClass("current");
		
		
		subNavCurr.stop(true,true).animate({backgroundColor: '#78797c'}, 1000,'linear',function(){
		});
		
		
		subNavNew.stop(true,true).animate({backgroundColor: '#4b4b4b'}, 1000,'linear',function(){
		});
		

		
		Cufon.refresh()
		
	}

}

//**********************************************************
// sets up and displays bottom sub nav if required.
//**********************************************************
function setupSubNav(items){
	var subNav = $('#subNav')
		
	subNav.html('<ul>'+items.html()+'</ul>');

	Cufon.refresh();

	var items = $('li',subNav);
	var width = 0
	var subNavItem
	
	
	items.each(function(index, value) { 
		subNavItem = $(value);
		
		//need this cause subNavItem.width() = 0 in IE!!!!!
		var cufonItems = $('cufon',subNavItem);
		cufonItems.each(function(index1, cufonValue) {
			width += parseInt($(cufonValue).width()) 
		})
		width += 31

	})
	
	//subNav.css({marginLeft: -(subNav.width()/2)+'px'})
	subNav.css({marginLeft: -(width/2)+'px'})
	
	if ($.browser.msie && parseInt($.browser.version)<9){
		subNav.show()
	}else{
		subNav.stop().fadeTo(300,1);
	}
	
	$('a', '#subNav').bind('click', function(e) {
		
		if(isSubSliding == false && isMainSliding == false){
			subMenuItem = $(this).attr('rel');
		
			scrollGoUp('#' + currentContent + '-')
		}
		e.preventDefault();
	});
	
	
	$('ul li', '#subNav').hover(
		function() {
			if(!$(this).hasClass('current')){
				$(this).stop(true,true).animate({'backgroundColor': '#4B4B4B'}, 400);
			}
		},
		function() {
			if(!$(this).hasClass('current')){
				$(this).stop(true,true).animate({'backgroundColor': '#78797C'}, 400);
			}
		}
	);
	
}


//**********************************************************
// adjust 'top' of each content to follow directly 
// below theprevious content
//**********************************************************
function setContentHeight(){
	var content = $('#content')
	var last = $('.section:last', content)
	
	//adjust content height so same as background image and also next content directly below previous
	var contents = $('.section', content)
	var top = 0
	var aContent
	var imageWidth
	var imageHeight
	var browserWidth = $(window).width()
	var browserHeight = $(window).height()
	var lastcontentArea = $('.contentArea',last)
	var lastcontentAreaHeight = lastcontentArea.outerHeight() + parseInt(lastcontentArea.css('margin-top')) + 60
	
	contents.each(function(index, value) { 
		aContent = $(value)
		imageWidth = aContent.attr('imageX')
		imageHeight = aContent.attr('imageY')
		
		aContent.height(imageHeight)
		aContent.css({top: top + 'px'})
		
  		top += parseInt(imageHeight)
  		
  		//Set height of all background images
		var backImages = $('.backgroundImage', aContent)
		backImages.each(function(index, value) { 
			$(value).height(browserHeight)
		})
  		
	})
	$(window).scrollTop($(window).scrollTop()+1)
	$(window).scrollTop($(window).scrollTop()-1)
	
	
	
	//content.height(last.offset().top + $(window).height())
	content.height(last.offset().top + Math.max($(window).height(), lastcontentAreaHeight) )

}




function debug(something, content, contentFilter){
	if(content == undefined || content == contentFilter){
		document.getElementById("footerNav").innerHTML = something
	}
}

function debug1(){
	var op = '';
	
	/*
	if(debug1.caller.name != null){
		if(debug1.caller.name.toString() != ''){
			op = '<strong style="margin-right:30px;">'+arguments.callee.caller.name.toString() + '()</strong>';
		}
	}
	*/
	
	for(var i=0; i<arguments.length; i++){
		if(typeof(arguments[i]) == 'object'){
			for (var keyValue in arguments[i]){
				op += '<span style="margin-right:15px;"><strong><i>' + keyValue + '</i></strong> : ' + arguments[i][keyValue] + '</span>';
			}
		}else{
			//op += '<span style="margin-right:15px;"><strong><i>' + i + '</i></strong> : ' + arguments[i] + '</span>';
			op += '<span style="margin-right:15px;">' + arguments[i] + '</span>';
		}
	}
	$('#debugOp').append(op + '<br/>');

}

$(document).ready(function() {
	var theNav = $('#mainNav')
	var first = $('li',theNav).first()
	var subMenus = $(first).find('ul')

	$(window).scrollTop(0)
	
	if(subMenus.length > 0){
		var subNav = $('#subNav')
		
		setupSubNav(subMenus)
	}
	
	currentContent = $('a', first).attr("href")
	currentContent = currentContent.substr(1, currentContent.length-2)
	
	setContentHeight()
	
	$(window).bind("resize", function(){
		setContentHeight()
	 });
	  
	 
	 subMenuItem = 'something' //ie7 bug fix needs do be defined at start else global var doesn't exists!!!
	 

	 if(window.location.search != ''){
	 	var querryString = window.location.search.substring(1)
	 	var keyValues = new Array();
	 	var mainSection = '';
	 	var subSection = '';
	 	
        keyValues = querryString.split("&");

        for(var i = 0; i<keyValues.length; i++){
        	var aKeyValue = keyValues[i]
        	var key = aKeyValue.substring(0,aKeyValue.indexOf("="))
        	var value = aKeyValue.substring(aKeyValue.indexOf("=") + 1)
        	
        	if(key == 'main') mainSection = value;
        	if(key == 'sub') subSection = value;

        }
        //debug1('Ready!',querryString)
        
        if(mainSection != ''){
        	var mainSectionDiv = $('#'+mainSection)
        	currentContent = mainSection
        	
        	$(window).scrollTop(mainSectionDiv.offset().top)
        }
        
        setMainNavActive = false

	 }else{
	 	setMainNavActive = true
	 }
	
	//**********************************************************
	// Converts content/section links set within the CMS to
	// the correct function call ie content(a,b)
	//**********************************************************
	 var links = $('a[href^="###"]', '.contentArea');
	 jQuery.merge( links, $('a[href^="###"]', '#footerNav') )
	 jQuery.merge( links, $('a[href^="###"]', '#socialIcons') )
	 
	 links.each(function(index, value) {
	 	var link = $(value);
	 	
	 	
	 	link.click(function(e) {
			var link = $(this);
			var href = link.attr('href')
			var subMenu = href.substring(3);
			var subGalleryID
			
			href = href.substring(2)
			
			if(href.substr(1,2) == '||'){
				subGalleryID = href.substring(href.indexOf('#',1)+1)
				
				href = href.substr(0,1) + href.substr(3)
				subMenu = subMenu.substr(2)
				subMenu = subMenu.substr(0,subMenu.indexOf('#'))
				
				setUpGallery(subMenu.substring(0,subMenu.indexOf('_')), subGalleryID)
			}
			
			if(href.substring(href.length - 1) != '_'){
				href = href.substring(0,href.indexOf('_'))+'-'
			}else{
				href = href.substring(0,href.indexOf('_'))+'-'
			}
			
			
			content(href, subMenu);
			
			e.preventDefault();
		})
	 	
	 })
	 
	 
	
	
	//**********************************************************
	// Selects the direct unordered list and direct list items
	// of that list, and fades in their hidden drop-down.
	//**********************************************************
	$('> ul > li', '#mainNav').hover(
		function() {
			var subMenu = $(this).children('div');
			
			if (subMenu.length > 0) {
				//if (!subMenu.is(':visible')) {
					//subMenu.css('filter', 'alpha(opacity=40)');
					
					if ($.browser.msie && parseInt($.browser.version)<9){
						subMenu.show();
					}else{
						subMenu.stop(true,true).fadeIn(300);
					}
					
				//} else {
					//subMenu.stop(true,true).fadeOut(300);
				//}
			}
			
			if(!$(this).hasClass('current')){
				$(this).stop(true,true).animate({'backgroundColor': '#4B4B4B'}, 400);
			}
		},
		function() {
			var subMenu = $(this).children('div');
			if (subMenu.length > 0) {
				//if (subMenu.is(':visible')) {
					if ($.browser.msie && parseInt($.browser.version)<9){
						subMenu.delay(200).hide();
					}else{
						subMenu.stop(true,true).delay(50).fadeOut(300);
					}
				//}
			}
			
			if(!$(this).hasClass('current')){
				$(this).stop(true,true).animate({'backgroundColor': '#000000'}, 400);
			}
		}
	);

	
	//**********************************************************
	// Fades the background colours of any sub-menu link
	// that isn't already active, as you hover over it.
	//**********************************************************
	$('ul li ul li', '#mainNav').hover(
		function() {
			if(!$(this).hasClass('current')){
				$(this).stop(true,true).animate({'backgroundColor': '#4B4B4B'}, 400);
			}
		},
		function() {
			if(!$(this).hasClass('current')){
				$(this).stop(true,true).animate({'backgroundColor': '#78797C'}, 400);
			}
		}
	);
	
	
	
	//**********************************************************
	//rollover function, over image *_over.jpg, off image *_off.jpg
	//**********************************************************
	$('.rollover').hover(function(){
		//replace _over with _off
		$(this).attr('src', $(this).attr('src').replace(/_off./gi, "_over."));	  
	},
	function(){
		$(this).attr('src', $(this).attr('src').replace(/_over./gi, "_off."));
	});
	
	/*
	$(window).scroll(function() {
  		autoScrollDest = ''
	});
	*/
	
	

	
	//**********************************************************
	//Sets up the Gallery depending on what sub gallery is selected (if any)
	//**********************************************************
	function setUpGallery(theGallery, subGallery){
		var subGalleryImages = []

		var mainScrollHtml = ''
		var thumbnailsHtml = ''
		var theGalleryImage
		var holderDiv = $('.mainImage', '#'+theGallery)
		
		var galleryTopDiv =  holderDiv.parent()
		var viewFullGallery =  $('.viewFullGallery',galleryTopDiv)
		
		var currentImageDiv = $('.currentImage', holderDiv)
		var currentImage = $('img', currentImageDiv)
		var currentOverlay = $('.textOverlay', holderDiv)
		var currentHotspots = $('.hotSpots', holderDiv)
		
		var mainScrollDiv = $('.mainScroll', holderDiv)
		
		var thumbnailsDiv = $('.items', galleryTopDiv)
		
		var api = $(".scrollable", galleryTopDiv).data("scrollable")
		
		api.seekTo(0, 0);
		
		mainScrollDiv.html('')
		//thumbnailsDiv.html('')
		thumbnailsDiv.empty()
		
		if(subGallery == 0){
			viewFullGallery.hide()
		}else{
			viewFullGallery.show()
		}
		
		$('.greyOverlay', currentImageDiv).hide()
		$('.zoomAreaBox', currentImageDiv).hide()
		$('.zoomOverlay', currentImageDiv).hide()
		$('.imageHolderCurrent', currentImageDiv).unbind('mousemove');
		
		
		for(var i=0; i<galleryImages.length; i++){
		
			if(galleryImages[i].subGallery == subGallery || subGallery == 0){
				subGalleryImages.push(galleryImages[i])
			}
		}
		
		
		holderDiv.attr('max', subGalleryImages.length-1)
		holderDiv.attr('rel', 0)
		
		if(subGalleryImages.length > 0){
			for(i=0; i<subGalleryImages.length; i++){
			
				theGalleryImage = subGalleryImages[i]
				
				if(i == 0){
					currentImage.attr('src',theGalleryImage.src)
					currentImage.show()
					currentOverlay.html('<h2>'+theGalleryImage.title+'</h>' + theGalleryImage.body)
					if(jQuery.trim(theGalleryImage.title) == ''){
						$('.textOverlay', currentImageDiv).hide()
					}else{
						$('.textOverlay', currentImageDiv).show()
					}
					currentOverlay.css('bottom', 0)
					
					currentHotspots.html('')
					
					if(theGalleryImage.zoomAreas.length > 0){
						for(h=0; h<theGalleryImage.zoomAreas.length; h++){
							currentHotspots.append('<a class="galleryImageZoomMarker" style="top: '+theGalleryImage.zoomAreas[h].locY+'px; left: '+theGalleryImage.zoomAreas[h].locX+'px;" href="#">'+theGalleryImage.zoomAreas[h].text+'</a>')
						}
					}
				}
				
				mainScrollHtml += '<div class="imageHolder" rel="'+i+'" style="display:none;">';
				mainScrollHtml += '		<img rel="'+theGalleryImage.src+'" src="/img/loading.gif" zoom="'+theGalleryImage.zoom+'">';
				mainScrollHtml += '		<div class="textOverlay" '+((jQuery.trim(theGalleryImage.title) == '')?'style="display:none;"':'')+'>';
				mainScrollHtml += '			<h2>'+theGalleryImage.title+'</h2>';
				mainScrollHtml += 			theGalleryImage.body;
				mainScrollHtml += '		</div>';
				mainScrollHtml += '		<div class="hotSpots">';
				if(theGalleryImage.zoomAreas.length > 0){
					for(h=0; h<theGalleryImage.zoomAreas.length; h++){
						mainScrollHtml += '			<a class="galleryImageZoomMarker" style="top: '+theGalleryImage.zoomAreas[h].locY+'px; left: '+theGalleryImage.zoomAreas[h].locX+'px;" href="#">'+theGalleryImage.zoomAreas[h].text+'</a>';
					}
				}
				mainScrollHtml += '		</div>';
				mainScrollHtml += '</div>';
				
				
				
	
				if(i == 0 || i%7 == 0) thumbnailsHtml += '<div>'
				thumbnailsHtml += '	<img '+((i == 0)?'class="hilite"':'')+' src="'+theGalleryImage.thumb+'" rel="'+i+'"/>'
				if(i == subGalleryImages.length-1 || (i%7 == 6 && i != 0)){
					thumbnailsHtml += '</div>'
					api.addItem(thumbnailsHtml)
					thumbnailsHtml = '';
				}
	
			}
			
			
		}else{
			currentImage.attr('src','/img/noneFound.gif')
			currentOverlay.html('')
			$('.textOverlay', currentImageDiv).hide()
			currentHotspots.html('')
		}
		
		mainScrollDiv.html(mainScrollHtml)
		//thumbnailsDiv.html(thumbnailsHtml)
		//thumbnailsDiv.css('left',0)
			
		$('.prevMain', galleryTopDiv).addClass('disabled')
		$('.prev', galleryTopDiv).addClass('disabled')
		
		if(subGalleryImages.length > 1){
			$('.nextMain', galleryTopDiv).removeClass('disabled')
		}else{
			$('.nextMain', galleryTopDiv).addClass('disabled')
		}
		
		if(subGalleryImages.length > 7){
			$('.next', galleryTopDiv).removeClass('disabled')
		}else{
			$('.next', galleryTopDiv).addClass('disabled')
		}
		

		//$(".scrollable").scrollable();
		
	}
	

	//setUpGallery('Gallery1', 1)
	

	//**********************************************************
	//Scrolls the main gallery image when click on large next/prev buttons
	//**********************************************************
	$('a.prevMain', '#content').bind('click', function(e) {
		$('a.nextMain', '#content').removeClass('disabled')
		doGalleryMainImageSlide(this, -1, e)
	});
	
	$('a.nextMain', '#content').bind('click', function(e) {
		$('a.prevMain', '#content').removeClass('disabled')
		doGalleryMainImageSlide(this, 1, e)
	});
	
	function doGalleryMainImageSlide(who, direction, e){
		var me = $(who)
		
		var mainImageDiv = $('.mainImage',$(who).parent())
		var imageWidth = mainImageDiv.width();
		var max = parseInt(mainImageDiv.attr('max'))
		var current = parseInt(mainImageDiv.attr('rel'))
		
		var currentImageDiv = $('.currentImage',$(who).parent());
		var currentImage = $('img', currentImageDiv)
		var currentOverlay = $('.textOverlay', currentImageDiv)
		var currentHotSpots = $('.hotSpots', currentImageDiv)
		
		var mainScrollDiv = $('.mainScroll',$(who).parent());
		var nextImageDiv = $($('.imageHolder',mainScrollDiv)[current+direction])
		var nextImage = $($('img', mainScrollDiv)[current+direction])
		var overlay = $('.textOverlay',nextImageDiv)
		var hotSpots = $('.hotSpots',nextImageDiv)
		
		var thumbnails = $('.items',$(who).parent().parent());
		
		var currThumbnail = $('img.hilite',thumbnails);
		var nextThumbnail = $('img[rel="'+(parseInt(current)+direction)+'"]',thumbnails);
		
		
		$('.greyOverlay', currentImageDiv).hide()
		$('.zoomAreaBox', currentImageDiv).hide()
		$('.zoomOverlay', currentImageDiv).hide()
		$('.imageHolderCurrent', currentImageDiv).unbind('mousemove');
		
		
		if(isGalleryMainSliding == false){
			isGalleryMainSliding = true
			
			currThumbnail.removeClass('hilite')
			
			mainScrollDiv.css('left', imageWidth * direction)
			nextImageDiv.show()
			
			if(nextImage.attr('rel') != 'loaded'){
				nextImage.attr('src',nextImage.attr('rel'))
				nextImage.attr('rel','loaded')
			}

			mainScrollDiv.animate({
      			left: parseInt(mainScrollDiv.css('left'),10) - imageWidth *direction
    		}, 1000, function() {
    		
    			isGalleryMainSliding = false;

    			current += direction
    			mainImageDiv.attr('rel', current)
    			
    			nextThumbnail.addClass('hilite')
				
				$('.imageHolderCurrent',currentImageDiv).css('background-image', 'url("'+nextImage.attr('src').replace(/ /g, '%20')+'")');
				currentImage.hide()
				currentImage.attr('src',nextImage.attr('src'))
				currentImage.attr('zoom',nextImage.attr('zoom'))
				
				currentOverlay.html(overlay.html())
				if(overlay.is(':hidden')){
					currentOverlay.hide()
				}else{
					currentOverlay.show()
				}
				
				currentOverlay.stop(true,true)
				currentOverlay.css('bottom', 0)
				setupCloseTextOverlay(currentOverlay)
				
				currentHotSpots.html(hotSpots.html())
				
				nextImageDiv.fadeOut(1)
				
    			if(current == ((direction == 1)?max:0)){
    				me.addClass('disabled')
    			}
  			});

		}
		
		e.preventDefault();
	}
	
	
	$('a.prevMain', '#content').addClass('disabled')
	




	//**********************************************************
	//Scrolls the thumbnails when click on small next/prev buttons
	//**********************************************************
	$(".scrollable").scrollable();
	
	
	
	
	//**********************************************************
	//Scrolls the main gallery image when click on tumbnails
	//**********************************************************
	$(".items img").live('click', function() {

		
		
		var me = $(this)
		//var url = $(this).attr("src").replace("_t", "");
		var id = $(this).attr('rel')
		
		var topDiv = $(this).parent().parent().parent().parent();
		
		var mainScrollDiv = $('.mainScroll',topDiv);
		var mainImageDiv = $('.mainImage',topDiv)
		var imageWidth = mainImageDiv.width();
		var max = parseInt(mainImageDiv.attr('max'))
		var current = parseInt(mainImageDiv.attr('rel'))
		var direction = (id > current)?1:-1;
		
		var currentImageDiv = $('.currentImage',topDiv);
		var currentImage = $('img', currentImageDiv)
		var currentOverlay = $('.textOverlay', currentImageDiv)
		var currentHotSpots = $('.hotSpots', currentImageDiv)
		
		//var mainScrollDiv = $('.mainScroll',topDiv);
		var nextImageDiv = $($('.imageHolder',mainScrollDiv)[id])
		var nextImage = $($('img', mainScrollDiv)[id])
		var overlay = $('.textOverlay',nextImageDiv)
		var hotSpots = $('.hotSpots',nextImageDiv)
		
		var thumbnails = $(this).parent().parent();
		var currThumbnail = $('img.hilite',thumbnails);
		
		$('.greyOverlay', currentImageDiv).hide()
		$('.zoomAreaBox', currentImageDiv).hide()
		$('.zoomOverlay', currentImageDiv).hide()
		$('.imageHolderCurrent', currentImageDiv).unbind('mousemove');

		if ($(this).hasClass("hilite") || isGalleryMainSliding) { return; }
		
		
		//setupCloseTextOverlay(overlay)
		
		currThumbnail.removeClass('hilite')
		mainScrollDiv.css('left', imageWidth * direction)
		nextImageDiv.show()
		
		if(nextImage.attr('rel') != 'loaded'){
			nextImage.attr('src',nextImage.attr('rel'))
			nextImage.attr('rel','loaded')
		}
			
		mainScrollDiv.animate({
			left: parseInt(mainScrollDiv.css('left'),10) - imageWidth *direction
		}, 1000, function() {
		
			isGalleryMainSliding = false;
			$('a.prevMain', '#content').removeClass('disabled');

			mainImageDiv.attr('rel', id)
			
			me.addClass('hilite')
			
			$('.imageHolderCurrent',currentImageDiv).css('background-image', 'url("'+nextImage.attr('src').replace(/ /g, '%20')+'")');
			currentImage.hide()
			currentImage.attr('src',nextImage.attr('src'))
			currentImage.attr('zoom',nextImage.attr('zoom'))
			
			currentOverlay.html(overlay.html())
			if(overlay.is(':hidden')){
				currentOverlay.hide()
			}else{
				currentOverlay.show()
			}
			
			currentOverlay.stop(true,true)
			currentOverlay.css('bottom', 0)
			setupCloseTextOverlay(currentOverlay)
			
			currentHotSpots.html(hotSpots.html())
			
			nextImageDiv.fadeOut(1)
				
			if(id == 0){
				$('a.prevMain', '#content').addClass('disabled')
			}else{
				$('a.prevMain', '#content').removeClass('disabled')
			}
			
			if(id == max){
				$('a.nextMain', '#content').addClass('disabled')
			}else{
				$('a.nextMain', '#content').removeClass('disabled')
			}
		});
		
		isGalleryMainSliding = true
		
		
	// when page loads simulate a "click" on the first image
	}).filter(":first").click();
	
	
	
	//**********************************************************
	//Displays/hides Gallery image text
	//**********************************************************
	$('.imageHolderCurrent', '#content').hover(
		function() {
			var overlay = $('.textOverlay',this)

			overlay.stop(true,true).delay(300).animate({
				bottom: 0
			}, 500, function() {
				
			});
		},
		function() {
			var overlay = $('.textOverlay',this)
			setupCloseTextOverlay(overlay)
		}
	);
	
	
	//**********************************************************
	//Auto hides Gallery image text
	//**********************************************************
	function setupCloseTextOverlay(who){
		who.stop(true,true).delay(5000).animate({
			bottom: -who.outerHeight()
		}, 500, function() {
			
		});
	}
	
	
	//setupCloseTextOverlay($('.textOverlay:first', '#content'))
	
	
	
	
	//**********************************************************
	//Zoom - Displays larger image when click on a Gallery Image Hot Spot
	//**********************************************************
	$('a.galleryImageZoomMarker').live('click', function(e) {
		var thisLink = $(this);
		var imageHolderCurrent = thisLink.parent().parent()
		var zoomOverLay = $('.zoomOverlay', imageHolderCurrent)
		var zoomText = $('.zoomText', zoomOverLay)
		var normalImageURL = $('img', imageHolderCurrent).attr('src')
		var zoomedImageURL = $('img', imageHolderCurrent).attr('zoom')
		var textOverlay = $('.textOverlay', imageHolderCurrent)
		var greyOverlay = $('.greyOverlay', imageHolderCurrent)
		var zoomAreaBox = $('.zoomAreaBox', imageHolderCurrent)
		var mode = (thisLink.position().left < imageHolderCurrent.width()/2)?'hotSpotOnLHS':'hotSpotOnRHS'
		var maxX = 0
		var minX = 0
		
		
		greyOverlay.show()
		
		zoomAreaBox.show()
		zoomAreaBox.css('background-image', 'url('+normalImageURL+')');
		
		zoomOverLay.show()
		zoomOverLay.css('background-image', 'url('+zoomedImageURL+')');
		//zoomOverLay.css('background-repeat', 'no-repeat');
		zoomOverLay.css('border', '4px solid #ffffff');
		
		if(thisLink.html() != ''){
			zoomText.html(thisLink.html())
			zoomText.show()
		}else{
			zoomText.hide()
		}
		
		textOverlay.stop(true,true).animate({
			bottom: -textOverlay.outerHeight()
		}, 500, function() {
			
		});


		
		if(mode == 'hotSpotOnLHS'){
			zoomOverLay.css('left', '');
			zoomOverLay.css('right', '0');
			minX = 0
			maxX = imageHolderCurrent.width() - zoomOverLay.outerWidth() - zoomAreaBox.outerWidth()
		}else{
			zoomOverLay.css('left', '0');
			zoomOverLay.css('right', '1');
			minX = zoomOverLay.outerWidth()
			maxX = imageHolderCurrent.width() - zoomAreaBox.outerWidth()
		}
		
		
		imageHolderCurrent.mousemove(function(e) {
  			updateZoomAreaBox(e, imageHolderCurrent, zoomAreaBox, minX, maxX, zoomOverLay)
		});
		
		updateZoomAreaBox(e, imageHolderCurrent, zoomAreaBox, minX, maxX, zoomOverLay)

		e.preventDefault();
	});
	
	
	function updateZoomAreaBox(e, imageHolderCurrent, zoomAreaBox, minX, maxX, zoomOverLay){
		var locX = e.pageX - imageHolderCurrent.offset().left - Math.round(zoomAreaBox.outerWidth()/2)
		var locY = e.pageY - imageHolderCurrent.offset().top - Math.round(zoomAreaBox.outerHeight()/2)
		
		if(locX < minX) locX = minX
		if(locX > maxX) locX = maxX
		if(locY < 0) locY = 0
		if(locY > imageHolderCurrent.height() - zoomAreaBox.outerHeight()) locY = imageHolderCurrent.height() - zoomAreaBox.outerHeight()
		
		zoomAreaBox.css('top', locY + 'px')
		zoomAreaBox.css('left', locX + 'px')
		
		zoomOverLay.css('background-position', (-locX*2) + 'px' + ' ' + (-locY*2) + 'px')
		zoomAreaBox.css('background-position', -locX + 'px' + ' ' + -locY + 'px')
	}
	
	
	//**********************************************************
	//Close Zoom 
	//**********************************************************
	$('a','.zoomAreaBox').bind('click', function(e) {
		var thisLink = $(this);
		var imageHolderCurrent = thisLink.parent().parent()
		var zoomOverLay = $('.zoomOverlay', imageHolderCurrent)
		var zoomAreaBox = $('.zoomAreaBox', imageHolderCurrent)
		var greyOverlay = $('.greyOverlay', imageHolderCurrent)
		
		greyOverlay.hide()
		zoomAreaBox.hide()
		zoomOverLay.hide()
		
		imageHolderCurrent.unbind('mousemove');
		
		e.preventDefault();
	});
	
	
	//**********************************************************
	//Form submit - Contact Us
	//**********************************************************
	var isSending = false
	$(".submitButton").click(function(e) {
		var isError = false;
		var submitButton = $(this);
		var theForm = $(this).parents('.messageForm')
		
		var salutation = $('#salutation', theForm);
		var firstname = $('#firstname', theForm);
		var surname = $('#surname', theForm);
		
		var company = $('#company', theForm);
		var workTitle = $('#workTitle', theForm);
		
		var email = $('#email', theForm);
		var phone = $('#phone', theForm);
		
		var address = $('#address', theForm);
		var city = $('#city', theForm);
		var state = $('#state', theForm);
		var postcode = $('#postcode', theForm);
		
		var message = $('#message', theForm);
		
		if(isSending == false){
			if(jQuery.trim(firstname.val()) == ''){
				$('label',firstname.parent()).addClass("error");
				isError = true
			}else{
				$('label',firstname.parent()).removeClass("error");
			}
			
			if(jQuery.trim(email.val()) == ''){
				$('label',email.parent()).addClass("error");
				isError = true
			}else{
				$('label',email.parent()).removeClass("error");
			}
			
			if(jQuery.trim(message.val()) == ''){
				$('label',message.parent()).addClass("error");
				isError = true
			}else{
				$('label',message.parent()).removeClass("error");
			}
			
			
			if(jQuery.trim(state.val()) == '...'){
				$('label',state.parent()).addClass("error");
				isError = true
			}else{
				$('label',state.parent()).removeClass("error");
			}
			
			
			if(isError == false){  
				//$(submitButton).attr('disabled', 'disabled');
				$(submitButton).fadeTo(300,0.5);
				isSending = true
				
				$.ajax({
					dataType: 'json',
					data:{salutation: salutation.val(), firstname: jQuery.trim(firstname.val()), surname:jQuery.trim(surname.val()), company:jQuery.trim(company.val()), workTitle:jQuery.trim(workTitle.val()), email:jQuery.trim(email.val()), phone:jQuery.trim(phone.val()), address:jQuery.trim(address.val()), city:jQuery.trim(city.val()), state:state.val(), postcode:jQuery.trim(postcode.val()), message:jQuery.trim(message.val())},
					type: "POST",
					url: 'formSubmit.php',
					success: function(data) {  
						//$(submitButton).removeAttr('disabled');
						$('.formElements',theForm).hide();
						$('.formResponse',theForm).show();
						isSending = false
						$(submitButton).fadeTo(300,1);
					}  
				}); 
			}
		}

		e.preventDefault();
	})
	
	//**********************************************************
	//Form submit - Newsletter
	//**********************************************************
	$(".submitButtonNewsletter").click(function(e) {
		var isError = false;
		var submitButton = $(this);
		var theForm = $(this).parents('.messageForm')
		
		var salutation = $('#salutation', theForm);
		var firstname = $('#firstname', theForm);
		var surname = $('#surname', theForm);
		
		var company = $('#company', theForm);
		var workTitle = $('#workTitle', theForm);
		
		var email = $('#email', theForm);
		
		if(isSending == false){
			
			if(jQuery.trim(email.val()) == ''){
				$('label',email.parent()).addClass("error");
				isError = true
			}else{
				$('label',email.parent()).removeClass("error");
			}
			
			if(isError == false){  
				$(submitButton).fadeTo(300,0.5);
				isSending = true
				
				$.ajax({
					dataType: 'json',
					data:{salutation: salutation.val(), firstname: jQuery.trim(firstname.val()), surname:jQuery.trim(surname.val()), company:jQuery.trim(company.val()), workTitle:jQuery.trim(workTitle.val()), email:jQuery.trim(email.val())},
					type: "POST",
					url: 'formSubmitNewsletter.php',
					success: function(data) {  
						$('.formElements',theForm).hide();
						$('.formResponse',theForm).show();
						isSending = false
						$(submitButton).fadeTo(300,1);
					}  
				}); 
			}
		}

		e.preventDefault();
	})
	
	//**********************************************************
	//Form submit
	//**********************************************************
	$('a',".formResponse").click(function(e) {
		var theForm = $(this).parents('.messageForm')
		
		$('.formElements',theForm).show();
		$('.formResponse',theForm).hide();
		isSending = false
		
		e.preventDefault();
	})
	
	
	if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod'){
     	$("#footerNav").css("position", "static");
     	$("#subNav").css("position", "static");
     	$("#mainNav").css("position", "static");
     	$("#socialIcons").css("position", "static");
     	$("#mainLogo").css("position", "static");
	};

	
	
	//**********************************************************
	//Dubug
	//**********************************************************
	$('#debug').click(function(e) {
		
		
		$('#debugOp').toggle();
		
		e.preventDefault();
	})
});


