var yellow = yellow||{};
yellow.print = {
    sendPrintEvents: function(){
    	new OmnitureEvent(this, s).init()
    		.withLinkType('o')
    		.withLinkDescription('Print')
    		.sendLink();
    	
		yellow.reporting.withEventType("printBpp").submit();
	},
	onPrintInvoked: function(){  yellow.print.sendPrintEvents(); }
};
var yellow = yellow||{};
yellow.popup = {
    displayAdWin: function(windowUrl, width, height){
        return this._openWin(windowUrl, "displayAdWin", 'width=' + width + ',height=' + height + ',scrollbars=yes,resizable=no');
    },
    emailWin: function(windowUrl){
        return this._openWin(windowUrl, 'emailWin', 'width=575,height=700,scrollbars=yes,resizable=yes');
    },
    sendPageWin: function(windowUrl){
        return this._openWin(windowUrl, 'sendPage', 'width=280,height=650,scrollbars=yes,resizable=yes');
    },
    helpWhatWin: function(windowUrl){
        return this._openWin(windowUrl, 'helpWhatWin', 'width=500,height=600,scrollbars=no,resizable=yes');
    },
    helpHotTipsWin: function(windowUrl){
        return this._openWin(windowUrl, 'hotTips', 'width=800,height=700,scrollbars=yes,resizable=yes')
    },
    pickLocationWin: function(windowUrl){
        return this._openWin(windowUrl, 'pcikLocationWin', 'width=500,height=560,scrollbars=no,resizable=yes');
    },
    addressWindow: function(windowUrl){
        return this._openWin(windowUrl, 'addressWindow', 'width=470,height=360,menubar=no,status=no,location=no,toolbar=no,scrollbars=no,resizable=yes');
    },
    fontWin: function(windowUrl){
        return this._openWin(windowUrl, 'fontWin', 'width=570,height=600,scrollbars=yes,resizable=yes');
    },
    /**
     * new window handler for help window.
     *
     * @param windowUrl the url of the window to open.
     * @param windowName the identifiable window name for targeting.
     * @param windowFeatures a string of window attributes and values.
     * @return null
     */
    _openWin: function(windowURL, windowName, windowFeatures){
        var newWindow;
        newWindow = window.open(windowURL, windowName, windowFeatures);
        if (window.focus) {
            newWindow.focus();
        }
        return;
    }
};
var yellow = yellow || {};

yellow.search = {
	set: function(fieldName, fieldValue){
	    $j("#f-listingsSearchForm input[name='" + fieldName + "']").val(fieldValue);
	    return this;
	},
	sortBy: function(sortBy) {
		yellow.search.set("eventType", 'sort');
		return yellow.search.set('sortBy', sortBy);
	},
	rankType: function(rankTypeValue) {
		$j("#f-listingsSearchForm input[id='rankType']").val(rankTypeValue);
		return this;
	},
	reset: function(fieldName){
		return yellow.search.set(fieldName, '');
	},
	refineAdPoint: function(value) {
		yellow.search.set("eventType", 'refinement');
    	$j("<input type='hidden' name='adPs'/>").val(value).appendTo('#f-listingsSearchForm');
		return this;
	},
	removeAdPoint: function(value) {
		yellow.search.set("eventType", 'expansion');
	    $j("#f-listingsSearchForm input[name='adPs'][value=" + value + "]").remove();
		return this;
	},
    resetVisitedPages: function() {
        $j("#f-listingsSearchForm input[name='visitedIAPages']").remove();
        $j("#f-listingsSearchForm input[name='visitedTMPages']").remove();
        return this;
    },
	refineByHeadingCode: function(value) {
		yellow.search.set("eventType", 'refinement');
		$j("#f-listingsSearchForm input[name='headingCode']").val(value);
		return this;
	},
	removeHeadingCode: function() {
		yellow.search.set("eventType", 'expansion');
		$j("#f-listingsSearchForm input[name='headingCode']").val("");
		return this;
	},
    userLocation: function(address) {
		return yellow.search
			.set('userLocation.latitude', address.coordinates.latitude)
			.set('userLocation.longitude', address.coordinates.longitude)
			.set('userLocation.street', address.street.fullName)
			.set('userLocation.suburb', address.suburb)
			.set('userLocation.streetNumber', (address.streetNumber == null) ? "" : address.streetNumber);
    },
	resetCurrentLetterAndVisitedPages: function(){
		return yellow.search.reset('currentLetter').resetVisitedPages();
	},
	setCurrentLetter: function(letter) {
        yellow.search.resetCurrentLetterAndVisitedPages();
        if (letter == '#') {
            yellow.search.set('currentLetter', '0');
        } else if (letter != 'all') {
            yellow.search.set('currentLetter', letter);
        }
		return this;
	},
	setSurroundingSuburbs: function(includeSurroundingSuburbs){
        yellow.search.resetVisitedPages();
		yellow.search.set("includeSurroundingSuburbs", includeSurroundingSuburbs ? 'true' : 'false');
		yellow.search.set("surroundingSuburbsModifiedByUser", 'true');
		yellow.search.set("eventType", includeSurroundingSuburbs ? 'expansion' : 'refinement');
		return this;
	},
	setServicingArea: function(servicingArea){
        yellow.search.resetVisitedPages();
		yellow.search.set("serviceArea", servicingArea ? 'true' : 'false');
		yellow.search.set("serviceAreaModifiedByUser", 'true');
		yellow.search.set("eventType", servicingArea ? 'expansion' : 'refinement');
		return this;
	},
	submit: function() {
		$j("#f-listingsSearchForm").submit();
		return this;
    }
};
var yellow = yellow || {};

yellow.reporting = {
	withReferredBy: function(referredBy) {
		$j("#drpReferredBy").val(referredBy);
		return this;
	},
	withContext: function(context) {
		$j("#drpContext").val(context);
		return this;
	},
	withEventType: function(eventType) {
		$j("#drpEventType").val(eventType);
		return this;
	},
	withProductId: function(productId) {
		$j("#drpProductId").val(productId);
		return this;
	},
	withProductVersion: function(productVersion) {
		$j("#drpProductVersion").val(productVersion);
		return this;
	},
	withContentValue: function(contentValue) {
		$j("#drpContentValue").val(contentValue);
		return this;
	},
	submit: function() {
		var action = $j("#f-reportingForm").attr('action');
		$j.post(action, $j("#f-reportingForm").serialize());
		return this;
    }
};

$j(document).ready(function() {
	
	$j('.orpDuplicateEvent').click(function() {
			var alreadySentOrpEvent = $j(this).attr('alreadySentOrpEvent');
			var hrefLink = $j(this).attr('href');
			
			if (alreadySentOrpEvent == 'false') {
				$j(this).attr( {
					href: hrefLink + '&alreadySentOrpEvent=false',
					alreadySentOrpEvent : 'true'
				});
			} else {
				$j(this).attr('href', hrefLink.replace('&alreadySentOrpEvent=false', '&alreadySentOrpEvent=true'));
			}
		}
	)
});
yellow = yellow || {};
yellow.youTube = yellow.youTube || {};

yellow.youTube.currentVideo = null;
yellow.youTube.currentChannel = null;
yellow.youTube.videos = new Array();
yellow.youTube.channels = new Array();
yellow.youTube.opened = false;
yellow.youTube.playing = false;
yellow.youTube.flashPlayer = null;
yellow.youTube.pollFlashPlayerTimeout = null;

yellow.youTube.STATE = {
		"ENDED": 0,
		"PLAYING": 1,
		"PAUSED": 2,
		"BUFFERING": 3,
		"CUED": 5
};


yellow.youTube.common = {
		
	checkFlash: function() {
		return jQuery.browser.flash;
	},
	
	applyMetaData : function(id, thumbnailUrl, title, duration, publishedDate, numOfVideos) {
		$j("#video_" + id + " img").attr("src", thumbnailUrl).attr("title", title);
		$j("#title_" + id + " span").text(title).attr("title", title);
		
		if (duration != undefined && duration != "")
		{
			duration = yellow.youTube.common.secondsToTime(duration);
			$j("#duration_" + id).append(duration);
		}
		
		if (publishedDate != undefined && publishedDate != "")
		{
			publishedDate = publishedDate.split('T');
			publishedDate = publishedDate[0].replace(/-/g, "/");
			publishedDate = new Date(publishedDate);
			$j("#publishedDate_" + id).append(publishedDate.format("mmmm dd, yyyy"));
		}
		
		if (numOfVideos != undefined && numOfVideos != "")
		{
			$j("#numOfVideos_" + id).append(numOfVideos + " Videos");
		}
		
		yellow.string.abbreviate();
	},
	
	secondsToTime : function(secs) {
	    var hours = Math.floor(secs / (60 * 60));
	   
	    var divisor_for_minutes = secs % (60 * 60);
	    var minutes = Math.floor(divisor_for_minutes / 60);
	 
	    var divisor_for_seconds = divisor_for_minutes % 60;
	    var seconds = Math.ceil(divisor_for_seconds);
	    
	    if (hours > 0 && minutes >= 0 && minutes < 10) {
	    	minutes = "0" + minutes;
	    }
	    
	    if (seconds < 10) {
	    	seconds = "0" + seconds;
	    }
	    
	    var time = minutes + ":" + seconds;
	    if (hours > 0) {
	    	return hours + ":" + time
	    }
	    else {
	    	return time;
	    }
	},
	
	stateChange : function(newState) {
		if (yellow.youTube.opened) {
			
			if (!yellow.youTube.playing && newState == yellow.youTube.STATE.PLAYING) {
				yellow.youTube.playing = true;
				yellow.youTube.currentVideo.sendOmnitureStartVideoEvent();
				yellow.youTube.common.sendOrpEvent("watchVideoStart");
				yellow.youTube.pollFlashPlayerTimeout = setTimeout("yellow.youTube.common.pollFlashPlayerFor50PercentPlayed();", 1000);
			} else if (newState == yellow.youTube.STATE.PLAYING) {
				yellow.youTube.currentVideo.sendOmnitureResumeVideoEvent();
			} else if (newState == yellow.youTube.STATE.PAUSED || newState == yellow.youTube.STATE.BUFFERING) {
				yellow.youTube.currentVideo.sendOmniturePauseVideoEvent();
			} else if (newState == yellow.youTube.STATE.ENDED) {
				yellow.youTube.playing = false;
				yellow.youTube.currentVideo.sendOmnitureEndVideoEvent();
				yellow.youTube.common.sendOrpEvent("watchVideoFull");
				clearTimeout(yellow.youTube.pollFlashPlayerTimeout);
				yellow.youTube.above50PercentPlayed = false;
			}
		}
		
		if (newState == yellow.youTube.STATE.CUED)  {
			yellow.youTube.playing = false;
			clearTimeout(yellow.youTube.pollYouTubePlayerTimeout);
		}
	},
	
	pollFlashPlayerFor50PercentPlayed: function() {
		clearTimeout(yellow.youTube.pollFlashPlayerTimeout);
		if (yellow.youTube.common.isFlashPlayerAbove50PercentPlayed()) {
			yellow.youTube.common.sendOrpEvent("watchVideoHalf");
		} else {
			yellow.youTube.pollFlashPlayerTimeout = setTimeout("yellow.youTube.common.pollFlashPlayerFor50PercentPlayed();", 1000);
		}
	},

	isFlashPlayerAbove50PercentPlayed: function() {
		if (yellow.youTube.flashPlayer && yellow.youTube.flashPlayer.getCurrentTime() && yellow.youTube.flashPlayer.getDuration()) {
			return yellow.youTube.flashPlayer.getCurrentTime() >= yellow.youTube.flashPlayer.getDuration() / 2;
		}
		return false;
	},
	
	sendOrpEvent : function(eventType) {
		yellow.reporting.withEventType(eventType).submit();
	}
};

$j(document).ready(function() {
	
	$j(".video[isChannel]").each(function() {
		var isChannel = $j(this).attr("isChannel") == "true";
		var metaDataUrl = $j(this).attr("metaDataUrl");
		var url = $j(this).attr("url");
		var videoId = $j(this).attr("videoId");
		if (isChannel) {
			var maxResults = $j(this).attr("maxChannelResults");
			var channel = new yellow.youTube.channel(videoId, url, metaDataUrl, maxResults);
			channel.show();
		}
		else {
			var video = new yellow.youTube.video(videoId, url, metaDataUrl);
			video.show();
		}
	});
	
});

$j(document).bind('contentLoaded', function(event, scope) {
	
	var lightbox = $j(scope).find(".video-info a").lightbox({
		
		formLoaded: function() {
		
			$j("#lightbox_container .youTubeCloseLink").click(function() {
				if (yellow.youTube.currentVideo) {
	 				yellow.youTube.currentVideo.sendOmniturePauseVideoEvent();
					reinitializeVariables();
					swfobject.removeSWF("youTubeObject");
				}
				
				$j("#lightbox_container").html("");
				$j("#lightbox_container").css('visibility','hidden');
				$j("#lightbox_overlay").hide().css({height: 0, width: 0});
			});
		},
		
		formReady: function() {
			yellow.youTube.opened = true;
		}
		
	});
});

function reinitializeVariables() {
	yellow.youTube.opened = false;
	yellow.youTube.playing = false;
	yellow.youTube.flashPlayer = null;
	yellow.youTube.currentVideo = null;
	yellow.youTube.currentChannel = null;
	clearTimeout(yellow.youTube.common.pollFlashPlayerFor50PercentPlayed);
}

//this function is a requirement for youTube api
function onYouTubePlayerReady(playerId) {
	//show the video bar once the player has loaded to fix layout changes.
	$j("#videoBar").show();
	yellow.youTube.flashPlayer = document.getElementById("youTubeObject");
	yellow.youTube.flashPlayer.addEventListener("onStateChange", "yellow.youTube.common.stateChange");
}

yellow = yellow || {};
yellow.youTube = yellow.youTube || {};

yellow.youTube.video = function (id, url, metadataUrl) {
		this.id = id;
		this.url = url;
		this.metadataUrl = metadataUrl;
		this.title = null;
		this.thumbnailUrl = null;
		this.positionInChannel = 0;
		this.URL_PARAMETERS = "&autoplay=1&rel=0&fs=1&enablejsapi=1&playerapiid=player1";
		
		this.loadVideo = function() {
			var videoUrl = this.url + this.URL_PARAMETERS;
			var params = { allowScriptAccess: "always", wmode: "opaque",  allowFullScreen: "true"  };
		    var atts = { id: "youTubeObject" };
		   	swfobject.embedSWF(videoUrl, "videoPlayer", "640", "385", "8", null, null, params, atts);
		},
		
		this.show = function() {
			yellow.youTube.videos[this.id] = this;
			$j.getJSONWithError(this.metadataUrl, {}, function(json){
				if (json !== undefined && json != null){
					var thumbnailUrl = json.entry.media$group.media$thumbnail[0].url;
					var title = json.entry.media$group.media$title.$t;
					var duration = json.entry.media$group.yt$duration.seconds;
					var publishedDate = json.entry.published.$t;
					yellow.youTube.common.applyMetaData(id, thumbnailUrl, title, duration, publishedDate);
					$j('#video-info_'+id).show();
				} else {
				}
			}, function(req, status, error){
			});
		},
		
		this.play = function() {
			if (yellow.youTube.common.checkFlash()) {
				$j("#youTubePlayerFailure").hide();
				yellow.youTube.currentVideo = this;
				this.loadVideo();
			}
		},
		
		this.removeVideo = function (){
			//this removes the current video that is playing in the flash player
		},
		
		this.playChannelVideo = function() {
			if (!$j("#youTubeVideo_" + this.positionInChannel).hasClass("active")) {
				$j(".youTubeVideoBarItem.active").removeClass("active");
				$j("#youTubeVideo_" + this.positionInChannel).addClass("active");
				var videoUrl = this.url + this.URL_PARAMETERS;
				if (yellow.youTube.flashPlayer) {
					if (yellow.youTube.playing) {
						// stop the currently playing video
						$j("#youTubeObject").get(0).stopVideo();
					}
					yellow.youTube.playing = false;
					yellow.youTube.currentVideo = this;
					yellow.youTube.flashPlayer.loadVideoByUrl(videoUrl, 0);
				}
			}
			return false;
		}, 
		
		this.sendOmnitureStartVideoEvent = function() {
			var omnitureEvent = this.getOmnitureEvent();
			omnitureEvent.startVideo(this.id, yellow.youTube.flashPlayer.getDuration());
		},
		
		this.sendOmnitureResumeVideoEvent = function() {
			var omnitureEvent = this.getOmnitureEvent();
			omnitureEvent.resumeVideo(this.id, yellow.youTube.flashPlayer.getCurrentTime());
		},
		
		this.sendOmniturePauseVideoEvent = function() {
			var omnitureEvent = this.getOmnitureEvent();
			omnitureEvent.pauseVideo(this.id, yellow.youTube.flashPlayer.getCurrentTime());
		},
		
		this.sendOmnitureEndVideoEvent = function() {
			var omnitureEvent = this.getOmnitureEvent();
			omnitureEvent.endVideo(this.id, yellow.youTube.flashPlayer.getCurrentTime());
		},
		
		this.getOmnitureEvent = function() {
			var omnitureEvent = new OmnitureEvent(null, s).init().withPageName("Search:Business Profile Page");
			return omnitureEvent;
		}
};
yellow = yellow || {};
yellow.youTube = yellow.youTube || {};

