// JavaScript Document

imageArray = [
"images/homepage-slider1-940x260.png" ,
"images/homepage-slider2-940x260.png",
"images/homepage-slider3-940x260.png" 
];

linkArray = [
"/_blog/Recent_Projects/post/Tuihana_-_Mountview_subdivision,_Papamoa/",
"/_blog/About_RPC/post/A_rich_and_colourful_past/",
"/_blog/About_RPC/post/Meet_the_directors/"
]

slideIndex = 0;
var clickTimer, runTimer;
var initialTab = 'Residential';

function loadImg(path, container, idName, pCallback) {
	var img = new Image();
	// wrap our new image in jQuery, then:
	$(img)
	// once the image has loaded, execute this code
		.load(function () {
			// set the image hidden by default    
			$(this).hide();
			$(this).attr('id', idName);
			// with the holding div #loader, apply:
			$(container)
			  // remove the loading class (so no background spinner), 
			  // then insert our image
			  .append(this);
					if (pCallback){
						var cb;
						cb = pCallback;
						cb(this);
				  }
			// fade our image in to create a nice effect
				$(this).fadeIn();
			})
			// if there was an error loading the image, react accordingly
		.error(function ( ) {
			// notify the user that the image could not be loaded
			alert('Apologies, there was a error on the page, please refresh and try again');
		})
	// *finally*, set the src attribute of the new image to our image
	.attr('src', path );
}





