﻿//Requires
/// JQuery
/// <reference path="MapPoint.js" />
/// <reference path="jquery.tools.min.js" />  ??
/// <reference path="jquery.colorbox-min.js" />
/// <reference path="jquery.labelify.js" />


//InfoBox
function makeArrowHtml(options) {
    return '<div class="arrow-outer-container"><div class="arrow-outer"></div><div class="arrow-inner"></div></div>';
}
function makeInfoBox(target, options) {
    options = $.extend({ "leftOffset": 0, "topOffset": 0, "html": ""}, options);
    $('.info-box').remove();
    $('body').prepend("<div class='info-box'><div class='info-box-inner wrapTarget'></div></div>");
    $(".info-box").append(makeArrowHtml(null))
    $(".info-box > .info-box-inner").html(options.html);
    $(".info-box > .info-box-inner").append("<div class='CloseX'><a href='#'></a></div>");
    $(".info-box > .info-box-inner > .CloseX").click(function(e) {
        e.preventDefault(); 
        hideInfoBox(); 
    });
    //if (options.paddBottomForMouseOver) {
    //    $(".info-box").css("paddingBottom", $(target).height());
    //}
    
    var ibW = $(".info-box").width();
    var ibH = $(".info-box").height();

    var targetPos = $(target).offset();
    var halfTW = $(target).width() * 0.5;

    var targetLeft = targetPos.left + halfTW;
    var targetTop = targetPos.top;
    var leftPos = targetLeft - (ibW * 0.5) + options.leftOffset;
    var topPos = targetTop - ibH + options.topOffset;

    //set display to none so we can fade in.
    $(".info-box").css('display', 'none');
    $(".info-box").css('visibility', 'visible');
    $(".info-box").css('left', leftPos);
    $(".info-box").css('top', topPos);
    if (options.postSetup) {
        try {
            options.postSetup($(".info-box > .info-box-inner"));
        } catch (e) {
            if (e.message)
                alert(e.message);
            else
                alert(e);
        }
    }
    $(".info-box").fadeIn('fast');
    //$('.info-box').bind('mouseleave', function() { hideInfoBox(); });  
}
function hideInfoBox() {
    $(".info-box").fadeOut('fast', function() { $('.info-box').remove(); });
}




//RPCompare
var RPCompare = {};
RPCompare.SetOfCompareListItems = [];
RPCompare.lastSiteAdded = null;
//Let's just say RPCompare is something like an abstract class.... 
RPCompare.GetRPMap = function() { alert("RPCompare.GetRPMap must be replaced programatically"); }

function AjaxErrorMaker(message) {
    return function() {
        alert(message);
    }
}


