var g_playFlashGirl=true;
var g_pid;
var g_NavXml = "Data.xml"; //Default Navigation XML Filename
var photocount = 0;
var videocount = 0;
var newscount = 0;
var specialcount = 0;
var linkcount = 0;
var documentcount = 0;
var g_pageTracker;

//Called For Every Page
function Init()
{
	var v = getIEVersion();
	if( (v != -1) && (v < 7) ) {window.location="/prereq/getie.html";}

    //Launch Flash Map if [find] is Clicked
	$("a[rel='find']").click(function(e)
	{
		e.preventDefault(); 
		ShowFlashMap();
		return false;
	});

	//Init Google Analytics
	$(document).ready(function()
	{	
		try 
		{
			//g_pageTracker = _gat._getTracker("UA-633377-1");  
			//g_pageTracker._setDomainName(".aspensquare.com");
			g_pageTracker = _gat._getTracker("UA-633377-22");  
			g_pageTracker._trackPageview();
		} 
		catch(err) {}
	});
}

function InitAspenHome()
{    
    $(document).ready(function()
    {
        Init();
        
		//Background Image
		var num = Math.floor(Math.random() * 3) + 1;
		$("#hometop").css("background-image", "url(../HomeImages/" + num.toString() + ".jpg)");
		//Pictures
		var pic1 = Math.floor(Math.random() * 3) + 1;
		$("#picture1").css("background-image", "url(../HomeImages/pic1/" + pic1.toString() + ".jpg)");
		
		var pic2 = Math.floor(Math.random() * 3) + 1;
		$("#picture2").css("background-image", "url(../HomeImages/pic2/" + pic2.toString() + ".jpg)");
		
		var pic3 = Math.floor(Math.random() * 3) + 1;
		$("#picture3").css("background-image", "url(../HomeImages/pic3/" + pic3.toString() + ".jpg)");
		
		
		
		//Embed Flash
		swfobject.embedSWF("/Flash/Map/Flash_Map.swf", "flashMap", 600, 284, "9.0.45.0", "/Flash/expressInstall.swf", {playmovie: true}, {wmode: "transparent"});
		
		//Load Featured Communities
		$.ajax({ type: "GET",
            url: "/WCF/Aspen.svc/GetFeaturedCom",
            contentType: "application/json",                 //Of Request
            dataType: "json",                                //Return Type Expected
            cache: true,
            success: function(d) 
            { 
                var str = "";
                for(var i = 0; i < d.length; i++)
                {
			  var ix  = d[i].URL.lastIndexOf("/", d[i].URL.length-2); //2nd to Last "/"
			  var src = d[i].URL.substring(ix+1, d[i].URL.length-1);  //Last Folder
			  src = src.replace(/-/g, "") + "_thumb.jpg";
                    str += "<li><a href=\"" + d[i].URL + "\"><img src=\"propertyThumbs/" + src + "\"/><br style=\"clr\"/><span>" + d[i].Text + "</span></a></li>";
                }
                $("#ftrList").html(str);
            }
        });
        
    });
}


