var SE_PreLoadTest_PropDisplay = 1;
var SE_PD_Current_ListingID = -1;
var SE_PD_ClientID = "";
var SE_PD_TOUR_COUNT = 0;
var SE_PD_QUERYSTRING = "";
var SE_PD_Current_ConcatListingIDCSV = null;
var SE_PD_PublicSearchID = null;		
var SE_PD_ForceAddressDisplay = 0;

var SE_PD_IMG_ADDITIONAL_OFFSET = 2; //To account for a border, this value should be 2x the IMG border attribute.
var SE_PD_DEFAULT_X_OFFSET = 0;
var SE_PD_DEFAULT_Y_OFFSET = 0;
var SE_PD_DEFAULT_PHOTO_WIDTH = 320;
var SE_PD_DEFAULT_PHOTO_HEIGHT = 240;
var SE_PD_BUTTON_WIDTH = 57;
var SE_PD_BUTTON_HEIGHT = 17;
var SE_PD_BUTTON_OVERLAP = 1; // The 1px overlap makes the buttons "share" a border

function SE_PD_Action(action, listingID)
{
    var url;
    if (listingID)
        SE_PD_Current_ListingID = listingID;
   
	switch(action.toLowerCase())
	{
        case "map":
            SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_LargeMapUrl) + "listingID=" + SE_PD_Current_ListingID
			    + (SE_PD_ForceAddressDisplay ? "&forceAddr=1" : "")
			    + (typeof (SE_PD_IsOpenHomesSearch) != 'undefined' && SE_PD_IsOpenHomesSearch == 'true' ? "&OpenHomes=yes" : ""));
			break;
		case "email":
		    url = SE_LN_EmailListingUrl;
		    if (SE_PD_ForceAddressDisplay)
		        url = SE_LN_PrepURL(url) + "forceAddr=1";
		    if (typeof(SE_PD_IsOpenHomesSearch) != 'undefined' && SE_PD_IsOpenHomesSearch == 'true') 
			    url = SE_LN_PrepURL(url) + "OpenHomes=yes";
			SE_LN_SendSingleEmail(url, SE_PD_Current_ListingID);
			break;
		case "estimatepayment":
			SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_MortgageCalculatorUrl) + "listingID=" + SE_PD_Current_ListingID);
			break;
		case "phototour":
			SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_PhotoTourUrl) + "listingID=" + SE_PD_Current_ListingID, 775, 600);
			break;
		case "phototourmap":
			SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_LargeMapUrl ) + "isMap=yes&listingID=" + SE_PD_Current_ListingID, 775, 600);
			break;
		case "viewtour":
			if (SE_PD_TOUR_COUNT==0) return;
			SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_VirtualTourViewerUrl) + "listingID=" + SE_PD_Current_ListingID, 775, 600);
			break;

        case "print":
            SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_PropertyFlyerUrl) + "listingID=" + SE_PD_Current_ListingID + "&print=true" + (SE_PD_ForceAddressDisplay ? "&forceAddr=1" : "") + (typeof (SE_PD_IsOpenHomesSearch) != 'undefined' && SE_PD_IsOpenHomesSearch == 'true' ? "&OpenHomes=yes" : ""), 775, 600);
			break;
		case "directions":
		    SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_DrivingDirectionsUrl) + "listingID=" + SE_PD_Current_ListingID + (SE_PD_ForceAddressDisplay ? "&forceAddr=1" : "") + (typeof (SE_PD_IsOpenHomesSearch) != 'undefined' && SE_PD_IsOpenHomesSearch == 'true' ? "&OpenHomes=yes" : ""), 700, 700);
			break;
		case "neighborhoodprofile":
			SE_LN_OpenWin('/Common/PropertyDetail/ExternalSite.aspx?target=neighborhoodprofile&listingID=' + SE_PD_Current_ListingID, 900, 700);													
			break;
		case "localschools":
			SE_LN_OpenWin('/Common/PropertyDetail/ExternalSite.aspx?target=localschools&listingID=' + SE_PD_Current_ListingID, 700, 600);													
			break;	}
}

