/* ----- Taylor Wimpey jQuery ------------------------------------------------------------- */
/* ----- PH 2011 -------------------------------------------------------------------------- */
/* ----- enjoy, but please don't rip things off outright ---------------------------------- */

$(document).ready(function() {
	
	initDocument();
	
});

function initDocument() {

	if($("#ticker-wrapper").exists()) {
		//initTicker();		
          var options = {
            newsList: "#ticker-wrapper ul",
            tickerRate: 20,
            startDelay: 10,
            placeHolder1: "",
            placeHolder2: "",
            controls: false,
            stopOnHover: false
          }
          $().newsTicker(options);
          
    }

}

//////////----- CORE ------------------------------------------//////////
//---------------------------------------------------------------------//
jQuery.fn.exists = function() {
	return jQuery(this).length > 0;
}

//////////----- GA TRACKING -----------------------------------//////////
//---------------------------------------------------------------------//
function GATrackEvent(category, action, label) {
	_gaq.push(["_trackEvent", category, action, label]);
}

function GATrackPageView(page) {
	_gaq.push(["_trackPageview", page]);
}

function initGAEvents() {
	
	$("a").each(
		function() {
			var destinationURL = $(this).attr("href");
			if(destinationURL.indexOf(".pdf") > -1) {
				var category = "Link"; //Report PDF download event
				var action = "Download";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			} else if(destinationURL.indexOf("http") > -1 && destinationURL.indexOf("taylorwimpey.co.uk") == -1) {
				var category = "Link"; //Report external link click event
				var action = "Exit";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			}
		}
	);
	
}

//////////----- OVERLAYS --------------------------------------//////////
//---------------------------------------------------------------------//
function initOverlay() {
	
	$("body").append("<div id=\"overlay\"><div class=\"frame\"><div class=\"panel\"><div class=\"content\"><span class=\"loader\"></span></div><p id=\"overlay-close\"><a href=\"#site\">Close</a></p></div></div></div>");
	
	$("#overlay-close").live("click", function() {
		$("#overlay .frame").fadeOut(200, function() {
			$("#overlay").fadeOut(200, function() {
				$("#overlay .content").empty().css({
					"height": "auto"
				});
				$("#overlay").removeClass("enable");
			});
		});
		return false;
	});
	
	$("a.overlay").live("click", function() {
		launchOverlay($(this));
		return false;
	});
	
}

function launchOverlay(thisLink, overlayLoadCallback) {
	
	var overlayID = $(thisLink).attr("class");
	overlayID = overlayID.substr(8);
	
	if(!$("#overlay .content span.loader").exists()) {
		$("#overlay .content").prepend("<span class=\"loader\"></span>");
	}
	$("#overlay").addClass("enable").fadeIn(200, function() {
		//Overlay positioning setup + centre on launch
		var winH = $(window).height(); //Actual window height	
		var overlayH = 32 + 18 + 54 + 24; //Overlay loader height + margin + content padding + frame padding
		var winY = Math.floor((winH-overlayH)/2) - 24; //Subtract offset (24)
		$("#overlay .panel").css({
			"margin-top": winY+"px"
		});
		$("#overlay .frame").fadeIn(200, function() {
			
			//Load overlay content
			$("#overlay .content").load(siteRoot+"Overlays.aspx #"+overlayID, function() {
				
				var overlayTargetH = $("#overlay .content").height();
				/*
				if(overlayH > winH) {
					//Fix overlay to safe height and init vertical scrolling
					overlayTargetH = winH - $("#overlay-top").height() - $("#overlay-bottom").height() - 36 - 36;
					$("#overlay-content div").addClass("scroll");
					$("#overlay-content .scroll").css({ "height": overlayTargetH+"px" });
				}
				*/
				var overlayTargetY = Math.floor(((winH-(overlayTargetH + 54 + 24))/2)-24);
				$("#" + overlayID).hide();
				$("#overlay .content").animate({
					"height": overlayTargetH+"px"
				}, 400, function() {
					$("#" + overlayID).fadeIn(400, overlayLoadCallback);
				});
				$("#overlay .panel").animate({
					"margin-top": overlayTargetY+"px"
				}, 400);
							
				//$("#overlay .content span.loader").remove();
		        initDocument();
		        initValidation();
			});
			
		});
		
	});
	
}

