
var hovertext = new Array();

var hovercolour   = new Array();
var hoverbgcolour = new Array();
var hoversize     = new Array();
var mapinitialised = false;

	hoversize['pouches'] = 15;
	hoversize['home']    = 14;
	hoversize['lifeguards'] = 14;
	hoversize['media'] = 13;
	hoversize['sunpouchhq'] = 13;
	hoversize['competition'] = 20;
	hoversize['gallery'] = 20;
		
	hovercolour['pouches'] = '#222222';
	hovercolour['home']    = '#BCBCBC';
	hovercolour['lifeguards'] = '#68BADA';
	hovercolour['media'] = '#68BADA';
	hovercolour['sunpouchhq'] = '#68BADA';
	hovercolour['competition'] = '#FFFFFF';
	hovercolour['gallery'] = '#FFFFFF';
	

	hoverbgcolour['pouches'] = '#FFFFFF';
	hoverbgcolour['home']    = '#000000';
	hoverbgcolour['lifeguards'] = '#000000';
	hoverbgcolour['media'] = '#FFFFFF';
	hoverbgcolour['sunpouchhq'] = '#0000000';
	hoverbgcolour['competition'] = '#4C054C';
	hoverbgcolour['gallery'] = '#4C054C';


	hovertext['pouches'] = "Who said sunscreen had to be a drag? Well we don't think it does. Here at the Australian Pouch Company we've decided to pop our Sunpouch SPF30+ in these funky, squishy little pouches that you'll just love. We also treat every skin as precious so we don't use any extra perfume, additives or other nasty stuff in our products which makes them all suitable for even the most sensitive of skins. Each pouch holds 75ml of our tried and tested UVA/UVB 30+ lotion and it is also 4 hours water resistant so perfect for a day on the beach or out for a surf or cycle.";
	
	hovertext['home'] = "Sunpouch is a little pocket of sun protection you can carry with you, no worries. It's small enough to keep one in your bag, one in your desk and one at home. Easy, that way you won't ever forget it.  Whilst you're protecting your skin we're doing our bit to protect the environment by popping your sunscreen in this eco friendly packet.";

	hovertext['lifeguards'] = "Our ambassadors are the lifeguards from Bondi Rescue - not only are they the iconic image for Australian health and fitness but work with us to promote our company policy of making the sun a fun and safe place to be.";
	
	
	hovertext['media'] = "Have a butchers...";
	hovertext['gallery'] = "";
	hovertext['sunpouchhq'] = "Sunpouch HQ. Where it all happens.";
	
	hovertext['poucheshoverblackandwhite'] = "The funky Black + White pouch. This little beauty looks super cool in any ladies handbag or even better tucked in a wet suit ready to get out and surf.";
	
	hovertext['poucheshoverpurple'] = "Our Purple pouch looks wicked in your pocket and who wouldn't be wanting to try some on in the school yard, at the skate park or down on the beach.";
	
	hovertext['poucheshoverstripy'] = "The sassy Stripey pouch is the boys favourite looking pretty cool down on the beach in your boardies, stashing one in your sports bag or just in your pocket, hanging out at a summer festival.";
	
	hovertext['poucheshoverkids'] = "This is our Kids pouch. It especially formulated for young sensitive skins and what little tyke wouldn't be the talk of the playground if they had this in their change bag.";
	
	hovertext['competition'] = "<span id='win' class='toenter'>WIN</span> a <span id='vip' class='toenter'>VIP Bondi Lifeguard Experience</span> on Bondi Beach for you and a friend including travel expenses AND $500 cash to spend.<br><br>Plus the lucky winner will also receive a signed copy of Bondi Rescue the book, a years supply of Sunpouch SPF 30+ AND a years supply of <img src='carmexlogocomp.png' id='carmex' class='carmex'/> <br>lip balm.<br><br>10 runners up will receive a Sunpouch Summer Pack of: 3 Sunpouch SPF 30+ and a Carmex lip balm Click Stick.<br><br><span id='toenter' class='toenter'>To enter</span> purchase any Sunpouch SPF 30+ sunscreen at your local pharmacy tell us in 25 words or less 'Why you can't live without Sunpouch SPF 30+ this summer? - click 'To Enter' to get started";
	
    hovertext['biohoverdeano']   = "Deano's real name is Dean Andrew Gladstone and he was born 1979. He joined the Maroubra nippers when he was 5 and became a lifeguard at 21.";
	
	hovertext['biohoverreidy']   = "Reidy's real name is Andrew Reid and he has a real energetic personality. Born in 1980 he has be lifeguarding for 6 years.";
	
	hovertext['biohovercorey']   = "Corey Oliver has been a lifeguard for 11 years now and takes pride in the fact his office is the beach. He has an enduring passion for the water and always wears a smile.";

	hovertext['biohoverkerbox']  = 'Rod Kerr, at 40 years old has ridden a wave or two in his time. A former professional surfer he made the natural progression to becoming a lifeguard 13 years ago. A true veteran.';
	
	hovertext['biohoverhoppo']   = 'Bruce Hopkins aka Hoppo has been a lifeguard for nearly 20 years now and in 2006 won the Australian Lifeguard of the Year Award. He is the top boss man on Bondi beach and is well respected by his colleagues.';

    hovertext['biohoverharries'] = 'Harries Carroll is the joker of the pack keeping everyone on their toes with his constant pranks and infectious laugh. He is a loveable character whom embodies the essence of true blue Australian beach culture.';

	function testme(thetext)
	{
	alert(thetext);	
	}



		//function for contact form dropdown
	function competition() {
		//alert("dd");
		if ($("#competitionForm").is(":hidden")){
		
			$("#competitionForm").slideDown("slow");
			$("#competitionbackgroundPopup").css({"opacity": "0.7"});
			$("#competitionbackgroundPopup").fadeIn("slow"); 
		}
		else{
			$("#competitionForm").slideUp("slow");
			$("#competitionbackgroundPopup").fadeOut("slow");  
		}
		return true;
	}
	



