window.hzmr = window.hzmr || [];
/************* Start topicNavigation.js for locale en-US **************/
try {function expandStyles(){return $(".filterlistitemHidden").removeClass("filterlistitemHidden"),$(".filterlistExpand").hide(),!1}HZ.navigation.SideBar=new function(){function a(){k.show(),j.addClass("hovered").addClass("expanded")}function b(){t||(q&&clearTimeout(q),q=setTimeout(c,r))}function c(){g(null),j.removeClass("expanded")}function d(b){q&&clearTimeout(q),p&&clearTimeout(p);var c=$(b.target),d=c.attr("menuName"),e=c.attr("topicNamespace");e==HZ.data.Topics.NAMESPACE_NAVIGATION&&(g(d),a()),o=b.pageX}function e(c){var d=$(c.target),e=d.attr("menuName"),f=d.attr("topicNamespace");e&&f!=HZ.data.Topics.NAMESPACE_NAVIGATION?b():f==HZ.data.Topics.NAMESPACE_NAVIGATION&&(a(),c.pageX<o+2&&g(e)),o=c.pageX}function f(a){var b=a.target;if(b&&b.tagName&&"span"==b.tagName.toLowerCase()){var c=$(b).attr("href");c&&(document.location.href=HZ.utils.Config.baseUrl+c)}}function g(a){if(m!=a){var b=$("#topicHomeImage")[0],c=u[a],d=0;void 0!==c?d=420*c:a="topicPaneMoreRooms",m=a,b.style.backgroundPosition="-"+d+"px center",k.children().each(function(){var b=this.id;b==a?$(this).show():$(this).hide()}),l.each(function(){var b=$(this),c=b.attr("menuname");c==a?b.addClass("navigationExpandedItem"):b.removeClass("navigationExpandedItem")})}}function h(a){var b=UIHelper.getBounds(j[0]),c=UIHelper.getBounds(k[0]),d=getEventPosition(a);!UIHelper.isInsideRectangle(d,b)&&!UIHelper.isInsideRectangle(d,c)}var i,j,k,l,m,n=!1,o=0,p=null,q=null,r=300,s=null,t=!1,u={};this.init=function(a){i=$("#topicHomeContainer"),j=$("#topicHomeMenu"),k=$("#topicNavigationSideMenu"),l=$(".topicHomeMenuMain span"),n="popupMode"==i[0].className,j.mouseenter(d).mouseout(h).mousemove(e).click(f);for(var b=0;b<l.length;b++)u[$(l[b]).attr("menuname")]=b;s=a.defaultMainTopic,g("menu_"+s)}},HZ.navigation.Utils=new function(){function a(a){a.stopPropagation();var b=$(a.target).closest(".sidebar"),c=$(b).find(".sidebar-header span"),d=$(b).find(".sidebar-body"),e=Math.floor(d.height()/200*300);c.hasClass("more-icon")?(c.addClass("down-icon").removeClass("more-icon"),d.slideDown(e,function(){b.removeClass("state-collapsed")})):c.hasClass("down-icon")&&(c.addClass("more-icon").removeClass("down-icon"),d.slideUp(e,function(){b.addClass("state-collapsed")}))}this.expandBox=function(a){$("#"+a+" .hidden").removeClass("hidden"),$("#"+a+"More").hide()},this.handleMetroAreaChanged=function(a){var b=document.getElementById("metroAreaSelector"),c=b.options[b.selectedIndex].value,d=a;c=""!==c?"/"+c:"",d.indexOf("/_3_")>0?d=d.replace("/_3_",c):d+=c;var e=null!=pageSearchQuery?"/"+encodeURIComponent(pageSearchQuery):"";document.location=d+e},this.handlePriceFilterChanged=function(a){var b=document.getElementById("fromPrice").value,c=document.getElementById("toPrice").value;return""!=b&&!$.isNumeric(b)||""!=c&&!$.isNumeric(c)?void window.location.reload():""!=b&&""!=c&&(b=parseInt(b,10),c=parseInt(c,10),b>c)?void window.location.reload():(b=Math.max(0,b),""!=c&&(c=Math.max(0,c)),void(document.location=a.replace(/XXXXX/,b).replace(/YYYYY/,c)))},this.initSidebarToggle=function(){$(document).ready(function(){$(".sidebar-header").click(a),$(".sidebar-header .toggle").click(a),$(".sidebar-icon.info-icon").hover(function(){var a=$(this);a.tipBubble({content:a.attr("tooltip-data"),id:"sidebar-tooltip",width:100,offsetX:5,offsetY:16,borderColor:"#ccc",showCloseBtn:!1,position:"absolute",attachTo:"body",fadeDuration:0})},function(){var a=$(this);a.tipBubble("hide")})})}};

window.hzmr.push("topicNavigation:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End topicNavigation.js  **************/
/************* Start hzGtm.js for locale en-US **************/
try {HZ.ns("HZ.utils"),HZ.utils.Gtm=new function(){var a={enabled:!1,visitMonth:null,refId:null},b=null;this.init=function(c){b=$.extend({},a,c)},this.pushData=function(a,c,d){if(b.enabled){var e={};c||(c=a),e.event=a,e.ecomm_pagetype=c,e.visit_month=b.visitMonth,e.m_refid=b.refId?b.refId:"",d&&$.extend(e,d),dataLayer.push(e)}}};

window.hzmr.push("hzGtm:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End hzGtm.js  **************/
/************* Start spaceActions.js for locale en-US **************/
try {// <script>


function showAddToMyGalleryForm (spaceId) {
}

function showPostToForumForm (spaceId, ownedByPro) {
}


HZ.ns("HZ.spaceActions");

/* **************************************************************************
 * Add to Ideabook
 * ************************************************************************** */

HZ.spaceActions.AddToIdeabookDialog = new function() {
	var FORM_SCREEN = 0,
		CONFIRM_SCREEN = 1,
		WELCOME_SCREEN = 2,
        MOBILE_SCREEN = 3,
        TRUSTPILOT_SCREEN = 4,
		LOADING_SCREEN = 5,
        weightedScreens = [],
        uname = null,
		spaceId = null,
		colorPalette = null,
        imageId = null,
		buzzData = null, // data returned from a successful call
		galleries = null,
		galleriesById = null,
		lastGalleryId = null,
		defaultGalleryTitle = null,
		view = null,	// jQuery object
		delegate = null,
		showIdeabookConfirm = true,
		showWelcomeScreen = false,
		showMobileScreen = false,
        hasTrustPilotReview = false,
		commentField, privacyField, postToFbField, galleryChoiceField, newGalleryTitleField, galleryChoiceRadio, addToMyGalleryForm;

	this.init = function(_spaceId) {
		spaceId = _spaceId;
		
	};
	
	this.setColorPalette = function(_colorPalette){
		colorPalette = _colorPalette;
	};

	this.setDelegate = function (_delegate) {
		delegate = _delegate;
	};

    this.setTrustPilotReview = function(_boolean)
    {
        hasTrustPilotReview = _boolean;
    }

	this.setGalleries = function (_galleries) {
		galleries = _galleries;
		galleriesById = {};
		if (galleries.recent && galleries.recent.length > 0)
		{
			for (var i in galleries.recent)
			{
				var gallery = galleries.recent[i];
				galleriesById[gallery.id] = gallery;
			}
		}
		if (galleries.own && galleries.own.length > 0)
		{
			for (var i in galleries.own)
			{
				var gallery = galleries.own[i];
				galleriesById[gallery.id] = gallery;
			}
		}
		if (galleries.shared && galleries.shared.length > 0)
		{
			for (var i in galleries.shared)
			{
				var gallery = galleries.shared[i];
				galleriesById[gallery.id] = gallery;
			}
		}
	};

    this.setImageId = function (_imageId) {
        imageId = _imageId;
    }

	this.getGalleries = function () {
		return galleries;
	}

    this.setUserName = function(name){
        uname = name;
    }

	this.setShowIdeabookConfirm = function(_showIdeabookConfirm) {
		showIdeabookConfirm = _showIdeabookConfirm;
	};

    this.setWelcomeScreen = function(_showWelcomeScreen) {
        showWelcomeScreen = _showWelcomeScreen;
    }

    this.setMobileScreen = function(boolean) {
        showMobileScreen = boolean;
    }

	this.setLastGalleryId = function (_lastGalleryId) {
		lastGalleryId = _lastGalleryId;
	};

	this.getLastGalleryId = function () {
		return lastGalleryId;
	};

	this.setDefaultGalleryTitle = function (_defaultGalleryTitle) {
		defaultGalleryTitle = _defaultGalleryTitle;
	};

	var handleGalleryChanged = function(event) {
		if (event)
		{
			switch (event.target.id) {
			case "gallerySelector":
				addToMyGalleryForm.selectGallery[0].checked=true;
				break;
			case "newGalleryTitle":
				addToMyGalleryForm.selectGallery[1].checked=true;
				$('#gallerySelector option[value="-2"]').prop('selected', true);
				break;
			default:
			}
		}

		if (addToMyGalleryForm && addToMyGalleryForm.selectGallery[0].checked)
		{
			// disable FB UI when adding to a private Ideabook
			if (galleryChoiceField.options.length > 0 && galleryChoiceField.options[galleryChoiceField.selectedIndex])
			{
				var galleryId = galleryChoiceField.options[galleryChoiceField.selectedIndex].value;
				var gallery = galleriesById[galleryId];
				if (gallery && gallery.isPrivate)
				{
					HZ.publish.Manager.setActionEnabled(true);
					$("#addToIdeabookDialog").addClass("disableFbTimelineUI");
					return;
				}
				if(event == null || event.type == 'change'){
					if(galleryId == -2){
						addToMyGalleryForm.selectGallery[1].checked=true;
						$("#newGalleryTitle").focus();
					} else {
						$('#gallerySpaceComments').focus();
					}
				}
			}
		}

		HZ.publish.Manager.setActionEnabled(true);
		$("#addToIdeabookDialog").removeClass("disableFbTimelineUI");
	};

	this.getView = function () {        
		// return a jQuery contents object
		if (!view) {
			view = $("<div id='addToIdeabookDialog'></div>")
				.addClass("dialogFrame")
				.append(
					"<div id='addToIdeabookDialog_"+ LOADING_SCREEN +"' style='display:none;'>"
					+ "<div class='dialogTitle'>" + _hgt("Save to Ideabook") + "</div>"
					+ "<div class='dialogBody'>"
					+ "<div class='hzLoadingDlgThrobber'></div><div class='hzLoadingDlgMessage'>" + _hgt("Loading your ideabooks...") + "</div>"
					+ "</div>"
					+ "</div>"
					+ "</div>"
				)
				.append(
					"<div id='addToIdeabookDialog_"+FORM_SCREEN+"' style='display:none;'>"
					+ "<div class='dialogTitle'>" + _hgt("Save to Ideabook") + "</div>"
					+ "<div class='dialogBody'>"
					+ "<form id='addToMyGalleryForm' name='addToMyGalleryForm' action='javascript:;'>"
					+ "<div class='dialogStatus' id='addToGalleryFormError'></div>"
					+ "<div class='dialogSection chooseGallery form-horizontal'>"
                        + "<div class='dialogImageContainer'><img id='dialogImage' src='" + spaceImageUrl + "'></div>"
						+ "<div id='ideabookNameSettings' class='control-group'>"
						+ "<div id='chooseIdeabookText' class='control-label'><label class='radio' for='existingGalleryRadio'>" + _hgt("Choose an Ideabook:") + "</label><input id='existingGalleryRadio' type='radio' class='radio' name='selectGallery' value='existingGallery' /></div>"
						+ "<div class='controls' id='gallerySelectorControl'><span class='dropdown-wrapper'><select class='dropdown' id='gallerySelector' name='galleryId'></select><i></i></span></div>"
						+ "<div id='newGalleryControl' class='control-group mtm'>"
						+ "<div class='control-label'><label for='newGalleryRadio'><input id='newGalleryRadio' type='radio' class='radio' name='selectGallery' value='newGallery' /></label></div>"
						+ "<div class='controls'><input id='newGalleryTitle' type='text' name='newGalleryTitle' value='' placeholder='" + _hgt("My New Ideabook") + "' maxlength='71' /></div>"
						+ "</div>"
                        + "</div>"
					+ "</div>"
					+ "<div class='dialogSection'>"
						+ "<div class='dialogCaption'><b>" + _hgt("What do you like about this photo?") + "</b></div>"
						+ "<textarea id='gallerySpaceComments' name='gallerySpaceComments'></textarea>"
						+ "<div id='gallerySpaceCommentsPrivacyDiv'><label class='checkbox' for='gallerySpaceCommentsPrivacy'><input id='gallerySpaceCommentsPrivacy' name='gallerySpaceCommentsPrivacy' type='checkbox' />" + _hgt("Make Comment Private") + "</label></div>"
					+ "</div>"
					+ "<div class='dialogSection' id='postToFacebookDiv'>"
						+ "<label class='checkbox' for='postToFacebook'><input id='postToFacebook' name='postToFacebook' type='checkbox' /><img src='"+HZ.utils.Config.emptyGifData+"' /><b>" + _hgt("Add to Timeline") + "</b></br><span class='tiny-text'>" + _hgt("Share this photo with your friends on Facebook") + "</span></label>"
					+ "</div>"
					+ "</form>"
					+ "<div class='dialogControls'></div>"
					+ "</div></div>"
				)
				.append(
					"<div id='addToIdeabookDialog_"+CONFIRM_SCREEN+"' style='display:none;'>"
					+ "<div class='dialogTitle'>" + _hgt("Photo Added") + "</div><div class='dialogBody'>"
					//+ "<div class='dialogCaption'>This photo has been added to your ideabook</div>"
					+ "<div class='addToIdeabookInfo'>"
					+	"<div id='confirmImage' class='addToIdeabookImage'></div>"
					+	"<div id='ideabookCompletedMsg' class='addToIdeabookCompletedMsg'>"
					+	"</div>"
					+	"<div style='clear: both;'></div>"
					+ "</div>"
					+ "<a id='addToIdeabookCTAMsg' class='colorLink CTAMsg' href='http://www.houzz.com/professionals#' target='_blank'>" + _hgt("Ready to Renovate?  Find a local Pro") + " <span class='more-icon'></span></a>"
					+ "<div id='addToIdeabookConfirmMsg'></div>"
					+ "<div class='dialogControls'></div>"
					+ "</div></div>"
				)
                .append(
                    "<div id='addToIdeabookDialog_"+TRUSTPILOT_SCREEN+"' style='display:none;'>"
                        + "<div class='dialogTitle'>" + _hgt("Photo Added") + "</div><div class='dialogBody'>"
                        //+ "<div class='dialogCaption'>This photo has been added to your ideabook</div>"
                        + "<div class='addToIdeabookInfo'>"
                        +	"<div id='trustPilotConfirmImage' class='addToIdeabookImage'></div>"
                        +	"<div id='trustPilotIdeabookCompletedMsg' class='addToIdeabookCompletedMsg'>"
                        +	"</div>"
                        +	"<div style='clear: both;'></div>"
                        + "</div>"
                        + "<a id='trustPilotCTAMsg' class='colorLink CTAMsg' href='javascript:;' target='_blank'>" + _hgt("Love Houzz? Write a review about us") + " <span class='more-icon'></span></a>"
                        + "<div class='dialogControls'>"
                        + "</div>"
                        + "</div></div>"
                )
                .append(
                    "<div id='addToIdeabookDialog_"+WELCOME_SCREEN+"' style='display:none;'>"
                    + "<div class='dialogTitle'>" + _hgt("Welcome to Houzz!") + "</div>"
                    + "<div class='dialogBody'>"
                            + "<div id='dialogWelcomeMsg'>" + _hgt("Remodel your dream home from start to finish:") + "</div>"
                            + "<div id='welcomeImagesContainer'>"
                                + "<div class='welcome-image'><a href='" + HZ.utils.Links.getPageUrl(HZ.utils.Config.spaceCommand) + "'><span id='welcomePhotos'></span><p>" + _hgt("Browse Photos") + "</p></a></div>"
                                + "<div class='welcome-image'><a href='" + HZ.utils.Config.baseBrowseProductsLink + "'> <span id='welcomeProducts'></span><p>" + _hgt("Find Products") + "</p></a></div>"
                                + "<div class='welcome-image'><a href='" + HZ.utils.Config.baseBrowseProfessionalsLink + "'><span id='welcomePros'></span><p>" + _hgt("Connect with Pros") + "</p></a></div>"
                            + "</div>"
                        + "<div class='dialogControls'></div>"
                    + "</div>"
                    + "</div>"
                )
                .append(
                    "<div id='addToIdeabookDialog_"+MOBILE_SCREEN+"' style='display:none;'>"
                        + "<div class='dialogTitle'>" + _hgt("Photo Added") + "</div>"
                        + "<div class='dialogBody'>"
                            + "<div id='recommendationComplete' class='dialogSection'>"
                                + "<div class='dialogImageContainer'><img id='recommendationsImage' src='" + spaceImageUrl + "'></div>"
                                + "<div id='recommendationCompleteText'>" +
                                	+ "<div id='mainRecoText'>" + _hgt("Congratulations!") + "</div>"
                                		+ _hgt("You've saved 5 photos. You will now <br>have <t1>personalized recommendations.</t1>",{t1:{'tag':'a', 'attr':{'href': HZ.utils.Config.baseRecommendationsLink + uname, 'class':'colorLink'}}})
                                		+ "<div id='dialogProgressBar'</div>"
                                	+ "</div>"
                            + "</div>"
                        + "</div>"
                        + "<div class='dialogControls'></div>"
                        + "</div>"
                );

			$("body").append(view);

			var cancelButton = HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("Cancel"), "", $.proxy(cancel,this));
			var addToIdeabookButton = HZ.ui.InputButtonUtils.createPrimaryInputButton(_hgt("Save to Ideabook"), "", $.proxy(addToIdeabook,this));
			$("#addToIdeabookDialog_"+FORM_SCREEN+" .dialogControls", view)
				.append (HZ.ui.AjaxThrobber.getThrobber())
				.append (cancelButton)
				.append (addToIdeabookButton);

            // CONFIRM SCREEN BUTTONS
			var emailButton = HZ.ui.InputButtonUtils.createPrimaryInputButton( _hgt("Email{contextEmailVerb}",{'contextEmailVerb':''}) ,"hzEmailSpace",sendSpaceEmail),
                finishedButton = HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("Done"), "", $.proxy(cancel,this));
            $("#addToIdeabookDialog_"+CONFIRM_SCREEN+" .dialogControls", view)
                .append(finishedButton)
                .append (emailButton);

            // WELCOME SCREEN BUTTONS
            // Add continue browsing button for welcome to houzz tour dialog
            var continueBrowsingButton = HZ.ui.InputButtonUtils.createPrimaryInputButton( _hgt("Continue Browsing"), "", $.proxy(cancel,this));
            $("#addToIdeabookDialog_"+WELCOME_SCREEN+" .dialogControls", view)
                .append (continueBrowsingButton);

            // TRUST PILOT SCREEN BUTTONS
            var doneButton = HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("No Thanks"), "", $.proxy(cancel,this)),
                reviewButton = $("<a id='trustPilotReview' class='hzBtn primary' href='javascript:;' target='_blank'>" + _hgt("Review Houzz") + "</a>");
            $("#addToIdeabookDialog_"+TRUSTPILOT_SCREEN+" .dialogControls", view)
                .append (doneButton)
                .append(reviewButton);

            var mobileDoneButton = HZ.ui.InputButtonUtils.createPrimaryInputButton( _hgt("Done"), "", $.proxy(cancel,this));
            $("#addToIdeabookDialog_"+MOBILE_SCREEN+" .dialogControls", view)
                .append (mobileDoneButton);

			$("#postToFacebookDiv").mouseenter(function() {
				$("#postToFacebookToolTip").removeClass("hideToolTip");
			});

			commentField = $("#gallerySpaceComments")[0];
			privacyField = $("#gallerySpaceCommentsPrivacy")[0];
			galleryChoiceField = $("#gallerySelector")[0];
			galleryChoiceRadio = document.getElementsByName("selectGallery");
			newGalleryTitleField = $("#newGalleryTitle")[0];
			// set private reference to form that is used in handleGalleryChanged
			addToMyGalleryForm = document.forms.addToMyGalleryForm;

			$("#gallerySelector").change(handleGalleryChanged);
			$("#gallerySelector").focus(handleGalleryChanged);
			$("#newGalleryTitle").focus(handleGalleryChanged);
			$("#existingGalleryRadio").click(handleGalleryChanged);
			$("#newGalleryRadio").click(handleGalleryChanged);

		}
        // if we are showing the dialog post sign up, then hide dropdown and add class to ideabook name to allow styling
        if (showWelcomeScreen){
            // Hide select
            $("#gallerySelectorContorl").hide();
            // change title from "Choose an Ideabook" to "Create New Ideabook"
            $("label[for='existingGalleryRadio']").innerHTML = _hgt("Create New Ideabook") + ":";
            // add extra class to new Gallery textbox
            $("#newGalleryControl").addClass("extra-bottom-margin");
        }
        // set preview image for first step of add to ideabook dialog
        if (spaceId){
            var spaceImageUrl = HZ.utils.Links.getSpaceImageUrl(spaceId, 90, 90);
        }
        else {
            var spaceImageUrl = HZ.utils.Links.getImageUrl(imageId, 90, 90);

        }
        // add spaceImgUrl to all dialogs that need it
        var dialogImage = view.find("#dialogImage");
        if (dialogImage){
			if(colorPalette){
				//add disclaimer!!!				
				var disclaimer = $("<div class='behrDisclaimer'><i>"+_hgt("The colors displayed on-screen may not match BEHR color standards")+"</i></div>");
				view.find(".dialogSection.chooseGallery").prepend(disclaimer);
				var paletteImgUrl = HZ.utils.Config.baseUrl + '/' + 'generateColorPaletteImage' + HZ.viewSpace.colorPicker.generatePaletteImageUrl() + '/m=1';
				dialogImage.attr('src', paletteImgUrl);
			} else {
				view.find('.behrDisclaimer').remove();
				dialogImage.attr('src', spaceImageUrl);
			}            
        }		
        var recommendationsImage = view.find("#recommendationsImage");
        if (recommendationsImage){
            recommendationsImage.attr('src', spaceImageUrl);
        }
		return view;
	};

	this.viewLoaded = function () {
		// reset the form:
		showError("");
		commentField.value = "";
		privacyField.checked = false;
		HZ.ui.AjaxThrobber.setInCall(false);
		if (!galleries) {
			showScreen(LOADING_SCREEN);
			var self = this;
			HZ.ajaz.Services.getMyGalleries(function (response) {
				if (response.galleries) {
					self.setGalleries(response.galleries);
					self.updateGalleriesList();
					// show the first screen:
					showScreen(FORM_SCREEN);
					commentField.focus();
				}
			});
		}
		else {
			this.updateGalleriesList();
			showScreen(FORM_SCREEN);
			commentField.focus();
		}
		HZ.publish.Manager.initAction("fb_publish_addtoideabook",
            function(val) {
		        var postToFbField = $("#postToFacebook")[0];
		        if (postToFbField)
			        postToFbField.checked = (val == 1 || val == 2);
            },
            function() {
            	var postToFbField = $("#postToFacebook")[0];
                return postToFbField ? (postToFbField.checked ? 1 : 0) : null;
            }
        );

		if (HZ.publish.Manager.isUiShown()) {
			$("#addToIdeabookDialog").removeClass("fbTimelineDisabled");
		} else {
			$("#addToIdeabookDialog").addClass("fbTimelineDisabled");
		}

		if (HZ.publish.Manager.isPromoShown()) {
			$("#addToIdeabookDialog").removeClass("hideFbPromo");
		    $("#postToFacebookToolTip").removeClass("hideToolTip");
		}
		else {
			$("#addToIdeabookDialog").addClass("hideFbPromo");
			$("#postToFacebookToolTip").addClass("hideToolTip");

			$("#postToFacebookDiv").mouseleave(function() {
				$("#postToFacebookToolTip").addClass("hideToolTip");
			});
		}
	};

	this.updateGalleriesList = function () {
		var featured, gallery;

		// populate the Questions Topic list:
		$(galleryChoiceField).empty();

		if (galleries.recent.length > 0){
			HZ.ui.Utils.addOptionGroupToSelect (galleryChoiceField, _hgt("Recently Used:"), -1, 'recentIdeabooks');
		}

		for (var i=0; i<galleries.recent.length; i++) {
			gallery = galleries.recent[i];
			featured = gallery.featured?" (Featured)":"";
			HZ.ui.Utils.addOptionToGroupSelect (galleryChoiceField, gallery.title + featured, gallery.id, gallery.id == lastGalleryId, 'recentIdeabooks');
		}

		//if (galleries.recent.length > 0)
			HZ.ui.Utils.addOptionGroupToSelect (galleryChoiceField, _hgt("Your Ideabooks:"), -1, 'yourIdeabooks');

		for (var i=0; i<galleries.own.length; i++) {
			gallery = galleries.own[i];
			featured = gallery.featured ? " (" + _hgt("Featured") + ")" : "";
			HZ.ui.Utils.addOptionToGroupSelect (galleryChoiceField, gallery.title + featured, gallery.id, gallery.id == lastGalleryId, 'yourIdeabooks');
		}

		if (galleries.shared.length > 0){
			HZ.ui.Utils.addOptionGroupToSelect (galleryChoiceField, _hgt("Shared Ideabooks:"), -1, 'sharedIdeabooks');
		}

		for (var i=0; i<galleries.shared.length; i++) {
			gallery = galleries.shared[i];
			HZ.ui.Utils.addOptionToGroupSelect (galleryChoiceField, gallery.title + " (" + _hgt("Shared") + ")" , gallery.id, gallery.id == lastGalleryId, 'sharedIdeabooks');
		}

		HZ.ui.Utils.addOptionToGroupSelect (galleryChoiceField, _hgt("Create New Ideabook"), -2, false, "");

		if (galleries.own.length || galleries.shared.length) {
			galleryChoiceRadio[0].checked = true;
			newGalleryTitleField.value = "";
		} else {
			galleryChoiceRadio[1].checked = true;
			newGalleryTitleField.value = defaultGalleryTitle;
		}

		handleGalleryChanged(null);
	}

	this.viewUnloaded = function () {};

	function showScreen(screenId) {
		var divId = "addToIdeabookDialog_" + screenId;
		view.children().each(
			function(i) {
				this.style.display = (this.id == divId)?"block":"none";
			}
		)
		delegate.center();
	}

	function addToIdeabook() {
		if (HZ.ui.AjaxThrobber.isInCall())
			return;

		// validation:
		showError("");
		if ((document.forms.addToMyGalleryForm.selectGallery[1].checked && UIHelper.trim(newGalleryTitleField.value) == "") ||
				(document.forms.addToMyGalleryForm.selectGallery[0].checked && galleryChoiceField.selectedIndex < 0))
			return showError (_hgt("Please enter a title for a new ideabook"));
		if (document.forms.addToMyGalleryForm.selectGallery[0].checked && galleryChoiceField.options[galleryChoiceField.selectedIndex].value < 0)
			return showError (_hgt("Please select an ideabook"));

		HZ.publish.Manager.processAction($.proxy(processAddToIdeabook, this), true);
	}

	function processAddToIdeabook() {
		var galleryId = galleryChoiceField.options[galleryChoiceField.selectedIndex].value;
		var newGalleryName = newGalleryTitleField.value;
		var privacy = privacyField.checked?1:3;
		var comment = commentField.value;		
		if(colorPalette !== null){
			if(newGalleryName)
				galleryId = "NewIdeabook";
			HZ.ajaz.Services.saveColorPalette(spaceId, colorPalette, galleryId, comment, privacy, newGalleryName, $.proxy(addToIdeabookCallback, this));
			//colorPalette = null;
			return;
		}
		HZ.ui.AjaxThrobber.setInCall(true);
		if (document.forms.addToMyGalleryForm.selectGallery[1].checked) {
			HZ.ajaz.Services.addToGallery(spaceId, newGalleryName, null, privacy, comment, $.proxy(addToIdeabookCallback, this));
		} else {
			HZ.ajaz.Services.addToGallery(spaceId, null, galleryId, privacy, comment, $.proxy(addToIdeabookCallback, this));
		}
	}

	function addToIdeabookCallback(data) {
		HZ.ui.AjaxThrobber.setInCall(false);
		if (data.success == "true") {
			buzzData = data;
			this.setLastGalleryId(data.galleryId);
			if (data.isNewGallery == "true") {
				galleries.own.unshift({id:data.galleryId, title:data.galleryTitle});
				this.updateGalleriesList();
			}

			_gaq.push(['_trackEvent', 'AddToIdeabookDialog', 'added', (HZ.publish.Manager.isPublishExpected() ? "timeline" : "no_timeline")]);

			var userFbOptIn = HZ.publish.Manager.isPrefChanged() && HZ.publish.Manager.isPublishExpected();
            if (showWelcomeScreen)
            {
                showScreen(WELCOME_SCREEN);
                // after welcome screen has been shown once, set it to false so it does not show up on further photo adds to ideabook
                this.setWelcomeScreen(false);
            }
			else if (showIdeabookConfirm)
            {
                // if weightedScreens array does not exist init it here
                if(weightedScreens.length <= 0)
                {
                    initWeightedScreens();
                }
			    updateConfirmScreen(data, userFbOptIn);
            }
			else
				cancel(); // done; just close this dialog
		} else {
			var link="";
			if(data.galleryId){
				link = "<br/><a class='boldLink colorLink icon-wrap' style='position:relative;top:5px;' href='http://www.houzz.com/ideabooks/"+data.galleryId+"/thumbs'>" + _hgt("Go to your ideabook") +" <span class='more-icon'></span></a>"
			}
			showError(data.error+link);
		}
	}

    function initWeightedScreens()
    {
        // weights for the post ideabook add confirm screens array (should add upto 100)
        // if user has already reviewed Houzz on trust pilot, then weights for trustpilot_screen should be 0
        var weights = (hasTrustPilotReview || HZ.data.CurrentSessionUser.hasOwnProperty("trustPilotImps")) ? [100, 0, 0] : [99, 0, 1],
            screens = [CONFIRM_SCREEN, MOBILE_SCREEN, TRUSTPILOT_SCREEN],
            truth = hasTrustPilotReview || HZ.data.CurrentSessionUser.hasOwnProperty("trustPilotImps");
        // reset weighted screens
        weightedScreens.length = 0;
        // populate weighted screens
        for(var i = 0, j = weights.length; i < j; i++)
        {
            for(var k = 0; k < weights[i]; k++)
            {
                weightedScreens.push(screens[i]);
            }
        }
    }
    // weighted random number selection for choosing post ideabook add screen
    function chooseConfirmScreenType()
    {
        var randomNum = Math.floor(Math.random()*100);
        return weightedScreens[randomNum];
    }

	function updateConfirmScreen(data, userFbOptIn) {
		var galleryUrl = HZ.utils.Links.getGalleryLink(data.galleryId),
            screenType = chooseConfirmScreenType(),
            photoAddedToIdeabookMsg,
            addToIdeabookImage = $("#confirmImage"),
            trustPilotIdeabookImage = $("#trustPilotConfirmImage"),
            addToIdeabookCompletedMsg = $("#ideabookCompletedMsg"),
            trustPilotIdeabookCompletedMsg = $("#trustPilotIdeabookCompletedMsg"),
            addToIdeabookCTAMsg = $("#addToIdeabookCTAMsg"),
            trustPilotCTAMsg = $("#trustPilotCTAMsg"),
            addToIdeabookConfirmMsg = $("#addToIdeabookConfirmMsg");
        switch(screenType)
        {
            case MOBILE_SCREEN:
            case CONFIRM_SCREEN:
                if(colorPalette){
                    var paletteImgUrl = HZ.utils.Config.baseUrl + '/' + 'generateColorPaletteImage' + HZ.viewSpace.colorPicker.generatePaletteImageUrl() + '/m=1';
                    addToIdeabookImage
                        .empty()
                        .append("<img width=160 height=160 src='"+paletteImgUrl+"'/>");                    
                } else {
                    addToIdeabookImage
                        .empty()
                        .append("<img src='"+data.imageUrl+"'/>");
                }
                if (data.galleryTitle) {					
					if(colorPalette)
						photoAddedToIdeabookMsg = _hgt('This palette has been added to:') +'<br/>' +
							'<a class="colorLink" id="addToIdeabookGalleryLink" href="">'+ data.galleryTitle + '</a><br/></br/>';
					else
						photoAddedToIdeabookMsg = _hgt('This photo has been added to:') +'<br/>' +
							'<a class="colorLink" id="addToIdeabookGalleryLink" href="">'+ data.galleryTitle + '</a><br/></br/>';
                }
                else {
					if(colorPalette)
						photoAddedToIdeabookMsg = _hgt('This palette has been added to <t1>your ideabook</t1>.',{t1:{'tag':'a', 'attr':{ 'href':'', 'class':'colorLink', 'id':"addToIdeabookGalleryLink"}}}) + '<br/><br/>';
					else
						photoAddedToIdeabookMsg = _hgt('This photo has been added to <t1>your ideabook</t1>.',{t1:{'tag':'a', 'attr':{ 'href':'', 'class':'colorLink', 'id':"addToIdeabookGalleryLink"}}}) + '<br/><br/>';
                }
                addToIdeabookCompletedMsg
                    .empty()
                    .append (photoAddedToIdeabookMsg)
                    .append (_hgt("Like this photo on Facebook!") + "<br>"
                        + "<iframe src='http://www.facebook.com/plugins/like.php?href="+encodeURIComponent(data.spaceUrl)+"&layout=button_count&show_faces=false&width=80&height=21&action=like&font=arial&colorscheme=light&ref=addibk' "
                        + "scrolling='no' frameborder='0' allowTransparency='true' id='addToIdeabookFacebookFrame'></iframe>"
                    );
                addToIdeabookConfirmMsg.empty();
                if (userFbOptIn)
                {
                    addToIdeabookConfirmMsg
                        .append ("<div>" + _hgt("Photos saved to your public ideabooks will now be shared to your Facebook timeline. <br /><br /><t1>You can edit this setting at any time.</t1>", {t1:{'tag':'a', 'attr':{ 'href':'https://www.houzz.com/editProfile', 'class': 'colorLink'}}}) + "</div>");
                }
                if (data.isProduct === true) {
                    addToIdeabookCTAMsg.hide();
                    $("#hzEmailSpace").val( _hgt("Email this Product") );
                } else {
                    HZ.utils.Logger.sendEventLog('atici');
                    addToIdeabookCTAMsg
                        .unbind("mousedown")
                        .bind("mousedown", function(){HZ.utils.Logger.sendEventLog('aticfp') })
                        .show();
                    $("#hzEmailSpace").val( _hgt("Email this Photo") );
                }
                $("#addToIdeabookGalleryLink")
                    .attr("href", galleryUrl);
                showScreen(screenType);
				colorPalette = null;
                break;
            case TRUSTPILOT_SCREEN:
                HZ.ui.AjaxThrobber.setInCall(true);
                if(colorPalette){
                    var paletteImgUrl = HZ.utils.Config.baseUrl + '/' + 'generateColorPaletteImage' + HZ.viewSpace.colorPicker.generatePaletteImageUrl() + '/m=1';
                    trustPilotIdeabookImage
                        .empty()
                        .append("<img width=160 height=160 src='"+paletteImgUrl+"'/>");                    
                } else {
                    trustPilotIdeabookImage
                        .empty()
                        .append("<img src='"+data.imageUrl+"'/>");
                }
				if (data.galleryTitle) {					
					if(colorPalette)
						photoAddedToIdeabookMsg = _hgt('This palette has been added to:') +'<br/>' +
							'<a class="colorLink" id="addToIdeabookGalleryLink" href="">'+ data.galleryTitle + '</a><br/></br/>';
					else
						photoAddedToIdeabookMsg = _hgt('This photo has been added to:') +'<br/>' +
							'<a class="colorLink" id="addToIdeabookGalleryLink" href="">'+ data.galleryTitle + '</a><br/></br/>';
                }
                else {
					if(colorPalette)
						photoAddedToIdeabookMsg = _hgt('This palette has been added to <t1>your ideabook</t1>.',{t1:{'tag':'a', 'attr':{ 'href':'', 'class':'colorLink', 'id':"addToIdeabookGalleryLink"}}}) + '<br/><br/>';
					else
						photoAddedToIdeabookMsg = _hgt('This photo has been added to <t1>your ideabook</t1>.',{t1:{'tag':'a', 'attr':{ 'href':'', 'class':'colorLink', 'id':"addToIdeabookGalleryLink"}}}) + '<br/><br/>';
                }                
                trustPilotIdeabookCompletedMsg
                    .empty()
                    .append (photoAddedToIdeabookMsg);
                HZ.utils.Logger.sendEventLog('atictp');
                // fetch trustPilot link via ajax call and add it to banner at bottom and button
                // FIXME: [Abhas] - should we show this outside US
                HZ.ajaz.Services.getTrustPilotUrl(HZ.TrustPilot.Settings.getTrustPilotUrl, function(response){
                    if(response.hasOwnProperty("trustPilotUrl"))
                    {
                        // record that we have showed user the trsut pilot banner during this session and also call weights array again to reset screen weights
                        HZ.data.CurrentSessionUser.trustPilotImps = 1;
                        initWeightedScreens();
                        // trust pilot review banner link
                        trustPilotCTAMsg.attr("href", response["trustPilotUrl"]);
                        // click event for "Review Houzz" button
                        $("#trustPilotReview").click(function(){
                            $(this).attr("href", response["trustPilotUrl"]);
                            // set user preference for trust pilot reviews
                            HZ.ajaz.Services.setTrustPilotUserPreference(HZ.TrustPilot.Settings.setTrustPilotUserPreference, function(response){});
                            HZ.utils.Logger.sendEventLog('atitb');

                            cancel();
                        });
                    }
                    trustPilotCTAMsg
                        .unbind("mousedown")
                        .bind("mousedown", function(){
                            HZ.utils.Logger.sendEventLog('atitm');
                            // set user preference for trust pilot reviews
                            HZ.ajaz.Services.setTrustPilotUserPreference(HZ.TrustPilot.Settings.setTrustPilotUserPreference, function(response){});
                        })
                        .show();
                    $("#addToIdeabookGalleryLink")
                        .attr("href", galleryUrl);
                    HZ.ui.AjaxThrobber.setInCall(false);
                    showScreen(TRUSTPILOT_SCREEN);
                }, {type:"GET"});
				colorPalette = null;
                break;
        }
	}

	function sendSpaceEmail() {
		if (buzzData && buzzData.spaceId && buzzData.spaceTitle) {
			sendEmail(buzzData.spaceId, buzzData.spaceTitle, (buzzData.isProduct === true ? HZ.sendEmail.texts.DEFAULT_MESSAGE_PRODUCT:HZ.sendEmail.texts.DEFAULT_MESSAGE_SPACE));
		}
	}

	function sendEmail(spaceId, subject, msg) {
		HZ.dialogs.EmailDialog.prepare({
			type: HZ.sendEmail.types.SPACE,
			referenceId: spaceId,
			subject: subject,
			message: msg,
			event: HZ.sendEmail.events.ADDTOIBK
		});
		HZ.ui.Yamdi.switchDialog(HZ.dialogs.EmailDialog);
	}

	function cancel () {
		colorPalette = null;
		delegate.hide(null);
	}

	function showError(message) {
		$("#addToGalleryFormError")
			.empty()
			.append(message);
		if (message) {
			$("#addToGalleryFormError").show();
		}
		else {
			$("#addToGalleryFormError").hide();
		}

	}
};


/* **************************************************************************
 * Questions
 * ************************************************************************** */

HZ.spaceActions.QuestionDialog = new function() {
	var WAIT_SCREEN = 0,
		CHOOSE_SCREEN = 1,
		WRITE_SCREEN = 2,
		CONFIRM_SCREEN = 3,
		space = null,
		spaceId = null,
		view = null,	// jQuery object
		delegate = null,
		titleField, commentField,	// fields for
		submitButton, createNewButton, seeWorkButton,
		showLinkOnNewWindow = false, viewInitialized = false,
		questionTopic, questionUpsellLink,
		trackingEventSource = null;

	this.SPACE_TOPIC = 14;
	this.PRODUCT_TOPIC = 17;

	this.JSON_KEY_DAILY_QUESTIONS_QUOTA_EXCEEDED = null;
	this.JSON_KEY_SPACE_ID = null;
	this.JSON_KEY_QUESTIONS = null;

	questionTopic =this.SPACE_TOPIC;
	var SPACE_DIALOG_TITLE = _hgt("Ask a question about this photo.") + " ",
		PRODUCT_DIALOG_TITLE = _hgt("Ask a question about this product.") + " ",
		CONFIRM_TITLE = _hgt("Your question was posted."),
		SPACE_INPUT_PLACEHOLDER_TEXT = _hgt("Write your question here. (ex: Love the chair! Where is it from?)"),
		PRODUCT_INPUT_PLACEHOLDER_TEXT = _hgt("Write your question here. (ex: Love the chair! What is it made of?)");

	var waitScreen = "<div id='questionDialog_"+WAIT_SCREEN+"'>"
		+ "<div class='dialogTitle'>"+SPACE_DIALOG_TITLE+"</div><div class='dialogBody'>"
		+ "<div class='dialogCenterCaption'>Please wait..." + HZ.ui.AjaxThrobber.getThrobber() + "</div>"
		+ "<div class='dialogControls'></div>"
		+ "</div></div>";
	var chooseQuestionScreen = "<div id='questionDialog_"+CHOOSE_SCREEN+"'>"
		+ "<div class='dialogTitle'>"+SPACE_DIALOG_TITLE+"</div><div class='dialogBody'>"
		+ "<div class='dialogStatus' id='questionQuotaExceeded'>" + _hgt("You've reached the maximum number of questions permitted per day. Please visit us again tomorrow if you have more questions.") + "</div>"
		+ "<div class='dialogCaption' id='questionsListCaption'>" + _hgt("The answer you need may already be here:") + "</div>"
		+ "<div class='dialogList' id='questionsList'></div>"
		+ "<div class='dialogControls'></div>"
		+ "</div></div>";
	var writeQuestionScreen = "<div id='questionDialog_"+WRITE_SCREEN+"'>"
		+ "<div class='dialogTitle'>"+SPACE_DIALOG_TITLE+"</div><div class='dialogBody'>"
			+ "<form id='askQuestionForm' name='postToForumForm' action='javascript:;'>"
			+ "<div class='dialogStatus' id='questionFormError'></div>"
			+ "<div><input id='askQuestionInputTitle' type='text' maxlength='70' placeholder='" + _hgt("Write your question here. (ex: Love the chair! Where is it from?)") + "'></div>"
			+ "<div><textarea id='askQuestionInputComment' placeholder='" + _hgt("Tell us the details here.") + "'></textarea></div>"
			+ "<div id='questionsGuidelines'>"
				+ "<div id='questionGuidelinesBody'>" + _hgt("Pros on Houzz are encouraged but not obligated to answer questions.<br/><br/>Polite questions are more likely to receive responses.") + "</div>"
			+ "</div>"
			+ "<input type='submit' style='display:none'></input>"
			+ "<div class='dialogControls'></div>"
		+ "</form></div></div>";
	var confirmScreen = "<div id='questionDialog_"+CONFIRM_SCREEN+"'>"
		+ "<div class='dialogTitle'>"+CONFIRM_TITLE+"</div><div class='dialogBody'>"
		+ "<div id='askQuestionConfirmationMessage'></div>"
		+ "<div class='dialogControls'></div>"
		+ "</div></div>";

	this.init = function (_spaceId, _ownedByPro) {
		spaceId = _spaceId;
	}

	this.setDelegate = function (_delegate) {
		delegate = _delegate;
	};

	this.setTrackingEventSource = function(_trackingSource) {
		trackingEventSource = _trackingSource;
	}
	this.setShowLinkOnNewWindow = function (_showLinkOnNewWindow) {
		showLinkOnNewWindow = _showLinkOnNewWindow;
	};

	this.setQuestionTopic = function (_questionTopic) {
		questionTopic = _questionTopic;
	};

    this.setQuestionUpsellLink = function (_upsellLink) {
        questionUpsellLink = _upsellLink;
    }

	this.openQuestionPage = function(questionId) {
		var link = HZ.utils.Links.getQuestionLink(questionId);

		if (showLinkOnNewWindow)
			window.open(link);
		else
			window.location = link;
	};

	function isProductQuestion() {
		return questionTopic == HZ.spaceActions.QuestionDialog.PRODUCT_TOPIC;
	}

	this.getView = function () {
		// return a jQuery contents object
		if (!view) {
			var iter = 0;
			view = $("<div id='askQuestionDialog'></div>")
				.addClass("dialogFrame")
				.append(waitScreen)
				.append(chooseQuestionScreen)
				.append(writeQuestionScreen)
				.append(confirmScreen);

			submitButton = HZ.ui.InputButtonUtils.createPrimaryInputButton(_hgt("Submit"),"",$.proxy(submitQuestion,this));

//			$(createButton("Submit", null, "submitNewQuestion", null))
//				.click ($.proxy(submitQuestion, this));

//			createNewButton = $(createButton("I have another question", null, "createNewQuestionsButton", null))
//				.click ($.proxy(showWriteQuestionScreen, this));

			createNewButton = HZ.ui.InputButtonUtils.createPrimaryInputButton( _hgt("I have another question") ,"",$.proxy(showWriteQuestionScreen,this));
			seeWorkButton = HZ.ui.InputButtonUtils.createPrimaryInputButton( _hgt("See Their Work"), null, function() {window.location.href=questionUpsellLink;}, null, null, "seeWorkButton");
			$("body").append(view);
			$("#questionDialog_"+WAIT_SCREEN+" .dialogControls", view)
				.append(HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("Cancel"), null, null, null, null, "cancelButton"));
			$("#questionDialog_"+CHOOSE_SCREEN+" .dialogControls", view)
				.append(HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("Cancel"), null, null, null, null, "cancelButton"))
				.append(createNewButton);
			$("#questionDialog_"+WRITE_SCREEN+" .dialogControls", view)
				.append(HZ.ui.AjaxThrobber.getThrobber())
				.append(HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("Cancel"), null, null, null, null, "cancelButton"))
				.append(submitButton);
			$("#questionDialog_"+CONFIRM_SCREEN+" .dialogControls", view)
				.append(HZ.ui.InputButtonUtils.createSecondaryInputButton( _hgt("No Thanks"), null, null, null, null, "cancelButton"))
				.append(seeWorkButton);

			$(".cancelButton",view).click ($.proxy (cancel, this));


			titleField = $("#askQuestionInputTitle")[0];
			$("#askQuestionInputTitle").charCount(
			{
				css: 'counter tiny-text',
				counterElement: 'div',
				allowed: 70,
				prewarning: 20,
				warning: 10,
				counterText: _hgt('Characters Left')+' '
			});
			commentField = $("#askQuestionInputComment")[0];
		}

		return view;
	};

	this.viewLoaded = function () {
		// reset the form:
		showError("");
		titleField.value = "";
		$(titleField).trigger("change");
		commentField.value = "";
		HZ.ui.AjaxThrobber.setInCall(false);
		if (!viewInitialized) {
			viewInitialized = true;
			$('[placeholder]','#askQuestionDialog').initPlaceHolders({
				saveContainer:'#askQuestionDialog',
				saveEvent:'submit.question'
			});
		}
		else {
			$('[placeholder]','#askQuestionDialog').initPlaceHolders('refresh');
		}
		var dialogTitle = (isProductQuestion()) ? PRODUCT_DIALOG_TITLE : SPACE_DIALOG_TITLE,
			placeholderText = (isProductQuestion()) ? PRODUCT_INPUT_PLACEHOLDER_TEXT : SPACE_INPUT_PLACEHOLDER_TEXT;
		$("#questionDialog_"+WAIT_SCREEN+" .dialogTitle", view).html(dialogTitle);
		$("#questionDialog_"+CHOOSE_SCREEN+" .dialogTitle", view).html(dialogTitle);
		$("#questionDialog_"+WRITE_SCREEN+" .dialogTitle", view).html(dialogTitle);
		if (isProductQuestion()) {
			$('#questionsGuidelines').hide();
		}
		else {
			$('#questionsGuidelines').show();
		}
		// show the first screen:
		showWaitScreen();
	};

	this.viewUnloaded = function () {};

	function showScreen(screenId) {
		var divId = "questionDialog_" + screenId;
		view.children().each(
			function(i) {
				this.style.display = (this.id == divId)?"block":"none";
			}
		)
		delegate.center();
	}

	function cancel () {
		delegate.hide(null);
	}

	function showWaitScreen() {
		showScreen(WAIT_SCREEN);
		HZ.ui.AjaxThrobber.setInCall(true);
		HZ.spaceActions.getExistingQuestions(spaceId, $.proxy (getExistingQuestionsCallback, this));
	}

	function getExistingQuestionsCallback(data) {
		HZ.ui.AjaxThrobber.setInCall(false);
		if (data.success) {
			if (data[HZ.spaceActions.QuestionDialog.JSON_KEY_DAILY_QUESTIONS_QUOTA_EXCEEDED] || data[HZ.spaceActions.QuestionDialog.JSON_KEY_QUESTIONS].length > 0) {
				showChooseQuestionScreen(data);
			} else
				showWriteQuestionScreen();
		}
	}

	function showChooseQuestionScreen(data) {
		var questions = data[HZ.spaceActions.QuestionDialog.JSON_KEY_QUESTIONS];
		var spaceId = data[HZ.spaceActions.QuestionDialog.JSON_KEY_SPACE_ID];
		var quotaExceeded = data[HZ.spaceActions.QuestionDialog.JSON_KEY_DAILY_QUESTIONS_QUOTA_EXCEEDED];

		var html = "<ul>";
		for (var i=0; i<questions.length; i++) {
			var question = questions[i];
            var numberOfAnswers = parseInt(question.numberOfAnswers, 10);
			html += "<li><a href='javascript:HZ.spaceActions.QuestionDialog.openQuestionPage("+question.questionId+")'>"+question.title+"</a>";
            if(numberOfAnswers > 0) {
                html += " <span class='reply'>(";
            }
			switch (parseInt(question.numberOfAnswers, 10)) {
				case 0: break;
				case 1:
					html += _hgt("1 reply");
					break;
				default:
					html += _hgt("{replyCount} replies", {'replyCount': question.numberOfAnswers});
			}
            if(numberOfAnswers > 0) {
                html += ")</span>";
            }
		}
		html += "</ul>";
		$("#questionsList").empty()
			.append(html);
		$('#questionsListCaption')[0].style.display = (questions.length > 0)?"block":"none";
		$("#questionQuotaExceeded")[0].style.display = quotaExceeded?"block":"none";
		createNewButton[0].style.display = quotaExceeded?"none":"inline";
		showScreen(CHOOSE_SCREEN);
	};

	function showError(message) {
		$("#questionFormError")
			.empty()
			.append(message);
		if (message) {
			$("#questionFormError").show();
		}
		else {
			$("#questionFormError").hide();
		}
		$('[placeholder]','#askQuestionDialog').initPlaceHolders('refresh');
	}

	function showWriteQuestionScreen() {
		showScreen(WRITE_SCREEN);
	}

	function submitQuestion() {
		if (HZ.ui.AjaxThrobber.isInCall())
			return;

		$('#askQuestionDialog').trigger('submit.question');
		// Validation:
		var title = UIHelper.trim(titleField.value),
			comment = UIHelper.trim(commentField.value);

		if (title=="") {
			showError (_hgt("Please write your question."));
		} else {
			HZ.ajaz.Services.postToForum(spaceId, title, comment, questionTopic, $.proxy (submitQuestionCallback, this));
		}
		return false;
	}

	function submitQuestionCallback(data) {
		HZ.ui.AjaxThrobber.setInCall(false);
		if (data.success == "true") {
			var discussionLink = questionUpsellLink,
				message = _hgt("Want to see what other Houzzers are working on?");

			if (data.quotaReached){
				message = "<div class='overQuota'>" + _hgt("Please note: You have reached the maximum number of questions permitted per day.") + "</div>" + message;
			}

			$("#askQuestionConfirmationMessage").empty().append(message);

			if(trackingEventSource != null) {
				HZ.utils.Logger.sendEventLogOnce(trackingEventSource);
			}
			showScreen(CONFIRM_SCREEN);
		} else {
			HZ.ui.Yamdi.hide(this);
			HZ.ui.yamdi.Common.alert(data.error);
		}
	}
};