//////////----- TEXT FORMATTING -------------------------------//////////
//---------------------------------------------------------------------//
function initTextFormatting() {
	
	//Initials
	if($("p.foreword.initial").exists()) {
		var initialWidth = 87; //84+3	
		var initialLetter = $("p.foreword").text().trim().substr(0,1);
		var forwardWidth = $("p.foreword.initial").parent("div").width()-initialWidth;
		$("p.foreword.initial").text($("p.foreword.initial").text().substr(1));
		$("p.foreword.initial").prepend("<span class=\"initials\"></span>").css({
			"width": forwardWidth+"px",
			"padding-left": initialWidth+"px"
		});
		$("p.foreword.initial span.initials").css({
			"background-image": "url(/images/initials/"+initialLetter+".gif)"
		});
	}
	
}

//////////----- GLOBAL NAV ------------------------------------//////////
//---------------------------------------------------------------------//
function initGlobalNav() {
	
	$("#global-nav").bind("mouseleave", function() {
		$("#global-nav li a.t-l").removeClass("current");
		$("#global-nav li ul").hide();
	});
	
	$("#global-nav li a.t-l").bind("mouseover", function() {
		$("#global-nav li a.t-l").removeClass("current");
		$("#global-nav li ul").hide();
	});
	
	$("#global-nav").children("li").children("ul").children("li").children("a").bind("mouseover", function() {
		$("#global-nav li ul li ul").hide();
	});
	
	$("#global-nav li ul").each(
		function() {
			var pLeft = Math.round($(this).siblings("a").width()/2)-7;
			if(!$(".pointer", this).exists()) {
				$("li:first-child", this).prepend("<span class=\"pointer\"></span>");
				$(".pointer:eq(0)", this).css({
					"left": pLeft+"px"
				}).addClass("s-l");
			}
			
			var menuSize = $(this).children("li").length;
						
			$(this).siblings("a").bind("mouseover", function() {
				$(this).addClass("current");
				$("#global-nav li ul li ul").hide();
				$(this).siblings("ul").show();
			});
			
			$(this).bind("mouseleave", function() {
				$(this).siblings("a").removeClass("current");
				$(this).hide();
			});
		}
	);
	
}

//////////----- FORM FOCUS ------------------------------------//////////
//---------------------------------------------------------------------//
function initFormFocus() {
	
	$("p.field input:text").bind("focus", function() {
		$(this).siblings("label").hide();
		$(this).parent().siblings("label").hide();
	}).bind("blur", function() {
		if($(this).val() == "") {
			$(this).siblings("label").show();
			$(this).parent().siblings("label").show();
		}
	}).attr("value", "");
	
}

//////////----- PROPERTY SEARCH -------------------------------//////////
//---------------------------------------------------------------------//
function initPropertySearch() {
	
	$("#property-search").bind("mouseover", function() {
		$(this).addClass("focus");
	}).bind("mouseleave", function() {
		$(this).removeClass("focus");
	});
	
}

//////////----- NEWS TICKER -----------------------------------//////////
//---------------------------------------------------------------------//
function initTicker() {
	
	tickerItems = new Array();
	tickerIndex = 0;
	var tickerMaxChars = 142;
	
	$("#ticker li a").each(
		function() {
			var tickerItemText = $(this).text();
			if(tickerItemText.length > tickerMaxChars) {
				tickerItemText = tickerItemText.substr(0, tickerMaxChars);
				tickerItemText += "...";
			}/* else {
				tickerItemText += "...";
			}*/
			$(this).text(tickerItemText);
			tickerItems[tickerIndex] = $(this).text();
			tickerIndex++;
			$(this).text("");
			$(this).hover(
				function() {
					stopTicker();
				}, function() {
					tickerInterval = setInterval(runTicker, 6000);
				}
			);
		}
	);
	
	$("#ticker li").hide();
	tickerIndex = 0;
	tickerLength = $("#ticker li").length;
	tickerInterval = setInterval(runTicker, 6000);
	runTicker();
	$("#ticker").show();
	
}