function initialisemap()
{
return;
	if(mapinitialised == true)
{
alert("map initialised");
return;
}
   if (GBrowserIsCompatible()) {
      var Icon = new GIcon(G_DEFAULT_ICON);
      //Icon.image = "stripeyicon.png";

      var gmarkers = [];
      var htmls = [];
      var i = 0;

      // A function to create the marker and set up the event window
      function createMarker(point,name,html) {
        var marker = new GMarker(point,Icon);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });

        // Switch icon on marker mouseover and mouseout
        //GEvent.addListener(marker, "mouseover", function() {
          //marker.setImage("facebook48x48.png");
        //});
        //GEvent.addListener(marker, "mouseout", function() {
          //marker.setImage("twitter54x54.png");
        //});
        gmarkers[i] = marker;
        htmls[i] = html;
        i++;
        return marker;
      }

      // create the map
      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(-33.82479361826488,151.336669),4);


      // Read the data from example.xml
      var request = GXmlHttp.create();
      request.open("GET", "ddd.xml", true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
			
          var xmlDoc = GXml.parse(request.responseText);
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");
         
          for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
           var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
            var html = markers[i].getAttribute("html");
            var label = markers[i].getAttribute("label");
            // create the marker
			 //alert(lat+lng); 
            var marker = createMarker(point,label,html);
            map.addOverlay(marker);
          }
        }
      }
      request.send(null);
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
	mapinitialised = true;
	alert("map now initialised");
}

	
$(document).ready(function(){
		
					initialise();
	//Caption Sliding (Partially Hidden to Visible)
				$('.boxgrid.caption').hover(function(){
					$(".cover", this).stop().animate({top:'110px'},{queue:false,duration:160});
				}, function() {
					$(".cover", this).stop().animate({top:'160px'},{queue:false,duration:160});
				});
	
		
		
		

			$("a.sunrise").fancybox({
						'hideOnContentClick': false

			});

		
		
						   
	//function for contact form dropdown
	function contact() {
		//alert("dd");
		if ($("#contactForm").is(":hidden")){
		
			$("#contactForm").slideDown("slow");
			$("#backgroundPopup").css({"opacity": "0.7"});
			$("#backgroundPopup").fadeIn("slow"); 
		}
		else{
			$("#contactForm").slideUp("slow");
			$("#backgroundPopup").fadeOut("slow");  
		}
		return true;
	}
	
	
 
	
	//run contact form when any contact link is clicked
	$(".competitionclose").click(function(){competition()});
	 
	//run contact form when any contact link is clicked
	$(".contact").click(function(){contact()});
	
	//run contact form when any contact link is clicked
	$(".close").click(function(){contact()});
	 
	//animation for same page links #
	$('a[href*=#]').each(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname
		&& this.hash.replace(/#/,'') ) {
		  var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
		  var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
			if ($(this.hash).length) {
				$(this).click(function(event) {
					var targetOffset = $(this.hash).offset().top;
					var target = this.hash;
					event.preventDefault();			   
					$('html, body').animate({scrollTop: targetOffset}, 500);
					return false;
				});
			}
		}
	});


				
   //submission scripts
  $('.contactForm').submit( function(){							 
		//statements to validate the form	
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var email = document.getElementById('e-mail');
		if (!filter.test(email.value)) {
			$('.email-missing').show();
		} else {$('.email-missing').hide();}
		if (document.cform.name.value == "") {
			$('.name-missing').show();
		} else {$('.name-missing').hide();}	
		if (document.cform.message.value == "") {
			$('.message-missing').show();
		} else {$('.message-missing').hide();}		
		if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "")){
			return false;
		} 
		
		if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
			//hide the form
			$('.contactForm').hide();
		
			//show the loading bar
			$('.loader').append($('.bar'));
			$('.bar').css({display:'block'});
		
		// 'this' refers to the current submitted form
		var str = $(this).serialize();
			//send the ajax request	
	var dataString = 'url=http://www.emailmeform.com/fid.php?formid=479311' + '&' + str;
	//alert(dataString);
	
	$.post( 'proxy.php',dataString , function(data){
              //hide the graphic
              $('.bar').css({display:'none'});
              
			  	//alert(data);
            } );
			
			//waits 2000, then closes the form and fades out
			setTimeout(function () {resetContactForm()}, 4000);
			
			//stay on the page
			return false;
		} 
									 });

  //submission scripts
  $('.competitionForm').submit( function(){							 
	{
			//hide the form
			$('.competitionForm').hide();
		
			//show the loading bar
			$('.competitionloader').append($('.competitionbar'));
			$('.competitionbar').css({display:'block'});
		
		// 'this' refers to the current submitted form
		var str = $(this).serialize();
			//send the ajax request	
	var dataString = 'url=http://www.emailmeform.com/fid.php?formid=502207' + '&' + str;
	//alert(dataString);
	
	$.post( 'proxy.php',dataString , function(data){
              //hide the graphic
              $('.competitionbar').css({display:'none'});
              
			  	//alert(data);
            } );
			
			//waits then closes the form and fades out
			setTimeout(function () {resetCompetitionForm()}, 4000);
			
			//stay on the page
			return false;
		} 




});
	//only need force for IE6  
	$("#backgroundPopup").css({  
		"height": document.documentElement.clientHeight 
	}); 
	
	//only need force for IE6  
	$("#competitionbackgroundPopup").css({  
		"height": document.documentElement.clientHeight 
	}); 
	
	
				//Caption Sliding (Partially Hidden to Visible)
				$('.boxgrid.caption').hover(function(){
					$(".cover", this).stop().animate({top:'125px'},{queue:false,duration:160});
				}, function() {
					$(".cover", this).stop().animate({top:'155px'},{queue:false,duration:160});
				});




	
	$.fn.maxlength = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function length(el) {
    	var parts = el.value;
    	if ( settings.words )
    		parts = el.value.length ? parts.split(/\s+/) : { length : 0 };
    	return parts.length;
    }
    
    return this.each(function () {
        var field = this,
        	$field = $(field),
        	$form = $(field.form),
        	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
        	$charsLeft = $form.find(settings.feedback);

    	function limitCheck(event) {
        	var len = length(this),
        	    exceeded = len >= limit,
        		code = event.keyCode;

        	if ( !exceeded )
        		return;

            switch (code) {
                case 8:  // allow delete
                case 9:
                case 17:
                case 36: // and cursor keys
                case 35:
                case 37: 
                case 38:
                case 39:
                case 40:
                case 46:
                case 65:
                    return;

                default:
                    return settings.words && code != 32 && code != 13 && len == limit;
            }
        }


        var updateCount = function () {
            var len = length(field),
            	diff = limit - len;

            $charsLeft.html( diff || "0" );

            // truncation code
            if (settings.hardLimit && diff < 0) {
            	field.value = settings.words ? 
            	    // split by white space, capturing it in the result, then glue them back
            		field.value.split(/(\s+)/, (limit*2)-1).join('') :
            		field.value.substr(0, limit);

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }

        updateCount();
    });
};