function InitPropPg()
{
    Init();
    
	//See If We Have Cookie Saying To Not Play Flash Girl. If Not Create One So She Plays Only Once.
	if( $.cookie("playFlashGirl") == null )
	{
		$.cookie("playFlashGirl", 0, {path: '/', expires: 1} );
	}
	else {g_playFlashGirl=false;}

	//Check Cookie For Last PropertyID & Set Current PID. Special won't play if current pid is stored in cookie.
	var bShowSpecial = ($.cookie("pid") == null || $.cookie("pid") != g_pid) ? true : false;
	$.cookie("pid", g_pid, {path: '/', expires: 1} );


	//Embed Flash Nav & Specials Banner & Property Title
	swfobject.embedSWF("/Flash/PropertyTitle/titlebanner.swf", "propertytitle", 590, 90, "9.0.45.0", "/Flash/expressInstall.swf", flashTitleVars, {wmode: "transparent"} );
	swfobject.embedSWF("/Flash/Nav/smallflashnav.swf", "flashNav", 710, 210, "9.0.45.0", "/Flash/expressInstall.swf", {xmlFile: g_NavXml}, {wmode: "opaque"} );
	if( bShowSpecial && (flashSpecialVars) && flashSpecialVars.apartmentText != null && flashSpecialVars.apartmentText != "")
	{
		swfobject.embedSWF("/Flash/Special/specialpopup.swf", "specialbanner", 600, 320, "9.0.45.0", "/Flash/expressInstall.swf", flashSpecialVars, {wmode: "transparent"} );
	}

	

	//Launch Photo Gallery If [pg] Link Is Clicked
	$("a[rel='pg']").click(function(e)
	{
		e.preventDefault(); 
		ShowPhotoGallery();
		try 
		{

			g_pageTracker._trackPageview(GetPageFolder() + "photogallery.html");
		} 
		catch(err) {}

		return false;
	});
	
	//Launch Video Gallery If [vg] Link Is Clicked
	$("a[rel='vg']").click(function(e)
	{
		e.preventDefault(); 
		ShowVideoGallery(); 
		try 
		{
			g_pageTracker._trackPageview(GetPageFolder() + "videogallery.html");
		} 
		catch(err) {}

		return false;
	});
	
	//Wire Link Exchange Form
	$("a[rel='linkex']").click(function(e)
	{
		e.preventDefault();
		var a = e.target;
		if(a.nodeName.toLowerCase() != "a")
		{
			a = $(a).closest("a");
		}
		a = $(a);

		ShowDialog( a[0].href, 723, 418, true, '', 5000);
		try 
		{
			g_pageTracker._trackPageview(GetPageFolder() + "linkex.aspx");
		} 
		catch(err) {}

		return false;
	});


	//Wire Contact Form
	$("a[rel='contact']").click(function(e)
	{
		e.preventDefault();
		ShowDialog( $(e.target)[0].href, 723, 418, true, '', 5000);
		try 
		{
			g_pageTracker._trackPageview(GetPageFolder() + "contact.aspx");
		} 
		catch(err) {}

		return false;
	});
	

	//Wire Spanish Form
      $("#spanishContactLnk").click(function(e)

      {
            e.preventDefault();
            ShowDialog( $(e.target)[0].href, 750, 620, true, '', 5000);
            try
            {
                  g_pageTracker._trackPageview(GetPageFolder() + "spanish.aspx");
            }
            catch(err) {}
            return false;
      });
	  
	//Wire Rent Now Form (Only Works If Link Visible)
	$("a[rel='rentnow']").click(function(e)
	{
		e.preventDefault();
		ShowDialog( $(e.target)[0].href, 713, 430, true, '', 5000);
		try 
		{
			g_pageTracker._trackPageview(GetPageFolder() + "rentnow.aspx");
		} 
		catch(err) {}

		return false;
	});
	
	//Wire Directions
	$("a[rel='directions']").click(function(e)
	{
		e.preventDefault(); 
		ShowDialog('directions.html', 743, 470, true);
		try 
		{
			g_pageTracker._trackPageview(GetPageFolder() + "directions.html");
		} 
		catch(err) {}

		return false;
	});
	
	if (videocount < 1) { $ ("#navVideoGallery").remove(); }
	if (photocount < 1) { $ ("#navPhotoGallery").remove(); }
	if (newscount < 1) { $ ("#navNews").remove(); }
	if (specialcount < 1) { $ ("#navSpecials").remove(); }
	//if (documentcount < 1) { $ ("#navRentalForms").remove(); }
	if (linkcount < 1) { $ ("#navFriends").remove(); }
}