function runTicker() {
	
	$("#ticker li").hide();
	$("#ticker li:eq(" + tickerIndex + ")").show();
	
	var tickerText = "";
	var tickerTextLength = tickerItems[tickerIndex].length;
	var tickerCharIndex = 0;
	tickerCharInterval = setInterval(runTickerChar, 10);
	
	function runTickerChar() {
		tickerText += tickerItems[tickerIndex].charAt(tickerCharIndex);
		$("#ticker li:eq(" + tickerIndex + ") a").text(tickerText);
		//$("#ticker li:eq(" + tickerIndex + ")").text(tickerText);
		tickerCharIndex++;
		if(tickerCharIndex == tickerTextLength) {
			clearInterval(tickerCharInterval);
			tickerIndex++;
			if(tickerIndex == tickerLength) {
				tickerIndex = 0;
			}
		}
	}
	
}

function stopTicker() {
	clearInterval(tickerInterval);
}

//////////----- SEARCH RESULTS --------------------------------//////////
//---------------------------------------------------------------------//
function initSearchResults() {
	
	$("#search-results .col-278 h2 a.toggle").each(
		function() {
			if($(this).text().toLowerCase()=="hide") {
				var state = 1;
			} else {
				$(this).parents("h2").after("<div class=\"mask\"></div>");
				var mask = $(this).parents("h2").siblings(".mask");
				var maskHight = $(this).parents(".col-278").height()-($(this).parents("h2").height()+16); //Add H2 padding and bottom border (15+1)
				$(mask).css({
					"height": maskHight+"px"
				}).fadeIn("300");
				$(this).text("show");
				state = 0;
			}
			$(this).bind("click", function() {
				if(state == 1) {
				    $(this).parents("h2").after("<div class=\"mask\"></div>");
					var mask = $(this).parents("h2").siblings(".mask");
					var maskHight = $(this).parents(".col-278").height()-($(this).parents("h2").height()+16); //Add H2 padding and bottom border (15+1)
					$(mask).css({
						"height": maskHight+"px"
					}).fadeIn("300");
					$(this).text("show");
					state = 0;
				} else {
				    var mask = $(this).parents("h2").siblings(".mask");
					$(mask).fadeOut("300", function() {
						$(mask).remove();
					});
					$(this).text("hide");
					state = 1;
				}
				return false;
			});			
		}
	);
	
}

//////////----- TOGGLE PANEL ----------------------------------//////////
//---------------------------------------------------------------------//
function initTogglePanel() {
	
	$(".toggle-panel").each(
		function() {
			var hiddenObject = $(".hidden", this);
			$("a.toggle", this).bind("click", function() {
				if($(hiddenObject).is(":hidden")) {
					$(hiddenObject).slideDown(400);
					var linkText = $(this).text();
					linkText = linkText.replace("View", "Close");
					$(this).text(linkText);
					$(this).removeClass("link").addClass("back");
					if($(this).parents(".content").siblings(".scene").exists()) {
						$(this).parents(".content").siblings(".scene").fadeIn(400);
					}
				} else {
					$(hiddenObject).slideUp(400);
					var linkText = $(this).text();
					linkText = linkText.replace("Close", "View");
					$(this).text(linkText);
					$(this).removeClass("back").addClass("link");
					if($(this).parents(".content").siblings(".scene").exists()) {
						$(this).parents(".content").siblings(".scene").fadeOut(400);
					}
				}
				return false;
			});
		}
	);
	
}

//////////----- GENERAL ACCORDION -----------------------------//////////
//---------------------------------------------------------------------//
function initAccordion() {
	
	$(".accordion a").each(
		function() {
			var accordionContent = $(this).parent().next(".hidden");
			$(this).bind("click", function() {
				if($(accordionContent).is(":hidden")) {
					$(accordionContent).slideDown(400);
					$(this).addClass("open");
				} else {
					$(accordionContent).slideUp(400);
					$(this).removeClass("open");
				}
				return false;
			});
		}
	);
	
	openTopAccordion();
	
}