function promoSlider(direction) {
	if($("div.mainSlider").find('div.slideContainer:eq(0)').filter(":animated").length == 0) {
		if(direction == 'right') {
			if(slideIndex < imageArray.length-1) {
				slideIndex += 1;
			} else {
				slideIndex = 0;	
			}
			
		} else if (direction == 'left'){
			if(slideIndex > 0) {
				slideIndex -=1;
			} else {
				slideIndex = imageArray.length-1;	
			}	
		}  

		if(!$("#slide"+ String(slideIndex)).length) {
			
			if(direction == 'right') {
				$("div.slideDrawer").append('<div class="slideContainer" id="slide' + slideIndex +'">'
                    +    '<a href="#"><span>› Find out more</span></a>'
                    +	 '</div>');
				  $("#slide"+slideIndex).find('a').attr('href', linkArray[slideIndex]);	
				lastMark = $("div.mainSlider .slideDrawer").find('div.slideContainer').filter(':last').css( 'left');
				lastMark = lastMark.substr(0, lastMark.lastIndexOf('px'));
				lastMark = (Number(lastMark) + 940) + 'px';
				$("#slide" + slideIndex).css({ 'left' : lastMark });
			} else {
				$("div.slideDrawer").prepend('<div class="slideContainer" id="slide' + slideIndex +'">'
                    +    '<a href="#"><span>› Find out more</span></a>'
                    +	 '</div>');
				$("#slide" + slideIndex).css({ 'left' : -940 });
			}
			loadImg(imageArray[slideIndex], $("#slide"+slideIndex), "imgSlide"+String(slideIndex), function(imgReturn) {				
				  if(direction == 'right') {
					  $("div.mainSlider .slideDrawer").find('div.slideContainer').each ( function() {
						  currentLeft = $(this).css('left');
						  currentLeft = currentLeft.substr(0, currentLeft.lastIndexOf('px'));
						  currentLeft = (Number(currentLeft) - 940) + 'px';
						  if( !$(this).is(':animated') ) {
							  $(this).stop().animate ({ 
								  left : currentLeft
							  }, 450);
						  }
					  });
				  } else {
					  $("div.mainSlider .slideDrawer").find('div.slideContainer').each ( function() {
						  currentLeft = $(this).css('left');
						  currentLeft = currentLeft.substr(0, currentLeft.lastIndexOf('px'));
						  currentLeft = (Number(currentLeft) + 940) + 'px';
						  if( !$(this).is(':animated') ) {
							  $(this).stop().animate ({ 
								  left : currentLeft
							  }, 450);
						  }
					  });
				  }
				
			});
			
		} else {
			if(direction == 'right') {
				initialSlidePosition =  $("div.mainSlider .slideDrawer").find('div.slideContainer').filter(':last').css('left');
		
				$("div.mainSlider .slideDrawer").find('div.slideContainer').filter(":first").clone().appendTo($("div.slideDrawer"));
				slideCount =$("div.mainSlider .slideDrawer").find('div.slideContainer').length;
				initialSlidePosition = initialSlidePosition.substr(0, initialSlidePosition.lastIndexOf('px'));
				initialSlidePosition = (Number(initialSlidePosition) + 940) + 'px';
				$("div.mainSlider .slideDrawer").find('div.slideContainer').filter(":last").css({ left : initialSlidePosition  });
		
				$("div.mainSlider .slideDrawer").find('div.slideContainer').each ( function() {
					currentLeft = $(this).css('left');
					currentLeft = currentLeft.substr(0, currentLeft.lastIndexOf('px'));
					currentLeft = (Number(currentLeft) - 940) + 'px';
					shifted = ($(this).index());
					shifted++;
					if( !$(this).is(':animated') ) {
						if(shifted === slideCount) {
							$(this).stop().animate ( { 
								left : currentLeft
							}, 450, "easeInOutSine",  function() {
								$("div.mainSlider .slideDrawer").find('div.slideContainer').filter(":first").remove();
							});
						} else {
							$(this).stop().animate ( { 
								left : currentLeft
							}, 450, "easeInOutSine");
						}
					}
				});
		
			} else {
				$("div.mainSlider .slideDrawer").find('div.slideContainer').filter(":last").clone().prependTo($("div.slideDrawer"));
				slideCount =$("div.mainSlider .slideDrawer").find('div.slideContainer').length;
				initialSlidePosition =  $("div.mainSlider .slideDrawer").find('div.slideContainer:eq(1)').css('left');
				initialSlidePosition = initialSlidePosition.substr(0, initialSlidePosition.lastIndexOf('px'));
				initialSlidePosition = (Number(initialSlidePosition) - 940) + 'px';
				$("div.mainSlider .slideDrawer").find('div.slideContainer').filter(":first").css({ left : initialSlidePosition  });
		
				$("div.mainSlider .slideDrawer").find('div.slideContainer').each ( function() {
					currentLeft = $(this).css('left');
					currentLeft = currentLeft.substr(0, currentLeft.lastIndexOf('px'));
					currentLeft = (Number(currentLeft) + 940) + 'px';
					shifted = ($(this).index());
					shifted++;
					if( !$(this).is(':animated') ) {
						if(shifted === slideCount) {
							$(this).stop().animate ( { 
								left : currentLeft
							}, 450, "easeInOutSine",  function() {
								$("div.mainSlider .slideDrawer").find('div.slideContainer').filter(":last").remove();
							});
						} else {
							$(this).stop().animate ( { 
								left : currentLeft
							}, 450, "easeInOutSine");
						}
					}
				});
			}
		}
	}
}

function projectTabBox(clickTarget) {
	var slideIndex, clickIndex, shiftMargin, buttonMark;
		
	buttonMark = $(clickTarget);
	if(!(jQuery.browser.msie)) {
		slideIndex = $(clickTarget).parent().find('li.on').index();
		clickIndex = $(clickTarget).index();
	} else {
		slideIndex = $(clickTarget).parent().find('li.on').index();
		slideIndex = Math.floor(slideIndex/2);
		clickIndex = $(clickTarget).index();
		clickIndex = Math.floor(clickIndex/2);
	}
	//clickIndex = $(clickTarget).index();
	
	
	$(".col270Wide .typeContact:visible").hide();
	$( "#"+(buttonMark.find('a').text()).toLowerCase() + "Contact").show();
	
	
	if(clickIndex != slideIndex) {
		/*
		shiftMargin = -325 * clickIndex;
		$("div.tabBoxContentDrawer").stop().animate({
			top : shiftMargin
		}, 450);
		$(clickTarget).parent().find('li.on').removeClass('on');
		$(clickTarget).addClass('on');
		*/
		//$("div.tabBoxContentDrawer").stop();
		 $("#mainContent").find(".tabBoxSlide:visible").fadeOut(400);
		 $("#mainContent").find(".tabBoxSlide:eq(" + clickIndex + ")").fadeIn(400);
		$(clickTarget).parent().find('li.on').removeClass('on');
		$(clickTarget).addClass('on');
	}
	
	
	
	setTabActiveMark()
}