function InitState()
{
	$(document).ready(function()	   
    {
        Init();
		var num = Math.floor(Math.random() * 3) + 1;
		$("#companybanner").css("background-image", "url(CSS/Img/Company/" + "companybanner" + num.toString() + ".jpg)");
        var num = Math.floor(Math.random() * 3) + 1;
		$("#careersbanner").css("background-image", "url(CSS/Img/Careers/" + "careersbanner" + num.toString() + ".jpg)");
		var num = Math.floor(Math.random() * 3) + 1;
		$("#statebanner").css("background-image", "url(Img/" + "banner" + num.toString() + ".jpg)");
		var num2 = Math.floor(Math.random() * 3) + 1;
		$("#rightstateimage").css("background-image", "url(Img/" + num2.toString() + ".jpg)");
		var pic1 = Math.floor(Math.random() * 3) + 1;
		$("#smallpicture1").css("background-image", "url(/homeimages/smallpic1/" + pic1.toString() + ".jpg)");
		var pic2 = Math.floor(Math.random() * 3) + 1;
		$("#smallpicture2").css("background-image", "url(/homeimages/smallpic2/" + pic2.toString() + ".jpg)");
		var pic3 = Math.floor(Math.random() * 3) + 1;
		$("#smallpicture3").css("background-image", "url(/homeimages/smallpic3/" + pic3.toString() + ".jpg)");
		
		swfobject.embedSWF("/Flash/Title/statecitytitle.swf", "title", 575, 150, "9.0.45.0", "/Flash/expressInstall.swf", titleVars, {wmode: "transparent"} );
		
		$("#property li").click(function(e)
		{ 
			$("#property li").unbind();
			var a = $("a", $(e.currentTarget));
			window.location = a[0].href;
		});
	});
}

function InitCity()
{
	$(document).ready(function()	   
    {
        Init();
        
		var num = Math.floor(Math.random() * 3) + 1;
		$("#statebanner").css("background-image", "url(../Img/" + "banner" + num.toString() + ".jpg)");
		var num2 = Math.floor(Math.random() * 3) + 1;
		$("#rightstateimage").css("background-image", "url(../Img/" + num2.toString() + ".jpg)");
		var pic1 = Math.floor(Math.random() * 3) + 1;
		$("#smallpicture1").css("background-image", "url(/homeimages/smallpic1/" + pic1.toString() + ".jpg)");
		var pic2 = Math.floor(Math.random() * 3) + 1;
		$("#smallpicture2").css("background-image", "url(/homeimages/smallpic2/" + pic2.toString() + ".jpg)");
		var pic3 = Math.floor(Math.random() * 3) + 1;
		$("#smallpicture3").css("background-image", "url(/homeimages/smallpic3/" + pic3.toString() + ".jpg)");
		
		swfobject.embedSWF("/Flash/Title/statecitytitle.swf", "title", 700, 150, "9.0.45.0", "/Flash/expressInstall.swf", titleVars, {wmode: "transparent"} );
		
		$("#property li").click(function(e)
		{ 
			$("#property li").unbind();
			var a = $("a", $(e.currentTarget));
			window.location = a[0].href;
		});
	});
}