RPCompare.ChangeCompareListSuccess = function(result) {
    RPCompare.SetOfCompareListItems = result.split(",");
    RPCompare.InvokeComparePageIfAppropriate();
    $(document).trigger('compare_communities_reset');
    //alert(result);
}
//meh, hackityhack
RPCompare.PinClickShouldOpenNewWindow = true;
RPCompare.InvokeComparePageIfAppropriate = function() {
    var qstr = "";
    if (RPCompare.lastSiteAdded != null) {
        qstr = "?lastsite=" + RPCompare.lastSiteAdded;
        hideInfoBox();
        $.colorbox({
            href: AppRoot() + "ComparePopup.aspx" + qstr,
            innerWidth: 539,
            innerHeight: 422,
            iframe: true,
            opacity: 0.74, ///somehow this isn't matching what photoshop shows.
            onCleanup: function() {
            }
        });
    }
}
//for inline (ugh).
function ChangeCompareListManualCheckboxClickEvent(checkbox) {
    var site = $(checkbox).val();
    if (checkbox.checked) {
        RPCompare.lastSiteAdded = site;
        RealPage.ISearchService.ChangeCompareListString(site, "",
                        RPCompare.ChangeCompareListSuccess, AjaxErrorMaker("Failed to add site to Apartment Compare List"));
    } else {
        RPCompare.lastSiteAdded = null;
        RealPage.ISearchService.ChangeCompareListString("", site,
                            RPCompare.ChangeCompareListSuccess, AjaxErrorMaker("Failed to remove site from Apartment Compare List"));
    }
}
function makeRPPOIFromShape(shape) {
    var POI = new RPPOI();
    var note = $(shape.RPTheRSSHtml);
    //Get Property Address from Mappoint Popover.
    var address = jQuery.trim(note.find(".address .adr1").text()) + ", " + jQuery.trim(note.find(".address .adr2").text()) 
    POI.GetAddress = function() { return address; }
    var point = shape.GetPoints()[0];

    POI.GetLatitude = function() { return point.Latitude; }
    POI.GetLongitude = function() { return point.Longitude; }
    return POI;
}
//pin events
(function() {
	var intervalid = null;
	var currkey = null;
	function SetupPin(e, key, shape, RPMapObject) {
		// This has got to be one of the ugliest things I've ever been required to create.  
		// all this because Bing Maps doesn't have some sort of on-tooltip-load-complete event I can bind to.
		// because of this, I gotta regenerate the html dynamically.
		// please note: html generated from a checkbox may not maintain the checkbox state
		// (this happens in FF but may happen in other browsers as well)
		// sheesh.
		// POST EDIT:  I'm now using my own infobox (thanks to Ted), so I could probably remove some of this.
		// I'm just going to leave this for future generations.
		if (shape.RPTheRSSHtml) {
			//ModifyWithRSSOutput
			var item = $("<div class='ModifyWithRSSOutput GetDirectionsDiv' style='display:none'></div>");
			item.html(shape.RPTheRSSHtml);
			var checkbox = item.find("input:checkbox");
			var shouldCheckCheckbox = false;
			checkbox.each(function(index, elem) {
				shouldCheckCheckbox = jQuery.inArray(jQuery(elem).val(), RPCompare.SetOfCompareListItems) > -1;
			});
			//item.find("input:text").val(RPMapObject.GetSavedAddress());
			var html = item.html();
			var reg = /type=([\'\"]?)checkbox\1/i;
			if (shouldCheckCheckbox) {
				html = html.replace(reg, "type=\"checkbox\" checked=\"checked\"");
			}
			html = html.replace(reg, "type=\"checkbox\" onclick=\"return ChangeCompareListManualCheckboxClickEvent(this);\"");

			//shape.SetDescription(html);
			var POI = makeRPPOIFromShape(shape)
			RPMapObject.SetPOI(POI);
			var target = shape.GetIconElement();
			makeInfoBox(target, { "html": html, "topOffset": -16, postSetup: function(jQhtml) {
			    var myTextBox = jQhtml.find("input:text");

			    myTextBox.val(RPMapObject.GetSavedAddress());
			    
				myTextBox.attr("title", "Address, City, State OR Zip Code");
				myTextBox.labelify({ labelledClass: "labelHighlight" });
			}
			});
		}
	}

	$(document).bind('map_click', function(e, key, shape, RPMapObject) {

		//var clusterShape = RPMapObject.GetClusterShape();

		if (e != null) {
			alert('here' + e.elementID);
		}

	});

	//PROBLEM: This behavior is correct for Search and Comparison Pages, not so much for Property pages.
	//CRAPPY SOLUTION:  I can think of several.
	//GOOD SOLUTION: ???
	//For now, RPCompare.PinClickShouldOpenNewWindow will work
	$(document).bind('map_pin_click', function(e, key, shape, RPMapObject) {


		clearTimeout(intervalid);
		intervalid = null;
		//SetupPin(e, key, shape, RPMapObject);
		if (shape.RPTheRSSHtml && RPCompare.PinClickShouldOpenNewWindow) {
			var item = $("<div class='ModifyWithRSSOutput GetDirectionsDiv' style='display:none'></div>");  //ModifyWithRSSOutput
			item.html(shape.RPTheRSSHtml);
			var anchor = item.find("a.imglnk");
			var href = anchor.attr("href");
			window.open(href, null, "menubar=yes,location=yes,toolbar=yes,resizable=yes,scrollbars=1,status=yes,width=1024,height=850,left=100,top=10", null);
		}
		if (shape.RPTheRSSHtml && !RPCompare.PinClickShouldOpenNewWindow) {
			SetupPin(e, key, shape, RPMapObject);
		}

	});
	$(document).bind('map_pin_mouseover', function(e, key, shape, RPMapObject) {
		if (key != currkey && currkey != null) {
			clearTimeout(intervalid);
			intervalid = null;
		}
		currkey = key;
		intervalid = setTimeout(function() {
			SetupPin(e, key, shape, RPMapObject);
		}, 1000);
	});
	$(document).bind('map_pin_mouseout', function(e, key, shape) {
		clearTimeout(intervalid);
		intervalid = null;
	});

})();
$(document).ready( function(e) {
    //Get current compare list items. 
    RealPage.ISearchService.ChangeCompareListString("", "",
                    RPCompare.ChangeCompareListSuccess, AjaxErrorMaker("Failed to get Apartment Compare List"));
});

function EmailUsPopUp(siteid) {
    $.colorbox({
        href: AppRoot() + "ContactPopup.aspx?s=" + siteid,
        innerWidth: 500,
        innerHeight: 650,
        iframe: true,
        opacity: 0.74
    });  ///somehow this isn't matching what photoshop shows.
}

function ShowHideGetDirections(elem, contextp) {
    if (typeof contextp == 'undefined' || contextp === null) {
        contextp = {}
    }
    //default to Mappoint popup context
    contextp = $.extend( { parent: "div.communityResult", child: "div.GetDirectionsDiv > div" }, contextp);
    var mydiv = $(elem).parents(contextp.parent).find(contextp.child);
    if (mydiv.hasClass("hidden")) {
        mydiv.removeClass("hidden");
        $(elem).html("Hide Get Directions");
    }
    else {
        mydiv.addClass("hidden");
        $(elem).html("Get Directions");
    }
}

function DoGetDirections(elem, contextp) {
    if (typeof contextp == 'undefined' || contextp === null) {
        contextp = {}
    }
    //default to Mappoint popup context
    contextp = $.extend({ parent: "div.GetDirectionsDiv", child: "input:text" }, contextp);
    //get user typed address from Mappoint popover
    var address = jQuery.trim($(elem).parents(contextp.parent).find(contextp.child).val());
    if (address != '' ) {
    	RPCompare.GetRPMap().SetSavedAddress(address);
    	RPCompare.GetRPMap().GetDirections();
    }
}
