/*
lettuce.com.au
         __..--''``\--....___   _..,_
     _.-'    .-/";  `        ``<._  ``-+'~=.
 _.-' _..--.'_    \                    `(^) )
((..-'    (< _     ;_..__               ; `'   
           `-._,_)'      ``--...____..-'
Caloundra
*/

/*
	we want to have the header bg and the main header image fade at the same time... 
	might have to mod the fucntion to accomodate the two separate divs...
	something up with the two faders running at the same time...
	has something to do with the calling of the functions??
*/

var imagePath = "content/images/";

var globalScroll = 0;
var globalLeftAmount = 0;


//calundraLocation
var mapLat = -26.805500;
var mapLong = 153.126085;

var pathname = window.location.pathname;

$(document).ready(function() {
    /*
    independent controllers for the header image and background faders.
    same code, just applied to different sections.
    */
    headerImageFader();
    headerBGFader();

    /*
    scroll to the form. That's all.
    */
    enquireListener();

    /*
    center the content with no overflow scrolling when the screen is less than 1200px
    control the positioning of the floating nav section
    */
    centerContent();
    centerDropDown();

    $(window).bind("resize", centerContent);
    $(window).bind("resize", centerDropDown);

    /*
    add some colour to the form to make it more readable...

		7 cols....

		Using the find/each td in tr will give the follwing format...

		 _   _V_   _S_   _P_ 
    |0| |1 2| |3 4| |5 6| 

	*/

    ratesTableFix();

    checkNavOffset();

    /*
    if the page has the map holder, show the map
    */
    var hasMap = $(document).find('#mapHolder');
    if (hasMap.length >= 1) {
        setupMap();
    }

    //make rounded corners in IE
    makeCorners();

    //set the requested cabin in the dropdown list on the enquire page
    setSelectedCabin();
    
    /*hide the enquire button on the specialAccess page*/
    if (pathname.indexOf("specialAccess") > 0) {
        $(".enquireButton").css('display', 'none');
    }

})

//scroll to the enquiry form on the home page.
function enquireListener()
{
	$(".enquireButton").click(function()
	{
		$(document).scrollTo('#enquiryForm', 500);
	})
}

function headerBGFader()
{
	//Image fader
		
		// fading vars -------------------------------------------------
	    var ImageArray = []; // array to hold the src of the backgroun img	
	    var ImageArragEnd = ImageArray.length;	
	    var BannerLable = 0; // use to lable everything	
	    var counter = 0; // counts were the banner is upto
	    var BGcounter = 0; // counts were the banner background src is upto
	    var timer; // timer val
	
	    // -- start functions ------------------------------------------
	
	    //fading labler
	    $(".headerBG").children().each(function(){ // lables everything and add to array so can be use for fading.
	           //var BannerSRC = $(this).children().attr("src");
	           BannerLable ++; // jsut a counter for the class adder
	           $(this).addClass("imageBG"+ BannerLable +""); // adds class like "image1", "image2"
	           ImageArray.push(BannerLable) // push then
	           ImageArragEnd = ImageArray.length; // updating the array
	    });
	
	    // test to see if there is 1 or more images ---------------------
	    if(ImageArragEnd == 1){
	           //do nothing!
	           $(".imageBG1").css("display", "inline");
	           }else{
	           fadingFun(); // start the banner fade
	           //$("#fader").children().fadeOut(0); // hides all of the slides
	           $(".imageBG1").fadeIn(0); // hides all of the slides
	    }
	    //make the squares for the current image indication
	    /*
	    if(ImageArragEnd != 1)
	    {
		    for(var i = 1; i<ImageArragEnd; i++)
		    {

		    	$('<div id="indicator' + i + '" class="imageIndicator"></div>').appendTo("#rotatorIndicatorHolder");
		    	$("#indicator1").css('background-color', '#F2C300');
		    	//the first one wont take the colour in the fader loop... so set it here.
		    }
		}
		*/
	
	    // fading FUNction -----------------------------------------------
	    function fadingFun(){
	
	    ImageArragEnd = (ImageArray.length) + 1; //UPDAT PUT BOTH INTO A FUCNTION as a call back of each....
	            counter ++;
	            //BGcounter ++;
	            
	                   // $("#fader").css("background-image","url("+ ImageArray[BGcounter] +")");      
	                   // get this working
				if(counter == ImageArragEnd ){  // check were its upto in the line and if its the last one then *restart*
	                   counter = 1;
	            }
	            
	            //$(".sectionHeading").text(counter); //use this for testing the counter...
	            $(".imageIndicator").css('background-color','#A38816');
	            $("#indicator" + counter).css('background-color','#F2C300');

	            $(".faderItemBG").fadeOut(1000),
	                 clearTimeout(timer);
	               timer = setTimeout(eval("fadingFun"),"5000");  // rrestart the functions
	                $(".imageBG"+ counter +"").fadeIn(1000); //.. shows box one the hides it so i can be faded in! *failsafe
	
	             // restarter
	    }
}