/* **************************************************************************
 * Print dialog - Prompt users to use more environment friendly alternatives
 * Examples: Share by email or downloading mobile app
 * ************************************************************************** */

HZ.spaceActions.DontPrintDialog = new function() {
    var view = null,
        _lastInvokedDate = null,
        _delegate = null;

    this.setDelegate = function(delegate){
        _delegate = delegate;
    };

    this.lastInvokedDate =  function(){
        return _lastInvokedDate;
    }

    this.setLastInvokedDate = function(lastInvokedDate){
        _lastInvokedDate = lastInvokedDate;
    }

    this.daysElapsedFromToday = function(){
        var today = this.currentDateAsTimestamp();
        var previous = new Date(this.lastInvokedDate());
        var timeDiff = Math.abs(today - previous);
        return Math.floor(timeDiff/(1000 * 3600 * 24));
    }

    this.currentDateAsTimestamp = function(){
        var today = new Date();
        return today.getTime();
    }

    this.checkUserPref = function(url, popup){
        // if last invoked date has not been set or more than 1 day has passed since we last showed the dialog to user
        // then SHOW DIALOG
        if (!this.lastInvokedDate() || this.daysElapsedFromToday() > 1){
            this.setLastInvokedDate(this.currentDateAsTimestamp());
            HZ.ajaz.Services.updateUserPreferences(15, null, function(response){});
            // show print dialog and log the event
            HZ.utils.Logger.sendEventLog('dpd_shown');
            HZ.ui.Yamdi.show(HZ.spaceActions.DontPrintDialog, null);
            var continueElem = $("#continueToPrint");
            if (continueElem){
                continueElem.click(function(url, popup){
                    // Hide print dialog and log the event
                    HZ.utils.Logger.sendEventLog('dpd_print');
                    HZ.ui.Yamdi.hide(null);
                    HZ.utils.Print.printUrl(url, popup);
                });
            }
        }
        else {
            HZ.utils.Print.printUrl(url, popup);
        }

    }

    this.getView = function(){
        if (!view){
            view = $("<div id='dontPrintDialog'>")
                .addClass('dialogFrame')
                .append(
                    "<div class='dialogTitle'><span id='dontPrintTitleIcon'></span>" + _hgt("Print Photo") + "</div>"
                    + "<div class='dialogBody'>"
                    +   "<div class='dialogSection'><div class='dialog-section-header'>" + _hgt("Help the environment by sharing this photo another way:") + "</div>"
                    +       "<div id='emailSection' class='dialogSection-item'>"
                    +           "<div class='image-container'><a href='javascript:;' onclick=sendMail()> <span id='emailIcon'></span><p class='image-caption colorLink' href='javascript:;'>" + _hgt("Email{contextEmailVerb}",{'context.emailVerb':''}) + "</p><p class='secondary-caption'>" + _hgt("Send it now") + "</p></a></div>"
                    +       "</div>"
                    +        "<div id='downloadAppSection' class='dialogSection-item'>"
                    +           "<div class='image-container'><a href='http://www.houzz.com/mobileApps'><span id='downloadAppIcon'></span><p class='image-caption colorLink' href='javascript:;'>" + _hgt("Houzz App") + "</p><p class='secondary-caption'>" + _hgt("Take it with you") + "</p></a></div>"
                    +       "</div>"
                    +   "</div>"
                    +   "<div class='dialogControls'><a id='continueToPrint' class='colorLink' href='javascript:;'>" + _hgt("No thanks. Please print this photo") + "</a></div>"
                    +"</div></div>"
                );
            $("body").append(view);
        }
        return view;

    };

    this.viewLoaded = function() {};


    this.viewUnloaded = function () {};

    sendMail = function() {
        //Hide the dont print dialog
        HZ.ui.Yamdi.hide(null);
        // show email dialog
        // use generic send Email dialog on space Actions if it exists
        if (typeof(showSendEmailDialog) === 'function'){
            showSendEmailDialog();
        }
        // FIXME:else the print button which was clicked is in lightbox and we invoke lightbox email dialog
        else {
            HZ.lb.plugins.CommonActions.handleEmail();
        }
    };

};