$.fn.maxlength.defaults = {
    useInput : false,
    hardLimit : true,
    feedback : '.charsLeft',
    words : false
};
	
	
  
        $('textarea.wordLimited').maxlength({
            'words': true,
            'feedback': '.wordsLeft'
        });	
	
	
initialisemap();	
setupGallery();				
});

	
 
 
function mainHoverState(state)
{
	//alert("mainhoverstate");
	var mainhoverid  = $('#mainhover');
	var mainhoverpid = $('#mainhover p'); 
	
	if(state == 'hide')
	{
		mainhoverid.fadeTo(0, 0.0); 	
	    mainhoverpid.fadeTo(0, 0.0);
		mainhoverid.hide();
		mainhoverpid.hide();
		return false;
	}

	if(state == 'off')
	{
		mainhoverid.fadeTo(1200, 0.0); 	
	    mainhoverpid.fadeTo(1200, 0.0);
		mainhoverid.hide();
		mainhoverpid.hide();
	}
	if(state == 'on')
	{
		setTimeout(function(){
		mainhoverid.show();
		mainhoverpid.show();
		mainhoverid.fadeTo(1200, 0.8); 	
	    mainhoverpid.fadeTo(1200, 1.0);},500);
	}	
	return false;
}	
	
	function initialise()
	{ 
	
	//alert("fxn initialise");
		 slide("#sliding-navigation", 25, 15, 150, .8);


   $("#mainhover p").hover(
		function(){
        $('#mainhover').fadeTo(700, 0.7);
	$(this).fadeTo(700, 1.0); 
	   },function(){
	});	
  
   $("#mainhoverxx p").hover(
		function(){
        $('#mainhover').fadeTo(700, 0.7);
	$(this).fadeTo(700, 1.0); 
	   },function(){
	$(this).fadeTo(700, 0.0); 	
	$('#mainhover').fadeTo(700, 0.0);
        
	});	

	
 $( ".biohover" ).each(
  	
 function( intIndex ){
 addTooltip($(this));
  }
 );
 
 $( ".poucheshover" ).each(
  	
 function( intIndex ){
 addTooltip($(this));
  }
 );
    mainHoverState('off');
	$('#mainhover p').text(hovertext['home']);
	
	setTimeout(function () { setPanels('home',{mainpanel:homeimage,leftpanel:pouchesimage,middlepanel:lifeguardsimage});},2000);
	return false;
	}