function headerImageFader()
{
	//Image fader
		
		// fading vars -------------------------------------------------
	    var ImageArray = []; // array to hold the src of the backgroun img	
	    var ImageArragEnd = ImageArray.length;	
	    var BannerLable = 0; // use to lable everything	
	    var counter = 0; // counts were the banner is upto
	    var BGcounter = 0; // counts were the banner background src is upto
	    var timer; // timer val
	
	    // -- start functions ------------------------------------------
	
	    //fading labler
	    $(".headerImageHolderItems").children().each(function(){ // lables everything and add to array so can be use for fading.
	           //var BannerSRC = $(this).children().attr("src");
	           BannerLable ++; // jsut a counter for the class adder
	           $(this).addClass("image"+ BannerLable +""); // adds class like "image1", "image2"
	           ImageArray.push(BannerLable) // push then
	           ImageArragEnd = ImageArray.length; // updating the array
	    });
	
	    // test to see if there is 1 or more images ---------------------
	    if(ImageArragEnd == 1){
	           //do nothing!
	           $(".image1").css("display", "inline");
	           }else{
	           fadingFun(); // start the banner fade
	           //$("#fader").children().fadeOut(0); // hides all of the slides
	           $(".image1").fadeIn(0); // hides all of the slidess
	    }
	    //make the squares for the current image indication
	    /*
	    if(ImageArragEnd != 1)
	    {
		    for(var i = 1; i<ImageArragEnd; i++)
		    {

		    	$('<div id="indicator' + i + '" class="imageIndicator"></div>').appendTo("#rotatorIndicatorHolder");
		    	$("#indicator1").css('background-color', '#F2C300');
		    	//the first one wont take the colour in the fader loop... so set it here.
		    }
		}
		*/
	
	    // fading FUNction -----------------------------------------------
	    function fadingFun(){
	
	    ImageArragEnd = (ImageArray.length) + 1; //UPDAT PUT BOTH INTO A FUCNTION as a call back of each....
	            counter ++;
	            //BGcounter ++;
	            
	                   // $("#fader").css("background-image","url("+ ImageArray[BGcounter] +")");      // get this working
				if(counter == ImageArragEnd ){  // check were its upto in the line and if its the last one then *restart*
	                   counter = 1;
	            }
	            
	            //$(".sectionHeading").text(counter); //use this for testing the counter...
	            $(".imageIndicator").css('background-color','#A38816');
	            $("#indicator" + counter).css('background-color','#F2C300');

	            $(".faderItem").fadeOut(1000),
	                 clearTimeout(timer);
	               timer = setTimeout(eval("fadingFun"),"5000");  // rrestart the functions
	                $(".image"+ counter +"").fadeIn(1000); //.. shows box one the hides it so i can be faded in! *failsafe
	
	             // restarter
	    }
}

//center the content even after the window width is less than the width og the large image.

function centerContent()
{
	var windowWidth = $(window).width();

    //main content centerer
	if(windowWidth < 1200)
	{
		document.documentElement.style.overflowX = 'hidden';
		var scrollAmount = (windowWidth - 1200) / 2;
		$(document).scrollLeft(scrollAmount * -1);
	}

    //header nav centerer
	var lessThan1200 = 150;
	var rightMargin = ((windowWidth - 1200) / 2) + lessThan1200;
	if (windowWidth > 1200) 
	{
		globalScroll = rightMargin;
	    $(".navItems").css('margin-right', rightMargin);
	    logger("greater than 1200");
	}
	else if ((windowWidth < 1200) && (windowWidth > 906)) 
	{
        rightMargin = (windowWidth - 906) / 2;
        $(".navItems").css('margin-right', rightMargin);
        logger("less than 1200 greater than 906");
	}
	else 
	{
	    $(".navItems").css('margin-right', '0');
	    logger("less than 906");
	}
}