function PD_FavoriteCallBack() {
    switch ($("[ id $= 'hdnSuccessAction']").val()) {
        case "savedlisting":
            $("#spnRemoveListing").show();
            $("#spnSaveListing").hide();
            break;
        case "removedlisting":
            $("#spnRemoveListing").hide();
            $("#spnSaveListing").show();
            break;
    } 
}

function PDPostAction(listingID, postAction, postArgs, event)
{
    if (postAction == "savelisting" ) {
        $aa.Registration.Execute({ 'toolkitAction': $aa.Registration.Action.SaveListing, 'listingID': listingID, 'dialogMessage': (postArgs && postArgs.dialogMessage ? postArgs.dialogMessage : '') }, 
            'Save Listing', function () { PD_FavoriteAction_CallBack($aa.Registration.Action.SaveListing); });
        return ;
    }
    else if (postAction == "removelisting" ) {
        $aa.Registration.Execute({ 'toolkitAction': $aa.Registration.Action.RemoveListing, 'listingID': listingID }, 
            'Remove Listing', function () { PD_FavoriteAction_CallBack($aa.Registration.Action.RemoveListing); });
        return ;
    }
    else {
        var qs = "";
        if ((typeof (SE_PD_PostQS) != 'undefined') && SE_PD_PostQS)
            qs += SE_PD_PostQS;

        var url = SE_LN_PropertyDetailUrl;

        if (typeof(SE_PD_FriendlyURL) != "undefined" && SE_PD_FriendlyURL[listingID] != null)
            url = SE_PD_FriendlyURL[listingID];

        var qsArgs = SE_GetArgs(qs);
        if (url.indexOf("?") != -1) {
            url = url.substring(0, url.indexOf("?"))
            var urlArgs = SE_GetArgs(url.substring(url.indexOf("?") + 1))
            for (var arg in urlArgs) {
                if (!qsArgs[arg])
                    qsArgs[arg] = urlArgs[arg];
            }
        }
        var strLoc = SE_LN_PrepURL(url) + SE_BuildQueryString(qsArgs, true) + "&listingID=" + listingID;

        if (postAction)
            strLoc = strLoc + "&postAction=" + postAction;
        if (postArgs)
            strLoc = strLoc + "&postArgs=" + postArgs;
        if (SE_PD_PublicSearchID && qs.toLowerCase().indexOf("publicsearchid=") == -1)
            strLoc = strLoc + "&publicSearchID=" + SE_PD_PublicSearchID;

        SE_Post_ToURL(strLoc, SE_PD_Current_ConcatListingIDCSV, "", "", "", "");
    }
}

function PD_FavoriteAction_CallBack(action) {
    switch (action) {
        case $aa.Registration.Action.SaveListing:
            $("#spnRemoveListing").show();
            $("#spnSaveListing").hide();
            break;
        default:
            $("#spnRemoveListing").hide();
            $("#spnSaveListing").show();
            break;
    }
}

function SE_PD_ViewPhoto()
{
	SE_PD_GetElement("viewMap").style.visibility = "visible";
	SE_PD_GetElement("zoomMap").style.visibility = "hidden";
	SE_PD_GetElement("viewPhoto").style.visibility = "hidden";
	var elImg = SE_PD_GetElement("propPhoto");
	if(SE_PD_PHOTO_COUNT>1)
	{
		SE_PD_GetElement("nextPhoto").style.visibility = "visible";
		//SE_PD_GetElement("propPhoto").src = SE_Fader_Photos[0];
		SE_Fader_SetImageAttributes(0, true);
	}
	else
	{
		elImg.src = SE_PD_PHOTO_PATH;
	}

	if(SE_PD_HasTour && SE_PD_HasMultiplePhotos)
	{
		var elImgLeft = SE_PD_FindPosX(elImg);
		if(SE_PD_IsIE())
		{
			SE_PD_GetElement("viewTour").style.posLeft = SE_PD_GetElement("viewTour").style.posLeft - 56;
		}
		else
		{
			var strViewTourLeft = SE_PD_GetElement("viewTour").style.left;
			if (strViewTourLeft.substring(strViewTourLeft.length - 2, strViewTourLeft.length) == 'px')
				strViewTourLeft = strViewTourLeft.substring(0, strViewTourLeft.length - 2);
			
			SE_PD_GetElement("viewTour").style.left = parseInt(strViewTourLeft) - 56 + 'px';
		}
	}
	
	if (document.getElementById("lnkPhotoTour") && document.getElementById("lnkPhotoTour").href)
		document.getElementById("lnkPhotoTour").href = "javascript:SE_PD_Action('phototour')";

    SE_PD_HandleDivLocations(elImg.offsetHeight, elImg.offsetWidth, true);
}