function projectContactSlider(clickTarget) {
	var slideIndex, clickIndex, shiftMargin, buttonMark;
		
	buttonMark = $(clickTarget);
	
	slideIndex = clickTarget.parent().find('li.active').index();
	clickIndex = clickTarget.index();

	
	if(clickIndex != slideIndex) {
		shiftMargin = -260 * clickIndex;
		$("div.projectContactDrawer").animate({
			left : shiftMargin
		}, 450);
		
		$(clickTarget).parent().find('li.active').removeClass('active');
		$(clickTarget).addClass('active');
	
	/*
		if(!(jQuery.browser.msie)) {
			$(clickTarget).parent().find('li.active').stop().animate({
			 "backgroundColor": "rgba(252, 250, 200, 0.00)" 
			
		}, 250, function() {
			$(this).removeClass('active');
			$(buttonMark).stop().animate({
			 "backgroundColor": "rgba(252, 250, 200, 1.00)"  
			}, 250, function() {
				$(clickTarget).addClass('active');
			});
		});
		} else {
			$(clickTarget).parent().find('li.active').removeClass('active');
			$(buttonMark).addClass('active');
		}
		*/
	
	}
}

function footerContact(target) {
	var slideIndex, clickIndex, shiftMargin, buttonMark;
		
	buttonMark = target
	
	if(!(jQuery.browser.msie)) {
		slideIndex = target.parent().find('li.active').index();
		clickIndex = target.index();
	} else {
		slideIndex = target.parent().find('li.active').index();
		clickIndex = target.index();
		slideIndex = Math.floor(slideIndex/2);
		clickIndex = Math.floor(clickIndex/2);
	}

	if(clickIndex != slideIndex) {
		shiftMargin = -170 * clickIndex;
		$("div.mapDrawer").stop().animate({
			top : shiftMargin
		}, 850);
	
		target.parent().find('li.active').stop().animate({
			 "margin-left" : 10
		}, 250, function() {
			$(this).removeClass('active').find('a').animate({ 'margin-left' : 0}, 250);
			$(buttonMark).find('a').stop().animate({
				"margin-left" : 10
			}, 250);
			$(buttonMark).stop().animate({
				"margin-left" : 0
			}, 350, function() {
				target.addClass('active');
			});
		});
	
	}
}
	