yellow.youTube.channel = function (id, url, metadataUrl, maxResults) {
	this.id = id;
	this.url = url;
	this.metadataUrl = metadataUrl;
	this.maxResults = maxResults;
	this.numberOfVideos = maxResults;
	this.channelResults = null;
	this.barResults = 0;
	this.videos = new Array();
	this.VIDEO_THUMBS_PER_PAGE = 4;
	this.numberOfVideoPages = 0;
	this.videoBarPage = 0;
	
	this.show = function() {
		yellow.youTube.channels[this.id] = this;
		$j.getJSONWithError(metadataUrl + "&max-results=1" , {}, function(json){
			if (json !== undefined && json != null){
				var thumbnailUrl = json.feed.entry[0].media$group.media$thumbnail[0].url;
				var title = json.feed.entry[0].media$group.media$title.$t;
				var duration = json.feed.entry[0].media$group.yt$duration.seconds;
				var publishedDate = json.feed.entry[0].published.$t;
				numberOfVideos = json.feed.openSearch$totalResults.$t>maxResults?maxResults:json.feed.openSearch$totalResults.$t;
				yellow.youTube.common.applyMetaData(id, thumbnailUrl, title, duration, publishedDate, numberOfVideos);
				$j('#video-info_'+id).show();
			}
		}, function(req, status, error)	{
		});
	}, 
	
	this.play = function() {
		if (yellow.youTube.common.checkFlash()) {
			$j("#youTubePlayerFailure").hide();
			yellow.youTube.currentChannel = this;
			this.loadChannel();
		}
	},
	
	this.loadChannel = function() {
		$j.getJSONWithError(metadataUrl+"&max-results=" + this.maxResults, {}, function(json){
			if (json !== undefined && json != null){
				yellow.youTube.currentChannel.loadChannelVideos(json.feed);
			}
		}, function(req, status, error)	{
		});
	},
	
	this.loadChannelVideos = function(feed) {
		for(var i=0; i< numberOfVideos; i++){
			var videoUrl = feed.entry[i].media$group.media$player[0].url;
			var id = feed.entry[i].id.$t;
			id = id.substring(id.lastIndexOf("/") + 1, id.length);
			videoUrl = "http://www.youtube.com/v/" + id;
			var video = new yellow.youTube.video(id, videoUrl, null);
			video.thumbnailUrl = feed.entry[i].media$group.media$thumbnail[0].url;
			video.title = feed.entry[i].media$group.media$title.$t;
			video.positionInChannel = i;
			this.videos[i] = video;
		}
		this.numberOfVideoPages = Math.ceil(this.videos.length / this.VIDEO_THUMBS_PER_PAGE);
		this.displayChannelVideoThumbnails();
	},
	
	this.displayChannelVideoThumbnails = function() {
		if (this.videos) {
			if(this.videos.length > 0) {
				$j("#video").append("<div id=\"videoBar\" style=\"display:none\"></div>");
				$j("#videoBar").append("<div id=\"videoBarItemContainer\"></div>");
				$j("#videoBarItemContainer").append("<span><span id=\"leftFadeOut\"></span></span>");
				$j("#videoBarItemContainer").append("<span><span id=\"rightFadeOut\"></span></span>");
				$j("#videoBarItemContainer").append("<div id=\"videoBarInner\"></div>");
				
				for (i = 0; i < this.videos.length; i++) {
					$j('#videoBarInner').append(this.renderThumbnail(this.videos[i], i));
					if (i == 0) {
						$j("#youTubeVideo_" + i).addClass("active");
					}
				}

				$j("#videoBar").prepend("<div id=\"videoBarLeft\"></div>");
				$j("#videoBar").append("<div id=\"videoBarRight\"></div>");
				if (this.videos.length > this.VIDEO_THUMBS_PER_PAGE) {
					this.addScrollBarForChannelVideos();
				} else {
					$j("#videoBarLeft").css("visibility", "hidden");
					$j("#videoBarRight").css("visibility", "hidden");
				}
				
				$j('#videoBar').append("<br class=\"clear\"/>");
				$j('#videoBarInner').append("<br class=\"clear\"/>");

				$j('#videoBarInner').width(this.videos.length * 140);
				
				this.fixIE();
			}
			yellow.youTube.currentVideo = this.videos[0];
			yellow.youTube.currentVideo.loadVideo();
			yellow.string.abbreviate();
			
		} else {
			$j("#video #videoPlayer").html("<p>This video is currently unavailable.</p>");
		}
	},

	this.fixIE = function() {
		$j(document).ready(function() {
			$j("#bpp #videoBar #videoBarItemContainer span").pngFix();
			
			$j("#bpp #videoBar .youTubeVideoBarItem, #bpp #videoBar #videoBarLeft, #bpp #videoBar #videoBarRight").hover( function() {
				$j(this).addClass('hover');
			}, function() {
				$j(this).removeClass('hover');
			});
		});
	},

	this.addScrollBarForChannelVideos = function() {
		$j("#videoBarLeft").mousedown(function() { $j("#videoBarLeft").addClass("clicked") });
		$j("#videoBarLeft").mouseup(function() { $j("#videoBarLeft").removeClass("clicked") });
		
		addEventForVideoBarLeftClicked();
		
		$j("#videoBarRight").mousedown(function() { $j("#videoBarRight").addClass("clicked") });
		$j("#videoBarRight").mouseup(function() { $j("#videoBarRight").removeClass("clicked") });
		
		addEventForVideoBarRightClicked();
	},
	
	addEventForVideoBarRightClicked = function(){
		$j("#videoBarRight").click(function() { 
			$j("#videoBarInner").animate({left: "-=528px"}, "slow", function() {
				// this one line piece of obscure nastiness is to get thumbnail text in IE's to display when browser is zoomed in or out
				document.body.className = document.body.className; 
			}); 
			yellow.youTube.currentChannel.videoBarPage += 1;
			if (yellow.youTube.currentChannel.videoBarPage >= yellow.youTube.currentChannel.numberOfVideoPages - 1) {
				$j("#videoBarRight").css("visibility", "hidden");
			}
			if (yellow.youTube.currentChannel.videoBarPage == 1) {
				$j("#videoBarLeft").css("visibility", "visible");
			}
		});
	},
	
	addEventForVideoBarLeftClicked = function(){
		$j("#videoBarLeft").click(function() { 
			$j("#videoBarInner").animate({left: "+=528px"}, "slow", function() {
				// this one line piece of obscure nastiness is to get thumbnail text in IE's to display when browser is zoomed in or out
				document.body.className = document.body.className;
			}); 
			yellow.youTube.currentChannel.videoBarPage -= 1;
			if (yellow.youTube.currentChannel.videoBarPage <= 0) {
				$j("#videoBarLeft").css("visibility", "hidden");
			}
			$j("#videoBar").show();
			if (yellow.youTube.currentChannel.videoBarPage == yellow.youTube.currentChannel.numberOfVideoPages - 2) {
				$j("#videoBarRight").css("visibility", "visible");
			}
		});
	},

	this.renderThumbnail = function(video, position) {
		return "<div id=\"youTubeVideo_" + position + "\" class=\"youTubeVideoBarItem\" onclick=\"yellow.youTube.currentChannel.videos['"+position+"'].playChannelVideo()\">" +
					"<span class=\"arrow\"></span>" + 
					"<img src=\"" + video.thumbnailUrl + "\" class=\"thumbnail\" alt=\"YouTube Video\" title=\"" + video.title + "\" />" + 
					"<span class=\"videoTitle\"><span class=\"ellipsis_text\" maxLength=\"25\" title=\"" + video.title + "\" >" + video.title + "</span></span>"
			   "</div>";
	}

};
var yellow = yellow || {};

yellow.browser = {
	isIE6: function(){
        return $j.browser.msie && $j.browser.version.substr(0,1) == '6';
	},
    isIE7: function(){
        return $j.browser.msie && $j.browser.version.substr(0,1) == '7';
    },
    isIE8: function(){
        return $j.browser.msie && $j.browser.version.substr(0,1) == '8';
    },
    isIE9: function(){
        return $j.browser.msie && $j.browser.version.substr(0,1) == '9';
    },
    isSafari: function(){
        // Both Chrome and Safari have the 'safari' substring in the user-agent,
        // but only Chrome has 'chrome'
        return (navigator.userAgent.toLowerCase().indexOf('safari') > -1)
            && !(navigator.userAgent.toLowerCase().indexOf('chrome') > -1);
    },
    isChrome: function(){
        return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    }

};
$j(document).ready(function() {
    if (yellow.browser.isIE6()) {
        $j('#ie6Obsolete').removeClass("hidden");
    } else {
        $j('#ie6Obsolete').remove();
    }
});

// this page assumes that ypCommon.js has been included in the original file

/* Override any s_code.js default settings here */
// s.currencyCode="AUD"

/* Populate Site Specific Variables */
s.server=window.location.host;

//s.prop1="SD"
//s.prop2="Dir";
//s.prop3="YP";
//s.eVar1=s.prop1
//s.eVar2=s.prop2
//s.eVar3=s.prop3

// define CMS variables so that we could set them in YAT
var cmsPageName;
var cmsChannel;
var cmsProp4;
var cmsProp5;


/* End of SiteCatalyst Variables */

/* Site specific doPlugins functions */
function s_prePlugins(s) {
	/* this gets run before standard doPlugins routines */
}

function s_postPlugins(s) {
	/* this gets run after standard doPlugins routines */
	
}

var omniture = {
	getTruncatedPageUrl: function() {
		return this.getUrlWithoutQueryString(window.location + "");
	},
	getUrlWithoutQueryString: function(url) {
		return url.replace(/\?.*$/,'');
	},
	overridePageUrls: function(s) {
		s.pageURL = omniture.getTruncatedPageUrl();
	},
	restorePageUrls: function(s) {
		s.pageURL = document.location.href;
	},
	overrideReferrer: function(s) {
		s.referrer = omniture.getTruncatedPageUrl();
	},
	restoreReferrer: function(s) {
		s.referrer = document.referrer;
	}
};

var trackedElement = "";

function sendOmnitureListingsEvent(listingProducts) {

	omniture.overridePageUrls(s);
	omniture.overrideReferrer(s);

	s.events = "event25";
    s.linkTrackEvents = s.events;
    s.products = listingProducts;
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.products, 'products');
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.products, 'events');
    s.tl(true, "o", "Search Listing Results");
}

function blank(text) {
    return text == null || text == ""
}

/* send omniture event */
function sendOmnitureEvents(link)
{	
	omniture.overridePageUrls(s);
	omniture.overrideReferrer(s);
	
    s.linkTrackVars = "";

    var eventNumb;
    var linkType = 'o';
    var linkId = link.id ? link.id : link.name;

    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.eVar47, 'eVar47');
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.products, 'products');
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.products, 'events');
    s.linkTrackEvents = eventNumb;
    s.events = eventNumb;
    s.tl(true, linkType, linkId);	
}

function appendVariableName(original, extraVariable, variableName) {
  if (original == null || original == "") {
      return variableName;
  } else if (extraVariable != null && extraVariable != "" && original.indexOf(variableName) < 0) {
      return original + ',' + variableName;
  }
  else {
      return original;
  }
}

function getStandardPageTitle(pageTitle)
{
    var lastHyphenPos = pageTitle.lastIndexOf(' - ');
    if (lastHyphenPos > 0)
    {
          pageTitle = pageTitle.substr(lastHyphenPos + 3, pageTitle.length - lastHyphenPos - 2);
    } 
    return pageTitle;
}

function getBusinessIndexPageTitle(pageTitle)
{
	var biPageTitle = pageTitle;
	if ($j('.omnitureListingsInLetterPartition').length > 0) {
		biPageTitle = 'Alphabetical Business Name page';
	}
	else if ($j('.omniturePartitionsInLetter').length > 0) {
		biPageTitle = 'Alphabetical Browse page';
	}
	else {
		var firstHyphenPos = pageTitle.indexOf(' - ');
		if (firstHyphenPos > 0)
		{
			biPageTitle = pageTitle.substr(0, firstHyphenPos);
		}
	}
	return biPageTitle; 
}

///**
// * Search form validation function.
// * 
// * @param form
// *            the form object.
// * @param defaultBusType.
// * @param defaultBusName.
// * @param defaultSuburb
// * @return boolean.
// */
function validateOmnitureSearchForm(form, defaultBusType, defaultBusName, defaultSuburb)
{
    var prefixErrorMessage = 'Oops!\nYou have not provided all the information we need for your search.\nPlease complete the following fields:\n';
    var errorMessage = '';

    if (form.id=="searchForm"
        && form.clue 
        && (form.clue.value.isEmpty() || form.clue.value == defaultBusType || form.clue.value == defaultBusName))
    {
        return false;
    }
    return true;
}

///**
// * Method returns the HTML element that fired the event. This method is cross
// * browser compliant This script is in mapPointRender.js and should be in
// * ypCommon.js
// */
function omnitureGetElementForEvent(e) {

    // MSIE
    if (window.event && window.event.srcElement) {
        return window.event.srcElement;
    }

    // Others
    if (e && e.target) {
        var theEvent;

        if (e.target.nodeType == 3) { // defeats Safari bug
            theEvent = e.target;
        }
        else {
            theEvent = e.target;
        }

        return theEvent;
    }

    return null;
}

function setListingPosition(positionIndex, pageNumber) {
    var listingPosition = $j('#listingPosition');
    var listingPositionForCurrentPage = $j('#listingPositionForCurrentPage');
    
    if (listingPosition) {
        if (isNaN(pageNumber) || isNaN(positionIndex)) {
        	listingPosition.val(positionIndex);
        } else {
        	var absolutePosition = (parseInt(pageNumber)-1)*40  + parseInt(positionIndex);
            listingPosition.val(absolutePosition);
        }
    }
    if (listingPositionForCurrentPage) {
        listingPositionForCurrentPage.val(positionIndex);
    }
}

function setValueForTrackedOmnitureElement(value) {
    trackedElement = value;
}

function setCategoryRefinementZeroResults()
{
    if ($j("#noCategoryRefinementResultsHeading").length)
    {
        s.prop37 = "0";
        s.eVar31 = "0";
        s.events="event12";
    } 
}

function omnitureCaptureEvent(eventType, linkDescription)
{
	omniture.overridePageUrls(s);
	omniture.overrideReferrer(s);
	
    s.events = eventType;
    s.linkTrackEvents = s.events;
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.eVar36, 'eVar36');
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.products, 'products');
    s.linkTrackVars = appendVariableName(s.linkTrackVars, s.products, 'events');
    s.tl(true, "o", linkDescription);
}

//// Called from omnitureVariables.xml
///*
// * override the onclick event to do the following: send the omniture event and
// * then execute the existing onclick event
// */
function overrideOnclickEvent(elementName)
{
	$j('#' + elementName).click(function() {
		sendOmnitureEvents(this);
	});
}

// Called from omnitureVariables.xml
/*
 * override the onclick event on the specified DOM element based on element name
 */
function overrideOnclickEventByName(elementName)
{
	$j('input[name=' + elementName + ']').click(function() {
     sendOmnitureEvents(this);
	});
}

// Called from omnitureVariables.xml
function addSendOmnitureEventAfterOnclickByName(elementName)
{
	$j('input[name=' + elementName + ']').click(function() {
		sendOmnitureEvents(this);
	});
}

/* Add the specified event type on the specified DOM element based on element Id */
function addOmnitureEventListener(elementId, eventType)
{
	$j('#' + elementId).bind(eventType, function() {
		sendOmnitureEvents(this);
	});
}

/*
 * Add the specified event type on the specified DOM element based on element
 * class
 */
function addOmnitureEventListenerToLinkByClass(elementClass, eventType)
{
	$j('a.' + elementClass).bind(eventType, function() {
		sendOmnitureEvents(this);
	});   
}
/*
 * Add the specified event type on the specified DOM element based on element
 * name
 */
function addOmnitureEventListenerByName(elementName)
{
	$j('[name=' + elementName + ']').click(function() {
		sendOmnitureEvents(this);
	});
}

function setupBusinessProfilePageLoadEvent() {
	var bppContent = $j('#bppContent');
	new OmnitureEvent(bppContent[0], s)
		.withListingName(bppContent.attr('listingName'))
		.withProduct(bppContent.attr('product'))
		.withBppChannel()
		.withEventNumber(bppContent.attr('events'))
		.withHeadingName(bppContent.attr('headingName'))
		.withLocalityAndState(bppContent.attr('localityAndState'));
}




/********** Old code above (aim to remove), new shiny one below **********/

function extractListingPositionalInformation(elementId) {
    var listingPosition = "";
    var listingPositionElement = document.getElementById(elementId);
    
    if (listingPositionElement != null && listingPositionElement != undefined) {
        listingPosition = listingPositionElement.value;
    }
    
    return listingPosition; 
}

function getOmnitureProductForListingPosition(listingPosition)
{
    if (!blank(listingPosition)) {
        return $j("li.listingContainer[listingposition=" + listingPosition + "]").attr("product");
    } else {
    	return $j("#bppContent").attr("product");
    }
}

function getListingNameForListingPosition(listingPosition)
{
    if (!blank(listingPosition)) {	
    	var listingName = $j("span#listing-name-"+listingPosition).text();
    	var paidOnFeName = $j("li.listingContainer[listingposition=" + listingPosition + "] > div.listingName > a.omnitureListingNameLink").text();
    
    	if (listingName){
    		return $j.trim(listingName);
    	}
    	else if (paidOnFeName){
    		return $j.trim(paidOnFeName);
    	}
    }
    else{
      	return $j.trim($j("h1.listingName").text());
    }
}


var OmnitureEvent = function(element, s) {

	var linkDescription;
	var linkType;
	
	this.init = function() {
		
		s.server=window.location.host;
		s.currencyCode = "AUD"
		
		s.pageURL = "" + window.location;
		s.referrer = "" + document.referrer; 
		
		s.channel = undefined;
		
		this.remove("eVar1").remove("eVar2").remove("eVar3").remove("eVar4").remove("eVar5").remove("eVar6").remove("eVar7").remove("eVar8").remove("eVar9").remove("eVar10")
		    .remove("eVar11").remove("eVar12").remove("eVar13").remove("eVar14").remove("eVar15").remove("eVar16").remove("eVar17").remove("eVar18").remove("eVar19").remove("eVar20")
		    .remove("eVar21").remove("eVar22").remove("eVar23").remove("eVar24").remove("eVar25").remove("eVar26").remove("eVar27").remove("eVar28").remove("eVar29").remove("eVar30")
			.remove("eVar31").remove("eVar32").remove("eVar33").remove("eVar34").remove("eVar35").remove("eVar36").remove("eVar37").remove("eVar38").remove("eVar39").remove("eVar40")
			.remove("eVar41").remove("eVar42").remove("eVar43").remove("eVar44").remove("eVar45").remove("eVar46").remove("eVar47").remove("eVar48").remove("eVar49").remove("eVar50")
			.remove("eVar66")
			.remove("prop1").remove("prop2").remove("prop3").remove("prop4").remove("prop5").remove("prop6").remove("prop7").remove("prop8").remove("prop9").remove("prop10")
		    .remove("prop11").remove("prop12").remove("prop13").remove("prop14").remove("prop15").remove("prop16").remove("prop17").remove("prop18").remove("prop19").remove("prop20")
		    .remove("prop21").remove("prop22").remove("prop23").remove("prop24").remove("prop25").remove("prop26").remove("prop27").remove("prop28").remove("prop29").remove("prop30")
			.remove("prop31").remove("prop32").remove("prop33").remove("prop34").remove("prop35").remove("prop36").remove("prop37").remove("prop38").remove("prop39").remove("prop40")
			.remove("prop41").remove("prop42").remove("prop43").remove("prop44").remove("prop45").remove("prop46").remove("prop47").remove("prop48").remove("prop49").remove("prop50")
			.remove("hier1")
			.remove("events")
			.remove("linkTrackEvents")
			.remove("linkTrackVars")
			.remove("products")
			.remove("pageName")
			.remove("pageType");
		
		return this;
	};
	
	this.withCommonPageLoadVariables = function() {
		this.add("eVar1","SD")
			.add("eVar2","Dir")
			.add("eVar3","YP")
			.add("prop1","SD")
			.add("prop2","Dir")
			.add("prop3","YP");
		
		return this;
	};
	
	this.withChannel = function(value) {
		s.channel = value;
		return this;
	};

	this.withHierarchy = function(value){
		this.add("hier1","SD|Dir|YP|" + value);
		return this;
	};
	
	this.withPageName = function(value){
		this.add("pageName", "SD:Dir:YP:" + value);
		return this;
	};
	
	this.withLinkDescription = function(value) {
		linkDescription = value;
		return this;
	};

	this.withLinkType = function(value) {
		linkType = value;
		return this;
	};
	
	this.withEvent = function(value) {
		this.add('events', value);
		return this;
	};
	
	this.withLinkTrackEvent = function(value) {
		s.linkTrackEvents = value;
		s.linkTrackVars = "events";
		this.add('events', value);
		return this;
	};
	
	this.withProduct = function(value) {
		s.products = value;
		return this;
	};
	
	this.withLinkTrackProduct = function(value) {
		s.products = value;
		this.addLinkTrackVar('products', s.products);
		return this;
	};
	
	this.withoutProducts = function() {
		s.products = '';
		this.removeLinkTrackVar('products');
		return this;
	};

	this.withoutEvents = function() {
		s.events = '';
		this.removeLinkTrackVar('events');
		return this;
	};
	
	this.withBppChannel = function() {
		s.channel = 'seoGcpPage';
		return this;
	};
	
	this.withListingName = function(value) {
		this.add('prop26', value);
		return this;
	};
	
	this.withHeadingName = function(value) {
		this.add('prop32', value);
		this.add('eVar42', value);
		return this;
	};
	
	this.withLocalityAndState = function(value) {
		this.add('eVar29', value);
		return this;
	};
	
	this.withAttribute = function(propName, attribute) {
		this.add(propName, $j(element).attr(attribute));
		return this;
	};
	
	this.withPageType = function(value){
		this.add('pageType', value); 
		return this;
	};
	
	this.add = function(key, value) {
		s[key] = value;
		return this;
	};
	
	this.remove = function(key){
		s[key] = undefined;
		return this;
	};
	
	this.addLinkTrackVar = function(key, value) {
		s[key] = value;
		s.linkTrackVars = this.appendVariableName(s.linkTrackVars, key);
		return this;
	}
	
	this.removeLinkTrackVar = function(key) {
		s.linkTrackVars = this.removeElement(s.linkTrackVars, key);
		return this;
	}
	
	this.appendVariableName = function(original, variableName) {
		if (original == null || original == "") {
		    return variableName;
		} else if (original.indexOf(variableName) < 0) {
		    return original + ',' + variableName;
		} else {
		    return original;
		}
	}
	
	this.removeElement = function(csv, element) {
		var arr = csv.split(',');
		var indexToRemove = arr.indexOf(element);
		if (indexToRemove >= 0) {
			arr.splice(indexToRemove, 1);
		}
		return arr.join(',');
	}
	
	var getTruncatedUrl =  function() {
		return getUrlWithoutQueryString(window.location + "");
	};
	
	var getUrlWithoutQueryString = function(url) {
		return url.replace(/\?.*$/,'');
	};

	this.reinitialise = function() {
		s.linkTrackVars = "None"
		s.linkTrackEvents = "None"
		return this;
	};

	this.sendLink = function() {
		// s.tl(disable 500ms delay?, link type, link description) 
		// link type options:
		// 'o' - custom
		// 'e' - exit
		// 'd' - download
		s.pageURL = getTruncatedUrl();
		s.referrer = getUrlWithoutQueryString(document.referrer);
		s.tl(true, linkType, linkDescription);
		//clear out s params as omniture will send a second event automagically on downloaded items and this is the only chance to clear them
    	this.init();
	};
	
	this.startVideo = function(videoId, videoLength) {
		s.Media.open(videoId, videoLength, s.Media.playerName);
		s.Media.play(videoId, 0);
		return this;
	};
	
	this.endVideo = function(videoId, endPosition) {
		s.Media.stop(videoId, endPosition);
		s.Media.close(videoId);
		return this;
	};
	
	this.pauseVideo = function(videoId, currentPosition) {
		s.Media.stop(videoId, currentPosition);
		return this;
	};
	
	this.resumeVideo = function(videoId, currentPosition) {
		s.Media.play(videoId, currentPosition);
		return this;
	};
	
};