function SE_PD_ISMapDisplayed() {

    var $Photo = $("#propPhoto");
    if ($Photo.length == 0)
        $Photo = $(window.parent.frames.frmData.document).find("#propPhoto");
    return $Photo.length == 1 
        && $Photo[0].src 
        && $Photo[0].src.toLowerCase().indexOf("map.aspx") != -1;  
}

function SE_PD_ViewMap()
{
	qs = window.location.search;
	if (SE_PD_QUERYSTRING != "") qs = SE_PD_QUERYSTRING;
	
	var elImg = SE_PD_GetElement("propPhoto");
	elImg.src = SE_PD_DOMAIN + "/Common/Images/map.aspx" + qs;
	elImg.width = SE_PD_DEFAULT_PHOTO_WIDTH;
	elImg.height = SE_PD_DEFAULT_PHOTO_HEIGHT;
	
	if(SE_PD_IsIE())
	{
		SE_PD_GetElement("loadingmap").style.posTop = SE_PD_FindPosY(SE_PD_GetElement("propPhoto")) + 220 / 2 + 7;
		SE_PD_GetElement("loadingmap").style.posLeft = SE_PD_FindPosX(SE_PD_GetElement("propPhoto"))+ 220 / 2 + 15;
	}
	else
	{
		SE_PD_GetElement("loadingmap").style.top = SE_PD_FindPosY(SE_PD_GetElement("propPhoto")) + 220 / 2 + 7 + 'px';
		SE_PD_GetElement("loadingmap").style.left = SE_PD_FindPosX(SE_PD_GetElement("propPhoto"))+ 220 / 2 + 15 + 'px';
	}

	SE_PD_GetElement("loadingmap").style.visibility = "visible";
	SE_PD_GetElement("viewMap").style.visibility = "hidden";
	SE_PD_GetElement("zoomMap").style.visibility = "visible";
	SE_PD_GetElement("nextPhoto").style.visibility = "hidden";
	SE_PD_GetElement("viewPhoto").style.visibility = "visible";
	setTimeout('SE_PD_EndLoading()',1250);

	if (document.getElementById("lnkPhotoTour") && document.getElementById("lnkPhotoTour").href)
		document.getElementById("lnkPhotoTour").href = "javascript:SE_PD_Action('phototourmap')";
	
	if(SE_PD_HasTour)
	{
		if(SE_PD_HasMultiplePhotos)
		{
			var elImgLeft =  SE_PD_FindPosX(elImg);
			if(SE_PD_IsIE())
			{
				SE_PD_GetElement("viewTour").style.posLeft = SE_PD_GetElement("viewTour").style.posLeft + 56;
			}
			else
			{
				var strViewTourLeft = SE_PD_GetElement("viewTour").style.left;
				if (strViewTourLeft.substring(strViewTourLeft.length - 2, strViewTourLeft.length) == 'px')
					strViewTourLeft = strViewTourLeft.substring(0, strViewTourLeft.length - 2);
				
				SE_PD_GetElement("viewTour").style.left = parseInt(strViewTourLeft) + 56 + 'px';
			}
		}
		else
		{
			//do nothing
		}
	}
	
	SE_PD_HandleDivLocations(242, 322, true, true);
}