function smallHomeGallery() {
	var currentIndex = 1;
	var galleryIndex = 0;
	
	var currentArray = [];
	
	$("div.gallerySlide").each( function() {
		$(this).find('.imageCaption').each( function(e) {
			$(this).css({'left' : $(this).index() * 300 });
		});
		$(this).find('img').each( function () {
			if( $(this).attr('src').substr(0,1) == '?' ) {
				$(this).parent().remove();	
			//$(this).remove();
			}
		});
	
		galleryVar = $(this).find('img').length;	
		$(this).append('<span class="imageCount">1 of ' + galleryVar + '</span>');

		$(this).parent().find('.smallNavRight').click ( function (e) {
			e.preventDefault();
			
			totalSlideCount = $(this).parent().find('div.imageCaption').find('img').length;
			lastPosition = $(this).parent().find('div.imageCaption:last').css('left');
			lastPosition = lastPosition.substr(0, lastPosition.length-2);
			lastPosition = Number(lastPosition)+300;
			
			currentIndex = Number($(this).parent().find('.imageCount').text().substr(0,1));
			
			currentIndex = currentIndex %totalSlideCount;
			currentIndex += 1;
			$(this).parent().find('div.imageCaption:first').clone().insertAfter($(this).parent().find('div.imageCaption:last'));
			$(this).parent().find('div.imageCaption:last').css({ 'left' : lastPosition });
			if(!$(this).parent().find('div.galleryDrawer:animated').length) {
				$(this).parent().find("div.galleryDrawer").animate({ 'left' : '-=300' }, 400, function (e) {
					$(this).find('.imageCaption:first').remove();
					$(this).parent().find('.imageCount').text(currentIndex + ' of ' + totalSlideCount);
				});
			}
		});
		
		$(this).parent().find('.smallNavLeft').click ( function (e) {
			e.preventDefault();
			
			totalSlideCount = $(this).parent().find('div.imageCaption').find('img').length;
			lastPosition = $(this).parent().find('div.imageCaption:first').css('left');
			lastPosition = lastPosition.substr(0, lastPosition.length-2);
			lastPosition = Number(lastPosition)-300;
			
			currentIndex = Number($(this).parent().find('.imageCount').text().substr(0,1));
			currentIndex -=1;	
			currentIndex = currentIndex %totalSlideCount;
			currentIndex += (totalSlideCount-1);
			currentIndex = currentIndex %totalSlideCount;
			currentIndex +=1;

			$(this).parent().find('div.imageCaption:last').clone().insertBefore($(this).parent().find('div.imageCaption:first'));
			$(this).parent().find('div.imageCaption:first').css({ 'left' : lastPosition });
			if(!$(this).parent().find('div.galleryDrawer:animated').length) {
				$(this).parent().find("div.galleryDrawer").animate({ 'left' : '+=300' }, 400, function (e) {
					$(this).find('.imageCaption:last').remove();
					$(this).parent().find('.imageCount').text(currentIndex + ' of ' + totalSlideCount);
				});
			}
			
			/*
			e.preventDefault();
			totalImageCount = $(this).parent().find('div.gallerySlide').find('img').length;
			currentIndexCount = $(this).parent().find('div.gallerySlide').find('.imageCaption:visible');
			totalImageCount -= 1;
			
			if(currentIndexCount.index() > 0) {
				nextImageToShow = currentIndexCount.index() - 1;
			} else {
				nextImageToShow = totalImageCount;	
			}
			
			if(!$(this).parent().find('div.gallerySlide').find('.imageCaption:animated').length) {
				$(this).parent().find('div.gallerySlide').find('.imageCaption:visible').fadeOut(200);
				$(this).parent().find('div.gallerySlide').find('.imageCaption:eq(' + nextImageToShow + ')').fadeIn(300);
				$(this).parent().find('div.gallerySlide').find('.imageCount').html( (Number(nextImageToShow)+1) + ' of ' + (Number(totalImageCount)+1));
			}
			*/
		});
	});
}

function setTabActiveMark() {
	$("ul.tabNav").find("li span").remove();
	$("ul.tabNav").find("li.on").append('<span class="tabMark"></span>');	
}