function captureYelpClickEventForProduct(product) {
    new OmnitureEvent(this, s).init()
           .withLinkType('o')
           .withLinkTrackEvent('event30')
           .withLinkDescription('Yelp Clicks')
           .withLinkTrackProduct(product)
           .sendLink();

}
(function($j) {
        
  $j.fn.expandable = function(expanderLinkText, elementContainingExpandedText) {
    var expandableContainer = $j(this);
    if (expandableContainer.attr('truncated')) {
	    expander = $j('<a class="expander" href="javascript:void(0);" title="'+expanderLinkText+'" >'+expanderLinkText+'</a>')
	    expander.click( function() {
	    	expandableContainer.html(elementContainingExpandedText.html());
	    });
	    expandableContainer.append(expander)
    }
    return expandableContainer;
  }
    
})(jQuery);




(function($j) {
	// object that represents any one of the input text fields that are a part of the searching
	function HintTextField(field, options) {
	    // public member variables
		var hintTextField = this;

	    // public static member variables
	    this.defaultClass = 'hint';
	    this.errorClass = 'error';

	    // returns boolean signifying whether or not input field exists on the page
	    this.validElement = function() {
	        return field;
	    }

	    // performs the required blur functionality as required for each input field
	    this.handleBlur = function() {
	        if (field.val().trim() === '') {
	        	field.addClass(this.defaultClass).val(options.defaultHintText);
	        } else {
	        	field.removeClass(this.defaultClass);
	        }
	    }

	    // performs the required focus functionality as required for each input field
	    this.handleFocus = function() {
	    	field.removeClass(this.defaultClass);

	        if (field.val() === options.defaultHintText) {
	            field.val('');
	            field.select(); // fixes IE missing cursor bug when tabbing
	        }
	        
	    }
	    
		this.validate = function(failureCallback) {
			var value = field.val().trim();
			var isValid = value.length > 0 && value != options.defaultHintText;
			if (!isValid) {
				failureCallback();
				this.inError();
			}
			return isValid;
		};
		
		this.clearError = function() {
			field.removeClass(this.errorClass);
		};
		
		this.inError = function() {
			field.addClass(this.errorClass);
		}
		
	    // sets default appearance for input elements
	    if (this.validElement()) {
	    	var value = field.val();
	        if (value === '' || value === options.defaultHintText) {
	        	field.addClass(this.defaultClass).val(options.defaultHintText);
	        } else {
	            field.removeClass(this.defaultClass);
	        }
	    }

	    field.focus(function() {
	    	hintTextField.handleFocus();
	    });
	    field.blur(function() {
	    	hintTextField.handleBlur();
	    });
	}
	
	$j.fn.hintTextField = function(options) {
		return new HintTextField($j(this), options);
	}	

})(jQuery);
(function($j) {
	// minimum offset from the top of the screen
	var minTopOffset = 10;
	
	function overlay() {
		return $j("#lightbox_overlay");
	}
	
	function container() {
		return $j("#lightbox_container");
	}
	
	function hiddenContainer() {
		return $j("#lightbox_hidden_container");
	}
	
	function closeLink() {
		return container().find(".closeLink");
	}
	
	function tooltips() {
		return container().find(".lightboxToolTip");
	}
	
	function showOverlay() {
        overlay().show();
        calculateOverlaySize();
 	}
	
	function calculateOverlaySize() {
		var overlayTop = overlay().offsetParent().position().top;
		var overlayLeft = overlay().offsetParent().position().left;
        var width = $j(window).width() < 980 ? 980 : $j(window).width();
		overlay().css({top: -overlayTop + 'px', left: -overlayLeft + 'px', height: $j(document).height() + 'px', width: width + 'px'});
	}
	
	function close() {
		container().html("");
		overlay().hide().css({height: 0, width: 0});
		return false;
	}
	
	function hide() {
		var $container = container().children(":first-child").detach();
		$container.hide();
		$container.appendTo(hiddenContainer());
		close();
	}

	function bindEvents(closeEvent) {
		closeLink().click(closeEvent);
		tooltips().mouseover(function() { $j(this).find(".tooltip").css({display: "inline-block"}); } )
		tooltips().mouseout(function() { $j(this).find(".tooltip").hide(); } )
	}
	
	function positionContainer() {
		container().css('visibility','hidden');
		container().css({position: "absolute", top: "0", left: "0"});
		
		var leftOffset = (container().parent().width() - container().width())/2;
		var relativeOffset = ($j(window).height() - container().height())/2 + $j(window).scrollTop();
		if(relativeOffset < minTopOffset) {
			relativeOffset = minTopOffset;
		}
		
		// Adjust offset to be relative from the parent's offset from the top corner of the screen
		var topOffset = relativeOffset - container().parent().offset().top;

		container().css("top", topOffset + "px");
		container().css("left",  leftOffset +"px");
		container().css('visibility','visible');
	}
	
	function Lightbox(linkElements, options) {
		var self = this;
		this.formLoaded = options.formLoaded||function(){};
		this.formReady = options.formReady||function(){};
        this.noBindClickEvent = options.noBindClickEvent;
		
		//this.close = close;
		this.show = function(html) {
			container().html(html);
			bindEvents(close);
			this.formLoaded();

			positionContainer();
			showOverlay();
			this.formReady();
		};
		this.append = function($container) {
			$container.show();
			$container.appendTo(container());
			bindEvents(hide);
			this.formLoaded();

			positionContainer();
			showOverlay();
			this.formReady();
		};
		this.resize = function() {
			positionContainer();
			calculateOverlaySize();
		};

        this.postMethod = function(element) {
            $j.post($j(element).attr('href'), function(data) {
                self.show(data);
            });
        };

        if (!this.noBindClickEvent) {
            linkElements.click(function(event) {
                if (options.use_hidden_container) {
                    var $hidden_content = hiddenContainer().children(":first-child");
                    if ($hidden_content.length > 0) {
                        self.append($hidden_content);
                    }
                } else {
                    self.postMethod(this);
                }

                event.preventDefault();
            });
        }
    }

	$j.fn.lightbox = function(options) {
		return new Lightbox($j(this), options);
	}

	$j(window).resize(function() {
		if(overlay().is(':visible')) {
			calculateOverlaySize();
			positionContainer();
		}
	});

})(jQuery);
(function($j) {
		
  $j.fn.makeLinksFor = function(urlAndStartIndexPairs, linkAttrs) {
	  var origText = $j(this).html();
	  var modifiedText = '';
	  var normalTextIndex = 0;
	  var attrsStr = '';
	  for (var attrName in linkAttrs) {
		  var attrValue = linkAttrs[attrName];
		  attrsStr = attrsStr + ' ' + attrName + '="' + attrValue + '" ';
	  }
	  
	  $j.each(urlAndStartIndexPairs, function(index, urlAndStartIndexPair) {   
		  var url = urlAndStartIndexPair.url;
		  var startIndex = urlAndStartIndexPair.startIndex;
		  
		  var urlEscapedForHtml = yellow.string.escapeForHTML(url);
		  if (startIndex < origText.length) {
		  		  
			  var urlStartIndex = origText.indexOf(urlEscapedForHtml, startIndex);
			  if (urlStartIndex == startIndex) {
				  var href = url;
				  if(!href.match(/^[\w]+:\/\/.*$/i)) { 
					  href = 'http://' + href;
		          }
				  modifiedText = modifiedText + origText.substr(normalTextIndex, urlStartIndex - normalTextIndex) + '<a href="' + encodeURI(href) + '"' + attrsStr + '>' + url + '</a>';
				  normalTextIndex = urlStartIndex + url.length;
			  }
		  }
	  });
	  
	  modifiedText = modifiedText + origText.substr(normalTextIndex);
	  return $j(this).html(modifiedText);
  }
	
  $j.fn.makeUrlLinks = function(linkAttrs) {
      var startIndexAndUrlMap = yellow.string.findUrlInText($j(this).html());
      return $j(this).makeLinksFor(startIndexAndUrlMap, linkAttrs);
  }


})(jQuery);
(function($j) {
	
	function MaxLength(linkElement, maxlength) {
		var LEFT = 37;
		var UP = 38;
		var RIGHT = 39;
		var DOWN = 40;
		var ENTER = 13;
		var self = this;
		this.maxlength = maxlength;
		
		linkElement.keydown(function(event) {
			var key = event.which;
			
			if ((key >= 33 && key != LEFT && key != RIGHT && key != UP && key != DOWN) || key == ENTER) {
				if (this.value.length >= self.maxlength) {
					event.preventDefault();
				}
			}
		});
	}
	
	$j.fn.maxlength = function(maxlength) {
		return new MaxLength($j(this), maxlength);
	}
	
})(jQuery);
(function($j) {
        
  $j.fn.timestamp = function(dateTime, link, tooltip) {
	  if(!link){
		  link = "javascript:void(0);"
	  }
	  var day = dateTime.format("ddd");
	  var date = dateTime.format("dd mmm yyyy");
	  var time = dateTime.format("h:MM TT");
	  var anchor = '<a href="' + link + '" target="_blank" alt="'+tooltip+'" title="'+tooltip+'">'+day+'&nbsp;&nbsp;'+date+'&nbsp;&nbsp;'+time+'</a>';
	  $j(this).hide().html('<div class="timestamp">'+anchor+'</div>').prettyDate(dateTime).fadeIn('slow');
	  return $j(this);
  }
    
})(jQuery);
(function($j) {
        
  $j.fn.truncate = function(maxLength) {
    var originalText = $j(this).html();
    var originalTextUnescaped = yellow.string.unescapeForHTML(originalText);  // Changes &lt; and &gt; to < and >
    var lengthWithoutEllipsis = maxLength-3;
    if (originalText.length > lengthWithoutEllipsis) {
        var abbreviatedTextUnescaped = null;
        
        if (originalTextUnescaped[lengthWithoutEllipsis]!=' ') {
            var index = originalTextUnescaped.lastIndexOf(' ', lengthWithoutEllipsis - 1);
            abbreviatedTextUnescaped = originalTextUnescaped.substr(0, index);
        } else {
            abbreviatedTextUnescaped = originalTextUnescaped.substr(0, lengthWithoutEllipsis);
        }
        var abbreviatedTextEscaped = yellow.string.escapeForHTML(abbreviatedTextUnescaped);  // Changes < and > to &lt; and &gt;
        $j(this).attr('truncated', 'true').html(abbreviatedTextEscaped + '...');
       
    }
    return $j(this);
  }
})(jQuery);
$j(document).ready(function() {

	// prevent bubbling of event from popUpContainer
	$j(".popUpContainer").mouseup(function(event) {
		return false;
	});
	
	$j(".popUpContainer").click(function(event) {
		return event.target.tagName.toLowerCase() == 'a';
	});
	
	$j('.popUpContainer').bind( 'resizePopUp' , function() { $j(this).redrawShadow(); } );
	
	// Close menu item if we click anywhere on the page (expect the .popupContainer as mentioned above)
	$j(document).mouseup(function(event) {
		$j("#refineByOtherAdPoints .popUpContainer").hide().removeShadow();
		
		$j(".opened").not($j(event.target)).not($j(event.target).parent())
			.removeClass("opened")
			.siblings(".popUpContainer")
				.hide()
				.removeShadow();
	});
	
	var showPopup = function(el) {
        $j(el).addClass("opened");
        var top = $j(el).position().top;
        var left = $j(el).position().left;
        var height = $j(el).innerHeight();
        $j(el).siblings(".popUpContainer")
            .css("left", left)
            .css("top", top + height)
            .show()
            .dropShadow({left: 2, top: 2});
        $j(el).siblings(".popUpContainer").trigger('popUp');
    };

    var hidePopupMapFunc = function() {
        hidePopup(this);
    }

    var hidePopup = function(el) {
        $j(el)
		.removeClass("opened")
		.siblings(".popUpContainer")
        .hide().removeShadow();
    };

    var closeSiblings = function(el) {
        $j(el).parent().siblings().find(".opened").not($j(el)).map(hidePopupMapFunc);
    };

    var isPopupOpen = function(el) {
        return $j(el).hasClass("opened");
    };

	$j(".popUpMenuItem").click(function(event) {
		$j('.popUpContent').css("z-index", "17");
		$j('.dropShadow').hide();
        closeSiblings(this);
        if(isPopupOpen(this)){
            hidePopup(this);
        } else {
            showPopup(this);
        }
		$j('.dropShadow').show();
		return false;
	});
});


$j(document).ready(function() {

    function closeMenu() {
        $j("#improveBusinessListing .popUpContainer").removeClass("opened").hide().removeShadow();
        $j("#improveBusinessListingLink").removeClass("opened");
    }

    $j('#improveBusinessListing .popUpContainer').bind('popUp',function() {
        var topOffest, leftOffest;
        if(yellow.browser.isIE7()) {
            topOffest = 25;
            leftOffest = 6;
        } else {
            topOffest = 23;
            leftOffest = 6;
        }
        $j(this).css("top", $j(this).position().top - topOffest)
                .css("left", $j(this).position().left - leftOffest)
                .trigger('resizePopUp').css('z-index','10000');
        var shadowId = $j(this).attr('shadowid');
        $j('#'+ shadowId).css('z-index','9999')
    });

    $j('#improveBusinessListing #improveBusinessCloseLink').click(function(event) {
        closeMenu();
    });

    $j('#improveBusinessListing #editMyBusinessDetails').click(function(event) {
        selfServiceOmnitureEvent();
        closeMenu();
        var newWindow;
        newWindow = window.open($j(this).attr('href'), '_blank');
        if (window.focus) {
            newWindow.focus();
        }
    });
});


$j(document).ready(function() {
    $j('.selectMenu .popUpContainer').bind('popUp',function() {
		// limit size of the popup in a cross-browser way
		if($j(this).height()>220) {
			$j(this).find('>.popUpContent').css("width", "96%");
			$j(this).css("height", 220).trigger('resizePopUp');
		}
    });

	// Sort by Detail
    $j("#sortByDetailItem").click(function() {
    	yellow.search.resetCurrentLetterAndVisitedPages().sortBy('mostInfo').submit();
    });

	// Sort by Relevance
    $j("#sortByRelevanceItem").click(function() {
    	yellow.search.resetCurrentLetterAndVisitedPages().sortBy('closestMatch').submit();
    });	
});


$j(window).load(function(){
	$j('body#bpp #printAdImage').each(function (i) {
    	var printAdRawImage = new Image();
    	printAdRawImage.src = $j(this).attr('src');
    	
    	var hasBeenShrunk = printAdRawImage.width > $j('#rich-media').width();
    	
    	$j(this).attr('shrunk', hasBeenShrunk ? 'true' : 'false');

    	if ( hasBeenShrunk || ($j(this).attr('hasLargeImage') == 'true') ) {
    		var $printAdImageHtml = $j("body#bpp div#printAd").html();
    		var imageUrl = $j("body#bpp img#printAdImage").attr("largerUrl");
        	$j(this).addClass("clickablePrintAd").wrap("<div id='clickToEnlarge' class='highlightborder' />").wrap("<a href='#' title='Click To Enlarge'/>");
    		$j("body#bpp #printAd a").click(function() {
    			yellow.popup.displayAdWin(imageUrl, 613, 640);
    			
    			var product = $j(this).closest('.omnitureListing').attr('product');
    		    new OmnitureEvent(this, s).init()
    		    	.withLinkTrackEvent('event31')
    		    	.withLinkType('o')
    		    	.withLinkDescription('Print Ad Clicks')
    		    	.withLinkTrackProduct(product)
    		    	.sendLink();
    		    
    			return false;
    		});
    		
    		$j("div#clickToEnlarge.highlightborder").hover(
		    	function() {
					$j(this).removeClass("highlightborder");
					$j(this).addClass("highlightborder-mouseover");
		    	}, 
		    	function() {
					$j(this).removeClass("highlightborder-mouseover");
					$j(this).addClass("highlightborder");
		    	}
		    );
    	}
	});
});
$j(document).ready(function () {

    $j('#shareResultsContainer .popUpContainer').bind('popUp', function () {
        var topOffest, leftOffest;
        if (yellow.browser.isIE7()) {
            topOffest = 21;
            leftOffest = 6;
        } else if (yellow.browser.isIE8()) {
            topOffest = 23;
            leftOffest = 6;
        } else if (yellow.browser.isIE9()) {
            topOffest = 21;
            leftOffest = 6;
        } else {
            topOffest = 22;
            leftOffest = 6;
        }
        $j(this).css("top", $j(this).position().top - topOffest)
            .css("left", $j(this).position().left - leftOffest)
            .trigger('resizePopUp').css('z-index', '10000');
        var shadowId = $j(this).attr('shadowid');
        $j('#' + shadowId).css('z-index', '9999')
    });

    $j('#shareResultsContainer #shareResultsCloseLink').click(function (event) {
        closeShareResultsMenu();
    });

    function closeShareResultsMenu() {
        $j("#shareResultsContainer .popUpContainer").hide().removeShadow();
        $j("#shareResultsLink").removeClass("opened");
    }

    $j('#shareResultsToTwitterLink').click(function (e) {
        shareResultsOmnitureEvent('Share Results Twitter');
        closeShareResultsMenu();

        var message = $j('#searchFormBusinessClue').val() + ' in ' + $j('#searchFormLocationClue').val();
        var params = $j.param({ text:message, url:window.location.href});
        var url = '/app/shareUrlViaTwitter?' + params;
        window.open(url, 'twitterPopup', 'height=450,width=550,resizable=1');

        e.preventDefault();
    });

    // populate shareToEmail URL
    $j('#shareResultsContainer #shareResultsToEmailLink').each(function () {
        var params = $j.param({ srpUrl:window.location.href});
        $j(this).attr('href', $j(this).attr('href') + '&' + params);
    });

    $j('#shareResultsContainer #shareResultsToEmailLink').click(function () {
        shareResultsOmnitureEvent('Share Results Email Form Load');
        closeShareResultsMenu();
    });

    $j('#shareResultsContainer #shareResultsToFacebookLink').click(function (e) {
        shareResultsOmnitureEvent('Share Results Facebook');
        closeShareResultsMenu();

        var message = $j('#searchFormBusinessClue').val() + ' in ' + $j('#searchFormLocationClue').val();
        var params = $j.param({ text:message, url:window.location.href});
        var url = '/app/shareUrlViaFacebook?' + params;
        window.open(url, 'facebookPopup', 'height=400,width=500,resizable=1');

        e.preventDefault();
    });

});