function resetAccordions() {
    
    $(".accordion").each(
        function() {
            $("a", this).removeClass("open");
            $(this).next(".hidden").hide();
        }
    );
    
    openTopAccordion();    
    
}

function openTopAccordion() {

    if ($(".accordion").eq(0).parent("#office-locations").length == 0) {
	    $(".accordion").eq(0).next(".hidden").slideDown(400);
	    $(".accordion").eq(0).children("a").addClass("open");
	}

}

//////////----- GENERAL CONTENT TABS --------------------------//////////
//---------------------------------------------------------------------//
function initContentTabs() {	

	$(".content-tabs li").eq(0).children("a").addClass("current");
	$(".tabbed-content").eq(0).show();
	$(".content-tabs li a").each(
		function() {
			var thisTabContent = $(this).attr("href");
			$(this).bind("click", function() {
				if($(thisTabContent).is(":hidden")) {
					$(".content-tabs li a").removeClass("current");
					$(this).addClass("current");
					$(".tabbed-content").hide();
					$(thisTabContent).fadeIn(300, function() {
					    if ($(thisTabContent).find(".accordion").eq(0).parent("#office-locations").length == 0) {
	                        $(thisTabContent).find(".accordion").eq(0).next(".hidden").slideDown(400);
	                        $(thisTabContent).find(".accordion").eq(0).children("a").addClass("open");
	                    }
					});
					/*
					$(".tabbed-content").fadeOut(300, function() {
					    resetAccordions();
						$(thisTabContent).fadeIn(300);
					});
					*/
				}
				return false;
			});
		}
	);	

}

//////////----- GATEWAY PANELS --------------------------------//////////
//---------------------------------------------------------------------//
function initGatewayPanels() {	

	var gpLength = $("ul.gateway li").length;
	var gpCurrent = 1;
	var gpCounter = 1;	

	var gpStrHeight = 0;
	var gpInfHeight = 0;	

    var gpPerRow = 3;
    
    if ($("ul.gateway").parent("#col-912").length > 0) {
        gpPerRow = 4;
    }

	if(gpLength<gpPerRow) {
		$("ul.gateway li").each(
			function() {
				var thisGpStrHeight = $("strong", this).height();
				if(thisGpStrHeight>gpStrHeight) {
					gpStrHeight = thisGpStrHeight;
				}
				var thisGpInfHeight = $("span.info", this).height();
				if(thisGpInfHeight>gpInfHeight) {
					gpInfHeight = thisGpInfHeight;
				}
			}
		);
		$("ul.gateway li strong").css({
			"height": gpStrHeight+"px"
		});
		$("ul.gateway li span.info").css({
			"height": gpInfHeight+"px"
		});
	} else {
		$("ul.gateway li").each(
			function() {
				var thisGpStrHeight = $("strong", this).height();
				if(thisGpStrHeight>gpStrHeight) {
					gpStrHeight = thisGpStrHeight;
				}
				var thisGpInfHeight = $("span.info", this).height();
				if(thisGpInfHeight>gpInfHeight) {
					gpInfHeight = thisGpInfHeight;
				}				

				if(gpCounter==gpPerRow) {
					for(i=(gpCurrent-(gpPerRow-1)); i<=gpCurrent; i++) {
						$("ul.gateway li").eq(i-1).children("a").children("strong").css({
							"height": gpStrHeight+"px"
						});
						$("ul.gateway li").eq(i-1).children("a").children("span.info").css({
							"height": gpInfHeight+"px"
						});
					}
					gpStrHeight = 0;
					gpInfHeight = 0;
					gpCounter = 0;
				}				

				gpCurrent++;
				gpCounter++;
			}
		);
	}
}

//////////----- NEWSLETTER ------------------------------------//////////
//---------------------------------------------------------------------//
function initNewsletter() {
	
	$("#newsletter p.button a").bind("click", function() {
		if($("#bllak-bllak").val() != "") {
			$("#subForm").submit();
		}
		return false;
	});
	
}