function addTooltip(info)
{	

var myid = $(info).attr('id');
			$(info).qtip({
   content: hovertext[myid],
   show: { when: { event: 'mouseover',effect: 'fade'} } ,
   hide: 'mouseout'	,	
   position: {
      corner: {
         target: 'topRight'
         //tooltip: 'bottomLeft'
      }
   },

   style: { 
      border: {
         width: 1,
         radius: 8,
         color: '#852585'
      },
	  'font-family': "Trebuchet MS",
	  'font-size': 13,
      width: 200,
	  background: '#E8E8E8',
	  color: '#222222',
	  padding: 10
   } 
						 
});
return false;
}


function setHoverState(xxx,state)
{
if(state == 'off')
	{
		$( '.' + xxx).each(
  			function( intIndex ){
				var myid = $(this).attr('id');
				//alert(myid);
 				$('#' + myid).hide();
  			}
 			);
			//bioHover = 0;
	}
	else
	{
	   
		$( '.' + xxx).each(
  			function( intIndex ){
				var myid = $(this).attr('id');
				//alert(myid);
 				$('#' + myid).show();
  			}
 			);
			//bioHover = 1;
	}	
	return false;
}


function menuClicked(menu)
{
	
	if(menu != 'contactus')
	{
		closeContact();
	}

	//alert("menuClicked");
     if (menu == "home") 	
	 {
	      setPanels(menu,{mainpanel:homeimage,leftpanel:pouchesimage,middlepanel:lifeguardsimage});
	 }
     if (menu == "pouches") 
	 {
	      setPanels(menu,{mainpanel:pouchesimage,leftpanel:homeimage,middlepanel:mediaimage});
		  setHoverState('poucheshover','on');
		  }
	 if (menu == "lifeguards") 
	 {
      setPanels(menu,{mainpanel:lifeguardsimage,leftpanel:mediaimage,middlepanel:pouchesimage});
	  setHoverState('biohover','on');
	  $('iaamg#mainpanel').addClass('ffjLoupe');
	 }
     if (menu == "media") 
	 {
	      setPanels(menu,{mainpanel:mediaimage,leftpanel:lifeguardsimage,middlepanel:pouchesimage});
		  
	 }
     if (menu == "gallery")
         {
	      setPanels(menu,{mainpanel:homeimage,leftpanel:pouchesimage,middlepanel:lifeguardsimage});
             $('#thegallery').show(); 
         }

     if (menu == "sunpouchhq") 
	 {
	      setPanels(menu,{mainpanel:sunpouchhqimage,leftpanel:lifeguardsimage,middlepanel:homeimage});
	 }
	 
	 if (menu == "competition") 
	 {
	     
		  setPanels(menu,{mainpanel:competitionimage,leftpanel:lifeguardsimage,middlepanel:homeimage});
		  
	 $(".toenter").click(function(){competition();});
		 }
		 
		 $(function(){
   $(".toenter").hover(function() {
         $(this).effect("pulsate", { times:1 }, 1500);
   });
});

	 
	 if (menu == "contactus") 
	 {
	 	$(".contact").trigger('click');
	 }
	 return false;
         
}


	function closeContact()
	{
		if ($("#contactForm").is(":visible")){
			//alert("closeContact");
			$("#contactForm").slideUp("slow");
			$("#backgroundPopup").fadeOut("slow");  
		}		
	}