function InitPropHome()
{
	$(document).ready(function()
    {
		InitPropPg();
	
		//Embed Flash Girl
		var vars = { number: 7, playmovie: g_playFlashGirl };
		if (isCollege)
		{
			swfobject.embedSWF("/Flash/College/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
		else 
		{
			swfobject.embedSWF("/Flash/Corporate/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
			//swfobject.embedSWF("/Flash/Corporate/InnerPageVideos.swf", "flashGIrl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", {}, {wmode: "opaque"});
		}
		swfobject.embedSWF("/Flash/3Photos/3photos.swf", "threephotos", 440, 187, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});

		//Handle Body Link Clicks
		$("#centercol a").click(OnClickExtLink);
		
	});
}

function InitFriends()
{
	$(document).ready(function()
	{
		InitPropPg();
		
		//Handle Ext Links
		$("#centercol div.links a").click(OnClickExtLink);
	});
}


function InitLinkToUs()
{
	$(document).ready(function()
	{
		InitPropPg();
		
		//Handle Ext Links
		$("#centercol div.links a").click(OnClickExtLink);
	});
}





function InitFloorPlans()
{    
    $(document).ready(function()
    {
		InitPropPg();
		
		//Embed Flash Girl
		var vars = { number: 2, playmovie: g_playFlashGirl };
		if (isCollege)
		{
			swfobject.embedSWF("/Flash/College/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
		else 
		{
			swfobject.embedSWF("/Flash/Corporate/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
		
		//Wire Floorplan Table Links
        $("#fpTbl a").click(function(e)
        {
            var a = $(e.target);
            var divID = "#fp_" + a.attr("rel");  //Get ID Of Floorplan's Div Content
            var divFP = $(divID).html();
            
            ShowHTMLDlg("dlg", 600, 520, divFP, false, "Floorplan", 3000, "#fff");
		try 
		{
			g_pageTracker._trackPageview(GetPageFolder() + "floorplanpopup.html");
		} 
		catch(err) {}

        });
        
        

    });
}

function InitAmenities()
{    
    $(document).ready(function()
    {
		InitPropPg();
		
		//Embed Flash Girl
		var vars = { number: 1, playmovie: g_playFlashGirl };
		if (isCollege)
		{
			swfobject.embedSWF("/Flash/College/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
		else 
		{
			swfobject.embedSWF("/Flash/Corporate/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
    });
}

function InitArea()
{    
    $(document).ready(function()
    {
		InitPropPg();
		
		//Embed Flash Girl
		var vars = { number: 4, playmovie: g_playFlashGirl };
		if (isCollege)
		{
			swfobject.embedSWF("/Flash/College/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
		else 
		{
			swfobject.embedSWF("/Flash/Corporate/AspenInnerpageVideo.swf", "flashGirl", 275, 260, "9.0.45.0", "/Flash/expressInstall.swf", vars, {wmode: "opaque"});
		}
    });
}


function InitRentalForms()
{    
    $(document).ready(function()
    {
		InitPropPg();
		
		//Embed Flash
		swfobject.embedSWF("/Flash/Banners/money.swf", "flashMoney", 180, 200, "9.0.45.0", "/Flash/expressInstall.swf", {}, {wmode: "opaque"});

		//Handle Ext Links
		$("#centercol ul.rentalForms a").click(OnClickExtLink);
    });
}


function InitNews()
{    
    $(document).ready(function()
    {
		InitPropPg();
		
		//Embed Flash
		swfobject.embedSWF("/Flash/Banners/money.swf", "flashMoney", 180, 200, "9.0.45.0", "/Flash/expressInstall.swf", {}, {wmode: "opaque"});

		//Handle Ext Links
		$("#centercol ul.news a").click(OnClickExtLink);

    });
}

function InitSpecials()
{
	if(flashSpecialVars.apartmentText=="") {$("#showspecial").remove();}
	
    $(document).ready(function()
    {
	
		InitPropPg();
		
		//Embed Flash
		swfobject.embedSWF("/Flash/Banners/moneynolink.swf", "flashMoney", 180, 200, "9.0.45.0", "/Flash/expressInstall.swf", {}, {wmode: "opaque"});
		
		
		$("#showspecial").click(function()
		{
			var ph = $("#specialPlaceholder");
			if(!specialVisible)
			{
				ph.html("<div id=\"specialbanner\"></div>");
				swfobject.embedSWF("/Flash/Special/specialpopup.swf", "specialbanner", 610, 480, "9.0.45.0", "/Flash/expressInstall.swf", flashSpecialVars, {wmode: "transparent"} );
			}
			else
			{
				ph.html("");
			}
			specialVisible =  !specialVisible;
		});
		
		//Handle Ext Links
		$("#centercol ul.specials a").click(OnClickExtLink);
    });
}


function printElement(elStr)
{
    printID++; //Need this because FF is Retarded. Because Of A Bug It Needs a Unique ID for The IFrame Each Time Or It Won't Print.
    
    var el = $("#" + elStr)[0];
    
    //Remove Printing Iframe If Already Exists
    $("#printIFrame").remove();
   
    var html = "<html><head>";

    if (document.getElementsByTagName != null)
    {
        var headTags = document.getElementsByTagName("head");
        if (headTags.length > 0) html += headTags[0].innerHTML;
    }
    html += "</head><body style=\"background:#fff\">";

    html += el.innerHTML;
    html += "</body></html>";

     
    //Create Iframe To Hold Printing Contents. Display None Won't Work In FF
    var id = "printIFrame" + printID;
    $("<iframe id=\"" + id + "\" name=\"" + id + "\" style=\"width:0;height:0;border:none;\"></iframe>").appendTo($("body"));
    
    //Get Iframe's Document
    var iFrame = document.getElementById(id);
    var doc = iFrame.contentDocument;
    if (doc == undefined || doc == null) {doc = iFrame.contentWindow.document;}
    
    //Write HTML To Iframe's Document
    doc.open();
    doc.write(html);
    doc.close();
        
    window.frames[id].print();
    return false;
}

function ShowFlashMap()
{
    ShowHTMLDlg("dlg", 600, 284, "<div style=\"background:#eee\"><div id=\"flashFM\"</div></div>", false, "Find an Apartment", 3000);

    var params = { allowFullScreen: "true", loop: "false", menu: "false", quality: "high" };
    swfobject.embedSWF("/Flash/Map/findapartment.swf", "flashFM", 600, 284, "9.0.45.0", "/Flash/expressInstall.swf", {playmovie: true}, {wmode: "transparent"});
    //swfobject.embedSWF("/Flash/Map/Flash_Map.swf", "flashFM", 600, 284, "9.0.45.0", "/Flash/expressInstall.swf", {playmovie: true}, {wmode: "transparent"});
}



function ShowVideoGallery()
{
    ShowHTMLDlg("dlg", 871, 406, "<div id=\"flashVG\"></div>", false, "Video Gallery", 3000);

    var params = { allowFullScreen: "true", loop: "false", menu: "false", quality: "high" };
    swfobject.embedSWF("/Flash/VideoGallery/VideoGallery.swf", "flashVG", 871, 406, "9.0.45.0", "/Flash/expressInstall.swf", {}, params);
}

function ShowPhotoGallery()
{
    ShowHTMLDlg("dlg", 950, 550, "<div id=\"flashPG\"></div>", false, "Photo Gallery", 3000);

    var params = { allowFullScreen: "true", scale: "scale", menu: "false"};
    swfobject.embedSWF("/Flash/PhotoGallery/photogallery.swf", "flashPG", 950, 550, "9.0.45.0", "/Flash/expressInstall.swf", {}, params);
}

function ShowDialog(url, dw, dh, bModel, title, zIndex, bgColor,id)
{
    if (!id) { id = "dlg"; }
    var iframe = "<iframe frameborder=\"0\" src=\"" + url + "\" style=\"height:" + dh + "px;width:" + dw + "px\"></iframe>";
    ShowHTMLDlg(id, dw, dh, iframe, bModel, title, zIndex, bgColor);   
}



function ShowHTMLDlg(dlgID, dw, dh, html, bModal, title, zIndex, bgColor)
{
    $("#" + dlgID).remove(); //Remove Any Previous Dlg Cuz This Will Get Recalled Multiple Times

    //Make Title Blank If NULL
    if (!title) { title = ""; }

    if(!bgColor) {bgColor = "#000";}

    //Determine If Dialog Should Be Fixed Or Absolute Positioned. If Height Available > Dialog Use Fixed.
	var pos = "absolute";
	if( $(window).height() > dh )
	{
		pos = "fixed";
	}

    //Create Non Client Area
    var dlg = $("<div class=\"dlg\" id=\"" + dlgID + "\" style=\"position:" + pos + ";width:" + dw + "\"><div class=\"t\"><span>" + title + "</span><a class=\"dlgClose\"></a></div><div class=\"body\" style=\"height:" + dh + "px;width:" + dw + "px;background:" + bgColor + "\"></div><div style=\"clear:both\"></div></div>");

    /*
    <div class="dlg" style="width:300px;">
        <div class="t"><span>" + title + "</span><a class="dlgClose"></a></div>
        <div class="body" style="width:300px;height:300px">
            <p>My Window Content</p>
        </div>
	<div style=\"clear:both\"></div>
    </div>
    */

    //Set zIndex Of Dlg If Given
    if (zIndex) { dlg[0].style.zIndex = zIndex; }

    CenterDlg(dlg, dw, dh);
    dlg.appendTo($("body"));

    //Inject HTML Into Dlg
    $("div.body", dlg).append(html);
    

    //Register W/ JQM
    dlg.jqm(
    {
        modal: bModal, onHide: OnHideFrameDlg,
        onShow: function(h)
        {
            //Fade In Overlay
            h.o.fadeIn("def");
        }
    });
    dlg.jqmAddClose(".dlgClose");

    //Launch JQM Dialog
    dlg.jqmShow();
}
function OnHideFrameDlg(h)
{
    //Hide Dialog
    h.w.hide();

    //Fade, Remove Overlay
    h.o.fadeOut('def', function() { h.o.remove(); h.w.remove(); });
}
function CenterDlg(d, dw, dh)
{
    var wh = $(window).height();
    var ww = $(window).width();

    //dw,dh Is Client Area Dimensions. Doesn't Include NC Area.
    dh += 23; //Add NC Area
    dw += 2;

    var y = Math.round((wh / 2) - (dh / 2));
    if( y < 0 ) {y = 0};
    
    var x = Math.round((ww / 2) - (dw / 2));
    
    
    d.css("left", x + "px");
    d.css("top", y + "px");
}

function OpenDlg(name)
{
	if( name == "photogallery" ) { $("#navPhotoGallery a").click(); }
	else if( name == "videogallery" ) { $("#navVideoGallery a").click(); }
	else if( name == "contact" ) { $("#navContactUs a").click(); }
}
function GetPageFolder()
{
    var path = location.pathname;
    var ix = path.lastIndexOf("/");	
    return path.substring(0, ix+1);	
}

function removeSpecialBanner()
{
	$("#specialbanner").remove();
	if(typeof specialVisible != "undefined") {specialVisible=false;}
}


//Used By Floorplan Popup
function ShowContactForm(url)
{
	ShowDialog(url, 723, 418, true, '', 5000, "#000", "contactDlg");
	return false;
}
function ShowRentNowForm(url)
{
    ShowDialog( url, 743, 465, true, '', 5000, "#000", "rentDlg");
    return false;
}


function OnClickExtLink(e)
{
	e.stopPropagation();
	e.preventDefault();

	var a = e.target;
	if(a.nodeName.toLowerCase() != "a")
	{
		a = $(a).closest("a");
	}
	a = $(a);
	var url = a[0].href;

	var wh = $(window).height() + 100;
	var ww = $(window).width();

	var h = 500;
	var w = 800;
	var left = (ww - w) / 2;
	var top  = (wh - h) / 2;
	var features = "width=" + w + ",height=" + h + ",left=" + left + ",top=" + top + ",resizable=1,scrollbars=1";
	var w = window.open(url, "", features);
	if(w != null){ w.focus(); }

	return false;
}
function getIEVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser)
{
 var rv = -1; // Return value assumes failure
 if (navigator.appName == 'Microsoft Internet Explorer')
 {
  var ua = navigator.userAgent;
  var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  if (re.exec(ua) != null)
   rv = parseFloat( RegExp.$1 );
 }
 return rv;
}