//////////----- PAGINATION ------------------------------------//////////
//---------------------------------------------------------------------//
function initPagination() {	

	$("ul.pagination").each(
		function() {
			var maxW = 624;		
			var pagW = $(this).find("li").length * 24;
			var offsetX = Math.ceil((maxW-pagW)/2);
			$(this).parent(".paging").css({
				"margin-left": offsetX+"px"
			});
		}
	);	

}

//////////----- PAGE FEATURES ---------------------------------//////////
//---------------------------------------------------------------------//
function initPageFeature() {	

	var pageFeatureContent = $("#col-624 .page-feature-content").html();
	$("#col-624 .page-feature").html(pageFeatureContent);
	$("#col-624 .page-feature-content").empty();	

}

//////////----- FORM OBJECTS ----------------------------------//////////
//---------------------------------------------------------------------//
function showSpinner(thisObject) {
	$(thisObject).after("<span class=\"spinner\"></span>");
}

function hideSpinner(thisObject) {
	if(thisObject) {
		$(thisObject).next(".spinner").remove();
	} else {
		$(".spinner").remove();
	}
}

function initFormObjects() {
	
	$("p.field input:text, p.field textarea").bind("focus", function() {
		$(this).siblings("label:not(.persist)").hide();
		$(this).parent().siblings("label:not(.persist)").hide();
	}).bind("blur", function() {
		if($(this).val() == "") {
			$(this).siblings("label").show();
			$(this).parent().siblings("label").show();
		}
	}).each(function(){
	    if($(this).val()) {
			$(this).siblings("label").hide();
			$(this).parent().siblings("label").hide();
		}
	});
	
}

function initFormSubmissionObjects() {
	
	$(".submitForm").each(
		function() {
			var targetForm = $(this).attr("data-targetForm");
			allowSubmission = 1;
			
			$(this).bind("click", function() {
				if(allowSubmission==1) {
					//showSpinner($(this));
					allowSubmission = 0;
					validateForm(targetForm);
				}
				return false;
			});
			$("#site input, #ctl00_site input, #ctl00_ctl00_site input").keyup(
				function(e) {
					if(e.keyCode==13) {
						e.preventDefault();
						//showSpinner($("#"+targetForm+" a.submitForm"));
						validateForm(targetForm);
						return false;
					}
				}
			);
		}
	);
	
}

function validateForm(targetForm) {
    targetForm = "aspnetForm"
	if($("#"+targetForm).valid()==false) { //Error
		$("#"+targetForm+" input.error").each(
			function() {
				$(this).parent("p").addClass("error");
				$(this).siblings("label:not(.error, .persist)").css({
					"color": "#d52b1e"
				});
				allowSubmission = 1;
				//hideSpinner();
			}
		);
	} else if($("#"+targetForm).valid()==true) { //Success
		$("#"+targetForm+" p.field").removeClass("error");
		$("#"+targetForm).submit();
	}
	
	$("input.required").bind("change", function() {
		if($(this).valid()==true) {
			$(this).parent("p").removeClass("error");
		}
	});
	
}

function initSiteSearch() {
    
    $(".site-search-input").keyup(
		function(e) {
			if(e.keyCode==13) {
				e.preventDefault();
				//showSpinner($("#"+targetForm+" a.submitForm"));
				if($(this).val() != "") {
    				doSiteSearch(this);
    			}
				return false;
			}
		}
	);
	
}

function doSiteSearch(input) {
    
    var searchTerm;
    var postURL = $(input).siblings(".postURL").attr("value");
    var paramName = "usterms";
    var paramVal = $(input).val();
    searchTerm = postURL+"?"+paramName+"="+escape(paramVal);
    window.location = searchTerm;
    
}

function initAreaSearch() {
    
    $("#q").keyup(
		function(e) {
			if(e.keyCode==13) {
				e.preventDefault();
				//showSpinner($("#"+targetForm+" a.submitForm"));
				if($("#q").val() != "") {
    				doAreaSearch();
    			}
				return false;
			}
		}
	);
	
}