function SE_PD_HandleDivLocations(intHeight, intWidth, isOffset, forceDefault)
{
	// sometimes the dimensions come in with and extra 2 pixels for borders and sometimes they don't
	if (typeof(SE_PD_DontShowDivs) != 'undefined' && SE_PD_DontShowDivs) return;
    if (typeof(isOffset) == "undefined") {isOffset = false;}
    if (typeof(forceDefault) == "undefined") {forceDefault = false;}
	
	//A reference to our IMG element
	var elImg = SE_PD_GetElement("propPhoto");
	
	//Set the actual x and y position of the IMG element used to display the photo(s).
	var elImgTop = (forceDefault) ? SE_PD_FindDefaultPosY(elImg) : SE_PD_FindPosY(elImg);
	var elImgLeft = (forceDefault) ? SE_PD_FindDefaultPosX(elImg) : SE_PD_FindPosX(elImg);
    
    //If the height/width is provided then apply any offset logic as needed, otherwise get the offsetHeight/offsetWidth from the IMG.
	var imgOffsetHeight = (intHeight) ? ((isOffset) ? intHeight : intHeight + SE_PD_IMG_ADDITIONAL_OFFSET) : elImg.offsetHeight;
	var imgOffsetWidth = (intWidth) ? ((isOffset) ? intWidth : intWidth + SE_PD_IMG_ADDITIONAL_OFFSET) : elImg.offsetWidth;
	
	if (!SE_PD_GetElement("viewMap")) return; 

	var divTop = (elImgTop + imgOffsetHeight - SE_PD_BUTTON_HEIGHT - SE_PD_IMG_ADDITIONAL_OFFSET);

	SE_PD_GetElement("viewMap").style.top = divTop + "px";
	SE_PD_GetElement("viewMap").style.left = (elImgLeft + imgOffsetWidth - SE_PD_BUTTON_WIDTH + SE_PD_BrowserAdjustment('left')) + "px";
	SE_PD_GetElement("viewPhoto").style.top = divTop + "px";
	SE_PD_GetElement("viewPhoto").style.left = (elImgLeft + imgOffsetWidth - SE_PD_BUTTON_WIDTH + SE_PD_BrowserAdjustment('left')) + "px";
	SE_PD_GetElement("zoomMap").style.top = (divTop + 1) + "px";
	SE_PD_GetElement("zoomMap").style.left = (elImgLeft + SE_PD_BrowserAdjustment('left')) + "px";
	SE_PD_GetElement("nextPhoto").style.top = divTop + "px";
	SE_PD_GetElement("nextPhoto").style.left = (elImgLeft + imgOffsetWidth - (2 * SE_PD_BUTTON_WIDTH) + SE_PD_BrowserAdjustment('left') + SE_PD_BUTTON_OVERLAP) + "px";
	SE_PD_GetElement("viewTour").style.top = divTop + "px";
	SE_PD_GetElement("viewTour").style.left = (elImgLeft + imgOffsetWidth - SE_PD_BUTTON_WIDTH + SE_PD_BrowserAdjustment('left')) + "px";
	
	//Check to see if the property detail is already displaying a map. If so, hide the View Map button.
	if(elImg.src.indexOf("map.aspx",0) == -1)
	{	
		if (typeof(SE_PD_isMappable) == 'undefined')
			SE_PD_GetElement("viewMap").style.visibility = "visible";
		else
		{
			if (SE_PD_isMappable)
				SE_PD_GetElement("viewMap").style.visibility = "visible";
			else
			{
				SE_PD_GetElement("viewMap").style.visibility = "hidden";
				//SE_PD_GetElement("viewTour").style.left = 
				//    parseInt(SE_PD_GetElement("viewTour").style.left.replace('px','')) + SE_PD_BUTTON_WIDTH;
				SE_PD_GetElement("nextPhoto").style.left = 
				    parseInt(SE_PD_GetElement("nextPhoto").style.left.replace('px','')) + SE_PD_BUTTON_WIDTH;
		    }
		}
	
		SE_PD_GetElement("zoomMap").style.visibility = "hidden";
		if (SE_PD_HasMultiplePhotos )
			{SE_PD_GetElement("nextPhoto").style.visibility = "visible";}
		else
			{SE_PD_GetElement("nextPhoto").style.visibility = "hidden";}
	}
	else
	{
		SE_PD_GetElement("viewMap").style.visibility = "hidden";
		SE_PD_GetElement("zoomMap").style.visibility = "visible";
		SE_PD_GetElement("nextPhoto").style.visibility = "hidden";
	}

	//Check to see if a virtual tour exists for this listing
	if(SE_PD_HasTour)
	{
		//If a photo exists, slide the virtual tour button to the left
		if(SE_PD_HasPhoto)
		{
			if(SE_PD_IsIE())
			{
				SE_PD_GetElement("viewTour").style.posLeft = SE_PD_GetElement("viewTour").style.posLeft - SE_PD_BUTTON_WIDTH + SE_PD_BUTTON_OVERLAP;
			}
			else
			{
				var strViewTourLeft = SE_PD_GetElement("viewTour").style.left;
				if (strViewTourLeft.substring(strViewTourLeft.length - 2, strViewTourLeft.length) == 'px')
					strViewTourLeft = strViewTourLeft.substring(0, strViewTourLeft.length - 2);
				SE_PD_GetElement("viewTour").style.left = parseInt(strViewTourLeft) - SE_PD_BUTTON_WIDTH + SE_PD_BUTTON_OVERLAP + 'px';
			}
		}

		//If multiple photos exist, slide the virtual tour button over to the left some more
		if(SE_PD_HasMultiplePhotos)
		{
			if(SE_PD_IsIE())
			{
				SE_PD_GetElement("viewTour").style.posLeft = SE_PD_GetElement("viewTour").style.posLeft - SE_PD_BUTTON_WIDTH + SE_PD_BUTTON_OVERLAP;
			}
			else
			{
				var strViewTourLeft = SE_PD_GetElement("viewTour").style.left;
				if (strViewTourLeft.substring(strViewTourLeft.length - 2, strViewTourLeft.length) == 'px')
					strViewTourLeft = strViewTourLeft.substring(0, strViewTourLeft.length - 2);
				SE_PD_GetElement("viewTour").style.left = parseInt(strViewTourLeft) - SE_PD_BUTTON_WIDTH + SE_PD_BUTTON_OVERLAP + 'px';
			}
		}

		//Finally, display the virtual tour button
		SE_PD_GetElement("viewTour").style.visibility = "visible";
	}
}