$j(document).ready(function() {

    $j("div[intro_text_truncate_at]").each(function() {
        truncateText(this, $j(this).attr("intro_text_truncate_at"));
    });

    $j("a[title_text_truncate_at]").each(function() {
        truncateText(this, $j(this).attr("title_text_truncate_at"));
    });
    
    $j("div[author_text_truncate_at]").each(function() {
        truncateText(this, $j(this).attr("author_text_truncate_at"));
    });
    
    function truncateText(myElement, maxLength) {
        var originalText = $j(myElement).html();
        var originalTextUnescaped = yellow.string.unescapeForHTML(originalText);  // Changes &lt; and &gt; to < and >
        var lengthWithoutEllipsis = maxLength-3;
        if (originalText.length > lengthWithoutEllipsis) {
            var abbreviatedTextUnescaped = originalTextUnescaped.substr(0, lengthWithoutEllipsis);
            var abbreviatedTextEscaped = yellow.string.escapeForHTML(abbreviatedTextUnescaped);  // Changes < and > to &lt; and &gt;
            $j(myElement).html(abbreviatedTextEscaped + '...');
        }
    }
    
    $j("#related-articles").each(function() {
//    	alert("hello");
//    	var height = $j(this).outerHeight();
//    	$j(this).height(height);
    	$j(this).css("zoom", "1");
    });
});
function adjustHeightsOfTabContentWithRHSColumn() {
    // work out the height of the right column
	function calculateRHSColumnHeight() {

	    // use innerHeight so we don't pick up any margins
		var height = $j("body#bpp div#right-column").innerHeight();

	    // cater for the border of right column
	    if (height > 2) {
	    	height = height - 2;
	    }


		$j("#bpp #rich-media").each(function() {
	    	// IE6 has an extra 10 pixels most likely due to the different border-box model.
	    	if ($j.browser.msie && ($j.browser.version == 6.0 || $j.browser.version == 7.0)) {
	    		height = height - 10;
	    		$j("#bpp #breadcrumbs").css("margin-top", "0");
	    	}
	    });

	    return height;
	}


	function calculateTabContentColumnHeight() {
		return $j("#bpp div#tab-content").innerHeight();
	}

	var tabContentHeight = calculateTabContentColumnHeight();

    // moved from document.ready to window.load as we need dom to be loaded when calculating height of right-column with <img> tags
	$j("#paidOnFE").each(function() {
    	$j("#bpp #rich-media, #bpp #tab-content, #bpp div#right-column").removeClass("applyMinHeight");

    	// put 10px gap between rich-media and paidOnFE div when rich-media exist
    	$j("#bpp #rich-media").css("margin-bottom", "10px");

    	var calculatedHeight = calculateRHSColumnHeight();
    	if (calculatedHeight > tabContentHeight) {
    		// bit of an IE hack to fix issue with min-height bug
    		$j("#bpp div#tab-content").css("min-height", calculatedHeight + "px");
    	}
	});
}

$j(window).load( function() {
	// Need this to run after document ready because click.loadTab is bound in document.ready
	$j("#bpp #listingContentBottom #tabs .top-tab").triggerHandler('click.loadTab');

	adjustHeightsOfTabContentWithRHSColumn();
});

$j(document).ready(function() {

    $j.fx.interval = 50;  // this is to fix degraded scrolling animation in firefox

    $j(document).ready(function() {

    	function carousel_initCallback(carousel) {

    		// the slow speed at which the jcarousel code updates the UI means that it is possible to click the next/previous buttons
    		// more times than the pagination should allow.  To counter this UI behaviour, we do a quick check to make sure that the
    		// carousel is not currently animating, or that the next or previous element after the 'currently active div' in the dom
    		// is of the class 'page-indicator' which is the class assigned to the divs that represent the dots on the screen

    	    $j('.jcarousel-next').bind('click', function() {
    	    	var $active = $j(".active");
    	    	var $next = $active.next();
    	    	if (carousel.animating || !$j(".active").next().hasClass("page-indicator")) {
    	    		return false;
    	    	}
    	    	carousel.next();
    	        $j(".active").removeClass("active").addClass("inactive").next().removeClass("inactive").addClass("active");
    	        return false;
    	    });

    	    $j('.jcarousel-prev').bind('click', function() {
    	    	if (carousel.animating || !$j(".active").prev().hasClass("page-indicator")) {
    	    		return false;
    	    	}
    	        carousel.prev();
    	        $j(".active").removeClass("active").addClass("inactive").prev().removeClass("inactive").addClass("active");
    	        return false;
    	    });

    	    $j('.page-indicator').bind('click', function() {
    	        carousel.scroll($j.jcarousel.intval($j(this).attr("intval")));
    	        $j(".active").removeClass("active").addClass("inactive");
    	        $j(this).removeClass("inactive").addClass("active");
    	        return false;
    	    });

    	};

    	var imageGalleryPageCount = $j('#photo-carousel').attr('imageGalleryPageCount');
    	// we add this pseudo class so that we can determine if we are not displaying pagination
    	// we are unable to use attribute selectors in IE6, so we use this class instead
    	if (imageGalleryPageCount === "1") {
    		$j('#photo-carousel').addClass("no-imageGallery-pagination");
    	}

    	var $pagination = $j("#carousel-pagination");
    	for (var x=0; x<imageGalleryPageCount; x++) {
    		// the intval attribute is used by the carousel plugin to determine which image to scroll to the first location in the carousel
    		if (x===0) {
    			$pagination.append("<div class=\"page-indicator active\" intval=\""+((x*3)+1)+"\"></div>");
    		} else {
    			$pagination.append("<div class=\"page-indicator inactive\" intval=\""+((x*3)+1)+"\"></div>");
    		}
    	}
    	$pagination.append("<div class=\"clearfix\"></div>");

        $j('#carousel').jcarousel({
            size: (imageGalleryPageCount * 3),
            initCallback: carousel_initCallback,
            animation: "10"
        });
    });

	function setSelectedTabContent(selectedTabContentId) {
		$j("#tab-content").children(".tab-selected-content").addClass("tab-content").removeClass("tab-selected-content");
		$j("#"+selectedTabContentId).addClass("tab-selected-content").removeClass("tab-content");
	}

    function roundTabsRightSideCorners() {
        $j("#bpp .first-tab").addClass("rounded_tr_corner");
        $j("#bpp .last-tab").addClass("rounded_br_corner");
        $j("#bpp .selected-tab").removeClass("rounded_tr_corner").removeClass("rounded_br_corner");
    }

	// Setup tab selection support.  div#bpptab-xxx corresponds to div#bppcontent-xxx
    $j(".tab").each(function(index) {
		if (index == 0) {
			$j(this).addClass("first-tab").addClass("top-tab").addClass("selected-tab").addClass("rounded_tl_corner");
		} else if (index == ($j(".tab").length - 1)) {
			$j(this).addClass("bottom-tab");
		} else {
			$j(this).addClass("middle-tab");
		}

        if (index == ($j(".tab").length - 1)) {
            $j(this).addClass("last-tab").addClass("rounded_bl_corner");
        }

		$j(this).click(function() {
    		var clickedOnTabContentId = $j(this).attr("id").replace("bpptab", "bppcontent");
    		setSelectedTabContent(clickedOnTabContentId);
    		$j("ul.sections > li").removeClass("selected-tab");
    		$j(this).addClass("selected-tab");
            roundTabsRightSideCorners();
		});
    });

    var paginatorTemplate = null;

    // Call out to the content api to get yelp review data for the aboutId
    $j("#bpptab-ratings-and-reviews").click(function(){
		if ( $j("#bpptab-ratings-and-reviews").attr("tabContentLoaded") != 'true' ) {

			// reset the height properties that are set to equalise tab content area height with PaidOnFE height
			// review content area will then resize appropriately.
			$j("#bpp div#tab-content").css("height", "").css("min-height", "");
			var aboutId = $j("#bppContent").attr("aboutId");
            loadYelpReviews(aboutId, 0);
		}
    });

    roundTabsRightSideCorners();


    // hack to fix flicking on page load when javascript is slow
    $j("#bpp div#listingContentTop").css("visibility", "visible");

    // hack to fix flicking on page load when javascript is slow
    $j("#tab-content").css("visibility", "visible");

    // Hide the tabs div if there are no internal tabs being displayed.
	if ($j("body#bpp div#tabs ul li").length == 0) {
		$j("body#bpp div#tabs").hide();
	}

	// Set initial tab
    $j("#bpp #tab-content .tab-content:first").each( function() {
    	var selectedTabContentId = $j(this).attr("id");
    	setSelectedTabContent(selectedTabContentId);
    });

    // Standard hoverable behaviour
    $j("body#bpp div#tabs ul li.tab").hover(
   	    function(event) {
       		$j(this).addClass("hover");
   		},
   		function(event) {
       		$j(this).removeClass("hover");
   		}
    );

    $j(".highlightborder").hover(
    	function() {
			$j(this).removeClass("highlightborder");
			$j(this).addClass("highlightborder-mouseover");
    	},
    	function() {
			$j(this).removeClass("highlightborder-mouseover");
			$j(this).addClass("highlightborder");
    	}
    );

    // Add a class to the first 'about us' table data item, (ie ABN, ACN, etc..) if we have some
    // content above it.  This allows us to add a border and appropriate padding.
    if ($j("body#bpp div#bppcontent-about-us div.about-us-text-content, body#bpp div#openingHours").length > 0) {
    	// Only need to add class it content exists
    	if ($j("body#bpp div#about-us-table-content div.tab-contents-item").length > 0) {
    		$j("body#bpp div#bppcontent-about-us div#about-us-table-content").addClass("requires-divider");
    	} else {
    		// Remove about-us-table-content container div if it has no content.
        	// Saves us having to hack around IE6 css issues
    		$j("body#bpp div#bppcontent-about-us div#about-us-table-content").remove();
    	}
    } else {
    	// Remove tab-contents-text-blocks container div if it has no content.
    	// Saves us having to hack around IE6 css issues
    	if($j("body#bpp div#bppcontent-about-us div.about-us-text-content").length == 0) {
    		$j("body#bpp div#bppcontent-about-us div.tab-contents-text-blocks").remove();
    	}
    }

    yellow.string.abbreviate();

    // since javascript is enabled, we need to remove the href for each of the anchor tags in
    // the tabs menu to ensure that the browser will not jump around the page when clicked
    $j("body#bpp div#tabs ul li.tab a").removeAttr("href");

    // setting up click on coupon click to send a DRP event
    $j('.coupon a').click(function(event) {
    	var href = $j(this).attr('href');
    	yellow.reporting.withEventType("viewCouponOffer").withContentValue(href).submit();
    	return true;
    });

    // use 'live' event to catch clicks on AJAX-based components
    $j('div.yelp-review-body a.yelp-review-expand-link').live('click', function(event) {
        var index = $j(this).attr('index');

        $j('div.yelp-review-body div#yelp-review-collapsed-' + index).hide();
        $j('div.yelp-review-body div#yelp-review-expanded-' + index).show();

        return false;
    });

    // use 'live' event to catch clicks on AJAX-based components
    $j('div.yelp-review-body a.yelp-review-collapse-link').live('click', function(event) {
        var index = $j(this).attr('index');

        $j('div.yelp-review-body div#yelp-review-expanded-' + index).hide();
        $j('div.yelp-review-body div#yelp-review-collapsed-' + index).show();

        return false;
    });

    function updatePaginator(aboutId, currentPage) {
    	currentPage = parseInt(currentPage);

    	var yelpInfo = $j(".yelp-reviews-count");

    	var totalReviews = parseInt(yelpInfo.attr("count"));

    	var reviewsPerPage = parseInt(yelpInfo.attr("reviews-per-page"));

    	var pagesToDisplay = 10;

    	var totalPages = totalReviews / reviewsPerPage;

    	var paginatorModel = {pages: new Array()};

    	paginatorModel.prevPage = currentPage - 1;
    	paginatorModel.showPrev = currentPage > 0;

    	paginatorModel.nextPage = currentPage + 1;
    	paginatorModel.showNext = currentPage < totalPages - 1;

    	var firstPage = Math.max(currentPage - pagesToDisplay / 2, 0);
    	var lastPage = Math.min(firstPage + pagesToDisplay, totalPages);

    	var paginator = "";

    	if (lastPage - firstPage > 1) {
			for (var i = firstPage; i < lastPage; i++) {
				var page = {
					caption: i + 1,
					number: i,
					activeState: i == currentPage ? "Inactive" : "Active"
				}
				paginatorModel.pages.push(page);
			}
	    	paginator = Mustache.to_html(paginatorTemplate, paginatorModel);
    	}

    	$j("#paginator").html(paginator);

    	$j('#paginator .reviewPaginatorElementActive').click(function() {
    		  $j('html, body').scrollTop(0);
    		  var pageNumber = $j(this).attr("pagenumber");
    		  loadYelpReviews(aboutId, pageNumber);
    	});
    }

	function loadYelpReviews(aboutId, pageNumber) {
		$j("#ratings-and-reviews-container").html("<div class='yelp-waiting-message'><img src='/ui/standard/bpp/waiting.gif' alt='waiting...'/></div>");
		jQuery.ajax({
			type: "GET",
			url: "/app/reviews/"+aboutId+"?offset=" + pageNumber,
			cache: false,
			success: function(data) {
				$j("#ratings-and-reviews-container").html(data);
				$j("#bpptab-ratings-and-reviews").attr("tabContentLoaded", "true");

	            // expand/collapse functionality
	            $j('div.yelp-review-body').expander({
	                slicePoint: 1500,
	                expandText: 'Show more',
	                userCollapseText: 'Show less'
	            });

	            $j('div.yelp-review-body .read-more a').attr('title', 'Expand review');
	            $j('div.yelp-review-body .read-less a').attr('title', 'Collapse review');


	            if (paginatorTemplate == null) {
		            jQuery.ajax({
		    			type: "GET",
		    			url: "/ui/template/paginator.mustache",
		    			cache: true,
		    			success: function(templateView) {
		    				paginatorTemplate = templateView;
		    				updatePaginator(aboutId, pageNumber);
		    			},
		    			dataType: "text",
		    			error: function(req, status, error) {
		    			}
		            });
	            } else {
	            	updatePaginator(aboutId, pageNumber);
	            }

	            adjustHeightsOfTabContentWithRHSColumn();

			},
			dataType: "html",
			error: function(req, status, error) {
				$j("#paginator").empty();	
				$j("#ratings-and-reviews-container").html("<div class='yelp-error-message'><span>Due to technical difficulties, we are unable to display ratings and reviews.</span><br/><span>Please try again later.</span></div>");
			}
		});
	}
});



$j(document).ready(function() {

    $j("#bpptab-products-and-services").click(function () {
    	submitYellowReportingEvent("viewProductsAndServices");
    });
        
    $j("#bpptab-additional-locations").click(function () {
    	submitYellowReportingEvent("viewAdditionalLocations");
    });
    
    $j("#bpptab-about-us").click(function () {
    	submitYellowReportingEvent("viewAboutUs");
    });
    
    $j("#bpptab-additional-contacts").click(function () {
    	submitYellowReportingEvent("viewAdditionalContacts");
    });
    
    $j("#bpptab-faqs").click(function () {
    	submitYellowReportingEvent("viewFaqs");
    });

    $j("#bpptab-ratings-and-reviews").click(function () {
    	submitYellowReportingEvent("viewRatingsAndReviews");
    });
});

function submitYellowReportingEvent(eventName) {

    if (yellow.reporting) {
		yellow.reporting.withEventType(eventName).submit();
	}
}

(function ($) {
	//checks if browser object exists
	if (typeof $.browser === "undefined" || !$.browser) {
		var browser = {};
		$.extend(browser);
	}

	
	var initSupported = function () {
		if (window.ActiveXObject) {
			$.browser.flash = false;
			try {
				var activex = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				var flashVersion = activex.GetVariable("$version");
				var majorVersion = parseInt(flashVersion.match(/[\d]+/g)[0]);
				$.browser.flash = majorVersion >= 8;
			} catch (e) {}	

		} else {
			$.each(navigator.plugins, function () {
				var mimeType = navigator.mimeTypes['application/x-shockwave-flash'];
				if (mimeType && mimeType.enabledPlugin) {
					var flashVersion = mimeType.enabledPlugin.description;
					var majorVersion = parseInt(flashVersion.match(/[\d]+/g)[0]);
					$.browser.flash =  majorVersion >= 8;
					return false;
				} else {
					$.browser.flash = false;
				}
			});
		}
	};
	
	initSupported();
	
})(jQuery);
/* 
 * 
 * Review this code as part of the BPP redesign work in R30, and remove anything that is no longer relevant
 * 
 */

/*$j(document).ready(function(){
	var videoTabIndex = $j('#bpp #detail li').index($j('#video-tab'));
	
	$j("#bpp #detail").tabs({
		
		selected: (videoTabIndex == -1)? 0 : videoTabIndex,
		
		show: function(event, ui) {
			if($j(ui.tab).attr('href')=='#additional-locations') {
				$j("#bpp #state-tabs").tabs({
					load: function(event, ui) {
						var panel = ui.panel;
						$j('#bpp #state-tabs .ui-tabs-panel').each(function() {
							if(this!=panel) {
								$j(this).empty();
							}
						});
					}
				});
				
				$j("#bpp #state-tabs li.disabled-tab").each(function() {
					$j("#bpp #state-tabs").tabs("disable", $j('li', $j(this).parent()).index($j(this)));
				});
			}
			if($j(ui.tab).attr('href')!='#video') {
				if (yellow.youTube.ytPlayer) {
					yellow.youTube.ytPlayer.pauseVideo();
				}
			}
		}
	});
});
*/
$j(document).ready(function() {
	var oneMonthInHours = 24 * 30;
	
	// populate from cookie if the value is empty and not on the homepage
	$j('#searchFormBusinessClue').not('#home #searchFormBusinessClue').each(function() {
		if($j(this).val().isEmpty()) {
			$j(this).cookieFill();
		} else {
			$j(this).cookify();
		}
	});

	$j('#searchFormLocationClue').each(function() {
		if($j(this).val().isEmpty()) {
			$j(this).cookieFill();
			
			if($j(this).val().isEmpty()) {
				$j(this).val("All States");
			}
		} else {
			$j(this).cookify({hoursToLive: oneMonthInHours});
		}
	});
	
	$j("#searchForm").submit(function() {
    	$j('#searchFormBusinessClue').cookify();
    	$j('#searchFormLocationClue').cookify();
	});
});
var lightbox = lightbox || {};
lightbox.emailBusiness = lightbox.emailBusiness || {};

var displayEmailBusiness = function(element) {
    var lb = $j(element).lightbox({
         formLoaded: function() {
			$j('#emailBusinessBody form').submit(submitForm);

			$j('.contactUsLink').click(function() {
				lightbox.emailBusiness.close();
			});
		},

		formReady: function() {
			$j('#emailBusinessMessage').focus();
		}
    });
    return lb;
}

var displayEmailBusinessForMapPoiPopup = function(element) {
    var lb = $j(element).lightbox({
         formLoaded: function() {
			$j('#emailBusinessBody form').submit(submitForm);

			$j('.contactUsLink').click(function() {
				lightbox.emailBusiness.close();
			});
		},

		formReady: function() {
			$j('#emailBusinessMessage').focus();
		},

        noBindClickEvent: true
    });
    return lb;
}