function doAreaSearch() {
    
    var searchTerm;
    var postURL = $("#postUrl").attr("value");
    var paramName = $("#q").attr("name");
    var paramVal = $("#q").val();
    var paramName2 = $("#type").attr("name");    
    var paramVal2 = $("#type").val();    
    searchTerm = postURL+"?"+paramName+"="+escape(paramVal)+"&"+paramName2+"="+escape(paramVal2);
    
    if (paramVal != "")
    {
        window.location = searchTerm;       
    }
    
    return false;
    
}

//////////----- GENERAL SLIDESHOW -----------------------------//////////
//---------------------------------------------------------------------//
function initSlideshow() {	

	var imgW = 300;
	var posX = 0; //Starting x pos
	var imgCount = $("#slideshow-set ul li").length;
	var showW = imgW*imgCount;
	var showing = 1;

	$("#slideshow-set ul").css({ "width": showW+"px" });

	//$(".slideshow.l .loader").remove();

	$("#slideshow-controls .next a").bind("click", function() { //Next image
		if(showing<imgCount) {
			$("#slideshow-set ul").animate({
				"left": "-="+imgW+"px"
			}, 600);
			showing++;
			$("#slideshow-indicators a").removeClass("current");
			$("#slideshow-indicators li.img"+showing+" a").addClass("current");
			$("#slideshow-controls .previous").show();
			if(showing==imgCount) {
				$("#slideshow-controls .next").hide();
			}
		}
		return false;
	});

	$("#slideshow-controls .previous a").bind("click", function() { //Previous image
		if(showing>1) {
			$("#slideshow-set ul").animate({
				"left": "+="+imgW+"px"
			}, 600);
			showing--;
			$("#slideshow-indicators a").removeClass("current");
			$("#slideshow-indicators li.img"+showing+" a").addClass("current");
			$("#slideshow-controls .next").show();
			if(showing==1) {
				$("#slideshow-controls .previous").hide();
			}
		}
		return false;
	});

	//SLIDESHOW CONTROLS
	$("#slideshow-controls .previous").hide();
	$("#slideshow").bind("mouseover", function() {
		$("#slideshow-controls").fadeIn(300);
	}).bind("mouseleave", function() {
		$("#slideshow-controls").fadeOut(300);
	});
	
	//SLIDESHOW INDICATORS
    if(imgCount>1) {
		$("#slideshow-controls").after("<ul id=\"slideshow-indicators\"></ul>");
		var slideshowNavX = (imgW - ((13+3)*imgCount))/2; //(Page width x slideshow indicators (width + margin) x no. of nav items) /2
		$("#slideshow-indicators").css({ "margin-left": slideshowNavX+"px" });
		for(i=1;i<=imgCount;i++) {
			$("#slideshow-indicators").append("<li class=\"img"+i+"\"><a href=\"#Image"+i+"\">"+i+"</a></li>");
		}
		$("#slideshow-indicators li:first-child a").addClass("current");		

		$("#slideshow-indicators a").each(
			function() {
				var thisImage = $(this).text();
				var targetX = (thisImage-1)*imgW;
				$(this).bind("click", function() {
					if(showing!=thisImage) {
						$("#slideshow-set ul").animate({
							"left": "-"+targetX+"px"
						}, 600);
						showing = thisImage;
						$("#slideshow-indicators a").removeClass("current");
						$(this).addClass("current");
						if(showing==1) {
							$("#slideshow-controls .previous").hide();
						} else {
							$("#slideshow-controls .previous").show();
						}
						if(showing==imgCount) {
							$("#slideshow-controls .next").hide();
						} else {
							$("#slideshow-controls .next").show();
						}
					}
					return false;
				});
			}
		);
	}
	
}

function DefaultButtonKeyPress(evt, thisElementName) {

    if(evt.which || evt.keyCode)
    {
        if ((evt.which == 13) || (evt.keyCode == 13))
        {
            // alert('post back href: ' + document.getElementById(thisElementName).href;
            location = document.getElementById(thisElementName).href;
            return false;
        }
    }
    else
    {
        return true;
    }
    
}