/* ****************************************************************************
 * Post Sign up Overlay - Show post signup overlay on browse photos to encourage
 * users to add more photos
 * **************************************************************************** */

HZ.spaceActions.PhotoOverlay = new function(){
    var promoView = null;

    this.getPromoView = function(){
        if (!promoView){
            promoView = $("<div id='signup_overlay' class='promote' data-type='hover'><span class='likeIt icon-wrap'>" + _hgt("Save Photo") + " <span class='more-icon'></span></span><br/></div>");
        }
        return promoView;
    };

    this.assembleOverlayElements = function(){
        var overlayElements = [];
        if (HZ.data.CurrentSessionUser === null)
        {
            overlayElements.push(this.getPromoView());
        }
        return overlayElements;
    };
};



/* **************************************************************************
 * Email - should use HZ.email.EmailDialog in contactDialog
 * ************************************************************************** */

/* **************************************************************************
 * Embed
 * ************************************************************************** */




HZ.spaceActions.EmbedDialogClass = function () {
	var spaceId = null,
		largePhotoTextarea, smallPhotoTextarea,
		template = "<div class='dialogCaption'>" + _hgt("Copy this code to embed this photo on your site:") + "</div>"
			+ "<div class='dialogCaption' style='margin-top:10px;'>" + _hgt("Large Image (500 pixels):") + "</div>"
			+ "<textarea onclick='this.select()' readonly='readonly' class='embedPhoto500'></textarea>"
			+ "<div class='dialogCaption' style='margin-top:10px;'>" + _hgt("Small Image (320 pixels):") + "</div>"
			+ "<textarea onclick='this.select()' readonly='readonly' class='embedPhoto320'></textarea>"
			+ "<div class='dialogCaption' style='margin-top:10px;'>" + _hgt("Wordpress <t1>Shortcode</t1>:",{t1:{'tag':'a', 'attr':{ 'href':'http://www.houzz.com/buttonsAndBadges#shortcode'}}}) + "</div>"
			+ "<textarea onclick='this.select()' readonly='readonly' class='embedShortcode'></textarea>";

	HZ.spaceActions.EmbedDialogClass.superclass.constructor.call(this);

	this.prepare = function() {
		var okButton = HZ.ui.InputButtonUtils.createPrimaryInputButton(
									_hgt("Done"),
									_hgt("cancel"),
									$.proxy(cancel, this)
								);

		var body = $("<div>").append(template);
		largePhotoTextarea = $(".embedPhoto500", body);
		smallPhotoTextarea = $(".embedPhoto320", body);
		shortcodeTextarea = $(".embedShortcode", body);

		var dialogSettings = {
			title: _hgt('Embed a Photo'),
			body: body,
			dialogClassName: 'embedPhotoDialog',
			controls: [okButton],
			onViewLoaded: $.proxy(this.onViewLoaded, this)
		};

		this.init(dialogSettings);
	}

	this.setSpaceId = function (aSpaceId) {
		spaceId = aSpaceId;
	};

	this.onViewLoaded = function () {
		largePhotoTextarea.val("");
		smallPhotoTextarea.val("");
		shortcodeTextarea.val("");
		HZ.ajaz.Services.getEmbedSpaceCode(spaceId, $.proxy(updateTextareas, this));
	};

	function cancel () {
		this.getDelegate().hide(null);
	}

	function updateTextareas(data) {
		if (data.success) {
			largePhotoTextarea.val(data.largeImageEmbedCode);
			smallPhotoTextarea.val(data.smallImageEmbedCode);
			shortcodeTextarea.val(data.wordpressShortcode);
		}
	}
}
HZ.extend(HZ.spaceActions.EmbedDialogClass, HZ.ui.yamdi.Dialog);
HZ.spaceActions.EmbedDialog = new HZ.spaceActions.EmbedDialogClass();
HZ.spaceActions.EmbedDialog.prepare();