function homepageSetup() {
	
	 
	  $.address.history(false).strict(false).wrap(true).init( function(event) {

            
	}).change(function(event) {
		var current = event.value;
		$("ul.tabNav").find('li').each( function(index) {
			if(current == $(this).find('a').attr('href').substr(1, $(this).find('a').attr('href').length)) {
				projectTabBox($(this));	
			}
		
		});
		// Sets the page title
		//$.address.title($.address.title().split(' | ')[0] + ' | ' + current.text());
	
		
		
	}).history(true);
	 if ($.address.value() == '') {
     	$.address.value(initialTab);
     }
	 
	 $("#mainContent .tabBoxSlide:first").fadeIn(200);
	 
	smallHomeGallery();
	setTabActiveMark();
	
	$("#mainContent ul.contactList li").click( function (e) {
		e.preventDefault();		
		$.cookie('city_code_cookie', $(this).index(), { expires: 7 });
		projectContactSlider($(this));
		footerContact($("ul.mapNavList li:eq("+$(this).index() +")"));
	});
	
	$("ul.tabNav li").click( function (e) {
		e.preventDefault();
		//projectTabBox($(this));
		addressLink = $(this).find('a').attr('href').substr(1, $(this).find('a').attr('href').length);
		$.address.value(addressLink);
	});
	
	$("ul.tabNav li a").click( function (e) {
		e.preventDefault();
	});
	
	$("#rightNavArrow").click ( function (e) {
		e.preventDefault();
		clearInterval(clickTimer);
		clearInterval(runTimer);
		promoSlider('right');
		runTimer = setInterval( function() {
			promoSlider('right');
		}, 8000);
		
	});
	
	$("#leftNavArrow").click ( function (e) {
		e.preventDefault();
		clearInterval(clickTimer);
		clearInterval(runTimer);
		promoSlider('left');
		runTimer = setInterval( function() {
			promoSlider('right');
		},  8000);
	});
	
	
	clickTimer = setInterval( function() {
		promoSlider('right');
	}, 8000);
	
	
}

function detailPageSetup() {
	
	if(!$(".bodyBlog").length) {
		
	var array0, array1, array2;
	
	array0 = new Array;
	array1 = new Array;
	array2 = new Array;
	array3 = new Array;
	
	$(".rightHandModule").each( function () {
		var pointer;
		switch($(this).index()) {
		case 0:
			array0.push($(this).find('h4 a').text());
			pointer	= array0;
			break;
		case 1:
			array1.push($(this).find('h4 a').text());
			pointer = array1;
			break;
		case 2:
			array2.push($(this).find('h4 a').text());
			pointer = array2;
			break;
		case 3:
			array3.push($(this).find('h4 a').text());
			pointer = array3;
			break;
		default:
			pointer = array0;
			break;
		}
		
		$(this).find(".blogsitesummary li").each( function() {
			pointer.push($(this).find("a").text());
		});
	});
	
	$(".leftColumn").find(".blogPost").each ( function() {
		for(i = 1; i <= array0.length; i++) {
			if($(this).find('h2 a').text() == array0[i]) {
				$(this).find('h2 .blogSection').text( array0[0]);	
			}
		}
		for(i = 1; i <= array1.length; i++) {
			if($(this).find('h2 a').text() == array1[i]) {
				$(this).find('h2 .blogSection').text( array1[0]);	
			}
		}
		for(i = 1; i <= array2.length; i++) {
			if($(this).find('h2 a').text() == array2[i]) {
				$(this).find('h2 .blogSection').text( array2[0]);	
			}
		}
		for(i = 1; i <= array3.length; i++) {
			if($(this).find('h2 a').text() == array3[i]) {
				$(this).find('h2 .blogSection').text( array3[0]);	
			}
		}
	});
	} 
	/*
	if(!$("#indivualPost").length){
		$("#blogTitleHeading").show();
	}*/
}


$(document).ready(function() {
	
	$.easing.def = "easeInOutSine";
	$('body').addClass('js');
	
	projectContactSlider($("ul.contactList li:eq("+	$.cookie('city_code_cookie') +")"));
	footerContact($("ul.mapNavList li:eq("+ $.cookie('city_code_cookie') +")"));
	
	if($('body').hasClass('homepage')) {
		homepageSetup();	
	} else {
		detailPageSetup();
	}
	
	$("#footer ul.mapNavList li").click( function (e) {
		e.preventDefault();
		projectContactSlider($("ul.contactList li:eq("+$(this).index() +")"));
		footerContact($(this));	
		$.cookie('city_code_cookie', $(this).index(), { expires: 7 });

	});
	
});