function closeCompetition()
	{
		if ($("#competitionForm").is(":visible")){
			//alert("closeContact");
			$("#competitionForm").slideUp("slow");
			$("#competitionbackgroundPopup").fadeOut("slow");  
		}		
	}


function setPanels(menu,panels)
{
		//alert("setpanels " + menu);
		mainHoverState('hide');
		
		setHoverState('biohover','off');	
		setHoverState('poucheshover','off');	
		$('#mainhover').removeClass();
		$('#thegallery').hide();	
		var image;
		var count = 0;
	
		$.each(panels,
			   	function(panelToChange,image_to_use) 
					{
						if(count == 0)
						{
								image = image_to_use + '_full.jpg';
								$('.mainpanelimage').ImageSwitch({Type:'FadeIn', NewImage:image, EffectOriginal: false, Speed: 1000}); 
						}
						else
						{
							image = image_to_use + '_mini.jpg';
							
							$('img', '#' + panelToChange).attr('src', image);
							//$('img', '#' + panelToChange).attr('src', image);
							
				
						}
						//alert(count + " " + 'img' + '#' + panelToChange + ' ' + image);
					
					
					count++;
					}
					)
	
			
		
	
	
	$('#mainhover').addClass('mainhover' + menu);
		
		var mainhoverpid = $('#mainhover p');
	
		mainhoverpid.html(hovertext[menu]).css('color',hovercolour[menu]);
		mainhoverpid.css('font-size',hoversize [menu]);
		mainhoverpid.css('background-color',hoverbgcolour [menu]);
		

		mainHoverState('on');
		return false;
}