function submitForm() {

    var messageField = $j('#emailBusinessMessage textarea').val();
    if(messageField.isEmpty() || messageField.length > 500) {
        $j(this).find('#emailBusinessErrorMessage_messageFieldEmpty').show();
        $j(this).find('#emailBusinessMessage').addClass('error');
    } else {
        $j(this).find('#emailBusinessErrorMessage_messageFieldEmpty').hide();
        $j(this).find('#emailBusinessMessage').removeClass('error');
    }

    if($j('#emailBusinessName input').val().isEmpty()) {
        $j(this).find('#emailBusinessErrorMessage_nameFieldEmpty').show();
        $j(this).find('#emailBusinessName').addClass('error');
    } else {
        $j(this).find('#emailBusinessErrorMessage_nameFieldEmpty').hide();
        $j(this).find('#emailBusinessName').removeClass('error');
    }

    $j(this).find('#emailBusinessErrorMessage_emailFieldEmpty').hide();
    $j(this).find('#emailBusinessErrorMessage_emailFieldInvalid').hide();
    $j(this).find('#emailBusinessEmail').removeClass('error');
    if($j('#emailBusinessEmail input').val().isEmpty()) {
        $j(this).find('#emailBusinessErrorMessage_emailFieldEmpty').show();
        $j(this).find('#emailBusinessEmail').addClass('error');
    } else if(!$j('#emailBusinessEmail input').val().isEmail()) {
        $j(this).find('#emailBusinessErrorMessage_emailFieldInvalid').show();
        $j(this).find('#emailBusinessEmail').addClass('error');
    }

    if($j('div.error',this).length>0) {
        $j('#requiredInfo', this).addClass("error");
        $j('#lightboxErrorList', this).show();
        lightbox.emailBusiness.resize();
    } else {
        $j('#requiredInfo', this).removeClass("error");
        $j('#lightboxErrorList').hide();
        $j('#btn-sendEmail').attr("disabled", true);

        $j.post($j(this).attr('action'), $j(this).serialize(), function(data) {
            lightbox.emailBusiness.show(data);
        });
    }
    return false;
}

$j(document).bind('contentLoaded', function(event, scope) {
	
	lightbox.emailBusiness = displayEmailBusiness($j(scope).find(".emailBusinessLink"));
});
$j(document).ready(function() {
    $j("#surroundingCheckbox").click(function() {
    	$j(this).attr('disabled', 'true'); 
    	yellow.search.setSurroundingSuburbs(this.checked).submit();
    });
    
    $j("#servicingCheckbox").click(function() {
    	$j(this).attr('disabled', 'true'); 
    	yellow.search.setServicingArea(this.checked).submit();
    });
    
    // Reset cached form state
	// Call Reset for IE6 only. Envjs doesnt play nice with reset
	if((typeof(Envjs) == 'undefined') && ($j.browser.msie && $j.browser.version.substr(0,1)<7)) {
		$j("#f-listingsSearchForm").each(function() { this.reset(); });
	}
});
$j(document).ready(function() {
	$j("#facebookFeed_content").each(function() {
		var facebookFeedUrl = $j("#facebookFeed").attr("feedurl");
    	$j.getJSONWithError(facebookFeedUrl, {}, handleFacebookFeedResponse, handleFacebookFeedError);
    });
});

handleFacebookFeedResponse = function(json) {
	
	// hide the waiting animation
	$j("#facebookFeed div.contentLoading").hide();
	if ((json.data != null) && (json.data.length > 0) && (json.data[0] != null)) {
		
		var post = json.data[0];
		$j("<div id='facebookFeed_content_expanded'/>")
//			.hide()
		    .css("display", "none")
			.text(post.message)
			.makeUrlLinks({ 'rel' : 'nofollow', 'target' : '_blank' })
			.insertAfter("#facebookFeed_content");
		
		$j("#facebookFeed_content")
			.hide()
			.text(post.message)
			.truncate(141)
			.makeUrlLinks({ 'rel' : 'nofollow', 'target' : '_blank' })
			.expandable('read more', $j('#facebookFeed_content_expanded'))
			.fadeIn("slow");

		var postTimeStamp = getPostTimeStamp(post.updated_time);
		var postRedirectUrl = getPostRedirectUrl(post.id);
		$j("#facebookFeed_timestamp").timestamp(postTimeStamp, postRedirectUrl, 'View this post on Facebook');
		
	} else if(json.error && (json.error.message.indexOf("(#803)") != -1)) {
			$j("#facebookFeedHeader div.linkText").remove();
			$j("#facebookFeedHeader img").after('<div class="errorText">Unable to display Facebook feed.</div>');	
	} else {
			$j("#facebookFeed_content").append('<div class="errorText">Unable to display Facebook feed.</div>');
	} 
};

getPostTimeStamp = function(postUpdatedTime) {
	if(postUpdatedTime){
		var parts = postUpdatedTime.substring(0, postUpdatedTime.lastIndexOf('+0000')).split('T');
		var date = parts[0].split('-');
		var month = dateFormat.i18n.monthNames[date[1] - 1];
		var dateTime = new Date(Date.parse(month+" "+date[2]+", "+date[0]+" "+parts[1]+" UTC"));
		return dateTime;
	}
};

getPostRedirectUrl = function(postId) {
	if(postId){
		var parts = postId.split('_');
		var baseUrl = $j("#facebookFeed").attr("baseurl");
		return baseUrl + "/" + parts[0] + "/posts/" + parts[1];
	}
};


handleFacebookFeedError = function(req, status, error){
	// handle any error come back later
};

/* 
 * 
 * Review this code as part of the BPP redesign work in R30, and remove anything that is no longer relevant
 * 
 * Possibly split logic into separate js files if used on separate pages  
 * 
 */
$j(document).ready(function() {

	
	
	
	$j("#bpptab-additional-locations").bind('click.loadTab' ,function() {
		if ( $j("#bpptab-additional-locations").attr("tabContentLoaded") != 'true' )
			$j("#bpptab-additional-locations").attr("tabContentLoaded", "true");
		$j("#bpp #state-tabs").hide();
		
		// initialize the tab functionality
		
		$j("#bpp #state-tabs").tabs({
			load: function(event, ui) {   
			// clearing out the panels
			var panel = ui.panel;
			$j('#bpp #state-tabs .ui-tabs-panel').each(function() {
				if(this!=panel) {
					$j(this).empty();
				}
			});
		}
		});
		
		// disable all tab LI elements with the "disables-tab" class
		$j("#bpp #state-tabs li.disabled-tab").each(function() {
			$j("#bpp #state-tabs").tabs("disable", $j('li', $j(this).parent()).index($j(this)));
		});
		
		$j("#bpp #state-tabs").show();			
	});
	
	function applyLruPaginationBehaviour(element) {
		$j(document).trigger('contentLoaded', element);
		element.find('.lruPaginationLink a').each(function() {
			$j(this).click(function() {
				var container = $j(this).closest('.lruPagination').parent();
				container.load($j(this).attr('href'), function() {
					applyLruPaginationBehaviour(container);
					
					
					
				});
				return false;
			});
		});
	}

	
	// Apply behaviour on BPP tab load
	$j('#bpp #state-tabs').bind('tabsload', function(event, ui) {
		applyLruPaginationBehaviour($j(ui.panel));
		insertOrpDuplicateEventBehaviour();
	});
	
	
	// Apply behaviour to the results page
	$j('.showLruLink a').click(function(event) {
		var currentLink = this;
		var container = $j(this).closest('.lruListingsPanel').find('.lruContentPanel');
		container.load($j(this).attr('href'), function() {
			container.slideDown();
			insertOrpDuplicateEventBehaviour();
			applyLruPaginationBehaviour(container);
			$j(currentLink).parent().hide();
			container.parent().find('.hideLruLink').show();
		});
		event.stopImmediatePropagation();
		return false;
	});
	
	$j('.hideLruLink a').click(function() {
		var container = $j(this).closest('.lruListingsPanel');
		container.find('.lruContentPanel').slideUp();
		container.find('.hideLruLink').hide();
		container.find('.showLruLink').show();
		return false;
	});
	
	function insertOrpDuplicateEventBehaviour(){
		
		$j('.orpDuplicateEvent').click(function() {
			var alreadySentOrpEvent = $j(this).attr('alreadySentOrpEvent');
			var hrefLink = $j(this).attr('href');
			
			if (alreadySentOrpEvent == 'false') {
				$j(this).attr( {
					href: hrefLink + '&alreadySentOrpEvent=false',
					alreadySentOrpEvent : 'true'
				});
			} else {
				$j(this).attr('href', hrefLink.replace('&alreadySentOrpEvent=false', '&alreadySentOrpEvent=true'));
			}
		}
	)}
	
});


$j(window).load(function() {

    var drawInteractiveMap = function() {
		$j('head').append('<link rel="stylesheet" href="'+emsMapResourceUrl+'web/js/ol/theme/default/style.css" type="text/css" />');
		$j('head').append('<link rel="stylesheet" href="'+emsMapResourceUrl+'web/js/ems/theme/default/style.css" type="text/css" />');

		// there doesn't seem to be a way of doing this using jquery - chaining getScript causes errors...
		function loadScript(url, callback){
		    var script = document.createElement("script")
		    script.type = "text/javascript";

		    if (script.readyState){  //IE
		        script.onreadystatechange = function(){
		            if (script.readyState == "loaded" || script.readyState == "complete"){
		                script.onreadystatechange = null;
		                callback();
		            }
		        };
		    } else {  //Others
		        script.onload = function(){
		            callback();
		        };
		    }

		    script.src = url;
		    document.getElementsByTagName("head")[0].appendChild(script);
		}

		// load assets and create interactive map
		loadScript(emsMapResourceUrl+'web/js/ol/OpenLayers.js?compress=yes', function() {
			loadScript(emsMapResourceUrl+'web/js/ems/EMS.js?token='+emsMapToken, function() {
				$j('#resultsBody.listView #mapDisplay, #bppContent #mapDisplay').each(function() {
					$j(this).empty();

					var map = new EmsMap(this);

					var bppElement = $j('#bppContent.mappableListing')[0];
					if(bppElement) {
						map.addBppMarker($j(bppElement).attr('flagNumber'),$j(bppElement).attr('longitude'), $j(bppElement).attr('latitude'));
				    } else {
				    	$j('li.mappableListing').each(function() {
							var flagNumber = $j(this).attr('flagNumber');
							addFlagToListing(this);

							// create a marker if needed
							var marker = map.addListingsMarker(flagNumber, $j(this).attr('longitude'), $j(this).attr('latitude'));

							$j(this).hover(function() {
								marker.icon.setStickyState(1);
								$j('#listingsPanel .flag_icon_' + flagNumber).addClass('flag_icon_hover');
							}, function() {
								marker.icon.setStickyState(0);
								$j('#listingsPanel .flag_icon_' + flagNumber).removeClass('flag_icon_hover');
							});
				    	});
				    }
			    	map.setViewport();
				});
			});
		});
	};

	var EmsMap = function(element) {
		var markers = [];

		EMS.Services.communicationMode = "CrossDomain";
		var map = new EMS.Services.Map(element, {
			controls: [new EMS.Control.Scale(), new EMS.Control.Copyright()], maxResolution: .2, numZoomLevels: 18
		});
		map.whereis_hybrid_wms.imageOffset = new OpenLayers.Pixel(0, 10); 
		map.addControl(new EMS.Control.MouseDefaults());
	    map.addControl(new EMS.Control.ZoomBar(
	            map.whereis_street_wms,
	            map.whereis_photo_wms,
	            map.whereis_hybrid_wms,false,true));
	    
	    this.addBppMarker = function(id, longitude, latitude) {
	    	var marker = new OpenLayers.Marker(new EMS.LonLat(longitude, latitude), EMS.Services.StandardIcons.crossHair());
			marker.id = id;
	    	map.markersLayer.addMarker(marker);
	    	return marker;
	    };
	    
		this.addListingsMarker = function(flagNumber, longitude, latitude) {
			if(markers[flagNumber]==null) {
				var width = 22;
				var height = 25;
				var icon = new EMS.HoverIcon("/images/ico_poi" + flagNumber + ".png",
						new OpenLayers.Size(width, height),
						new OpenLayers.Pixel(-2 / 3 * width, -1 * height),
						null,
						3);				
				
				var marker = new OpenLayers.Marker(new EMS.LonLat(longitude, latitude), icon);
				marker.id = flagNumber;
				
				marker.events.register("mouseover", marker.element, function() {
					marker.icon.setStickyState(1);
					$j('#listingsPanel .flag_icon_' + flagNumber).addClass('flag_icon_hover');
				});

				marker.events.register("mouseout", marker.element, function() {
					marker.icon.setStickyState(0);
					$j('#listingsPanel .flag_icon_' + flagNumber).removeClass('flag_icon_hover');
				});
				
		    	map.markersLayer.addMarker(marker);
		    	markers[flagNumber] = marker;
		    	return marker;
			} else {
				var marker = markers[flagNumber];
				map.markersLayer.removeMarker(marker);
				map.markersLayer.addMarker(marker);
				return marker;
			}
		};
		
	    this.setViewport = function() {
		    // zoom to fit all listings
			if (map.markersLayer.markers.length > 1) {
		        map.zoomToExtent(map.markersLayer.getDataExtent(), true);
		        map.zoomOut();
		    } else {
		    	map.setCenter(map.markersLayer.markers[0].lonlat, 12);
		    }
	    }
	};

	var addFlagToListing = function(listing) {
		var flagNumber = $j(listing).attr('flagNumber');
		$j(listing).find('.flag_icon')
			.attr('title','Flag no.' + flagNumber + ' - Corresponds to flag on map indicating the location of ' + flagNumber)
			.addClass('flag_icon_' + flagNumber)
			.text(flagNumber)
			.show();
	};
	
	var locations = [];
	
	// Process mappableListings and assign flagNumbers for unique long/lat pairs
	$j('#resultsBody.listView .mappableListing, #bppContent.mappableListing').each(function() {
		var longitude = $j(this).attr('longitude');
		var latitude = $j(this).attr('latitude');

		var locationKey = longitude + ':' + latitude;
		if(locations.indexOf(locationKey) == -1) {
			locations.push(locationKey);
		}

		$j(this).attr('flagNumber', locations.indexOf(locationKey) + 1);
	});
	
	// Only try to display a map if there is at least one mappableListing
	if(locations.length > 0 && $j('#mapDisplay').length > 0) {
		
		$j('#mapDisplay').each(function() {
			var markerStrings = [];
			
			var addtoMarkers = function (element) {
				var marker = [];
	    		marker.push($j(element).attr('latitude'));
	    		marker.push($j(element).attr('longitude'));
	    		marker.push($j(element).attr('flagNumber'));
	    		markerStrings.push(marker.join(','));
	    		addFlagToListing(element);
			};
			
		    if ($j('li.mappableListing').length > 0) {
		    	$j($j('li.mappableListing').get().reverse()).each(function() {
		    		addtoMarkers(this);
		    	});
		    	var width = '386';
		    	var height = '248';
		    	var type = "listing"; // this corresponds with the enum MapType
		    } else {
		    	$j('#bppContent.mappableListing').each(function() {
		    		addtoMarkers(this);
			    });
		    	var width = '288';
		    	var height = '207';
		    	var type = "bpp"; // this corresponds with the enum MapType
		    }
		    
		    var staticMapHtml = '<div class="olMapViewport"><img class="staticMap" alt="No Map" galleryimg="no" />';
		    var interactiveMapHtml = "";
		    var legalImageHtml = "";
            var interactiveMapLinkText = $j('#mapBusinessMap').attr('interactiveMapLinkText');
            var imgSrc = '/app/staticMap?markers=' + markerStrings.join('|') + '&width=' + width + '&height=' + height + '&type=' + type;

		    if ($j.browser.msie && ($j.browser.version <= 6.0)) {
	    		// this will only work in ie6 (due to transparent png hack). For other browsers make into real img tag
		    	legalImageHtml = '<span class="legalImage" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/ui/standard/results/map/legal.png\', sizingMethod=\'scale\');"></span>';
                interactiveMapHtml = '<div class="interactiveMapContainer" style="width:'+width+'px; height: 23px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/ui/standard/results/map/maplink_bg.png\', sizingMethod=\'scale\');"><a href="#" class="interactiveMapLink" rel="nofollow">' + interactiveMapLinkText + '</a></div>';
	    	} else {
	    		legalImageHtml = '<img class="legalImage" src="/ui/standard/results/map/legal.png"/>';
                interactiveMapHtml = '<div class="interactiveMapContainer" style="width:'+width+'px; height: 23px;"><a href="#" class="interactiveMapLink" rel="nofollow">' + interactiveMapLinkText + '</a></div>';
	    	}
	    	
		    staticMapHtml += interactiveMapHtml;
	    	staticMapHtml += legalImageHtml;
	    	staticMapHtml += '<a href="http://www.whereis.com/products/terms-of-use/index.html" class="legalLink">legals</a></div>';
	    	$j('#mapDisplay')[0].innerHTML = staticMapHtml;

            // on failure to generate EMS image, replace with the 'No map is available...'
            $j('img.staticMap').error(function() {
                $j('#mapDisplay').remove();
                $j('#mapBusinessMap').addClass('noMap');
                $j('#mapBusinessMap')[0].innerHTML = type == 'bpp'
                    ? '<img id="noMapDisplay" alt="No map is available for this page" style="display:block;" src="/ui/standard/bpp/no_map.png"/>'
                    : '<img id="noMapDisplay" alt="No map is available for this page" style="display:block;" src="/ui/standard/results/map/no_map.png"/>';
            })
            // set src after registering the error handler
            .attr("src", imgSrc);

            $j('#mapDisplay').show();
		});
	} else {
		$j('#resultsBody.listView #noMapDisplay').show();
	};

	
	// change link to underline and pointer when hovering over map
	$j('.interactiveMapContainer, .olMapViewport img, .olMapViewport span').hover(function() {
		$j(this).css('cursor', 'pointer');
        $j('.interactiveMapLink').css({'text-decoration':'underline'});
    }, function(){
        $j('.interactiveMapLink').css({'text-decoration':'none'});
    });

    // click on static map pulls in assets and draws interactive maps for BPP
    $j("body#bpp .interactiveMapLink, body#bpp .olMapViewport img, body#bpp .olMapViewport span").click(drawInteractiveMap);

    //click on the static map for list view srp load the map view.
    $j("body#srp .interactiveMapLink, body#srp .olMapViewport img, body#srp .olMapViewport span").click(function() {
        $j('#mapView').click();
    });

	$j("#mapDisplayLoading").hide();

	
    // Make contact details same height as the map. 
	var maxheight = 0;
    $j("#bpp div#contactDetails, #bpp div#map").each(function() {
		var height = $j(this).height();
		if (height > maxheight) {
			maxheight = height;
		}
		$j('#listingContentTop').height(maxheight);
		$j(this).css('height','100%');
    });
});


function runOmnitureCodeAtEndOfSearchResultsPage(){
    // omnitureProductsByListingPosition is created via a javascript tag ypol:omnitureRenderListingProductStringsByPosition
    // in the keyword_listingDisplayBns.jsp and keyword_listingDisplayBns.jsp
    var listingProducts="";
    var viewType = $j(".omnitureBns, .omnitureBts").attr("viewType");

    try {
        for(var i=1; i<=60; i++)
        {
            var currentListing = getOmnitureProductForListingPosition(i);

            if(!blank(currentListing))
            {
                listingProducts += currentListing+",";
                if ((i % 15) == 0) {
                    sendOmnitureListingsEvent(listingProducts.substring(0, listingProducts.length-1), viewType);
                    listingProducts = "";
                }
            } else {
                if (!blank(listingProducts)) {
                    sendOmnitureListingsEvent(listingProducts.substring(0, listingProducts.length-1), viewType);
                }
                break;
            }
        }
    } catch(e) {
        // Expected if omnitureProductsByListingPosition is not defined
    }
};

function sendOmnitureListingsEvent(products, viewType){
    var isListView = $j('#mapViewContent').length == 0;
    var eventNumber = isListView ? 'event25' : 'event32';

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent(eventNumber)
            .withLinkType('o')
            .withLinkDescription('Search Listing Results: ' + viewType)
            .withLinkTrackProduct(products)
            .sendLink();
}