function SE_PD_UpdatePhotoPosition(n)
{
	var tdPhotoPositionLabel = SE_PD_GetElement("tdPhotoPosition");
	if (tdPhotoPositionLabel)
	{
		tdPhotoPositionLabel.innerHTML = "Photo " + n + " of " + SE_PD_PHOTO_COUNT;
	}
}

// ZoomIn (takes an image and Zooms In)
function SE_PD_ZoomIn(img) {
    SE_PD_Zoom(img, true)
}
function SE_PD_ZoomOut(img) {
    SE_PD_Zoom(img, false)
}
function SE_PD_Zoom(img, isZoomIn)
{
	var src = img.src;
	if (src.indexOf("map.aspx")==-1) return;
	var loc = src.substring(0,src.indexOf("?"));
	var qs = src.substring(src.indexOf("?") + 1);
	var args = SE_GetQueryArgs(qs);
	var zoomLevel = 14;
	if(args.zoomlevel) zoomLevel = parseInt(args.zoomlevel);
    if (isZoomIn)
        zoomLevel++;
    else
        zoomLevel--;

	if (zoomLevel < 1 || zoomLevel > 19) return;
	
	var newSrc = loc + "?zoomLevel=" + zoomLevel;
	if(args.mlsid) newSrc += "&mlsID=" + args.mlsid;
	if(args.classid) newSrc += "&classID=" + args.classid;
	if(args.listingid) newSrc += "&listingID=" + args.listingid;
	if(args.width) newSrc += "&width=" + args.width;
	if(args.height) newSrc += "&height=" + args.height;
	if(args.startpin) newSrc += "&startPin=" + args.startpin;
	if(args.x) newSrc += "&x=" + SE_URLEncode(args.x);

	img.src = newSrc;
}