function slide(navigation_id, pad_out, pad_in, time, multiplier)
{
	// creates the target paths
	var list_elements = navigation_id + " li.sliding-element";
	var link_elements = list_elements + " a";
	
	// initiates the timer used for the sliding animation
	var timer = 0;
	
	// creates the slide animation for all list elements 
	$(list_elements).each(function(i)
	{
		// margin left = - ([width of element] + [total vertical padding of element])
		$(this).css("margin-left","-180px");
		// updates timer
		timer = (timer*multiplier + time);
		$(this).animate({ marginLeft: "0" }, timer);
		$(this).animate({ marginLeft: "15px" }, timer);
		$(this).animate({ marginLeft: "0" }, timer);
	});

	// creates the hover-slide effect for all link elements 		
	$(link_elements).each(function(i)
	{
		$(this).hover(
		function()
		{
			$(this).animate({ paddingLeft: pad_out }, 150);
		},		
		function()
		{
			$(this).animate({ paddingLeft: pad_in }, 150);
		});
	$(this).click(
		function()
		{
				//alert("clicked " + i);
				hilite('off');
			//$(this).css('border','2px solid #0390C5');
			
			
				$(this).css('border','3px solid #852585');
			
			
			//alert('dddd');
			//$(this).animate({ paddingLeft: pad_in }, 150);
		});
	});
	return false;
}


function hilite(state)
{
	//alert('hilite ' + state);
		// creates the target paths
		var list_elements = "#sliding-navigation li.sliding-element";
		var link_elements = list_elements + " a";
		
		$(link_elements).each(function(i)
		{
		$(this).css('border','1px solid #1a1a1a');
		});
		
		
	

}


	



/*
  @author: remy sharp / http://remysharp.com
  @params:
    feedback - the selector for the element that gives the user feedback. Note that this will be relative to the form the plugin is run against.
    hardLimit - whether to stop the user being able to keep adding characters. Defaults to true.
    useInput - whether to look for a hidden input named 'maxlength' instead of the maxlength attribute. Defaults to false.
    words - limit by characters or words, set this to true to limit by words. Defaults to false.
  @license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
  @version: 1.2
  @changes: code tidy via Ariel Flesler and fix when pasting over limit and including \t or \n
*/



function resetContactForm()
{
    
	$("#backgroundPopup").fadeOut("slow"); 
	$("#contactForm").slideUp("slow");	
	$('.bar').css({display:'none'});
	$("#name").val("");
	$("#e-mail").val("");
	$("#mobile").val("");
	$("#message").val("");
	$('.contactForm').show();
	
	//alert("sddsds");
				
}

function resetCompetitionForm()
{
    
	$("#competitionbackgroundPopup").fadeOut("slow"); 
	$("#competitionForm").slideUp("slow");	
	$('.competitionbar').css({display:'none'});
	$("#competitionname").val("");
	$("#competitionemail").val("");
	$("#competitionmobile").val("");
	$("#competitiondob").val("");
	$("#competitionpostcode").val("");
	$("#competitionwhy").val("");
	$('.competitionForm').show();
	
	//alert("sddsds");
				
}