// Send to Mobile Form
function omnitureCaptureDisplayOfSendToMobileForm()
{
    var position = extractListingPositionalInformation("listingPositionForCurrentPage");
    var product = getOmnitureProductForListingPosition(position);
    var name = getListingNameForListingPosition(position);

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event39')
            .withLinkType('o')
            .withLinkDescription('Displayed STM Form')
            .withLinkTrackProduct(product)
            .addLinkTrackVar('eVar36', name)
            .addLinkTrackVar('prop26', name)
            .addLinkTrackVar('prop40', 'STM Form')
            .sendLink();
};

// Send to Mobile Success
function omnitureCaptureDisplayOfSendToMobileSuccess()
{
    var position = extractListingPositionalInformation("listingPositionForCurrentPage");
    var product = getOmnitureProductForListingPosition(position);
    var name = getListingNameForListingPosition(position);

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event40')
            .withLinkType('o')
            .withLinkDescription('Displayed STM Success')
            .withLinkTrackProduct(product)
            .addLinkTrackVar('eVar36', name)
            .addLinkTrackVar('prop26', name)
            .addLinkTrackVar('prop40', 'STM Success')
            .sendLink();
};

// Send to Mobile Error
function omnitureCaptureDisplayOfSendToMobileError()
{
    var position = extractListingPositionalInformation("listingPositionForCurrentPage");
    var product = getOmnitureProductForListingPosition(position);
    var name = getListingNameForListingPosition(position);

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event41')
            .withLinkType('o')
            .withLinkDescription('Displayed STM Error')
            .withLinkTrackProduct(product)
            .addLinkTrackVar('eVar36', name)
            .addLinkTrackVar('prop26', name)
            .addLinkTrackVar('prop40', 'STM Error')
            .sendLink();
};

// Send to Friend Success
function omnitureCaptureDisplayOfSendToFriendSuccess()
{
    var position = extractListingPositionalInformation("listingPositionForCurrentPage");
    var product = getOmnitureProductForListingPosition(position);

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event46')
            .withLinkType('o')
            .withLinkDescription('Email Send To Friend Success')
            .withLinkTrackProduct(product)
            .sendLink();
};

// Send to Email Success
function omnitureSendEmailSuccess(){
    var position = extractListingPositionalInformation("listingPositionForCurrentPage");
    var product = getOmnitureProductForListingPosition(position);

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event27')
            .withLinkType('o')
            .withLinkDescription('Email Business Success')
            .withLinkTrackProduct(product)
            .sendLink();
};

function getHeaderSearchClue() {
    var searchClue = $j("#headerAndLocation").text();
    return searchClue.substring(0, searchClue.indexOf(' in '));
}

function getHeaderLocationClue(headerAndLocationText) {
    var resolvedLocation = $j("#headerAndLocation").text();
    return resolvedLocation.substring(resolvedLocation.indexOf(' in ')+4, resolvedLocation.length);
}

function setOmniturePageLoadVariables() {

    // Selectors here will set an OmnitureEvent that is sent via omniture.jsp.

    // There is no need to call an explicit send() unless multiple omniture events
    // are required for a given selector.

    //Home page
    $j('#homeForm').each(function(){
        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Search")
                .withHierarchy("Search")
                .withPageName("Search:yellow.com.au")
                .add("eVar4", "Search");
    });

    // Search Results Page
    $j(".omnitureBns, .omnitureBts").each(function() {

        var isListView = $j('#mapViewContent').length == 0;
        var pageLoadEvent = isListView ? "event12" : "event47";

        var event = new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withEvent(pageLoadEvent)
                .withChannel("Search")
                .add("prop34", "Result")
                .add("eVar43", "Result")
                .add("eVar4", "Search")
                .withAttribute("prop27", "sortBy")
                .withAttribute("eVar37", "sortBy")
                .withAttribute("prop23", "searchState")
                .withAttribute("eVar33", "searchState")
                .withAttribute("prop24", "searchLocation")
                .withAttribute("eVar34", "searchLocation")
                .withAttribute("prop31", "adpoints")
                .withAttribute("eVar41", "adpoints")
                .withAttribute("prop33", "resultsPageNumber")
                .withAttribute("prop37", "totalResults")
                .withAttribute("eVar31", "totalResults");

        // name specific variables
        $j(".omnitureBns").each(function() {
            var pageName = isListView ? "Search:Name:Business Listings" : "Search:Name:Business Listings Map";
            event.withHierarchy("Search|Name")
                    .withPageName(pageName)
                    .add("prop4", "Name")
                    .add("eVar5", "Name");
        });

        // type specific variables
        $j(".omnitureBts").each(function() {
            var pageName = isListView ? "Search:Type:Business Listings" : "Search:Type:Business Listings Map";
            event.withHierarchy("Search|Type")
                    .withPageName(pageName)
                    .add("prop4", "Type")
                    .add("eVar5", "Type")
                    .add("prop30", getHeaderSearchClue())
                    .add("eVar40", getHeaderSearchClue());
        });
    });
    
    $j("#bppContent").delegate("a.yelp-exits-link", "click", function() {
    
        var product = $j('#bppContent').attr('product');
        
        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event30')
                .withLinkTrackProduct(product)
                .withLinkDescription("Yelp Exits")
                .withLinkType('o').sendLink();
    });

    // Business Profile Page
    $j('#bpp').each(function(){

        // Here we send an explicit Page Load event for PaidOnFE Listings
        var paidListingDetails = "";
        $j("li.listingContainer").each(function (){
            if(paidListingDetails !=""){
                paidListingDetails += ",";
            }
            paidListingDetails += $j(this).attr("product");
        });

        if (paidListingDetails != "") {
            new OmnitureEvent(null, s).init()
                    .withLinkTrackEvent('event26')
                    .withLinkDescription("Paid on FE")
                    .withLinkType('o')
                    .withLinkTrackProduct(paidListingDetails)
                    .sendLink();
        }

        var bppContent = $j('#bppContent');
        var product = bppContent.attr('product');
        var name = bppContent.attr('listingName');
        var event = bppContent.attr('events');
        var heading = bppContent.attr('headingName');
        var locality = bppContent.attr('localityandstate');

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Search")
                .withHierarchy("Search")
                .withEvent(event)
                .withPageName("Search:Business Profile Page")
                .withProduct(product)
                .add("eVar4", "Search")
                .add("eVar29", locality)
                .add("eVar36", name)
                .add("eVar42", heading)
                .add("prop26", name)
                .add("prop32", heading);
    });
    
    $j('#article-list').each(function() {
    	var heading = $j('#article-list-heading').text();
    	
        new OmnitureEvent(this, s).init()
        .withCommonPageLoadVariables()
        .withChannel("Article")
        .withHierarchy("Article|Article Index")
        .withPageName("Article:Article Index:Article Index Page")
        .add("eVar4", "Article")
        .add("eVar5", "Article Index")
        .add("eVar66", heading)
        .add("prop4", "Article Index")
        .add("prop44", heading);
    });
    
    // Article Details Page
    $j('body#article-show').each(function() {

		var yellowHeading = $j('div.article-details').attr("yellowHeading");  
		var articleName = $j('#article-heading').text();
		var articleId = $j('div.article-details').attr("articleId");
		
	    new OmnitureEvent(this, s).init()
	            .withCommonPageLoadVariables()
	            .withChannel("Article")
	            .withHierarchy("Article|Article Detail")
	            .withPageName("Article:Article Detail:Article Detail Page")
	            .add("eVar4", "Article")
	            .add("eVar5", "Article Detail")
	            .add("eVar66", yellowHeading)
	            .add("eVar67", articleName)
	            .add("eVar68", articleId)
	            .add("prop4", "Article Detail")
	            .add("prop44", yellowHeading)
	            .add("prop45", articleName)
	            .add("prop46", articleId);
    });

    // Index Page - Localities in State
    $j('title:contains("Towns and suburbs in")').each(function(){

        var titleText = $j('title').text();
        var pageName = $j.trim(titleText.substring(0, titleText.indexOf(" -")));

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Business Name Index")
                .withHierarchy("Business Name Index")
                .withPageName("Business Name Index:"+pageName)
                .add("eVar4", "Business Name Index");
    });

    // Index Page - Heading in Locality
    $j('title:contains("Business Categories")').each(function(){

        var pageName = "Business Categories By State";

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Business Name Index")
                .withHierarchy("Business Name Index")
                .withPageName("Business Name Index:"+pageName)
                .add("eVar4", "Business Name Index");
    });

    // Index Page - Listings in Heading in Locality
    $j('div.omnitureListingInHeadingInLocality').each(function(){

        var pageName = "Browse Category By Business Name";

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Business Name Index")
                .withHierarchy("Business Name Index")
                .withPageName("Business Name Index:"+pageName)
                .add("eVar4", "Business Name Index");
    });

    // Index Page - Partitions in Letter
    $j('div.omniturePartitionsInLetter').each(function(){

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Business Name Index")
                .withHierarchy("Business Name Index")
                .withPageName("Business Name Index:Alphabetical Browse page")
                .add("eVar4", "Business Name Index");
    });

    // Index Page - Listings in Letter Partition
    $j('div.omnitureListingsInLetterPartition').each(function(){

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Business Name Index")
                .withHierarchy("Business Name Index")
                .withPageName("Business Name Index:Alphabetical Business Name page")
                .add("eVar4", "Business Name Index");
    });

    // Page Not Found
    $j('h2:contains("Sorry we couldn\'t find that page.")').each(function(){

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Error")
                .withHierarchy("Error")
                .withPageName("Error:Missing file 404")
                .withPageType("errorPage")
                .add("eVar4", "Error");

        return false;

    });

    // Error Pages
    $j('h2:contains("Sorry there seems to be a problem on our end.")').each(function(){

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel("Error")
                .withHierarchy("Error")
                .withPageName("Error:Server Error 500")
                .add("eVar4", "Error")
                .remove("referrer");

        return false;

    });


    // Zero Results Page Load
    $j(".zeroResults").each(function() {
        var zeroResultsType = $j(this).attr('zeroresultstype');
        var searchType = zeroResultsType == "Zero Results" ? "Name" : "Type";

        var searchClue = $j("#searchFormBusinessClue").attr('value').toLowerCase();
        var searchLocation = $j("#searchFormLocationClue").attr('value').toLowerCase();

        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withHierarchy("Search|"+searchType+"|Business Listings")
                .withEvent("event12")
                .withChannel(searchType)
                .withPageName("Search:" + searchType + ":Business Listings:" + zeroResultsType)
                .add("prop34", "Result")
                .add("eVar43", "Result")
                .add("eVar4", searchType)
                .add("prop4", "Business Listings")
                .add("eVar5", "Business Listings")
                .withAttribute("prop27", "sortBy")
                .withAttribute("eVar37", "sortBy")
                .withAttribute("prop23", "searchState")
                .withAttribute("eVar33", "searchState")
                .withAttribute("prop24", "searchLocation")
                .withAttribute("eVar34", "searchLocation")
                .withAttribute("prop31", "adpoints")
                .withAttribute("eVar41", "adpoints")
                .withAttribute("prop33", "resultsPageNumber")
                .add("prop41", searchClue + "_" + searchLocation)
                .add("prop37", "0")
                .add("eVar31", "0")
    });

    $j(".omnitureRefineLocation").each(function() {
        var searchType = $j(this).attr('searchMode');
        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withHierarchy("Search|"+searchType+"|Location")
                .withChannel(searchType)
                .withPageName("Search:" + searchType + ":Location:Select Location")
                .add("prop4", "Location")
                .add("eVar4", searchType)
                .add("eVar5", "Location")
    });

    $j(".omnitureRefineCategory").each(function() {
        // this code is executed for both 'Type - Zero Results' and 'Type - Disambiguation';
        // we are only interested in disambiguation (since zero results was already handled above)
        var found = false;
        $j(".zeroResults").each(function() {
            found = true;
        });

        if (!found) {
            new OmnitureEvent(this, s).init()
                    .withCommonPageLoadVariables()
                    .withHierarchy("Search|Type|Category")
                    .withChannel("Type")
                    .withPageName("Search:Type:Category:Select Business Type/Select Type 21 C")
                    .add("prop4", "Category")
                    .add("eVar4", "Type")
                    .add("eVar5", "Category")
        }
    });

    // cms pages
    if (cmsPageName) {
        new OmnitureEvent(this, s).init()
                .withCommonPageLoadVariables()
                .withChannel(cmsChannel)
                .withPageName(cmsPageName)
                .add("prop4", cmsProp4 ? cmsProp4 : "")
                .add("prop5", cmsProp5 ? cmsProp5 : "")
                .add("eVar5", cmsProp4 ? cmsProp4 : "")
                .add("eVar15", cmsProp5 ? cmsProp5 : "");
    }
};


/////
// Click and other custom link functions
/////
function getDirectionsLinkClicked(link) {
    var product = $j(link).closest('.omnitureListing').attr('product');

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event9')
            .withLinkDescription('Map Directions')
            .withLinkType('o')
            .withLinkTrackProduct(product)
            .sendLink();
};

function couponLinkClicked(link) {

	var product = $j(link).closest('.omnitureListing').attr('product');
    new OmnitureEvent(this, s).init()
			.withLinkTrackEvent('event16')
			.withLinkType('e')
			.withLinkDescription('Yellow Offer Coupon Clicks')
			.withLinkTrackProduct(product)
			.sendLink();
};

function preferredWebAddressClicked(link) {
    var product = $j(link).closest('.omnitureListing').attr('product');
    new OmnitureEvent(this, s).init()
        .withLinkTrackEvent('event6')
        .withLinkType('e')
        .withLinkDescription('Website click through')
        .withLinkTrackProduct(product)
        .sendLink();

};

function sendEmailBusinessOmnitureEvent(link) {
    var product = $j(link).closest('.omnitureListing').attr('product');
    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event7')
            .withLinkType('o')
            .withLinkDescription('Email Business')
            .withLinkTrackProduct(product)
            .sendLink();

    // allows pop up to work
    return false;
};

function selfServiceOmnitureEvent() {
    var product = $j('.omnitureListing').attr('product');

    new OmnitureEvent(this, s).init()
            .withLinkTrackEvent('event49')
            .withLinkType('e')
            .withLinkDescription('Self Service Link Clicks')
            .withLinkTrackProduct(product)
            .sendLink();
};

function shareResultsOmnitureEvent(eVar57Msg) {
    new OmnitureEvent(this, s).init()
        .withLinkTrackEvent('event44')
        .withLinkDescription('Share Results')
        .withLinkType('o')
        .addLinkTrackVar('eVar57', eVar57Msg)
        .sendLink();
};

$j(document).ready(function() {

    // BPP Coupon link
    $j('a.couponLink').click(function() {
        couponLinkClicked(this);
    });

    // Send Email to Friend
    $j('input#id="btn-sendEmail').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event46')
                .withLinkDescription('Send Email To Friend')
                .withLinkType('o')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Search Submit
    $j('#searchForm').submit(function (e) {
        var searchClue = this.clue.value.toLowerCase();
        var locationClue = this.locationClue.value;

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event29')
                .withLinkType('o')
                .withLinkDescription('Search Form Submit')
                .addLinkTrackVar('prop12', searchClue)
                .addLinkTrackVar('eVar22', searchClue)
                .addLinkTrackVar('prop22', locationClue)
                .addLinkTrackVar('eVar32', locationClue)
                .sendLink();
    });

    // Physical and Target Media Listing Name Click
    $j('a.omnitureListingNameLink').click(function() {
        var listingContainer = $j(this).closest('li.listingContainer');
        var listingPosition = listingContainer.attr('listingPosition');
        var product = listingContainer.attr('product');
        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event11')
                .withLinkDescription('Listing Name Clicks')
                .withLinkType('o')
                .withLinkTrackProduct(product)
                .addLinkTrackVar('eVar47', listingPosition)
                .sendLink();
    });

    // Email Link
    $j('a.emailBusinessLink').click(function() {
        sendEmailBusinessOmnitureEvent(this);
    });

    // Get Directions Link
    $j('a.mapLink').click(function() {
        getDirectionsLinkClicked(this);
    });

    // Send To Facebook Link
    $j('.sendToFacebookLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event44')
                .withLinkDescription('Share to Facebook')
                .withLinkType('e')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Send To Twitter Link
    $j('.sendToTwitterLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event44')
                .withLinkDescription('Share to Twitter')
                .withLinkType('e')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Logo Link
    $j('a.omnitureLogoLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event33')
                .withLinkDescription('Logo Clicks')
                .withLinkType('e')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Menu Log - Order now - Listing Results Page
    $j('ul.menuLogLinks a[title^="Order"]').click(function() {
        new OmnitureEvent(this, s).init()
                .withLinkDescription('Order now')
                .withLinkType('e')
                .sendLink();
    });

    // Menu Log - Order now - Business Profile Page
    $j('#menuLogOrderUrlLink a[title^="Order"]').click(function() {
        new OmnitureEvent(this, s).init()
                .withLinkDescription('Order now with Menulog')
                .withLinkType('e')
                .sendLink();
    });

    // Menu Log - Book a table - Listing Results Page
    $j('ul.menuLogLinks a[title^="Book"]').click(function() {
        new OmnitureEvent(this, s).init()
                .withLinkDescription('Book a table')
                .withLinkType('e')
                .sendLink();
    });

    // Menu Log - Book a table - Business Profile Page
    $j('#menuLogBookingUrlLink a[title^="Book"]').click(function() {
        new OmnitureEvent(this, s).init()
                .withLinkDescription('Book a table with Menulog')
                .withLinkType('e')
                .sendLink();
    });

    // More Info Link
    $j('a.omnitureMoreInfoLink').click(function () {
        var listingContainer = $j(this).closest('li.listingContainer');
        var product = listingContainer.attr('product');
        var listingPosition = listingContainer.attr('listingPosition');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event36')
                .withLinkDescription('More Info Link')
                .withLinkType('o')
                .withLinkTrackProduct(product)
                .addLinkTrackVar('eVar47', listingPosition)
                .sendLink();
    });

    // Photos
    $j('a.omnitureImageGalleryLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event17')
                .withLinkDescription('Image Gallery')
                .withLinkType('o')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Send to Friend Link
    $j('body#bpp .sendToEmailLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event8')
                .withLinkDescription('Send to a friend')
                .withLinkType('o')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Showcase Link
    $j('a.omnitureShowCaseLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        var event = new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event34')
                .withLinkDescription('Links Clicks')
                .withLinkType('d')
                .withLinkTrackProduct(product)
        event.sendLink();
    });

    // Tab Click
    $j('li.omnitureTabLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');
        var tabName = $j(this).text();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event15')
                .withLinkDescription('Tab Clicks')
                .withLinkType('o')
                .withLinkTrackProduct(product)
                .addLinkTrackVar('eVar30', tabName)
                .sendLink();
    });

    // BPP Website Link
    $j('a.webAddressLink').click(function() {
        preferredWebAddressClicked(this);
    });

    // Listing Website Link
    $j('[name=listing_website]').click(function () {
        var product = $j(this).closest('li.listingContainer').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event6')
                .withLinkType('e')
                .withLinkDescription('Website click through')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // Type to Name search
    $j(".bts .lookingForBusinessByNameLink").click(function() {

        var searchClue = getHeaderSearchClue();
        var resolvedLocation = getHeaderLocationClue();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event42')
                .withLinkDescription('Type to Name Search')
                .withLinkType('o')
                .addLinkTrackVar('prop12', searchClue)
                .addLinkTrackVar('eVar22', searchClue)
                .addLinkTrackVar('prop22', resolvedLocation)
                .addLinkTrackVar('eVar32', resolvedLocation)
                .sendLink();
    });

    // Name to Type search
    $j('.bns .lookingForHeadingLink').add('.bns .lookingForAdPointLink').click(function() {

        var searchClue = getHeaderSearchClue();
        var resolvedLocation = getHeaderLocationClue();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event43')
                .withLinkDescription('Name to Type Search')
                .withLinkType('o')
                .addLinkTrackVar('prop12', searchClue)
                .addLinkTrackVar('eVar22', searchClue)
                .addLinkTrackVar('prop22', resolvedLocation)
                .addLinkTrackVar('eVar32', resolvedLocation)
                .sendLink();
    });

    // Type to Type Search Heading
    $j('.bts .lookingForHeadingLink').click(function() {

        var searchClue = getHeaderSearchClue();
        var resolvedLocation = getHeaderLocationClue();

        var heading = $j(this).text();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event28')
                .withLinkDescription('Type to Type Search')
                .withLinkType('o')
                .addLinkTrackVar('eVar44', heading)
                .addLinkTrackVar('prop12', searchClue)
                .addLinkTrackVar('eVar22', searchClue)
                .addLinkTrackVar('prop22', resolvedLocation)
                .addLinkTrackVar('eVar32', resolvedLocation)
                .sendLink();
    });

    // Type to Type Search Adpoint
    $j('.bts .lookingForAdPointLink').click(function() {

        var searchClue = getHeaderSearchClue();
        var resolvedLocation = getHeaderLocationClue();

        var adpoint = $j(this).text();
        var heading = $j(this).closest(".lookingfor-adpointlinks").siblings(".lookingForHeadingLink").text();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event28')
                .withLinkDescription('Type to Type Search')
                .withLinkType('o')
                .addLinkTrackVar('eVar44', heading)
                .addLinkTrackVar('eVar45', adpoint)
                .addLinkTrackVar('prop12', searchClue)
                .addLinkTrackVar('eVar22', searchClue)
                .addLinkTrackVar('prop22', resolvedLocation)
                .addLinkTrackVar('eVar32', resolvedLocation)
                .sendLink();
    });

    // Were You Looking For Link
    $j('#listing_you_could_try').click(function() {
        var suggestedSearch = 'TRY:' + this.innerHTML;

        new OmnitureEvent(this, s).init()
                .withLinkDescription('listing_did_you_mean')
                .withLinkType('o')
                .addLinkTrackVar('prop38', suggestedSearch)
                .addLinkTrackVar('eVar48', suggestedSearch)
                .sendLink();
    });

    $j('#listing_did_you_mean').click(function() {
        var suggestedSearch = 'DYM:' + this.innerHTML;

        new OmnitureEvent(this, s).init()
                .withLinkDescription('listing_did_you_mean')
                .withLinkType('o')
                .addLinkTrackVar('prop38', suggestedSearch)
                .addLinkTrackVar('eVar48', suggestedSearch)
                .sendLink();
    });

    //Map Clicks - these selectors don't exist initially - they are generated from map.js
    $j('.interactiveMapLink, .olMapViewport img, .olMapViewport span').live('click', function() {
        if ($j('li.mappableListing').length > 0) {
            new OmnitureEvent(this, s).init()
                    .withLinkTrackEvent('event23')
                    .withLinkType('o')
                    .withLinkDescription('Interactive Map Clicks')
                    .sendLink();
        }
        else if ($j('#bppContent.mappableListing').length > 0) {
            var product = $j(this).closest('.omnitureListing').attr('product');
            new OmnitureEvent(this, s).init()
                    .withLinkTrackEvent('event23')
                    .withLinkType('o')
                    .withLinkTrackProduct(product)
                    .withLinkDescription('Interactive Map Clicks')
                    .sendLink();
        }
    });

    // People Also Viewed Click link in BPP
    $j('.peopleAlsoViewedHeadingLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');
        var pavHeading = $j(this).text();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event24')
                .withLinkType('o')
                .withLinkDescription('PAV Clicks')
                .withLinkTrackProduct(product)
                .addLinkTrackVar('eVar44', pavHeading)
                .sendLink();
    });

    // Enlarge Print Ad click in BPP
    $j('.clickablePrintAd').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event31')
                .withLinkType('o')
                .withLinkDescription('Print Ad Clicks')
                .withLinkTrackProduct(product)
                .sendLink();
    });

    // deep links
    $j('#navigation .externalLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');
        var vanity = $j("a", this).text();

        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event45')
                .withLinkType('e')
                .withLinkDescription('Deep Link Clicks')
                .withLinkTrackProduct(product)
                .addLinkTrackVar('eVar39', vanity)
                .sendLink();
    });

    // messaging links
    $j('#bppcontent-additional-contacts .messagingContactLink').click(function() {
        var product = $j(this).closest('.omnitureListing').attr('product');
        var vanity = $j(this).attr('vanity');
        new OmnitureEvent(this, s).init()
                .withLinkTrackEvent('event45')
                .withLinkType('e')
                .withLinkDescription('Deep Link Clicks')
                .withLinkTrackProduct(product)
                .addLinkTrackVar('eVar39', vanity)
                .sendLink();
    });

    $j('#promoCategories a.promoCategoryLink').click(function() {
        var href = $j(this).attr('href');
        var categoryAndLocalityPattern = /\/find\/(.*)(\/(.*))?/g;
        var categoryAndLocality = categoryAndLocalityPattern.exec(href)[1];
        var categoryAndLocalityArray = categoryAndLocality.split('/');

        if (categoryAndLocalityArray[1]) {
            var prop43 =  categoryAndLocalityArray[0] + '_' + categoryAndLocalityArray[1];
        }
        else {
            var prop43 =  categoryAndLocalityArray[0] + '_all-states';
        }

        new OmnitureEvent(this, s).init()
                .withLinkType('o')
                .addLinkTrackVar("prop43", prop43)
                .withLinkDescription('Homepage Campaign Clicks')
                .sendLink();
    });


     $j('.yelp-average-review-summary .yelp-reviews-count').click(function(){
        var product = $j(this).closest('.omnitureListing').attr('product');
        captureYelpClickEventForProduct(product);
    });
});

var daysOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

$j(document).ready(function() {
	var todayIndex = new Date().getDay();
	
	$j("#" + daysOfWeek[todayIndex]).parent().addClass("today");
	
});

$j(document).ready(function() {

	// Apply behaviour to the results page
	$j('.drpImageGalleryLink').click(function(event) {
		yellow.reporting.withEventType("viewImageGallery").submit();
		return false;
	});
	
});
$j(document).ready(function() {
    if ($j.browser.msie) {
    	window.onafterprint=function() { yellow.print.onPrintInvoked(); }
    	$j("#printLink").click( function() { print(); });
    } else {
    	$j(document).keydown(function(evt) {
    		if (evt.metaKey && evt.which == 80) {
    			yellow.print.onPrintInvoked();
    		}
    	} );   
    	
        $j("#printLink").click(function() {  window.print(); yellow.print.onPrintInvoked(); });
    }

});
var upTriangle = '\u25B2';
var downTriangle = '\u25BC';

prepareLocationLabel = function() {
	if ($j('#promoCmsContent').attr('stateCode') == 'australia') {
		$j('#promoLocation').append('<span id="promoLocationDesc">choose your location<span id="promoLocationTriangle">' + downTriangle + '</span></span>');
	} else {
		$j('#promoLocation').append('Your location: <span id="promoLocationDesc">' + $j('#promoCmsContent').attr('stateDesc') + '<span id="promoLocationTriangle">' + downTriangle + '</span></span>');
	}	
}

prepareStateOptions = function() {
	$j('#promoCmsContentContainer').data('stateDropDown').suggestions = 
		$j('#promoStateOptions .stateOption').toArray().map( function(stateOptionSpan) { return $j(stateOptionSpan).attr('stateDesc'); } );
}

assignStateDropDownEventHandler = function() {
	dropDown = $j('#promoCmsContentContainer').data('stateDropDown');
	$j('#promoLocation').click( function() {
		dropDown.toggle();
		$j('#promoLocationTriangle').each( function() {
			if ($j(this).text() == downTriangle) {
				$j(this).text(upTriangle);
			} else if ($j(this).text() == upTriangle) {
				$j(this).text(downTriangle);
			}	
		});
		return false;
	});
	
	$j('body').click( function() {
		dropDown.hide();
		$j('#promoLocationTriangle').text(downTriangle);
	});
}

handleHomePromotionResponse = function(data) {
	$j('#promoCmsContentContainer').html(data).fadeIn();
	prepareLocationLabel();
	prepareStateOptions();
	assignStateDropDownEventHandler();
}

$j(document).ready(function() {
	prepareLocationLabel();
	
	$j('#promoLocation').each(function() {
		var dropDown = $j(this).autocomplete({
			width:180,
			onSelect: function(selectedStateDesc, data){ 
				var selectedStateId = $j($j('#promoStateOptions .stateOption').toArray().filter( function(stateOptionSpan) { 
							return $j(stateOptionSpan).attr('stateDesc') == selectedStateDesc; } )).attr('stateCode');
				$j('#promoCmsContent').hide();
				$j('#promoContentLoading').show();
				$j.post('/home/promotion.do', {"stateId" : selectedStateId}, handleHomePromotionResponse);
			}
		});	
		$j('#promoCmsContentContainer').data('stateDropDown', dropDown);
		prepareStateOptions();
		assignStateDropDownEventHandler();
	});
});
$j(document).ready(function() {
    $j("#refineByMenuBar .adpoint").click(function() {
    	yellow.search.resetVisitedPages();
        var code = $j(this).attr("adPointCode");
    	yellow.search.refineAdPoint(code).submit();
    });	
    
    $j(".removeAdPoint").click(function() {
    	yellow.search.resetVisitedPages();
        var code = $j(this).attr("adPointCode");
    	yellow.search.removeAdPoint(code).submit();
    });
});
$j(document).ready(function() {
    $j("#refineByMenuBar .refineByCategory").click(function() {
        yellow.search.resetVisitedPages();
        var code = $j(this).attr("headingCode");
    	yellow.search.refineByHeadingCode(code).submit();
    });	
    
    $j(".removeCategory").click(function() {
        yellow.search.resetVisitedPages();
    	var code = $j(this).attr("headingCode");
    	yellow.search.removeHeadingCode().submit();
    });
});
$j(document).bind('contentLoaded', function(event, scope) {
	var lightbox = $j(scope).find("#reportAnErrorLink").lightbox({
		formLoaded: function() {
			$j('#rae-body form').submit(submitForm);
			
			$j('.contactUsLink').click(function() {
				lightbox.close();
			});
			
		},
		
		formReady: function() {
			$j('#rae-error-type-select').focus();
			$j('.captchaInvalid').each(invalidateCaptcha);
		}
	});
	
	function submitForm() {
		var formScope = this;
		
		var messageField = $j('#rae-comment-input').val();
        if(messageField.length > 999) {
            $j('#rae_messageFieldTooLong').show();
            $j('#rae-comment').addClass('error');
        } else {
            $j('#rae_messageFieldTooLong').hide();
            $j('#rae-comment').removeClass('error');
        }
               
		var errorTypeField = $j('#rae-error-type-select').val();
		if(errorTypeField == "Select") {
			$j('#rae_errorTypeNotSelected').show();
			$j('#rae-error-type').addClass('error');
		} else {
			$j('#rae_errorTypeNotSelected').hide();
			$j('#rae-error-type').removeClass('error');
		}
		
		resetEmailInvalidFields();
		var emailField = $j('#rae-email-input').val();
		if(!emailField.isEmail()) {
			$j('#rae_yourEmailFieldInvalid').show();
			$j('#rae-email').addClass('error');
		} else if (emailField.length > 100) {
            $j('#rae_emailFieldTooLong').show();
            $j('#rae-email').addClass('error');
        } else {
            resetEmailInvalidFields();
			$j('#rae-email').removeClass('error');
		}
		
		resetNameInvalidFields();
		var nameField = $j('#rae-name-input').val();
		if(nameField.isEmpty()) {
			$j('#rae_nameFieldInvalid').show();
			$j('#rae-name').addClass('error');
		} else if (nameField.length > 100) {
		    $j('#rae_nameFieldTooLong').show();
            $j('#rae-name').addClass('error');
		} else {
		    resetNameInvalidFields();
			$j('#rae-name').removeClass('error');
		}
		
		if($j('#rae-captcha-input').val().isEmpty()) {
			$j('#rae_captchaCodeInvalid').show();
			$j('#rae-captcha').addClass('error');
		} else {
			$j('#rae_captchaCodeInvalid').hide();
			$j('#rae-captcha').removeClass('error');
		}

		if (summariseReportErrors()) {
			$j.post($j(formScope).attr('action'), $j(formScope).serialize(), function(data) {
				lightbox.show(data);
			});
		}
		
		return false;
	}
	
	function resetNameInvalidFields() {
	    $j('#rae_nameFieldInvalid').hide();
        $j('#rae_nameFieldTooLong').hide();
	}
	
	function resetEmailInvalidFields() {
	    $j('#rae_yourEmailFieldInvalid').hide();
        $j('#rae_emailFieldTooLong').hide();
    }
    
	
	function summariseReportErrors() {
		if($j('#rae-body form div.error').length>0) {
			$j('#requiredInfo').addClass("error");
			$j('#lightboxErrorList').show();
			lightbox.resize();
			
			$j('#rae-body form div.error input, #rae-body form div.error textarea').eq(0).focus();
			
			return false;
		} else {
			$j('#requiredInfo').removeClass("error");
			$j('#lightboxErrorList').hide();
            $j('#btn-report').attr("disabled", true);
			
            return true;
		}
	}
	
	function invalidateCaptcha() {
		$j('#rae_captchaCodeInvalid').show();
		$j('#rae-captcha').addClass('error');
		summariseReportErrors();
	}
});
$j(document).ready(function() {
	$j("#viewBarContainer .selectable").click(function() {
		var viewMode = $j(this).attr("viewMode");
		if (viewMode == "article") {
			window.location = $j(this).attr("url");
		}
		else {
			yellow.search.set("selectedViewMode", viewMode).set("eventType", "viewModeToggle");
			yellow.search.submit();
		}
	});

    $j("#viewBarContainer .selectable").hover(
            function() {
                $j(this).addClass("highlighttab");
            },
            function() {
                $j(this).removeClass("highlighttab");
            }
    );

    $j("#searchResultListings .listingContainer, #targetMediaListings .listingContainer, #similarListings .listingContainer").hover(
            function() {
                $j(this).find(".hoverTab").show();
            },
            function() {
                $j(this).find(".hoverTab").hide();
            }
    );

    $j("#searchResultListings .listingContainer, #targetMediaListings .listingContainer").each(function() {
        if ($j.browser.msie && $j.browser.version.substr(0, 1) <= 7) {

            var infoContainerHeight = $j(this).find(".listingInfoContainer").outerHeight();
            var logoAndDistanceContainerHeight = $j(this).find(".logoAndDistanceContainer").outerHeight();
            var heightDiff = infoContainerHeight - logoAndDistanceContainerHeight;
            var offsetHeightAdjustment = Math.abs(heightDiff);
            if (heightDiff > 0) {
                $j(this).find(".logoAndDistanceContainer").outerHeight(logoAndDistanceContainerHeight + offsetHeightAdjustment);
            } else {
                $j(this).find(".listingInfoContainer").outerHeight(infoContainerHeight + offsetHeightAdjustment);
            }
        }
    });

    $j("#newImage img").tooltip({
        effect: 'slide',
        position: 'center right',
        relative: true,
        offset: [-17, 2],
        delay: 500,
        predelay: 500
    });

    $j("#newImage .tooltip")
            .click(function(event) {
                event.stopPropagation();
            })
            .mouseenter(
            function(event) {
                $j("#viewBarContainer #viewBar li.selectable .tabText").css("text-decoration", "none");
            }).mouseleave(function(event) {
                $j("#viewBarContainer #viewBar li.selectable .tabText").removeAttr('style');

            });

    $j("#related-articles #more-articles span").click(function() {
        $j("#articleView").click();
    });
});


$j(document).ready(function() {
	
	$j('#home #searchFormBusinessClue').focus();
	
	// business clue auto-complete
	$j('#searchFormBusinessClue').each(function() {
		var businessClue = $j(this).autocomplete({
			serviceUrl: "/suggest/business",
			minChars:2,
			deferRequestBy:200,
			autoSubmit:false,
			paddingTop:50,
			maxHeight:230,
			width:312,
			onSelect: function(value, data){ 
				$j("#searchFormLocationClue").focus();
				$j("#searchFormLocationClue").select();
			},
			fnFormatResult: function(value, data, currentValue) {
				if(data=="name") {
					return value;
				} else {
					return "<strong>" + value + "</strong>";
				}
			}
		});	
		
		// trigger autocomplete on focus
		$j(this).focus(function(e) {
				businessClue.onValueChange();
		});
	});
	
	// show/hide examples on key press
	$j("#home #searchFormBusinessClue").keyup(function(e) {
		if($j("#searchFormBusinessClue").val().trim().length >= 2) {
			$j("#businessExamples").hide();
		} else {
			$j("#businessExamples").show();
		}
	});
	
	// location auto-complete
	$j('#searchFormLocationClue').each(function() {
		var locationClue = $j(this).autocomplete({
			serviceUrl: "/suggest/location",
			minChars:2,
			deferRequestBy:200,
			autoSubmit:false,
			paddingTop:50,
			maxHeight:230,
			width:312,
			onSelect: function(value, data){ 
				$j("#searchFormSubmit").focus();
			},
			fnFormatResult: function(value, data, currentValue) {
				return value;
			}
		});
		// trigger autocomplete on focus
		$j(this).focus(function(e) {
			if (this.value.toLowerCase() != 'all states')  {
				locationClue.onValueChange();
			}
		});
	});

	// show/hide examples on key press
	$j("#home #searchFormLocationClue").keyup(function(e) {
		if($j("#searchFormLocationClue").val().trim().length >= 2) {
			$j("#locationExamples").hide();
		} else {
			$j("#locationExamples").show();
		}
	});

	// Do not submit unless form is valid
	$j("#searchForm").submit(function(event) {
		$j("#searchFormLocationClue").val($j("#searchFormLocationClue").val().trim());
        if ($j("#searchFormBusinessClue").val().isEmpty()) {
	        alert('Help us help you\nWe need more information to complete your search.\n\n- Please enter a Search Term');
	        return false;
        } else {
        	return true;
        }
	});
	
	// select the clue field when a new search is selected
    $j(".newSearch").click(function() {
    	$j("#searchFormBusinessClue").select();
    	return false;
    });
});
$j(document).bind('contentLoaded', function(event, scope) {
	var lightbox = $j(scope).find(".sendToEmailLink").lightbox({
		formLoaded: function() {
			$j('#stf_body form').submit(submitForm);
			
			$j('.contactUsLink').click(function() {
				lightbox.close();
			});
			
		},
		
		formReady: function() {
			$j('#stf-to-input').focus();
			$j('.captchaInvalid').each(invalidateCaptcha);
		}
	});
	
	function submitForm() {
		var formScope = this;
		
		var messageField = $j('#stf-comment textarea').val();
		if(messageField.isEmpty() || messageField.length > 500) {
			$j('#stf_messageFieldEmpty').show();
			$j('#stf-comment').addClass('error');
		} else {
			$j('#stf_messageFieldEmpty').hide();
			$j('#stf-comment').removeClass('error');
		}
		
		
		$j('#stf_friendsEmailFieldInvalid').hide();
		$j('#stf-to').removeClass('error');
		$j.each($j('#stf-to input').val().split(/,[ ]*/), function(index, value) {
			if (!value.isEmail()) {
				$j('#stf_friendsEmailFieldInvalid').show();
				$j('#stf-to').addClass('error');
			}
		});
		
		if(!$j('#stf-email input').val().isEmail()) {
			$j('#stf_yourEmailFieldInvalid').show();
			$j('#stf-email').addClass('error');
		} else {
			$j('#stf_yourEmailFieldInvalid').hide();
			$j('#stf-email').removeClass('error');
		}
		
		if($j('#stf-name input').val().isEmpty()) {
			$j('#stf_nameFieldInvalid').show();
			$j('#stf-name').addClass('error');
		} else {
			$j('#stf_nameFieldInvalid').hide();
			$j('#stf-name').removeClass('error');
		}
		
		if($j('#stf-captcha-input').val().isEmpty()) {
			$j('#stf_captchaCodeInvalid').show();
			$j('#stf-captcha').addClass('error');
		} else {
			$j('#stf_captchaCodeInvalid').hide();
			$j('#stf-captcha').removeClass('error');
		}

		if (summariseErrors()) {
			$j.post($j(formScope).attr('action'), $j(formScope).serialize(), function(data) {
				lightbox.show(data);
			});
		}
		
		return false;
	}
	
	function summariseErrors() {
		if($j('#stf_body form div.error').length>0) {
			$j('#requiredInfo').addClass("error");
			$j('#lightboxErrorList').show();
			lightbox.resize();
			
			$j('#stf_body form div.error input, #stf_body form div.error textarea').eq(0).focus();
			
			return false;
		} else {
			$j('#requiredInfo').removeClass("error");
			$j('#lightboxErrorList').hide();
            $j('#btn-sendEmail').attr("disabled", true);
			
            return true;
		}
	}
	
	function invalidateCaptcha() {
		$j('#stf_captchaCodeInvalid').show();
		$j('#stf-captcha').addClass('error');
		summariseErrors();
	}
});
$j(document).ready(function() {
	
	var lightbox = $j(".sendToMobileListingLink").lightbox({
		formLoaded: function() {
			$j("#stm_form").submit(submitForm);
			
			$j("#stm_tryAgain").click(tryAgain);

			$j("#stm_help_link").click(function (){
				$j("#stm_help_content").slideToggle();
				return false;
			});
			
			$j("#dataConnectionHelpLink").click(function (){
				$j("#stm_data_connection_help_content").slideToggle();
				return false;
			});
			
			$j("#goneWrongHelpLink").click(function (){
				$j("#stm_what_else_help_content").slideToggle();
				return false;
			});
		}, 
		
		formReady: function() {
			if ($j('#stm_mobileNumber').length) {
		       	 $j('#stm_mobileNumber').focus();
		       } else if ($j('#stm_tryAgain').length) {
		           $j('#stm_tryAgain').focus()
		       } else {
		           $j('#stm_close').focus();
		       }
		}
	});
	
	function validate(mobileNumber) {
        var valid = true;
        if (!mobileNumber.match(/^[+\d\sa-zA-Z]+$/)) {
            $j("#stm_validation_msg").removeClass('stm_validation_msg_hide').addClass('stm_validation_msg_show');
            $j('#stm_mobileNumber').addClass('stm_validation_mobile_number').focus();
            valid = false;
        } else {
            $j("#stm_validation_msg").removeClass('stm_validation_msg_show').addClass('stm_validation_msg_hide');
            $j('#stm_mobileNumber').removeClass('stm_validation_mobile_number');
        }
        return valid;
	}
	
	function submitForm() {
		var mobileNumber = $j('#stm_mobileNumber').val();
	    var listingId = $j("#stm_form input[name='listingId']").val();
	    if (validate(mobileNumber)) {
            $j('#btn-send').attr("disabled", true);
            
		    var submitUrl = $j("#stm_form").attr("action") + "&listingId=" + encodeURIComponent(listingId) + 
                "&mobileNumber=" + encodeURIComponent(mobileNumber);
    		$j.get(submitUrl, function(data) {
    			lightbox.show(data);
    		});
    		
            setTimeout(function(){
            	$j('#busy-dialogue').removeClass('hide');
            }, 500);
        }
        return false;
	}
	
	function tryAgain() {
		var url= $j(this).attr("href");
		if($j("#stm_mobileConfirm").length){
			 url += "&mobileNumber=" + encodeURIComponent($j("#stm_mobileConfirm").text());
		}
		$j.get(url, function(data) {
			lightbox.show(data);
		});
		return false;
	}
	
});