function SE_PD_FindPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;

	return curleft;
}

function SE_PD_FindPosY(obj)
{
    var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

    return curtop;
}

//When switching from a photo to the map, we want to get a "default" position since the IMG can float within the container
//depending on the IMG width and height.  So we need the total offsets of the parents, summed with a "default" offset for the
//actual map image.
function SE_PD_FindDefaultPosX(obj)
{
	var curleft = 0;
	var isSelf = true;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
		    curleft += (isSelf) ? 0 : obj.offsetLeft;
			obj = obj.offsetParent;
			isSelf = false;
		}
	}
	curleft += SE_PD_DEFAULT_X_OFFSET

	return curleft;
}

function SE_PD_FindDefaultPosY(obj)
{
	var curtop = 0;
	var isSelf = true;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
		    curtop += (isSelf) ? 0 : obj.offsetTop;
			obj = obj.offsetParent;
			isSelf = false;
		}
	}
	curtop += SE_PD_DEFAULT_Y_OFFSET

	return curtop;
}

function SE_PD_BrowserAdjustment(direction)
{
	if(navigator.platform.indexOf("Win") == 0)
	{
		adjustment = 0;
	}
	else
	{
		if(direction == "top")
		{
			adjustment = -4;
		}
		else
		{
			adjustment = -2;
		}
	}

	return adjustment;
}

function SE_PD_NextPhoto()
{
	//for(var i=0;i!=SE_Fader_Photos.length;i++)
	for(var i=0;i!=SE_Fader_ImageObjects.length;i++)
	{
		//if(SE_Fader_Photos[i]==SE_PD_GetElement("propPhoto").src)
		if(SE_Fader_ImageObjects[i].src==SE_PD_GetElement("propPhoto").src)
		{
			//if (i+1 == SE_Fader_Photos.length)
			if (i+1 == SE_Fader_ImageObjects.length)
				SE_Fader_SetImageAttributes(0, true); //SE_PD_GetElement("propPhoto").src = SE_Fader_Photos[0];
			else
				SE_Fader_SetImageAttributes(i+1, true); //SE_PD_GetElement("propPhoto").src = SE_Fader_Photos[i+1];

			break;
		}
	}
}

function SE_PD_NextPhotoFade()
{
    SE_Fader_NextPhotoFade(true, true);
    var photo = document.getElementById(SE_Fader_PhotoID)
    SE_PD_HandleDivLocations(photo.offsetHeight, photo.offsetWidth, true);
}
function SE_PD_PrevPhotoFade()
{
    SE_Fader_PrevPhotoFade(true, true);
    var photo = document.getElementById(SE_Fader_PhotoID)
    SE_PD_HandleDivLocations(photo.offsetHeight, photo.offsetWidth, true);
}

function SE_PD_IsIE()
{
	return (navigator.appName != "Netscape");
}

function SE_PD_EndLoading()
{
	SE_PD_GetElement("loadingmap").style.visibility = "hidden";
}

function SE_PD_GetElement(id)
{
	if (SE_PD_ClientID.length > 0)
	{
		if (SE_PD_ClientID.substring(SE_PD_ClientID.length-1, SE_PD_ClientID.length-1) != "_")
			SE_PD_ClientID += "_";
	}
	return document.getElementById(SE_PD_ClientID + id);
}

function PD_LoadStartAddress() {

    var startLoc = SE_GetDocumentCookie(document, "LastStartLocation");
    if (startLoc && startLoc != '') {
        var aLoc = startLoc.split(",");
        startLoc = aLoc[0] + "," + aLoc[1] + "," + aLoc[2] + "," + aLoc[3];
        document.getElementById("pd_driving_directions_StartAddress").value = startLoc;
    }
}

function PD_HoverState() {
    //hover states on the static widgets
    $('.pd_content_container .pd_button').hover(
			function () { $(this).addClass('ui-state-hover'); },
			function () { $(this).removeClass('ui-state-hover'); }
		);
}

$(document).ready(function () {
    PD_HoverState();
});