function centerDropDown()
{
	var windowWidth = $(window).width();
	var docWidth = $("#mainContent").width();

	var leftAmount = (windowWidth - docWidth) / 2;
	globalLeftAmount = leftAmount;
}
/*
	make the rates table look nice here rather than 
	trying to add classes to each cell.
*/
function ratesTableFix()
{
	/*
		for each row (other than the heading ones...)

		element 0	= heading
		element 1,2 = group
		element 3,4 = group
		element 5,6 = group
	*/

	var rowArray = $("#ratesTable").find('tr');
	for(var i = 0; i <= rowArray.length; i++)
	{
		var thisRow = $(rowArray[i]).find('td');
		if(i>1)
		{
			thisRow.css('width','60px');
			$(rowArray[i]).addClass("hoverRow");
			for(var j = 0; j <=7; j++)
			{
				var currentTD = $(thisRow[j]);
				if(j==0)
				{
				    currentTD.css('width','180px');
				}
				if(j>1)
			    {
			        currentTD.css('padding-left','10px');
			        currentTD.css('padding-right','10px');
			    }
				
				if((j==1)||(j==2))
				{
					currentTD.addClass("tableGroup01");
				}
				else if((j==3)||(j==4))
				{
					currentTD.addClass("tableGroup02");	
				}
				else if((j==5)||(j==6))
				{
					currentTD.addClass("tableGroup03");
				}
			}
		}
	}
}


/*
	reposition the subnav so that it's centered to the content on mouseover
*/
function checkNavOffset()
{
	$(".navItems li").mouseenter(function()
	{
		var hoverItem = $(this);
		var windowWidth = $(window).width();
		var subNavWidth = hoverItem.find('ul').width();
		var narrowOffset = (windowWidth - subNavWidth)/2;

		var offset = hoverItem.offset();
		var tempLeftAmount = offset.left;
		logger("tempLeftAmount" + tempLeftAmount);
		var negativeLeft = tempLeftAmount * -1;

		if(windowWidth < 1200)
		{
			var actualAmount = negativeLeft + (narrowOffset + 50);
		}
		else
		{
			var actualAmount = negativeLeft + (globalLeftAmount - 50);
		}
		hoverItem.find('ul').css('left', actualAmount);

	});
}


/*
	make a custom map with a specified image set as the dropped pin.

	lat/long values are globals
*/
function setupMap()
{
		var latlng = new google.maps.LatLng(mapLat, mapLong);
		var settings = {
			zoom: 15,
			center: latlng,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
			navigationControl: true,
			navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
			mapTypeId: google.maps.MapTypeId.ROADMAP
    		};

    	var map = new google.maps.Map(document.getElementById("mapHolder"), settings);

    	var companyLogo = new google.maps.MarkerImage('/content/images/logo.png',
		new google.maps.Size(64,56),
		new google.maps.Point(0,0),
		new google.maps.Point(50,50)
		);
		// var companyShadow = new google.maps.MarkerImage('images/logo_shadow.png',
		// 	new google.maps.Size(130,50),
		// 	new google.maps.Point(0,0),
		// 	new google.maps.Point(65, 50)
		// );
		var companyPos = new google.maps.LatLng(mapLat, mapLong);
		var companyMarker = new google.maps.Marker({
			position: companyPos,
			map: map,
			icon: companyLogo,
			//shadow: companyShadow,
			title:"Caloundra Holiday Park"
		});
			
		google.maps.event.addListener(companyMarker, 'click', function() 
		{
		  window.open('http://maps.google.com.au/maps?q=Hibiscus+Holiday+Park,+Bulcock+Street,+Caloundra,+Queensland&hl=en&sll=-26.805466,153.124985&sspn=0.005679,0.004823&vpsrc=0&hq=Hibiscus+Holiday+Park,&hnear=Bulcock+St,+Caloundra+Queensland+4551&t=m&z=18','_blank');
		});
}


/*
	find the requested cabin via hidden input
	set the dropdown of the require form to 
*/
function setSelectedCabin()
{
    var cabin = $("#cabinId").val();
    var cabinList = $("#ddlCabinList").find('option');
    logger(cabin);
    
    for(var i=0; i<cabinList.length; i++)
    {
        var tempCabin = $(cabinList[i]).val();
        if(tempCabin == cabin)
        {
            $(cabinList[i]).attr('selected','selected');
        }
    }

}

/*
	give rounded corners to subnav drop down, and the nav items if IE
*/

function makeCorners()
{
	var userAgent = navigator.userAgent;
	
	if(userAgent.indexOf('MSIE') > 0)
	{
		var navCorners = $("#home #homeLink, #cabins #accomodationLink, #activities #activitiesLink, #facilities #facilitiesLink, #location #locationLink, #contact #contactusLink");
		navCorners.corner("8px");
	}
	else
	{
		var subNavCorners = $("#homeList ul, #accomodationList ul, #campingList ul");
		subNavCorners.corner("10px").corner("keep");
		$(".subNavTop").css('display','none');
		$(".subNavBottom").css('display','none');
		$(".navItems li ul").css('top','30px');
		$(".subNavArrow").css('top','-15px');
	}
}

function logger(msg)
{
	try
	{
		console.log(msg);
	}
	catch(e)
	{}
}