$j(document).ready(function() {

	// Apply behaviour to the results page
	$j('.showCaseLink a').click(function(event) {
		var href = $j(this).attr('href');
		yellow.reporting.withEventType("viewShowcase").withContentValue(href).submit();
		return true;
	});
	
});
$j(document).ready(function() {	
	
	$j("#sortByAZ .activeLetter").click(function() {
		yellow.search.setCurrentLetter(this.innerHTML).sortBy('alpha').submit();
	});

});
$j(document).ready(function() {
	// Sort by Detail
    $j("#sortByDetailItem").click(function() {
    	yellow.search.resetCurrentLetterAndVisitedPages().sortBy('mostInfo').submit();
    });
});


// Declare this here so we can stub out GEOCODER in test, but
// can't initalise because EMS doesn't exist yet at this point.
var GEOCODER = null;

$j(document).ready(function() {
	
	////////// helper methods ////////
	var referenceAddressField = null;
	
	var performDistanceSort = function(address) {
        yellow.search.sortBy("distance").rankType($j('[name=travelBy]').val()).userLocation(address).submit();
    };
    
    var displayMatchingAddresses = function(value, isError) {
    	$j('#matchingAddresses').append(value).show();
		$j('#sortByDistanceItem .popUpContainer').trigger('resizePopUp');
		if (isError) {
			$j('#matchingAddresses').addClass('error');
		}
    };
	
    var resetMatchingAddresses = function() {
    	$j('#matchingAddresses').html('').hide();
		$j('#matchingAddresses').removeClass('error');
		$j('#sortByDistanceItem .popUpContainer').trigger('resizePopUp');
    };

    var renderAddressLink = function (address) {

		var streetDetails = (address.streetNumber + ' ' + address.street.fullName).trim().toLowerCase();
		var displayAddress = (streetDetails != "" ? streetDetails + ', ' : "") + address.suburb.toLowerCase() + ', ' + address.state.toUpperCase();
		
  		return $j('<li></li>').append(
			$j('<a href="#">' + displayAddress + '</a>').click(function(event) {
				$j('#referenceAddress').val(displayAddress).cookify();
				performDistanceSort(address);
		    	event.preventDefault();				
			})
		);

    };
    
    var renderPaginationLink = function(response, index) {
    	return $j('<li></li>').append(
				$j('<a href="#">' + index + '</a>').click (function(event) {
					displayResults(response, index);	
					event.preventDefault();				
				})
			);
    };
    
    var renderPaginationPreviousLink = function(response, index) {
    	return $j('<li class="previous"></li>').append(
    			$j('<a id="sortByDistancePrevious" href="#"><img alt="Previous" src="/ui/standard/left.gif" /></a>').click(function(event) {
    				displayResults(response, index);	
    				event.preventDefault();				
    			})
    		);
    };
    
    var renderPaginationNextLink = function(response, index) {
    	return $j('<li class="next"></li>').append(
    			$j('<a id="sortByDistanceNext" href="#"><img alt="Next" src="/ui/standard/right.gif" /></a>').click(function(event) {
    				displayResults(response, index);	
    				event.preventDefault();				
    			})
    		);
    };
    
    var generateAddressList = function(response, pageNumber) {
    	var resultsPerPage = 5;
    	var addressList = $j('<ul></ul>');
		
    	var lowerIndex = (pageNumber - 1) * resultsPerPage;
    	var upperIndex = Math.min(lowerIndex + resultsPerPage, response.results.length);
		for (var i = lowerIndex; i < upperIndex ; i++){
			var address = response.results[i].address;
			addressList.append(renderAddressLink(address));

		}
		return addressList;
    };
    
    var generatePagination = function(response, currentPageNumber) {
    	
    	var pageCount = Math.ceil(response.results.length / 5);
    	if (pageCount > 1) {
	    	var pagination = $j("<div id='matchedAddressPagination' class='pagecount'></div>");
	    	var pageList = $j('<ul></ul>');
	    	
	    	if (currentPageNumber != 1) {
	    		pageList.append(renderPaginationPreviousLink(response, currentPageNumber - 1));
	    	}
	    	
	    	for (var i = 1; i <= pageCount; i++) {
	    		
	    		if (currentPageNumber == i) {
	    			pageList.append('<li class="currentPage">' + i + '</li>');
	    		} else {
	    			pageList.append(renderPaginationLink(response, i));
	    		}
	    	}
	    	
	    	if (currentPageNumber != pageCount) {
				pageList.append(renderPaginationNextLink(response, currentPageNumber + 1));
	    	}
	    	
	    	pagination.append(pageList);
	    	return pagination;
    	}
    };
    
    var displayResults = function(response, pageNumber) {
		var matchingAddressesMessage = '<p>We found ' + response.results.length + ' possible matches for <span>' + $j('#referenceAddress').val() + '</span>:</p>';
		var addressList = generateAddressList(response, pageNumber);
		var pagination = generatePagination(response, pageNumber);
		
		resetMatchingAddresses();
		displayMatchingAddresses(matchingAddressesMessage);
		displayMatchingAddresses(addressList);
		displayMatchingAddresses(pagination);
    }
	
	var geocodeCallback = function(response) {
		if (response.results.length == 0) {
			referenceAddressField.inError();
			displayMatchingAddresses($j('<p>We do not recognise that address.</p><p>Please check the information you entered and try again.</p>'), true);
		} else if (response.results.length == 1) {
			performDistanceSort(response.results[0].address);
		} else {
			referenceAddressField.clearError();
			limitTotalResults(response, 50);
			displayResults(response, 1);
		}

		$j('#sortByDistanceContinue input').removeAttr('disabled');
	};
	
	var limitTotalResults = function(response, maxResults) {
		var resultsToRemove = Math.max(0, response.results.length - maxResults);
		response.results.splice(maxResults, resultsToRemove);
	}
	
	var geocodeReferenceAddress = function() {
    	var query = {
    		'address': {
    			'unstructured': $j('#referenceAddress').val() 
    		}
    	};
    	GEOCODER.findGeocodedAddress(query, geocodeCallback, {});
	};
	
	var isEmptyValidationError = function() {
		displayMatchingAddresses($j('<p>Please enter an address</p>'), true);
	};

	/////////////////////////////////////

	if (typeof(EMS) !== 'undefined' && EMS !== null) {
		EMS.Services.communicationMode = "CrossDomain";
		GEOCODER = new EMS.Services.Geocoder();
		// bind sort by distance elements to cookies
		$j('#referenceAddress').cookieBind();
		$j('[name=travelBy]').cookieBind();
		
		// perform sort by distance
	    $j('#sortByDistanceContinue input').click(function(event) {
	    	resetMatchingAddresses();
	    	yellow.search.resetCurrentLetterAndVisitedPages();
	    	
	    	if (referenceAddressField.validate(isEmptyValidationError)) {
	    		$j(this).attr('disabled', 'disabled'); 
		    	geocodeReferenceAddress();
	    	}
	    	event.preventDefault();
	    });
	    
	    $j('#sortByDistance').submit(function(event) {
	    	$j('#sortByDistanceContinue input').trigger('click');
	    	event.preventDefault();
	    });
	    
        if (document.getElementById('referenceAddress')) {
        	referenceAddressField = $j('#referenceAddress').hintTextField({defaultHintText: 'eg. 123 High St, Preston, VIC'});
		}
	}

});
$j(document).ready(function() {
	// Sort by Relevance
    $j("#sortByRelevanceItem").click(function() {
    	yellow.search.resetCurrentLetterAndVisitedPages().sortBy('closestMatch').submit();
    });	
});


$j(document).ready(function() {
	$j("#thumbnail-photos a").lightbox({
		formLoaded: function() {
		}, 
	
		formReady: function() {
			
		}
	});
});
$j(document).ready(function() {
	$j('.tooltip > .displayText').hover(
		function() {
			var tooltipText = $j(this).siblings('.tooltipText');
			tooltipText
				.css("left", $j(this).position().left + ($j(this).width() + 3) - (tooltipText.width() / 2))
				.css("top", $j(this).position().top + $j(this).height());
		},
		function() {
			$j(this).siblings('.tooltipText')
				.css("left", "")
				.css("top", "");
		}
	);
});
$j(document).ready(function() {
	$j('body#bpp div#twitterFeed').each(function(index, e) {
		var twitterFeedUrl = "/twitter/feed.do?listingId=" + $j(this).attr("listingId");
		
		$j.getJSONWithError(twitterFeedUrl, {"alt": "json"},  handleTwitterFeedResponse, function(req, status, error) {});
	});
});

handleTwitterFeedResponse = function(json) {
	// hide the waiting animation
	$j("#twitterFeed div.contentLoading").hide();
	if (json.text) {
		handleTwitterFeedText(json);
	} else if(json.error) {
		handleTwitterFeedError(json);
	}
	else {
		$j("#twitterFeed_content").html("");
	}
};

handleTwitterFeedText = function(json) {
	var twFeedContent = $j("#twitterFeed_content");
	twFeedContent.hide().html("<div id='twitterFeedText'>" + json.text + "</div>");
	generateLinksInTwitterFeed(json);
	twFeedContent.fadeIn("slow");
	createTwitterTimeStamp(json);
};

handleTwitterFeedError = function(json) {
	if (json.error == "Not found") {
		var twLinkText = $j("#twitterFeed div.linkText");
		twLinkText.hide().html("Unable to display Twitter feed.").addClass("errorText");
		twLinkText.fadeIn("slow");
	}
	else if(json.error == "Timeout") {
		var twFeedContent = $j("#twitterFeed_content");
		twFeedContent.hide().html("<div id=\"twitterFeedText\" class=\"errorText\">Unable to display Twitter feed.</div>");
		twFeedContent.fadeIn("slow");
	}
};

createTwitterTimeStamp = function(json) {
	if (json.created_at) {
		var v = json.created_at.split(' ');
		var createdDate = new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
		$j("#twitterFeed_timestamp").timestamp(createdDate, generateTwitterTimestampUrl(json), 'View this tweet on Twitter');
	}
};

generateTwitterTimestampUrl = function(json) {
	if (json.id_str) {
		return $j("#twitterFeed_timestamp").attr("timestampUrl") + json.id_str;
	}
	
	return "null";
}

generateLinksInTwitterFeed = function(json) {
	if (json.entities && json.entities.urls) {
		
		var urlAndStartIndexPairs = $j.map(json.entities.urls, function(entityUrl, i) { 
			return { 'url' : entityUrl.url, 'startIndex' : entityUrl.indices[0] };
		});
		
		$j('#twitterFeedText').makeLinksFor(urlAndStartIndexPairs, { 'rel' : 'nofollow', 'target' : '_blank' } );
		// makeLinksFor() is executed AFTER the generic $j('#navigation .externalLink') click handler assignment has been completed,
		// so we have to explicitly add click handlers to the links created by makeLinksFor()
		$j('#twitterFeedText a').click(function() {
			var product = $j(this).closest('.omnitureListing').attr('product');

		    new OmnitureEvent(this, s).init()
		    	.withLinkTrackEvent('event45')
		    	.withLinkType('e')
		    	.withLinkDescription('Deep Link Clicks')
		    	.withLinkTrackProduct(product)
		    	.addLinkTrackVar('eVar39', 'Clickable Twitter')
		    	.sendLink();
		});
		
	}
};
(function ($) {

    var features = [
        {
            "id":"yelp-reviews-new-callout",
            "message":"View star ratings and read full reviews to find out what other customers think about this business.",
            "title":"Ratings &amp; reviews help you find the business that is right for you!",
            "helpPageLinkText":"Learn more",
            "helpPageLink":"/pages/help/ratings-and-reviews",
            "offsetX":10,
            "offsetY":-32,
            "clickable":true,
            "buildHtml":function(calloutId){
                this.html =
                    "<div callout-id='" + calloutId + "' class='whats-new-callout'>" +
                        "<div class='whats-new-callout-arrow-left'/>" +
                            "<div class='whats-new-callout-content'>" +
                                "<p class='callout-title'>" + this.title + "</p>" +
                                "<p class='callout-message'>" + this.message + "</p>" +
                                "<div class='whats-new-callout-buttons'>" +
                                    "<a class='callout-help-page-link' href='" + this.helpPageLink + "'>" + this.helpPageLinkText + "</a>" +
                                    "<a class='callout-close-button'></a>" +
                                "</div>" +
                            "</div>" +
                        "</div>";
            }
        },
        {
            "id":"srp-share-results-callout",
            "message":"Share these results with your friends.",
            "offsetX":-349,
            "offsetY":-22,
            "clickable":false,
            "buildHtml":function(calloutId){

                this.html =
                    "<div callout-id='" + calloutId + "' class='whats-new-callout-slim notPrintable'>" +
                        "<div class='whats-new-callout-slim-arrow-right'/>" +
                        "<div class='whats-new-callout-slim-content'>" +
                            "<span class='callout-message'>" + this.message + "</span>" +
                            "<a class='callout-slim-close-button'/></span>" +
                        "</div>" +
                    "</div>";
            }
        }
    ];

    /* hook into the window resize event so we can re-position any new callouts that are currently opened */
    $(window).resize(function () {
        $("div.whats-new-callout:visible, div.whats-new-callout-slim:visible").each(function () {
            var offsetX = Number($j(this.clickedElement).attr('callout-offset-x'));
            var offsetY = Number($j(this.clickedElement).attr('callout-offset-y'));

            $j(this).css("top", ($j(this.clickedElement).height() + $j(this.clickedElement).offset().top + offsetY) + "px");
            $j(this).css("left", ($j(this.clickedElement).width() + $j(this.clickedElement).offset().left + offsetX) + "px");
        });
    });

    $.whatsNew = {

        isIE7:function () {
            return $.browser.msie && parseInt($.browser.version) < 8;
        },

        getNewFeatures:function (options) {
            return features;
        },

        dismissCallout:function (featureid) {
            for (var i = 0; i < features.length; i++) {
                if (features[i].id === featureid) {
                    /* IE 7 and below */
                    if ($.whatsNew.isIE7()) {
                        $.cookies.setOptions({
                            expiresAt:new Date(2026, 1, 1)
                        });
                        $.cookies.set(features[i].id, "true");
                    } else {
                        $.jStorage.set(features[i].id, "true");
                    }
                }
            }
        },

        isNewFeature:function (id) {
            /* IE 7 and below */
            if ($.whatsNew.isIE7()) {
                return $.cookies.get(id) === null;
            } else {
                return $.jStorage.get(id) === null;
            }
        },

        attachCalloutToElement:function (element, feature) {

            var calloutId = "callout-" + feature.id + "-" + new Date().getTime();
            $(element).attr("callout-initiator-id", calloutId);

            feature.buildHtml(calloutId);

            var calloutDiv = $(feature.html).appendTo("body").hide();

            /* calloutDiv is an array, loop through all 'one'element, and set the clickedElement so we can retrieve it if need be in the resize handler */
            calloutDiv.each(function () {
                $j(element).attr('callout-offset-x', feature.offsetX);
                $j(element).attr('callout-offset-y', feature.offsetY);
                this.clickedElement = element;
            });

            /* set the callout position for on page load */
            var top = $j(element).height() + $j(element).offset().top + feature.offsetY;
            var left = $j(element).width() + $j(element).offset().left + feature.offsetX;
            $j(calloutDiv).css("top", top + "px");
            $j(calloutDiv).css("left", left + "px");

            /* close button click handler */
            $j("a.callout-close-button, a.callout-slim-close-button", calloutDiv).click(function () {
                $.whatsNew.dismissCallout(feature.id);
                calloutDiv.hide();
                return false;
            });

            /* help page link click handler */
            $j("a.callout-help-page-link", calloutDiv).click(function () {
                var onClickFeatureid = feature.id;
                $.whatsNew.dismissCallout(onClickFeatureid);
                return true;
            });

            /* click handler for clickable element */
            if (feature.clickable) {
                $(element).bind("click", function () {
                    /* reset the callout position on click */
                    var top = $j(this).height() + $j(this).offset().top + feature.offsetY;
                    var left = $j(this).width() + $j(this).offset().left + feature.offsetX;

                    calloutDiv.css("top", top + "px");
                    calloutDiv.css("left", left + "px");
                    calloutDiv.show();
                    return false;
                });
            }

            if ($.whatsNew.isNewFeature(feature.id)) {
                calloutDiv.show();
            }
        }
    }
})(jQuery);

$j(document).ready(function () {

    /* attach a whats new callout to any elements with a class that matches a new feature id */
    var callouts = $j.whatsNew.getNewFeatures();
    for (var i = 0; i < callouts.length; i++) {
        $j("." + callouts[i].id).each(function () {
            $j.whatsNew.attachCalloutToElement(this, callouts[i]);
        });
    }
});

