// Get rid of soon....
function MM_openBrWindow(theURL,winName,features) {
	window.open(theURL,winName,features);
	return false;
}

function dropDownRedirect() {
	var i = this.selectedIndex;
	if (i && this.options[i].value)
		location = this.options[i].value + ".aspx";
}

$(function() {

function urlEncode(s) {
  var url = "";
  var x = 0;
  s = s.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < s.length) {
    var match = regex.exec(s.substr(x));
    if (match != null && match.length > 1 && match[1] != "") {
    	url += match[1];
      x += match[1].length;
    } else {
      if (s[x] == " ")
        url += "+";
      else {
        var charCode = s.charCodeAt(x);
        var hexVal = charCode.toString(16);
        url += "%" + ( hexVal.length < 2 ? "0" : "" ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return url;
}

$.fn.wait = function(time, type) {
  time = time || 1000;
  type = type || "fx";
  return this.queue(type, function() {
    var self = this;
    setTimeout(function() { $(self).dequeue(); }, time);
  });
};

	if ( typeof(gallery) !== "undefined" && 1 < gallery.length ) {
		var $thumbs = $( "#thumbs" );
		var $gallery = $( ".gallery" );
		var $preview = $( "#gallery .preview" ).css("opacity", "0.8");

		var plan = $gallery.attr( "title" );
		if (1 == 1 || "3393W" == plan || "2942W" == plan || "2266W" == plan) {
			$thumbs.removeClass("hidden");
			$gallery.removeClass("hidden");
		}

		jQuery.each(gallery, function(index) {
			var imgUrl = this.toLowerCase().replace( "/images/homes/", "http://i.perryhomes.com/" );
			var thumbnailHtml = "<img class=\"thumbs\" src=\"" + imgUrl + "?33\" />";
			$thumbs.append( $( "<a href=\"" + imgUrl + "?800\">" + ( 5 <= index ? "" : thumbnailHtml ) + "</a>" ) );
			$preview.append( $( "<a rel=\"" + index + "\">" + thumbnailHtml + "</a>" ) );
		});

		if ($.fn.overlay && $.fn.gallery) {
			var $triggers = $("a", $thumbs).overlay({
				oneInstance: true,
				target: "#gallery",
				closeOnClick: false,
				expose: "#f1f1f1",
				onLoad: function(event) { $( "#flash-banner-movie" ).hide(); }
			}).gallery({ 
				autohide: false,
				speed: 900 ,
				template: "<div class=\"disclaimer\">Representative photo. Features and specifications may vary by community.</div> <strong>Plan " + plan + "</strong> <span>Image ${index} of ${total}</span>"
			});

			$( "a", $preview).click( function(e) { 
				e.preventDefault();
				var $trigger = $triggers.eq( $(this).attr( "rel" ) );
				if ( $trigger ) { 
					$trigger.isDefaultPrevented = function() { return true; };
					$trigger.overlay().load( $trigger );
				}
			});
		}
	}

	var banners = {
		"find-your-home": "excited",
		"move-to-texas": "excited",
		"getting-started": "first_time",
		"build-your-home": "build",
		"finance-your-home": "crestmark-v3",
		"customer-care": "customercare",
		"careers": "team",
		"real-estate-professionals": "satisfy_clients",
		"contact-us": "questions",
		"visit-us": "questions",
		"about": "trust",
		"my-account": "myfavorite"
	};

	var path = location.pathname.substring(1).toLowerCase();

	// Flash Banners: swfobject.embedSWF( swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes )
	$("#flash-search-map").each( function() {
		var params = { play: "true", loop: "true", wmode: "Transparent" };
		swfobject.embedSWF( "/images/main/2122_map_home.swf", this.id, "235", "259", "8.0.0", false, {}, params, { id: this.id + "-movie" } );
	});

	$("#flash-map").each( function() {
		var params = { play: "true", loop: "true" };
		swfobject.embedSWF( "/images/flash/2122_map.swf", this.id, "642", "391", "8.0.0", false, {}, params, { id: this.id + "-movie" } );
	});

	function flashBanner() {
		if ( !path )		
			return false;

		var branch = path.split("/")[ 0 ].replace( ".aspx", "" );

		return banners[ branch ] ? banners[ branch ] : false;
	}

	$("#flash-banner").each( function() {
		var $this = $(this);
		var title = $this.attr( "title" ) || flashBanner();
		if ( title ) {
			var params = { play: "true", loop: "true" };
			swfobject.embedSWF( "/images/flash/" + title + ".swf", this.id, "851", "185", "8.0.0", false, {}, params, { id: this.id + "-movie" } );
			$this.removeAttr("title");
		}
	});

	$("select.redirect").change(dropDownRedirect);

	$("a[rel='external2']").click(function(event) {
		window.open($(this).attr("href"));
		event.preventDefault();
	});

	$("a.virtual-tour").one("click", function() { 
		$( "#flash-banner-movie" ).hide();
	}).colorbox( {
		innerWidth: 765, 
		innerHeight: 600, 
		fixedWidth: 800,
		fixedHeight: 655,
		iframe: true 
	});
//	}).colorbox( {fixedWidth: 750 + 50, fixedHeight: 575 + 70, iframe: true } );

	$("a[target='velaro-chat']").unbind("click").removeAttr("onclick").bind("click", function(event) {
		window.open($(this).attr("href"), $(this).attr("target").replace("-", ""), "width=400,height=450,titlebar=no,toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=yes,replace=no");
		event.preventDefault();
	});

	$("a[target='map']").unbind("click").bind("click", function(event) {
		window.open($(this).attr("href"), $(this).attr("target").replace("-", ""), "width=750,height=550,titlebar=no,toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=yes,replace=no");
		event.preventDefault();
	});

	$(".side-banners > li").hover(
		function(event) { $(this).stop(true, true).fadeTo("slow", 0.6); },
		function(event) { $(this).stop(true, true).fadeTo("slow", 1.0); }
	);

	$(".hover-fade").hover(
		function(event) { $(this).stop(true, true).fadeTo("slow", 0.6); },
		function(event) { $(this).stop(true, true).fadeTo("slow", 1.0); }
	);

	// Google Analytics Campaigns
	function utmClick(event) {
		var href = $(this).attr("href");
		var campaign = $(this).data("utm_campaign").replace(/ /g, "-").toLowerCase();
		var medium = $(this).data("utm_medium");

		event.preventDefault();
		location = href + ( -1 != href.indexOf("?") ? "&" : "?" ) + "utm_source=phcom&utm_medium=" + medium + "&utm_campaign=" + campaign;
	}

	$(".side-banners > li[title]").each(function() {
		$(this).find("a").data("utm_medium", "side-banner").data("utm_campaign", $(this).attr("title")).click(utmClick).end().removeAttr("title");
	});

	$(".blurb-area > .content-blurb[title]").each(function() {
		$(this).find("a").data("utm_medium", "featured").data("utm_campaign", $(this).attr("title")).click(utmClick).end().removeAttr("title");
	});

	if (path) {
		setTimeout( function() { $( "a[href$='" + path + "']" ).addClass("selected") }, 20 );
	}

	$( ".floorplan[rel]" ).overlay( { effect: "apple", onLoad: function(event) { $( "#flash-banner-movie" ).hide(); } /* , onBeforeClose: function(event) { $( "#flash-banner-movie" ).show(); } */ } );

	// Turn on caching for AJAX requests, needing for getScript
	$.ajaxSetup( { 
		cache: true
	} );

	if ($.validator) {
		jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
			phone_number = phone_number.replace(/\s+/g, ""); 
			return this.optional(element) || ( phone_number.length >= 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/) );
		}, "Please specify a valid phone number");
	}

		var $usp = $("#section-usp-banner:not(:empty)").each( function(){
			var text = $(this).find("div").text();
			if (text && 0 < text.length) {
				setTimeout( function() {
					var $usp = $("#section-image").prepend("<div class=\"usp2 \">" + text + "</div>").find("div").css("padding-top", function(index, value) { return ( 144 - $(this).innerHeight() ) / 2 + "px"; }).end();
					var fadeOut = true; 
					$("img", $usp)[fadeOut ? "fadeOut" : "fadeIn" ]("slow", function() { fadeOut = !fadeOut; } );
					setInterval( function() { 
							$("img", $usp)[fadeOut ? "fadeOut" : "fadeIn" ]("slow", function() { fadeOut = !fadeOut; } ); 
							$("div", $usp)[!fadeOut ? "fadeOut" : "fadeIn" ]("fast");
						}, 4000);
				}, 2000);
			}
		});

		$(".ups-row").show();


	if ($("#phnet.phnet").length) {
	}

	$(".printit").click(function(e) {
		var w = 680, h = 750;
		var a = window.open('','','width='+w+',height='+h + ',scrollbars=yes, resizeable=no');
		//a.document.open("text/html");
		a.document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><link id=\"metaCssFile\" type=\"text/css\" rel=\"stylesheet\" href=\"/CMSPages/GetCSS.aspx?stylesheetname=Perry\" /></head><body onload=\"window.print()\">");
		a.document.write("<table width=\"100%\"><tr><td valign=\"bottom\" align=\"left\" class=\"MainTableBorderBottom\">");
		a.document.write("<img src=\"/images/logo.gif\">");
		a.document.write("</td></tr></table>");
		a.document.write("<table width=\"100%\"><tr><td class=\"MainTableBorderBottom\">");
		a.document.write($("#printit").html());
		a.document.write("</td></tr></table>");
		a.document.write("</body></html>");
		//a.document.close();
		setTimeout(function() { a.print(); }, 2000)
		//a.print();
		e.preventDefault();
	});
});