function showEmbedDialog (spaceId) {
	HZ.spaceActions.EmbedDialog.setSpaceId(spaceId);
	HZ.ui.Yamdi.show(HZ.spaceActions.EmbedDialog);
}





/* **************************************************************************
 * Social Networks Share
 * ************************************************************************** */

HZ.spaceActions.Share = {
	GOOGLE_PLUS: 0,
	FACEBOOK: 1,
	TWITTER: 2,
	openShareWindowForSpace: function(platform, spaceId) { // works only if the space is found in HZ.data.Spaces
		var space,
			link,
			title,
			caption,
			redirectLink,
			display;
		if (HZ.data && HZ.data.Spaces) {
			space = HZ.data.Spaces.get(spaceId);
			if (space) {
				link = HZ.utils.Links.getSpaceLinkWithSEO(space.id);
				title = space.t;
				if (platform == this.FACEBOOK) {
					var style = HZ.utils.Styles.getStyleUrl(space.s),
						category = HZ.data.Categories.getCategoryById(space.cat),
						metroArea = space.ma,
						spaceOwner = HZ.data.Users.get(space.ow);
					if (style) {
						title += " - " + style;
					}
					if (category) {
						title += " - " + category.name;
					}
					if (metroArea) {
						title += " - " + metroArea;
					}
					if (spaceOwner) {
						title += _hgt(" - by {owner}", {'owner': spaceOwner.d});
					}
					caption = "";
					redirectLink = HZ.utils.Links.getFbFeedRedirectLink();
					display = "popup";
				}
				this.openShareWindow(platform, link, title, caption, redirectLink, display);
			}
		}
	},
	openShareWindow: function(platform, link, title, caption, redirectLink, display) {
		var url;
		switch (platform) {
			case this.FACEBOOK:
				url = "https://www.facebook.com/dialog/feed?app_id=" + HZ.utils.Config.fbAppId +
					"&link=" + encodeURIComponent(link) +
					"&caption=" + encodeURIComponent(caption) +
					"&redirect_uri=" + encodeURIComponent(redirectLink) +
					"&display=" + encodeURIComponent(display);
				break;
			case this.TWITTER:
				url = "http://twitter.com/intent/tweet?url=" + encodeURIComponent(link) + "&text=" + encodeURIComponent(title);
				break;
			case this.GOOGLE_PLUS:
				url = "https://plus.google.com/share?url=" + encodeURIComponent(link);
				break;
		}
		if (url) {
			window.open(url, "lbShare"+platform, "height=600,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
		}
	},
	populateToGallerySelect: function (galleryChoiceField, selectedGalleryId) {
		var f, l, recentGallery, ownGallery, sharedGallery, gallery, isSelected, featured, optionElement, $gallerySelect;

		//reuse the AddToIdeabookDialog galleries
		var galleries = HZ.spaceActions.AddToIdeabookDialog.getGalleries();

		$gallerySelect = $(galleryChoiceField);

		if (galleries) {
			recentGallery = galleries.recent;
			l = recentGallery.length;
		}


		if (l > 0) {
			HZ.ui.Utils.addOptionGroupToSelect ($gallerySelect, _hgt("Recently Used:"), -1, 'recentIdeabooks');
		}

		for (var i = 0 ; i < l ; i ++) {
			gallery = recentGallery[i];
			featured = gallery.featured ? " (" + _hgt("Featured") + ")" : "";
			isSelected = gallery.id == selectedGalleryId;

			HZ.ui.Utils.addOptionToGroupSelect ($gallerySelect, gallery.title + featured, gallery.id, isSelected, 'recentIdeabooks');
		}

		//if (l > 0) {
			HZ.ui.Utils.addOptionGroupToSelect ($gallerySelect, _hgt("Your Ideabooks:"), -1, 'yourIdeabooks');
		//}
		if (galleries) {
			ownGallery = galleries.own;
			l = ownGallery.length;
		}

		for (var i = 0 ; i < l ; i ++) {
			gallery = ownGallery[i];
			featured = gallery.featured ? " (" + _hgt("Featured") + ")" : "";
			isSelected = gallery.id == selectedGalleryId;
			HZ.ui.Utils.addOptionToGroupSelect ($gallerySelect, gallery.title + featured, gallery.id, isSelected, 'yourIdeabooks');
		}

		if (galleries) {
			sharedGallery = galleries.shared;
			l = sharedGallery.length;
		}
		
		if (l > 0) {
			HZ.ui.Utils.addOptionGroupToSelect ($gallerySelect, _hgt("Shared Ideabooks:"), -1, 'sharedIdeabooks');
		}

		for (var i = 0 ; i < l ; i ++) {
			gallery = sharedGallery[i];
			isSelected = gallery.id == selectedGalleryId;
			HZ.ui.Utils.addOptionToGroupSelect ($gallerySelect, gallery.title + _hgt("(Shared)"), gallery.id, isSelected, 'sharedIdeabooks');
		}

	}
}

window.hzmr.push("spaceActions:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End spaceActions.js  **************/
/************* Start socialSdk.js for locale en-US **************/
try {//<script>
HZ.ns("HZ.sns");

HZ.sns.JsSdk = {};
HZ.sns.JsSdk.init = function() {};
HZ.sns.JsSdk.setFbTokenExpiration = function() {};
HZ.sns.JsSdk.isFbTokenExpired = function() {};
HZ.sns.JsSdk.getFbAccessToken = function() {};
HZ.sns.JsSdk.loadThirdPartyJsSdk = function() {};
HZ.sns.JsSdk.loadOnDocumentReady = function() {};
HZ.sns.JsSdkConstants = {};
HZ.sns.JsSdkConstants.STATUS_NOT_LOADED = 1;
HZ.sns.JsSdkConstants.STATUS_LOADING = 2;
HZ.sns.JsSdkConstants.STATUS_LOADED = 3;

HZ.sns.JsSdkConstants.FB = 1;
HZ.sns.JsSdkConstants.GOOGLE = 2;
HZ.sns.JsSdkConstants.TW = 3;

HZ.sns.JsSdkController = {};
HZ.sns.JsSdkController.sdkLoaded = {};
HZ.sns.JsSdkController.sdkConfig = {};
HZ.sns.JsSdkController.sdkConfig[HZ.sns.JsSdkConstants.FB] = {url: "//connect.facebook.net/en_US/all.js", id: "facebook-jssdk"};
HZ.sns.JsSdkController.sdkConfig[HZ.sns.JsSdkConstants.GOOGLE] = {url: "https://apis.google.com/js/platform.js", id: "gplatform-js"};
HZ.sns.JsSdkController.sdkConfig[HZ.sns.JsSdkConstants.TW] = {url: "//platform.twitter.com/widgets.js", id: "twitter-wjs"};
HZ.sns.JsSdkController.sdkStatus = {};
HZ.sns.JsSdkController.sdkStatus[HZ.sns.JsSdkConstants.FB] = HZ.sns.JsSdkConstants.STATUS_NOT_LOADED;
HZ.sns.JsSdkController.sdkStatus[HZ.sns.JsSdkConstants.GOOGLE] = HZ.sns.JsSdkConstants.STATUS_NOT_LOADED;
HZ.sns.JsSdkController.sdkStatus[HZ.sns.JsSdkConstants.TW] = HZ.sns.JsSdkConstants.STATUS_NOT_LOADED;

HZ.tmpFbLoader = new function() {
	
	var	fbAppId = '143965932308817',
		isInitialized = false, // whether or not FB.init has been called
		fbUserId = null,
		fbFirstName = null,
		fbLastName = null,
		fbEmail = null,
		fbAccessToken = null,
		fbTokenExpiration = 0,
		fbAuthResponse = null,
		isLoggedIn = false,
		self = this;

	this.setFbAppId = function(_appId) {
		fbAppId = _appId;
	};

	this.getFbAppId = function() {
		return fbAppId;
	};

	/**
		* returns true if the FB js sdk reports that the current page has a logged-in FB user
		* Note: this value is only valid after a call to either getLoginStatus or requestFbAuth
		*/
	this.isFbLoggedIn = function() {
		return isLoggedIn;
	};

	/**
		* returns the FB user id of the currently FB logged-in user, if available.  This will only be set
		* if the user has authorized the application, and if a call to either requestFbAuth or getFbLoginStatus
		* has been made previously.
		*/
	this.getFbUserId = function() {
		return fbUserId;
	};

	/**
		* only set if loadUserData has been called
		*/
	this.getFbLastName = function() {
		return fbLastName;
	};

	/**
		* only set if loadUserData has been called
		*/
	this.getFbFirstName = function() {
		return fbFirstName;
	};

	/**
		* only set if loadUserData has been called
		*/
	this.getFbEmail = function() {
		return fbEmail;
	};

	this.getFbAccessToken = function() {
		return fbAccessToken;
	};
	
	/**
	 * This function was used to load fb sdk asynchronously before.
	 * Now we use it to bind callback to the fbJsLoaded event if fb js sdk is not loaded yet, 
	 * otherwise run the callback directly.
	 */
	this.init = function(callback) {
		if(callback && typeof callback == "function") {
			if(!isInitialized) {
				$(document).bind('fbJsLoaded', callback);
			} else {
				callback();
			}
		}
	};
	
	this.loadThirdPartyJsSdk = function(sdkIds) {
		if(!sdkIds) {
			return;
		}
		// process sdk param so that we can load multiple third party js in one call
		if(Object.prototype.toString.call(sdkIds) !== Object.prototype.toString.call([])) {
			sdkIds = [sdkIds];
		}
		var fbJsSdkWanted = false;
		var win,dom,doc;
		var parentWin = window;
		var where,iframe = document.createElement('iframe');
		iframe.src = "javascript:false";
		iframe.title = "";
		(iframe.frameElement || iframe).style.cssText = "position: absolute; left: -10000px; top: -10000px; width: 0; height: 0; border: 0";
		where = document.getElementsByTagName('script');
		where = where[where.length - 1];
		where.parentNode.insertBefore(iframe, where);
	
		try {
			win = iframe.contentWindow;
			doc = win.document;
		} catch(e) {
			// will throw exception if the document's domain is set
			dom = document.domain;
			iframe.src="javascript:var d=document.open();d.domain='"+dom+"';void(0);";
			win = iframe.contentWindow;
			doc = win.document;
		}
		
		if(Array.prototype.indexOf) {
			fbJsSdkWanted = sdkIds.indexOf(HZ.sns.JsSdkConstants.FB) !== -1;
		} else {
			var countOfSdk = sdkIds.length;
			for(var i = 0; i <= countOfSdk; i++) {
				if(sdkIds[i] === HZ.sns.JsSdkConstants.FB) {
					fbJsSdkWanted = true;
					break;
				}
			} 
		}
		if(fbJsSdkWanted) {
			if (!document.getElementById('fb-root')) {
				var firstChild = document.body.firstChild;
				var fbRootDiv = document.createElement('div');
				fbRootDiv.id = 'fb-root';
				document.body.insertBefore(fbRootDiv, firstChild);
			}
		}
		if(fbJsSdkWanted && !window.fbAsyncInit) {
			window.fbAsyncInit = function() {
				HZ.sns.JsSdkController.sdkStatus[HZ.sns.JsSdkConstants.FB] = HZ.sns.JsSdkConstants.STATUS_LOADED;
				requireInitialization(null);
				$(document).trigger("fbJsLoaded");
			};
		}
		
		doc.open()._l = function() {
				while(sdkIds.length) {
				var sdkId = sdkIds.shift();
				if(HZ.sns.JsSdkController.sdkStatus[sdkId] !== HZ.sns.JsSdkConstants.STATUS_NOT_LOADED) {
					continue;
				}
				HZ.sns.JsSdkController.sdkStatus[sdkId] = HZ.sns.JsSdkConstants.STATUS_LOADING;
				var sdkConfig = HZ.sns.JsSdkController.sdkConfig[sdkId];
				var jsId = sdkConfig.id;
				if(!this.getElementById(jsId)) {
					win.inDapIF = true;
					var js = this.createElement("script");
					if(dom) {
						this.domain = dom;
					}
					if(jsId) {
						js.id = jsId;
					}
					if(js.readyState) {
						js.onreadystatechange = (function(sdkId) {
							return function() {
								if(js.readyState == "loaded" || js.readyState == "complete") {
									js.onreadystatechange = null;
									HZ.sns.JsSdkController.sdkStatus[sdkId] = HZ.sns.JsSdkConstants.STATUS_LOADED;
									if(sdkId === HZ.sns.JsSdkConstants.TW) {
										parentWin.twttr = parentWin.twttr || win.twttr || {};
										if(parentWin.twttr) {
											parentWin.twttr.widgets.load(parentWin.document.getElementById("shareList"));
										}
									} else if(sdkId === HZ.sns.JsSdkConstants.GOOGLE) {
										parentWin.gapi = parentWin.gapi || win.gapi || {};
										if(parentWin.gapi) {
											win.gapi = parentWin.gapi;
											parentWin.___gcfg = win.___gcfg = {
												lang: 'en-US',
												parsetags: 'explicit'
											};
											parentWin.gapi.plus.go(parentWin.document.getElementById("shareList"));
										}
									}
								}
							}
						})(sdkId);
					} else {
						js.onload = (function(sdkId) {
							return function() {
								HZ.sns.JsSdkController.sdkStatus[sdkId] = HZ.sns.JsSdkConstants.STATUS_LOADED;
								if(sdkId === HZ.sns.JsSdkConstants.TW) {
									parentWin.twttr = parentWin.twttr || win.twttr || {};
									if(parentWin.twttr) {
										parentWin.twttr.widgets.load(parentWin.document.getElementById("shareList"));
									}
								} else if(sdkId === HZ.sns.JsSdkConstants.GOOGLE) {
									parentWin.gapi = parentWin.gapi || win.gapi || {};
									if(parentWin.gapi) {
										win.gapi = parentWin.gapi;
										parentWin.___gcfg = win.___gcfg = {
											lang: 'en-US',
											parsetags: 'explicit'
										};
										parentWin.gapi.plus.go(parentWin.document.getElementById("shareList"));
									}
								}
							}
						})(sdkId);
					}
					js.src = sdkConfig.url;
					this.body.appendChild(js);
				}
			}
		};
		doc.write('<body onload="document._l();">');
		doc.close();
	};
	
	function loadFbJsSdk() {
		self.loadThirdPartyJsSdk(HZ.sns.JsSdkConstants.FB);
	}
	
	/**
	 * load the FB lib js on document.ready, or start immediately if the document
	 * is already fully loaded
	 */
	this.loadOnDocumentReady = function() {
		$(document).ready(loadFbJsSdk);
	};
	
	this.setFbTokenExpiration = function(_expirationTime) {
		fbTokenExpiration = _expirationTime;
	};

	this.getFbTokenExpiration = function() {
		return fbTokenExpiration;
	};

	/**
		* convenience method that returns true if the current time is greater than the stored FB
		* access token expiration time
		*/
	this.isFbTokenExpired = function() {
		var currTime = (new Date()).getTime() * 0.001;
		return currTime > fbTokenExpiration;
	};

	function requireInitialization(callerArgs) {
		if (HZ.sns.JsSdkController.sdkStatus[HZ.sns.JsSdkConstants.FB] != HZ.sns.JsSdkConstants.STATUS_LOADED && callerArgs) {
			HZ.sns.JsSdk.init(function() { callerArgs.callee.apply(HZ.sns.JsSdk, callerArgs); });
			if (HZ.sns.JsSdkController.sdkStatus[HZ.sns.JsSdkConstants.FB] == HZ.sns.JsSdkConstants.STATUS_NOT_LOADED)
				HZ.sns.JsSdk.loadOnDocumentReady();
			
			return false;
		}
		
		if (!isInitialized) {
			FB.init({
				appId      : fbAppId, // App ID
				status     : false, 
				cookie     : true, 
				xfbml      : true,
				channelUrl : 'http://www.houzz.com/res/2059/pic/channel.html?v=2059'
			});

			isInitialized = true;
		}
		
		return true;
	}

	/**
		* returns the response (if any) from the most recent requestFbAuth or getFbLoginStatus call
		* Note - in FB terms this is the response from either the FB.login or FB.getLoginStatus call
		*/
	this.getFbAuthResponse = function() {
		return fbAuthResponse;
	};

	/**
		* update the stored access token, user id and token expiration with the specified
		* response from FB (if the status is "connected"; e.g. user is logged into FB and has authorized
		* this app id)
		*/
	function setFbResponse(response) {
		fbAuthResponse = response;
		if (response) {
			if (response.status == "connected") {
				isLoggedIn = true;
				fbAccessToken = response.authResponse.accessToken;
				fbUserId = response.authResponse.userID;
				// assume that access token is ok on the client side and set default expiration
				var currTime = (new Date()).getTime() * 0.001;
				fbTokenExpiration = currTime + parseInt(response.authResponse.expiresIn, 10);
			}
			else if (response.status == "not_authorized") {
				isLoggedIn = true;
			} else {
				isLoggedIn = false;
			}
		}
	}

	/**
		* requests and stores the first name, last name, and email (if available) of the currently
		* logged in user; either getFbLoginStatus or requestFbAuth must have been called previously
		* to have an active access token
		*/
	function loadUserData(callback) {
		HZ.sns.JsSdk.graphApi("/me", function(response) {
			if (response.first_name)
				fbFirstName = response.first_name;
			if (response.last_name)
				fbLastName = response.last_name;
			if (response.email)
				fbEmail = response.email;

			if (typeof callback == "function")
				callback();
		});
	}

	/**
		* wrapper for FB.login call; request a set of permissions from the user for this FB app id
		* Note that this will result in a pop-up dialog from FB.
		*
		* failCallback - called instead of callback if the response from FB is not status "connected"
		* doloadUserData - if true, the loadUserData function is called after a successful login and before
		*                  the callback is triggered 
		* optParams - (optional) object map of parameters to pass into the FB.login call
		*/
	this.requestFbAuth = function(requestedScope, callback, failCallback, doLoadUserData, optParams) {
		if (!requireInitialization(arguments))
			return;

		if (!requestedScope)
			requestedScope = '';

		var loginParams = {scope: requestedScope};
		if (optParams) {
			loginParams = $.extend(loginParams, optParams);
		}

		FB.login(function(response) {
			setFbResponse(response);

			if (response && response.status == "connected") {
				if (doLoadUserData) {
					loadUserData(callback);
				}
				else {
					if (typeof callback == "function")
						callback();
				}
			}
			else {
				if (typeof failCallback == "function")
					failCallback();
			}
		}, 
		loginParams
		);
	};

	/**
		* wrapper for FB.api; either getFbLoginStatus or requestFbAuth must have been called previously
		* to obtain and set an active access token
		*/
	this.graphApi = function(path, callback) {
		FB.api(path, callback);
	};

	/**
		* calls FB.getLoginStatus, updating the stored access token and expiration time
		*/	
	this.getFbLoginStatus = function(callback) {
		requireInitialization(arguments);

		if (fbAuthResponse)
		{
			if (typeof callback == "function")
				callback(fbAuthResponse);
		}
		else
		{
			FB.getLoginStatus(function(response) {
				setFbResponse(response);

				if (typeof callback == "function")
					callback(response);
			});
		}
	};
	// Write something on Feed
	this.postToFeed = function(link, title, description, picture, redirectUrl) {
		var obj = {
			method: 'feed',
			redirect_uri: redirectUrl,
			link: link,
			picture: picture,
			name: title,
			caption: '',
			description: description
		};

		var callback = function(response) {
		};

		FB.ui(obj, callback);
	};
};

if (HZ.tmpFbLoader) {
	HZ.sns.JsSdk = HZ.tmpFbLoader;
}

window.hzmr.push("socialSdk:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End socialSdk.js  **************/
/************* Start siteAuth.js for locale en-US **************/
try {// <script>

HZ.ns("HZ.auth");

HZ.auth.LoginWrapperDialog = new function() {
	var LOGIN_WRAPPER_SCREEN = 0,
		view = null,	// jQuery object
		delegate = null,
		pageUrl = null,
		width = null,
		height = null;

	this.show = function(_pageUrl, callback, _width, _height) {
		this.init(_pageUrl);
		width = _width ? _width : 824;
		height = _height ? _height : 473;
		HZ.ui.Yamdi.show(this, callback);
	};
	
	this.init = function (_pageUrl) {
		pageUrl = _pageUrl;
	};
	
	this.setDelegate = function (_delegate) {
		delegate = _delegate;
	};

	this.getView = function () {
		// return a jQuery contents object
		if (!view) {
			view = $("<div id='loginWrapperDialog'></div>")
				.addClass("dlgWrapperFrame")
				.append("<div id='loginWrapperDialog_"+LOGIN_WRAPPER_SCREEN+"'>"
					+ "<iframe id='loginWrapperDialog_"+LOGIN_WRAPPER_SCREEN+"_frame' scrolling='no' frameborder='0' allowtransparency='false' style='border: medium none; overflow: hidden;'></iframe>"
					+ "</div>");
			$("body").append(view);
		}
		$("#loginWrapperDialog").css("width", width+"px");
		$("#loginWrapperDialog").css("height", height+"px");
		$("#loginWrapperDialog_"+LOGIN_WRAPPER_SCREEN+"_frame").css("width", width+"px");
		$("#loginWrapperDialog_"+LOGIN_WRAPPER_SCREEN+"_frame").css("height", height+"px");
		
		return view;
	};	

	this.viewLoaded = function () {
		// show the first screen:
		var redirectStr = pageUrl ? encodeURIComponent(pageUrl) : "";
		document.getElementById("loginWrapperDialog_"+LOGIN_WRAPPER_SCREEN+"_frame").src="https://www.houzz.com" + pageUrl;
		showScreen(LOGIN_WRAPPER_SCREEN);
	};
	
	this.viewUnloaded = function () {
		$("#loginWrapperDialog").remove();
		view = null;
		param = null;
	};
	
	function showScreen(screenId) {
		var divId = "loginWrapperDialog_" + screenId;
		view.children().each(
			function(i) {
				this.style.display = (this.id == divId)?"block":"none";
			}
		);
		delegate.center();
	}	
	
	function cancel () {
		delegate.hide(null);
	}
};



HZ.auth.Manager = new function() {
    var 	userId = null,
			displayMode = null,
			isMobile = false,
			callback = null,
			redirectUrl = null,
			createProProfileUrl = null,
			screen = null,
			email = null,
			messageId = null,
			errMsg = "",
			fbAccessToken = null,
			source = null,
			signupLabel = "signup success",  // default label for GA signup event
			signupSource = null, // source link or button
			sourcePage = null, // source page
			userCreated = false,
			showFbWelcome = true,
			hideFbLinking = false,
			layout = false,
			hideLoadingDialog = false,
			reauthenticate = false,
			openInNewWindow = false,
			serverStartTime = null, // current unix timestamp from server
			pageStartTime = null, // current local unix timestamp at page init
			rtEvent = null, // et code
			defaultFbLoginScope = false,
			signupBaseUrl = null,
			signinBaseUrl = null,
			supportUrl = null;

    this.setIsMobile = function(_isMobile) {
        isMobile = _isMobile;
    };

    this.setDisplayMode = function(_displayMode) {
        displayMode = _displayMode;
    };

    this.setSignupBaseUrl = function(url) {
        signupBaseUrl = url;
    };

    this.setSigninBaseUrl = function(url) {
        signinBaseUrl = url;
    };
	
	this.setSupportUrl = function(url) {
		supportUrl = url;
	};

    this.getDisplayMode = function() {
        return displayMode;
    };

    this.setUserId = function(_userId) {
        userId = _userId;
    };

    this.getUserId = function() {
        return userId;
    };
	
	this.isUserCreated = function() {
		return userCreated;
	};

    this.getScreen = function() {
        return screen;
    };
	
    this.setSignupLabel = function(_label) {
        signupLabel = _label;
    };

    this.setSignupSource = function(_source) {
        signupSource = _source;
    };

    this.getSignupSource = function() {
        return signupSource;
    };

    this.setSourcePage = function(_page) {
        sourcePage = _page;
    };

    this.getSourcePage = function(_page) {
        return sourcePage;
    };

    this.setServerStartTime = function(_startTimestamp) {
    	serverStartTime = _startTimestamp;
    };
        
    this.getMessageId = function() {
        return messageId;
    };
	
	this.getErrorMsg = function() {
		return errMsg;
	};

    this.setShowFbWelcome = function (_showFbWelcome) {
        showFbWelcome = _showFbWelcome;
    };
	
	this.setDefaultFbLoginScope = function (_scope) {
		defaultFbLoginScope = _scope;
	};
	
	this.getRedirectUrl = function() {
		return redirectUrl;
	};
	
	this.getCreateProProfileUrl = function() {
		return createProProfileUrl;
	};

    this.loginComplete = function() {
        if (typeof callback == "function") {
            callback();
        }
        else {
            if (userId) {
                // if user is logged in, then forward or reload page as appropriate
                if (redirectUrl) {
                    top.location = redirectUrl;
                }
                else {
                	top.location.reload();
                }
            }
        }
    };

    function getQueryString(params) {
        var clauses = new Array();
        for(var param in params) {
            if (param == "u") // base64Encode the redirect URL
            	clauses.push(encodeURIComponent(param.toString()) + "=" + HZ.utils.Links.base64Encode((params[param]).toString()));
            else
                clauses.push(encodeURIComponent(param.toString()) + "=" + encodeURIComponent((params[param]).toString()));
        }

        var queryStr = clauses.join("/");

        return queryStr;
    }

	function resetOptions() {
		displayMode = null;
		callback = null;
		redirectUrl = null;
		screen = null;
		email = null;
		messageId = null;
		hideFbLinking = false;
        layout = false;
		hideLoadingDialog = false;
		reauthenticate = false;
		openInNewWindow = false;
		rtEvent = null;
	}

    function getPageUrl() {
        if (!redirectUrl)
            redirectUrl = top.location.href.toString();

        var urlBase = "";
        switch (screen) {
	        case "signup":
		        urlBase = signupBaseUrl;
	            break;
	        case "signin":
            default:
                urlBase = signinBaseUrl;
        }

        var params = { u : redirectUrl, d : displayMode };
        if (email)
            params.username = email;
        if (messageId)
            params.m = messageId;
        if (source)
            params.t = source;
        if (fbAccessToken)
            params.ft = fbAccessToken;
        if (sourcePage)
            params.s = sourcePage;
        if (layout)
            params.fl = layout;
        if (reauthenticate)
            params.f = 1;
        if (rtEvent) {
        	var currTime = Math.floor((new Date()).getTime() * 0.001 - pageStartTime) + serverStartTime;
            params.rt = HZ.utils.Links.base64Encode(currTime + "," + rtEvent);
        }
        var url = urlBase + '/' + getQueryString(params);

        return url;
    }

    function loginRedirect() {
        var destUrl = getPageUrl();
        
        if (openInNewWindow) {
            window.open(destUrl);
        }
        else {
        	top.location = destUrl;
        }
    }

    function screenRedirect() {
    	window.location = getPageUrl();
    }

    function loginDialog() {
    	HZ.auth.LoginWrapperDialog.show(getPageUrl(), (typeof callback == "function") ? callback : null, 480, 480);
    }
	
    // currently only shown for FB signups
    function newUserWelcomeDialog() {
		var successDialogBody = HZ.signup.newPostSignup.init(
			function() {
				HZ.auth.Manager.loginComplete();
			}, 
			function() {
				HZ.ui.yamdi.Common.hideAllDialogs();
				HZ.ui.yamdi.Common.loading("Please wait..."); // prevent user from clicking anything else
				HZ.ajaz.Services.proSignup(function() {
					var createUrl = HZ.auth.Manager.getCreateProProfileUrl();
					top.location = createUrl;
				});
			}
		);

        HZ.ui.yamdi.Common.hideAllDialogs(); // make sure this is the only dialog being shown
        var userTypesDlg = new HZ.ui.yamdi.Dialog();
        userTypesDlg.init({
                title: '',
                dialogClassName: 'userTypesDialog',
                controls: []
        });
		userTypesDlg.setBody(successDialogBody);
		HZ.ui.Yamdi.show(userTypesDlg);
    }

    function loadOptions(options) {
    	options = options || {};

    	if (!isMobile) {
        	if (!displayMode)
            	displayMode = "web";
            if (options.displayMode)
            	displayMode = options.displayMode;
    	} else {
        	displayMode = "mobile";
    	}

        if (options.callback)
            callback = options.callback;

        if (options.redirectUrl)
            redirectUrl = options.redirectUrl;

        if (options.screen)
            screen = options.screen;

        if (options.email)
            email = options.email;

        if (options.messageId)
            messageId = options.messageId;

        if (options.source)
            source = options.source;

        if (source && !signupSource)
            signupSource = source;

        if (options.hideFbLinking)
        	hideFbLinking = options.hideFbLinking;

    	if (options.layout)
        	layout = options.layout;

    	if (options.hideLoadingDialog)
        	hideLoadingDialog = options.hideLoadingDialog;
    	
    	if (options.reauthenticate)
    		reauthenticate = options.reauthenticate;

		if (options.openInNewWindow)
			openInNewWindow = options.openInNewWindow;

		if (options.rtEvent)
			rtEvent = options.rtEvent;
    }

    function handleFbAuthSuccess() {
		if (HZ.sns.JsSdk.getFbAccessToken()) {
			handleFbLoginForAuthorizedUser();
		}
    }
	
	function trkSignupConversion() {
		// track user creation in GA
		_gaq.push(['_trackEvent', 'LoginDialog', 'SignUp', signupLabel]);
		HZ.utils.Gtm.pushData('sign_up');
	}

    function handleFbLoginForAuthorizedUser() {
        if (!hideLoadingDialog) {
			// show loading screen...
	    	HZ.ui.yamdi.Common.hideAllDialogs();
			HZ.ui.yamdi.Common.loading(_hgt("Connecting with Facebook..."));
        }
		
		if (!redirectUrl)
			redirectUrl = top.location.href;
        
		HZ.ajaz.Services.fbSignUp(function(response) {
			if (response && response.success) {
				userId = response.uid;
				var sUrl = false;
				if (response[HZ.ajaz.Authorize.JSON_KEY_REDIRECT_URL])
					redirectUrl = response[HZ.ajaz.Authorize.JSON_KEY_REDIRECT_URL];
				if (response[HZ.ajaz.Authorize.JSON_KEY_CREATE_PRO_PROFILE_URL])
					createProProfileUrl = response[HZ.ajaz.Authorize.JSON_KEY_CREATE_PRO_PROFILE_URL];
				if (response[HZ.ajaz.Authorize.JSON_KEY_SURL])
					sUrl = response[HZ.ajaz.Authorize.JSON_KEY_SURL];
			
				if (response.newUser) {
					userCreated = true;
					trkSignupConversion();
				}
				else {
					HZ.utils.Gtm.pushData('sign_in');
				}
				
				var fbSignupComplete = function() {
					if (response.newUser && displayMode != "mobile" && showFbWelcome) {
						// show welcome dialog to new users (new dialog will automatically hide loading screen)
						newUserWelcomeDialog();
					}
					else {
						if (!hideLoadingDialog) {
							// hide loading screen
							HZ.ui.yamdi.Common.hideAllDialogs();
						}
						HZ.auth.Manager.loginComplete();
					}
				};
				
				if (sUrl)
					HZ.ajaz.Services.setSession(sUrl, fbSignupComplete);
				else
					fbSignupComplete();
			}
			else if (response && response.error == 7 && !hideFbLinking) {
				// redirect user to the proper sign-in dialog
				email = response.email;
				screen = "signin";
				messageId = 1;
				fbAccessToken = HZ.sns.JsSdk.getFbAccessToken();
				screenRedirect();
			}
			else {
				if (!hideLoadingDialog) {
					// hide loading screen
					HZ.ui.yamdi.Common.hideAllDialogs();

					// ask user to contact support if they encounter issues logging in
					HZ.ui.yamdi.Common.alert(_hgt("We're sorry, please refresh and try again!"), 
						_hgt("We're sorry, but we encountered an unexpected issue - likely this page has timed out due to inactivity.  " +
							 "Please refresh this page and try again.<br/><br/>If you continue to have trouble logging in please contact us at {supportUrl} for assistance.",
							{'supportUrl' : supportUrl}));
				}
			}
		},
		redirectUrl,
		false,
		reauthenticate
		);
    }

    function handleFbAuthFailure() {
        if (typeof callback == "function") {
            callback();
        }
    }

    /**
     * Similar to HZ.auth.Manager.fbLogin, except that the user should already be logged into FB and have
     * authorized the Houzz app.  HZ.sns.JsSdk should already be initialized and have a valid accessToken.
     */
    this.fbLoginAuthorizedUser = function(options) {
        if (!options) {
            options = { hideFbLinking : true };
        }
    	loadOptions(options);

        if (typeof FB == "undefined") {
            return;  // can't do anything if FB lib failed to load
        }

        handleFbLoginForAuthorizedUser();
    };

    /**
     * FB Login / Signup - perform FB auth and either login an existing user or sign-up a new user.
     * This method respects most of the options available for the login method below. 
	 * 
     * Note that the new user welcome dialog is shown after a user is successfully created (on non-web
     * it will display as a page).
	 * 
	 * Note that this method also supports the optional "fbNonce" parameter; this is passed to FB on
	 * reauthentication flows to verify the retrieved access token.
	 * 
	 * If this method is called before the FB lib is loaded (by calling HZ.sns.JsSdk.loadOnDocumentReady)
	 * then the browser will likely block FB's login popup.  Please call HZ.auth.Manager.fbLoginLazyLoad
	 * sometime before the user is expected to trigger this method through an onclick handler.
     */
    this.fbLogin = function(options) {
        loadOptions(options);
        
        var params = false;
        if (options.reauthenticate) {
            params = {auth_type:'reauthenticate'};

            if (options.fbNonce)
                params.auth_nonce = options.fbNonce;
        }
		if (defaultFbLoginScope === false)
			defaultFbLoginScope = "email,publish_actions";
    	HZ.sns.JsSdk.requestFbAuth(defaultFbLoginScope, handleFbAuthSuccess, handleFbAuthFailure, false, params);
    };
	
	/**
	 * Perform an inline email signup - use this on custom signup flows that do not use
	 * the normal flow triggered by calling the login() or signup() methods in this module.
	 * 
	 * The callback will be triggered after the flow is complete, called with a single
	 * parameter to indicate successful account creation.  The client must then handle the
	 * redirect URL appropriately (obtain by calling: HZ.auth.Manager.getRedirectUrl()).
	 * If the signup was not successful but the redirect URL is set then the client should
	 * redirect immediately.  Otherwise the redirect can be handled as part of the intended
	 * flow.
	 */
	this.emailSignup = function(username, password, email, sourceLink, captchaChallenge, captchaResp, redirect, _callback) {
		callback = _callback;
		HZ.ajaz.Services.signup(username, password, email, sourceLink, captchaChallenge, captchaResp, redirect, handleSignupResponse);
	};
	
	function handleSignupResponse(response) {
		var success = false;
		var sUrl = false;
		redirectUrl = false;
		if (response && response[HZ.ajaz.Authorize.JSON_KEY_REDIRECT_URL]) {
			// store redirect url to send user to after flow is complete; relevant even if signup failed
			redirectUrl = response[HZ.ajaz.Authorize.JSON_KEY_REDIRECT_URL];
		}
		if (response && response.success && response.success == "true") {
			if (response[HZ.ajaz.Authorize.JSON_KEY_CREATE_PRO_PROFILE_URL])
				createProProfileUrl = response[HZ.ajaz.Authorize.JSON_KEY_CREATE_PRO_PROFILE_URL];
			if (response[HZ.ajaz.Authorize.JSON_KEY_SURL])
				sUrl = response[HZ.ajaz.Authorize.JSON_KEY_SURL];
			if (response.newUser) {
				userCreated = true;
				trkSignupConversion();
			}

			success = true;
		}
		else {
			errMsg = _hgt("We're sorry, but an unexpected error has occurred.  Please try again."); // default msg
			if (response && response["errorMessage"]) {
				errMsg = response["errorMessage"];
			}
		}
		var invokeCallback = function() {
			if (typeof callback == "function") {
				callback(success);
			}
		};
		if (sUrl) {
			HZ.ajaz.Services.setSession(sUrl, invokeCallback);
		}
		else
			invokeCallback();
	}
	
	/**
	 * see fbLogin for details
	 */
	this.fbLoginLazyLoad = function() {
		HZ.sns.JsSdk.loadOnDocumentReady();
	};

    /**
     * Houzz Signin / Signup
     * Initiate a sign-in or sign-up flow; the following options are supported:
     * callback : callback to be triggered after flow is complete; note that this is really only for unsuccessful 
     *            attempts - when login is successful the user is redirected or the page is reloaded
     * screen : "signin" or "signup"
     * displayMode : "web", "dialog", or "mobile" (note that mobile is forced if the user-agent is detected to be mobile server-side)
     * redirectUrl : page the user should be redirected to after a successful login
     * email : email address to pre-fill into the form
     * messageId : currently only recognized by signup; refer to SignupResponse for details
     * source : source id for tracking signup links
     * hideFbLinking : if true (default is false), a user attempting an FB login/signup will be prompted to link an
     *                 existing account with a matching email and/or FB uid.  Otherwise, the FB login will
     *                 fail silently.
     * layout : force a particular page layout (only some are supported, refer to the page code docs for details)
     * hideLoadingDialog : if true (default is false), don't block the page with a modal loading dialog when performing a FB login
     * reauthenticate : applies only to signin - if true (default is false), user is forced to reauthenticate
     * openInNewWindow : if true (default is false) the auth related page will be opened in a new window (instead of redirecting the current window)
     * rtEvent :      */
    this.login = function(options) {
		resetOptions();
        loadOptions(options);

        // if user is already logged in, then skip directly to login complete
        if (userId) {
            loginComplete();
            return;
        }

        switch (displayMode) {
            case "dialog":
                loginDialog();
                break;
            case "mobile":
        	case "web":
            	loginRedirect();
        	default:
        }
    };

    /**
     * simple wrapper around HZ.auth.Manager.login
     */
    this.signup = function(_source, _messageId, _redirectUrl, _callback, _options) {
		if (!_redirectUrl)
			_redirectUrl = top.location.href.toString();
		var params = { screen : "signup",  redirectUrl : _redirectUrl, source : _source };
		if (_messageId)
			params.messageId = _messageId;
		if (_callback)
			params.callback = _callback;

		// signup dialog is not supported on IE7
		if (_options && _options.displayMode && _options.displayMode == "dialog" && UIHelper.isIE7)
			_options.displayMode = "web";

		if (_options)
			params = $.extend(params, _options);
		
		HZ.auth.Manager.login(params);
    };

    /**
     * simple wrapper around HZ.auth.Manager.login
     */
    this.signin = function(_messageId, _redirectUrl, _callback) {
		if (!_redirectUrl)
			_redirectUrl = top.location.href.toString();
		var params = { screen : "signin",  redirectUrl : _redirectUrl };
		if (_messageId)
			params.messageId = _messageId;
		if (_callback)
			params.callback = _callback;
		HZ.auth.Manager.login(params);
    };

    // store page init time for tracking
    pageStartTime = (new Date()).getTime() * 0.001;
};



// </script>

window.hzmr.push("siteAuth:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End siteAuth.js  **************/
/************* Start postFbPageDialog.js for locale en-US **************/
try {HZ.ns("HZ.socialShare"),HZ.socialShare.PostFbPageDialog=new function(){function a(){j=$('head meta[property="og:title"]').attr("content"),m=$('head meta[property="og:image"]').attr("content"),k=$('head meta[property="og:description"]').attr("content"),k||(k=""),l=$('head meta[property="og:url"]').attr("content")}function b(){u||(q=new HZ.ui.yamdi.Dialog,r=HZ.ui.InputButtonUtils.createSecondaryInputButton(_hgt("Cancel"),"hzPostToFbPageCancelBtn"),s=HZ.ui.InputButtonUtils.createPrimaryInputButton(_hgt("Post"),"hzPostToFbPagePostBtn"),t=$("<div id='hzPostToFbPageRetryBtn' class='hzBtn fb'><span class='btnText'>"+_hgt("Retry")+"</span></div>"),q.init({title:_hgt("Connect to your Facebook Business Page"),dialogClassName:"postToFbPage",controls:[t,s,r]}),q.setBody("<div id=\"postPane\"><div><textarea id='postMessage' placeholder='"+_hgt("Say something about this...")+"'></textarea></div><div id='postPreview'><div class='imgPreview'></div><div class='txtPreview'></div></div><div id='selectFbPage'>"+_hgt("Posting to:")+'&nbsp;<select></select></div></div><div id="reconnectPane" style="display:none;"><div>'+_hgt('We\'re sorry, but we could not connect to your Facebook Page(s).<br /><br />Please note that both "post on your behalf" and "manage pages" permissions must be granted, and you must be an administrator of your Facebook Page.<br /><br />If the issue persists please contact us at http://support.houzz.com')+"</div></div>"),u=!0)}function c(){var a=$("#selectFbPage select");a.empty(),n&&$.each(n,function(b,c){a.append('<option value="'+c.page_id+'">'+c.name+"</option>")}),o&&"1"!=o&&a.val(o),$("#hzPostToFbPagePostBtn").unbind("click"),$("#hzPostToFbPagePostBtn").click(i),$("#hzPostToFbPageCancelBtn").unbind("click"),$("#hzPostToFbPageCancelBtn").click(function(){HZ.ui.Yamdi.hide(this)}),$("#hzPostToFbPageRetryBtn").unbind("click"),$("#hzPostToFbPageRetryBtn").click(h),e(),$("#postMessage").val("")}function d(a){$.each(["#reconnectPane","#hzPostToFbPageRetryBtn"],function(b,c){$(c).css("display","post"==a?"none":"block")}),$.each(["#postPane","#hzPostToFbPageCancelBtn","#hzPostToFbPagePostBtn"],function(b,c){$(c).css("display","post"==a?"block":"none")})}function e(){$("#postPreview .imgPreview").empty();var a=new Image;a.onload=function(){$(a).addClass(a.complete?a.width>a.height?"landscape":"portrait":"landscape"),$("#postPreview .imgPreview").append(a)},a.src=m,$("#postPreview .txtPreview").empty(),$("#postPreview .txtPreview").html("<div class='title'>"+j+"</div><div class='desc'>"+k+"</div>")}function f(){$("#hzPostToFbPagePostBtn").attr("disabled",!0),$("#hzPostToFbPageCancelBtn").attr("disabled",!0)}function g(){$("#hzPostToFbPagePostBtn").attr("disabled",!1),$("#hzPostToFbPageCancelBtn").attr("disabled",!1)}function h(){HZ.sns.JsSdk.requestFbAuth("manage_pages,publish_stream",function(){HZ.ui.yamdi.Common.hideAllDialogs(),HZ.ui.yamdi.Common.loading("Please wait..."),HZ.ajaz.FbUser.fbGetUserPages(function(a){HZ.ui.yamdi.Common.hideAllDialogs(),a&&a[HZ.ajaz.FbUser.JSON_KEY_PAGES]?"function"==typeof p&&p():HZ.socialShare.PostFbPageDialog.showReconnectDialog(p)})})}function i(){v=$("#selectFbPage select").val(),w=$("#postMessage").val(),f(),HZ.ajaz.FbUser.fbPostToPage(v,w,l,function(a){g(),HZ.ui.Yamdi.hide(this),a&&"true"==a.success||HZ.socialShare.PostFbPageDialog.showReconnectDialog(function(){HZ.socialShare.PostFbPageDialog.post()})})}var j,k,l,m,n=null,o=null,p=null,q=null,r=null,s=null,t=null,u=!1,v=null,w=null;this.show=function(e,f){n=e,o=f,b(),a(),HZ.ui.Yamdi.show(q),c(),d("post")},this.showReconnectDialog=function(a){p=a,b(),HZ.ui.Yamdi.show(q),c(),d("reconnect")},this.post=function(){HZ.ajaz.FbUser.fbGetUserPages(function(a){a&&a[HZ.ajaz.FbUser.JSON_KEY_PAGES]?HZ.socialShare.PostFbPageDialog.show(a[HZ.ajaz.FbUser.JSON_KEY_PAGES],a[HZ.ajaz.FbUser.JSON_KEY_PAGE_ID]):HZ.socialShare.PostFbPageDialog.showReconnectDialog()})},this.installFbPageTabApp=function(){HZ.sns.JsSdk.requestFbAuth("manage_pages,publish_stream",function(){HZ.ui.yamdi.Common.hideAllDialogs(),HZ.ui.yamdi.Common.loading("Please wait..."),HZ.ajaz.FbUser.fbGetUserPages(function(a){HZ.ui.yamdi.Common.hideAllDialogs(),a&&a[HZ.ajaz.FbUser.JSON_KEY_PAGES]?top.location=HZ.ajaz.FbUser.PAGE_TAB_INSTALL:HZ.socialShare.PostFbPageDialog.showReconnectDialog(function(){top.location=HZ.ajaz.FbUser.PAGE_TAB_INSTALL})})})}};

window.hzmr.push("postFbPageDialog:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End postFbPageDialog.js  **************/
/************* Start socialShareBar.js for locale en-US **************/
try {var ShareBar={MIN_WIN_WIDTH:1380,PARKED_TRIGGER:71,FLOAT_TOP:50,PARKED_TOP:0,FLOAT_BAR_WIDTH:80,FORCE_LEFT:!1,FORCE_TABLE:!1,shareBar:null,shareTable:null,pageContent:null,winwidth:null,HAS_RIGHT_SHARE_BAR:!1,MAP_MAIN_CONTENT_WIDTH:0,PAGE_CONTENT_CONTAINER:"#mainContent .container",init:function(){this.shareBar=$("#shareBar"),this.shareTable=$("#shareTable"),this.pageContent=$(this.PAGE_CONTENT_CONTAINER),EventConnector.connect(window,"onresize",this,this.show),EventConnector.connect(window,"onscroll",this,this.reposition),$(".signUpPromoContainer").length>0&&(this.FLOAT_TOP+=110),this.FLOAT_TOP+=56,this.PARKED_TRIGGER-=71,this.show()},show:function(){!this.shareBar||this.FORCE_TABLE?this.shareTable&&this.shareTable.length>0&&this.shareTable.show():(this.winwidth=document.body.clientWidth||window.innerWidth,this.HAS_RIGHT_SHARE_BAR?(this.shareBar.show(),this.winwidth<this.MIN_WIN_WIDTH?this.shareBar.addClass("shareBarRight"):this.shareBar.removeClass("shareBarRight")):this.winwidth<this.MIN_WIN_WIDTH?(this.shareBar.hide(),this.shareTable&&this.shareTable.length>0&&this.shareTable.show()):(this.FORCE_LEFT&&this.forceLeft(),this.shareBar.show(),this.shareTable&&this.shareTable.length>0&&this.shareTable.hide()),this.reposition())},forceLeft:function(){var a=this.pageContent.offset().left;this.shareBar.css("left",a-this.FLOAT_BAR_WIDTH)},reposition:function(){if(this.shareBar){var a=UIHelper.getScrollXY();if(a[1]>this.PARKED_TRIGGER?(this.shareBar.removeClass("parked"),this.shareBar.addClass("float"),this.shareBar.css("top",this.FLOAT_TOP+"px")):(this.shareBar.removeClass("float"),this.shareBar.addClass("parked"),this.shareBar.css("top",this.PARKED_TOP+"px")),this.shareBar.hasClass("parked"))this.shareBar.hasClass("shareBarRight")?(this.shareBar.css("left",""),this.shareBar.css("right",-this.FLOAT_BAR_WIDTH+"px")):this.FORCE_LEFT||this.shareBar.css("left","");else{var b=this.pageContent.offset();this.shareBar.hasClass("shareBarRight")?(this.shareBar.css("left",""),this.shareBar.css("right",this.winwidth-this.MAP_MAIN_CONTENT_WIDTH-b.left-this.FLOAT_BAR_WIDTH+"px")):(this.shareBar.css("left",b.left-this.FLOAT_BAR_WIDTH+"px"),this.shareBar.css("right",""))}}}};

window.hzmr.push("socialShareBar:2059");
} catch (err) {HZ.utils.Logger.sendJsExceptionStackTrace(err)}

/*************  End socialShareBar.js  **************/
