
// ------------------------------
// list action and marking management
// applies to
//	- lists of checkboxes (named SE_Checkbox_RepeatedCheckBoxName)
//	- paged lists of check boxes (with marked items saved in a hidden field that is managed by SE_List_CSVObject objects for marked listings and regular listings)
//  - pages without checkboxes where marked items and listitems are stored in a string that is managed by SE_List_CSVObject objects for marked listings and regular listings
var SE_PreLoadTest_CheckBoxHandler = 1;
// set this in calling page
var SE_Checkbox_RepeatedCheckBoxName = "";

var SE_COMMON_AJAX_HANDLER_URL = "/Common/PropertyDetail/AJAXHandlerPublicWebsiteUser.aspx";

// set these in calling page if the checkboxes or list are not stored in the current window/frame
var SE_CheckBox_Form = null;

var SE_LN_SelectedCount = 0;

// this object encapsulates the CSV lists of listing ids that may be stored
// in either a control or a javascript string variable
var SE_List_MarkedItemsCSV = null;
var SE_List_ListingIDsCSV = null;
function SE_List_CSVObject(object)
{
	if (typeof(object) == 'string')
	{
		this.object = object;
		this.value = object;
		this.SetValue = function(newValue){this.object = newValue; this.value = newValue;}
	}
	else
	{
		this.object = object;
		this.value = object.value;
		this.SetValue = function(newValue)
		{
		    this.value = newValue; 
		    this.object.value = newValue
		}
	}
	this.getArray = _SE_ListGetArray;
}
function _SE_ListGetArray()
{
	if (this.value.length > 0)
		return this.value.split(",");
	else
		return new Array();
}

// ----------------------------------------------
// start listing checkbox management
// ----------------------------------------------
// the checkboxes may be on a form that is not on our window (specified in SE_CheckBox_Form)
function SE_CheckBox_GetForm()
{
	if ((SE_CheckBox_Form) && (typeof(SE_GetListForm) != 'undefined'))
		SE_CheckBox_Form = SE_GetListForm();
	else if (SE_CheckBox_Form)
		return SE_CheckBox_Form;
	else if (typeof(SE_GetListForm) != 'undefined')
		SE_CheckBox_Form = SE_GetListForm();		
	if (!SE_CheckBox_Form)
		SE_CheckBox_Form = document.forms[0];
	return SE_CheckBox_Form;
}

// returns an array of checkbox objects
function SE_CheckBox_GetCheckBoxes(chkID)
{
	var chks = new Array();
	var frm = SE_CheckBox_GetForm();
	if (typeof(frm) != "undefined")
    {
	    if (arguments.length == 0) chkID = SE_Checkbox_RepeatedCheckBoxName;
	    for (var ax=0; ax < frm.elements.length; ax++)
	    {
	        var elem = frm.elements[ax];
	        if (elem.type == 'checkbox'
                && elem.offsetWidth > 0 
                && (elem.id.match(chkID) != null 
                    ||elem.name.match(chkID)!=null))
		    {
			    chks.push(elem);
		    }
	    }
    }
	return chks;
}

function SE_CheckBox_CheckAll(chkBoxName, masterCheck, skipListUpdate)
{
	
	if (!chkBoxName)
	    chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	if (!masterCheck)
		masterCheck = "chkMaster";;

	var masterIsChecked = document.getElementById(masterCheck).checked;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for(var i=0;i<ck.length;i++)
		ck[i].checked = masterIsChecked;
	
	if (!skipListUpdate && typeof(SE_List_MarkedItemsCSV) != 'undefined' && SE_List_MarkedItemsCSV != null)
		SE_PagedCheckBox_UpdateList();
}

function SE_CheckBox_UnCheckAll(chkBoxName, masterCheck, skipListUpdate)
{
	if (!chkBoxName)
	    chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	if (!masterCheck)
		masterCheck = "chkMaster";;

	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for(var i=0; i < ck.length; i++)
		ck[i].checked = false;
	
	if (!skipListUpdate && typeof(SE_List_MarkedItemsCSV) != 'undefined' && SE_List_MarkedItemsCSV != null)
		SE_PagedCheckBox_UpdateList();
}

function SE_CheckBox_CheckBoxSelected(strIdFieldName)
{
	SE_CheckBox_IsCheckBoxSelected(strIdFieldName, true);
}

function SE_CheckBox_IsCheckBoxSelected(strIdFieldName, showAlert)
{
	var intChecked = 0;
	var frm = SE_CheckBox_GetForm();
	for(var j=0; j< frm.elements.length; j++)
	{
		if(frm.elements[j].id.indexOf(strIdFieldName) != -1)
			if (frm.elements[j].checked)
				intChecked = 1;
	}
	if (intChecked == 0)
	{
		if (showAlert == true) alert("Please select at least one item on which to perform this action.");
		return false;
	}
	else
	{
		return true;
	}
}

function SE_CheckBox_MarkListing(listingID, bool, chkBoxName)
{
	if (arguments.length < 3) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);
	for(var i=0;i<ck.length;i++)
	{
		var cb = ck[i];
		if (cb.value == listingID)
		{
			cb.checked = bool;
			break;
		}
	}
}

function SE_CheckBox_SetMarkedFromList(list)
{
	var aMarked = new Array();
	if(list==undefined || arguments.length == 0)
	{
		if (!SE_List_MarkedItemsCSV)
			return;
		else
			aMarked = SE_List_MarkedItemsCSV.getArray();
	}
	else
	{
		if (list.length > 0) aMarked = list.split(",");
	}

	for(var i=0; i < aMarked.length; i++)
		SE_CheckBox_MarkListing(aMarked[i], true);
}

function SE_CheckBox_IsMarked(listingID, chkBoxName )
{
	if (arguments.length == 1) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	ck = SE_CheckBox_GetCheckBoxes(chkBoxName);
	for (var i=0;i<ck.length;i++)
	{
		if (ck[i].value == listingID)
		{
			return ck[i].checked;
			break;
		}
	}
}

function SE_CheckBox_GetFirstMarkedListing(chkBoxName)
{
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for(var i=0; i < ck.length; i++)
	{
		if(ck[i].checked)
			return ck[i].value;
	}
}

function SE_List_GetMarkedListingCount()
{
	if (SE_List_MarkedItemsCSV)
		return SE_PagedCheckBox_GetMarkedCount();
	else
		return SE_CheckBox_GetMarkedCount();
}


function SE_CheckBox_GetMarkedCount(chkBoxName)
{
	var count = 0;
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for(var i=0;i<ck.length;i++)
	{
		if(ck[i].checked)
			count++;
	}
	return count;
}

function SE_CheckBox_GetUnmarkedListingCount(chkBoxName)
{
	var count = 0;
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for(var i=0; i < ck.length; i++)
	{
		if(!ck[i].checked)
			count++;
	}
	return count;
}

function SE_CheckBox_GetMarkedListings()
{
	if (SE_List_MarkedItemsCSV)
	{
		// we are saving ids from multiple pages,
		SE_PagedCheckBox_UpdateList();
		return SE_List_MarkedItemsCSV.value;
	}
	else
	{
		if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
		return SE_CheckBox_GetMarkedCheckBoxes(chkBoxName);
	}
}

// returns a CSV string of listingids
function SE_CheckBox_GetMarkedCheckBoxes(chkBoxName)
{
	var s = "";
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	var k = 0;
	for (var i=0; i < ck.length; i++)
	{
		if(ck[i].checked)
		{
			if(s=="")
				s += SE_Checkbox_GetValue(ck[i]);
			else
				s += "," + SE_Checkbox_GetValue(ck[i]);
			k++;
		}
	}
	return s;
}

function SE_CheckBox_GetMarkedListingsWithoutLimit(chkBoxName)
{
	var s = "";
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	var k = 0;
	for (var i=0;i<ck.length;i++)
	{
		if(ck[i].checked)
		{
			if(s=="")
				s += SE_Checkbox_GetValue(ck[i]);
			else
				s += "," + SE_Checkbox_GetValue(ck[i]);
			k++;
		}
	}
	return s;
}

function SE_CheckBox_GetUnmarkedListings(chkBoxName)
{
	var s = "";
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for (var i=0; i<ck.length; i++)
	{
		if(!ck[i].checked)
		{
			if(s=="")
				s += SE_Checkbox_GetValue(ck[i]);
			else
				s += "," + SE_Checkbox_GetValue(ck[i]);
		}
	}
	return s;
}

// returns CSV string of all listings ids
function SE_CheckBox_GetAllListings(chkBoxName)
{
	var s = "";
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	var ck = SE_CheckBox_GetCheckBoxes(chkBoxName);

	for (var i=0;i<ck.length;i++)
	{
		if (ck[i].value && ck[i].value != "" && ck[i].value != "on" && ck[i].value != "off")
		{
		    if(s=="")
			    s += ck[i].value;
		    else
			    s += "," + ck[i].value;
	    }
	}
	return s;
}
// -------------------- End SE_CheckBox methods--------------

// -------------------- SE_PagedCheckBox methods--------------
// SE_PagedCheckBox methods understand that the list of listing and marked listings may
// be span multiple pages of check boxes. The CSV strings are the master data source
// and the checkboxes are kept in sync with this list
// -----------------------------------------------------------

function SE_PagedCheckBox_GetMarkedCount()
{
	SE_PagedCheckBox_UpdateList();
	if (SE_List_MarkedItemsCSV.value == "")
		return 0;

	aItems = SE_List_MarkedItemsCSV.getArray();
	return aItems.length;
}

function SE_PagedCheckBox_UpdateList(chkBoxName, markedItemsCSV)
{
	if (arguments.length == 0) chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	if (!chkBoxName || chkBoxName == "") return;
	var aChkBoxes = SE_CheckBox_GetCheckBoxes(chkBoxName);
	
	if (!markedItemsCSV)
	    markedItemsCSV = SE_List_MarkedItemsCSV;

	var aOldChecked = new Array();
	if (markedItemsCSV.value != "")
	{
		aOldChecked = markedItemsCSV.getArray();
		// remove all of the current items from the saved list
		for (var i=0; i < aChkBoxes.length; i++)
		{
			for (var j=0; j < aOldChecked.length; j++)
			{
				if(aOldChecked[j] == SE_Checkbox_GetValue(aChkBoxes[i]))
				{
					aOldChecked.splice(j,1);
					break;
				}
			}
		}
	}
	// add the currently checked items
	for (var i=0; i < aChkBoxes.length; i++)
	{
		if (aChkBoxes[i].checked)
			aOldChecked.splice(aOldChecked.length, 1, SE_Checkbox_GetValue(aChkBoxes[i]));
	}

	markedItemsCSV.SetValue(aOldChecked.join(",").replace(/^\s+|\s+$/, ''));;
	
}

function SE_Checkbox_GetValue(chkBox)
{
    var val =  chkBox.value;
    if (!val || val == "on") val = chkBox.itemID;
    return val;
}

function SE_PagedCheckBox_UpdateChecks(chkBoxName, csvNewSelections)
{
	if (chkBoxName == "") chkBoxName = SE_Checkbox_RepeatedCheckBoxName;
	if (chkBoxName == "") return;
	var aChkBoxes = SE_CheckBox_GetCheckBoxes(chkBoxName);

	var aOldChecked = new Array();
	var aNewSelections = new Array();
	if (csvNewSelections.length > 0)
		aNewSelections = csvNewSelections.split(",");
	// redo all of the checks
	for (var i=0; i < aChkBoxes.length; i++)
	{
		aChkBoxes[i].checked = false;
	}
	for (var i=0; i < aChkBoxes.length; i++)
	{
		for (var j=0; j < aNewSelections.length; j++)
		{
			if ( aNewSelections[j] == SE_Checkbox_GetValue(aChkBoxes[i]))
			{
				aChkBoxes[i].checked = true;
				break;
			}
		}
	}
	// replace the selected list (could be in a control or a js variable)
	if (SE_List_MarkedItemsCSV)
		SE_List_MarkedItemsCSV.SetValue(csvNewSelections.replace(/^\s+|\s+$/, ''));
}

function SE_PagedCheckBox_MarkListing(listingID, bMark)
{
	if (typeof(SE_List_MarkedItemsCSV) != "undefined")
	{
		aMarkedListings = SE_List_MarkedItemsCSV.getArray();
		//mark the listing in the local array
		if(bMark)
		{
			aMarkedListings.push(listingID);
		}
		else
		{
			for(var i=0; i < aMarkedListings.length; i++)
			{
				if (aMarkedListings[i] == listingID)
				{
					aMarkedListings.splice(i, 1);
				}
			}
		}
		SE_List_MarkedItemsCSV.SetValue(aMarkedListings.join(","));

		SE_PagedCheckBox_UpdateChecks(SE_Checkbox_RepeatedCheckBoxName, SE_List_MarkedItemsCSV.value );
	}

	// we have fixed the current page but if the calling page also has check boxes we need to update them too
	try
	{
		if(window.opener && !window.opener.closed && window.opener.SE_PagedCheckBox_UpdateChecks)
		{
			//try to mark the listing on the results page (will fail if page location has moved or page is closed)
			window.opener.SE_PagedCheckBox_UpdateChecks("", SE_List_MarkedItemsCSV.value);
		}
	} 
	catch(e){}
}

//  -------------------------------------------------------------
//  BEGIN PagedCheckBox Object (for managing checks across pages
//

//  sample client side code
//        <input type=hidden Runat=server ID=hdnSelectedIDs />
//        <script src="/common/utilities/checkboxhandler.js" type="text/javascript"></script>
//        <script type="text/javascript">
//	        var pagedCheckBoxHandler = new SE_PagedCheckBox('pagedCheckBoxHandler', 
//	            document.getElementById('<%=this.ClientID%>_hdnSelectedIDs'), 
//	            '<asp:Literal id="hdnIDsCSV" runat="server"/>', 
//	            'chkContact', 
//	            '<%=this.ClientID%>_pnlPrevNextTop', 
//	            'Contacts');
//	        function checkSubmit()
//	        {
//	            if (!pagedCheckBoxHandler.isSomethingSelected())
//	            {
//	                alert("Please select one or more contacts.");
//	                return false;
//	            }
//	            return true;
//	        }  
//        </script>
//  
//  also on client side, 
//        in chkMaster -  onclick="pagedCheckBoxHandler.check()
//        checkboxes must be HTMLInputCheckbox (not <asp:checkbox) in order to use "value property"
//        <input type=checkbox id="chkContact"  runat="server" 
//          onclick="pagedCheckBoxHandler.updateList();"  />
//   on server side
//        - set value of hdnSelectedIDs on initial load or any postback reset
//            set value to match checked boxes ("" or the csv string of all ids (if all are selected))
//            it will take care of itself when posting back after the initial load or reset
//            don't change during paging
//        - set value of hdnIDsCSV literal to csv of ALL ids (only when reloading the list of ids
//            don't change during paging
//        - on item databind or equivalent chk.Value =  contact.contactID.ToString();
//        - user hdnContactIDsCSV.Value to load a list of selectedids in code behind   
//              SelectedContactIDs = Functions.ConvertCSVToArrayList(hdnSelectedIDs.Value, "int"); 
 
function SE_PagedCheckBox(myName, markedItemCSV, allItemIDCSV, chkBoxName, prevNextPanel, itemName)
{
    this.name = myName;
    this.markedItemsCSV = new SE_List_CSVObject(markedItemCSV);
	this.allItemIDCSV = new SE_List_CSVObject(allItemIDCSV);
    this.checkBoxName = chkBoxName;
    this.masterCheckname = 'chkMaster';
    this.itemName = itemName;
    this.prevNextPanel = prevNextPanel;
    this.pagedCheckBoxDialog;
    this.check = SE_PagedCheckBox_SelectAllCheck;
    this.showSelectAllDialog = SE_PagedCheckBox_ShowSelectAllDialog;
    this.callback = SE_PagedCheckBox_SelectAllCallback;
    this.updateList = SE_PagedCheckBox_UpdateMyList;
    this.isSomethingSelected = SE_PagedCheckBox_IsSomethingSelected;
    this.hasItemsOnOtherPages = SE_PagedCheckBox_HasItemsOnOtherPages;
    this.checkSubmit = SE_PagedCheckBox_CheckSubmit;
}

function SE_PagedCheckBox_SelectAllCheck()
{
    var selectAll = document.getElementById(this.masterCheckname).checked;
    if (selectAll)
    {
        if (this.hasItemsOnOtherPages())
            this.showSelectAllDialog('Y', this.itemName); 
        else
        {
            SE_CheckBox_CheckAll(this.checkBoxName, "chkMaster", true);
            this.markedItemsCSV.SetValue(this.allItemIDCSV.value);   
        }
    }
    else
    {
        if (this.hasItemsOnOtherPages(true))
            this.showSelectAllDialog('N', this.itemName);
        else
        {
            SE_CheckBox_UnCheckAll(this.checkBoxName, "chkMaster", true);
            this.markedItemsCSV.SetValue("");   
        }
    }
}

function SE_PagedCheckBox_ShowSelectAllDialog(check)
{
    this.pagedCheckBoxDialog = new SE_ModalDialog(this.name + '.pagedCheckBoxDialog', this.callback);
    this.pagedCheckBoxDialog.dialogStyleElement = "baseStyle";

    if (this.pagedCheckBoxDialog.cssText == document.styleSheets["baseCSS"])
        this.pagedCheckBoxDialog.cssText = document.styleSheets["baseCSS"].cssText;
    else
        this.pagedCheckBoxDialog.cssText = document.styleSheets[0].cssText

    this.pagedCheckBoxDialog.callingObjectName = this.name ;
    this.pagedCheckBoxDialog.callingDialogName = this.name + ".pagedCheckBoxDialog";
    this.pagedCheckBoxDialog.show('/Common/PagingSelector/SelectAllDialog.aspx?check=' + check + "&item=" + this.itemName, 320, 170, 'Settings');
}

function SE_PagedCheckBox_SelectAllCallback()
{
    if (this.returnValue)
    {
       if (this.returnValue["action"] && this.returnValue["action"] != "")
       {
            var thisHandler = eval(this.callingObjectName);
        
        	if (this.returnValue["check"] == "CHECKED")
	        {
        	    SE_CheckBox_CheckAll(thisHandler.checkBoxName, "chkMaster", true);
	            if (this.returnValue["action"] == "YES")
		            thisHandler.markedItemsCSV.SetValue(thisHandler.allItemIDCSV.value);  		 
		        else
   	                SE_PagedCheckBox_UpdateList(thisHandler.checkBoxName, thisHandler.markedItemsCSV)      		                       	    
	        }
	        else if (this.returnValue["check"] == "UNCHECKED")
	        {
        	    SE_CheckBox_UnCheckAll(thisHandler.checkBoxName, "chkMaster", true);
	            if (this.returnValue["action"] == "YES")
	                thisHandler.markedItemsCSV.SetValue("");  
	            else
	                SE_PagedCheckBox_UpdateList(thisHandler.checkBoxName, thisHandler.markedItemsCSV)      
	        }
	    }
    }
    else
        document.getElementById('chkMaster').checked = ! document.getElementById('chkMaster').checked
}

function SE_PagedCheckBox_UpdateMyList()
{
    SE_PagedCheckBox_UpdateList(this.checkBoxName, this.markedItemsCSV);
}


function SE_PagedCheckBox_IsSomethingSelected()
{
    return this.markedItemsCSV.value.length > 0;
}

function SE_PagedCheckBox_CheckSubmit()
{
    if (!this.isSomethingSelected())
    {
        alert("Please select one or more " + this.itemName.toLowerCase() + ".");
        return false;
    }
    return true;
}
function SE_PagedCheckBox_HasItemsOnOtherPages(markedOnly)
{
    var itemsOnAllPages;
    if (markedOnly)
        itemsOnAllPages = this.markedItemsCSV.getArray();
    else
        itemsOnAllPages = this.allItemIDCSV.getArray();
        
    if (itemsOnAllPages.length > 0)
    {
        var currentItems;
        if (markedOnly)
            currentItems =  SE_CheckBox_GetMarkedListingsWithoutLimit(this.checkBoxName);
        else
            currentItems =  SE_CheckBox_GetAllListings(this.checkBoxName);
        
        if (currentItems != "")
        {
            var itemsOnCurrentPage = currentItems.split(",");
            for(var i = 0; i< itemsOnAllPages.length; i++)
            {
                var foundOnCurrentpage = false;
                for (var j = 0; j < itemsOnCurrentPage.length; j++)
                {
                    if (itemsOnCurrentPage[j] == itemsOnAllPages[i])
                    {
                        foundOnCurrentpage = true;
                        break;
                    }
                }
                if (!foundOnCurrentpage ) return true;
            }
        }
    }
    return false;
}



// ----------------------------------------------
// End Paged_Checkbox management
// ----------------------------------------------


// ---------------------------------------------
// List management without checkboxes
// assumes the following are set BEFORE these functions are called
// var SE_List_CurrentListing = "<%=Request.QueryString["listingID"]%>";
// ---------------------------------------------
	function SE_List_IsMarked(listingID)
	{
		return SE_List_MarkedItemsCSV.value.indexOf(listingID) != -1;
	}

	function SE_List_ViewDetail(url)
	{
		var sListings = "";
		if (SE_List_ListingIDsCSV) sListings = SE_List_ListingIDsCSV.value;
		var sMarkedListings = "";
		if (SE_List_MarkedItemsCSV) sMarkedListings = SE_List_MarkedItemsCSV.value;

		SE_Post_ToURL(url, sListings, sMarkedListings, SE_LN_PropertyDetailTarget, 750, 657);
	}

	// gets listings for any type of page (it figures out what data exists and uses it)
	function SE_LN_GetMarkedListings()
	{
		// handles either list or checkbox/hidden field storage of marked listing ids
		SE_LN_SelectedCount = 0;
		var markedListingsCount = 0;
		var markedListings = "";
		if (SE_List_MarkedItemsCSV)
		{
			markedListingsCount = SE_List_GetMarkedListingCount();
			if (markedListingsCount > 0)
				markedListings = SE_List_MarkedItemsCSV.value;
		}
		else
		{
			markedListingsCount = SE_List_GetMarkedListingCount();
			if (markedListingsCount > 0)
				markedListings = SE_CheckBox_GetMarkedListings();
		}
		SE_LN_SelectedCount = markedListingsCount;
		return markedListings;
	}
// ----------------------------------------------
// End list management without checkboxes
// ----------------------------------------------

// ---------------------------------------------
// ACTIONS
// ---------------------------------------------


	function SE_LN_PrintSelected()
	{
		var markedListings = SE_LN_GetMarkedListings();
		if(markedListings == "")
			alert("You must mark at least one listing to print.");
		else
		{
		    containerUrl = SE_LN_ReportViewUrl;
	        dataUrl = SE_LN_PrepURL(SE_LN_MultiplePageViewUrl) 
	            + "src=" +  encodeURIComponent(
	                SE_LN_PrepURL(SE_LN_PropertyDetailPrintUrl) 
	                + "&listingID=xx"
	                + "&format=ClientFullPhotosEmail");
	        var url = dataUrl;
	        if (containerUrl != "")
	            url = containerUrl + "&report=" + encodeURIComponent(dataUrl);
	        else
	        {
	            url += "&markedListings=" + markedListings
	            url += "&forPrint=yes";
	        }
	        
	        SE_PostListings_ToURL(url, "Print", 725, 600)
		}
	}

	function SE_LN_PrintSingle(listingID)
	{
		SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_PropertyFlyerUrl) + "listingID=" + listingID + "&print=true",725,600);
	}

	function SE_LN_MapSelected()
	{
		var markedListings = SE_LN_GetMarkedListings();
		if(markedListings == "")
		{
			alert("No listings are marked. You must select at least one listing to use this feature.");
			return;
		}
		if (SE_LN_SelectedCount > 30)
		{
			alert("Please select 30 or fewer listings to map. You currently have " + SE_LN_SelectedCount + " listings marked.");
			return;
		}
		SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_MapMultipleUrl) + "listingID=" + markedListings,725,600);
	}

	function SE_LN_InteractiveMapSelected()
	{
		var markedListings = SE_LN_GetMarkedListings();
		if(markedListings == "")
		{
			alert("No listings are marked. You must select at least one listing to use this feature.");
			return;
		}
		if (SE_LN_SelectedCount > 30)
		{
			alert("Please select 30 or fewer listings to map. You currently have " + SE_LN_SelectedCount + " listings marked.");
			return;
		}
		SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_InteractiveMapUrl) + "listingID=" + markedListings,725,600);
	}

	function SE_LN_RouteSelected()
	{
		var markedListings = SE_LN_GetMarkedListings();
		if(markedListings == "")
		{
    		alert("No listings are marked. You must select a least one listing to use this feature.");
			return;
		}

		if(SE_LN_SelectedCount==1)
		{
			SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_DrivingDirectionsUrl) + "listingID=" + markedListings, 700, 700);
			return;
		}

		if (SE_LN_SelectedCount > 30)
		{
			alert("Please select 30 or fewer listings to map. You currently have " + SE_LN_SelectedCount + " listings marked.");
			return;
		}

		SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_DrivingRouteUrl) + "listingID=" + markedListings, 700, 755);
	}

	function SE_LN_DeleteSelected(frm)
	{
		if (arguments.length == 0)
			frm = document.forms[0];
		var markedListings = SE_LN_GetMarkedListings(false);

		if(markedListings == "")
		{
			alert("You must mark at least one property to delete.");
		}
		else
		{
			if(confirm("You are about to delete " + SE_LN_SelectedCount + " listing(s) from this list of properties. Are you sure you want to do this?"))
			{
			    if (SE_List_MarkedItemsCSV) 
			        SE_List_MarkedItemsCSV.SetValue("");
		        else
			        SE_CheckBox_SetMarkedFromList("");
			
				SE_LN_DeleteListings(frm, markedListings);
			}
		}
	}

	function SE_LN_DeleteUnmarked(frm)
	{
        var count = 0;
        var unmarkedListings = "";
		if (arguments.length == 0)
			frm = document.forms[0];
        
        if (SE_List_MarkedItemsCSV && SE_List_ListingIDsCSV ) 
        {
            var allListings = SE_List_ListingIDsCSV.getArray();
            var marked = SE_List_MarkedItemsCSV.getArray();
            for(var iListing = 0; iListing < allListings.length; iListing++)
            {
                var isMarked = false;
                for (var iMarked = 0;iMarked < marked.length; iMarked++)
                {
                    if (marked[iMarked] == allListings[iListing])
                    {
                        isMarked = true;
                        break;
                    }                        
                }
                if (!isMarked)
                {
                    count++;
                    unmarkedListings += (unmarkedListings != "" ? "," : "") + allListings[iListing];
                }
            }
        }
        else 
        {
            if (SE_List_MarkedItemsCSV)
                SE_List_MarkedItemsCSV.value = "";
            count = SE_CheckBox_GetUnmarkedListingCount();
		    unmarkedListings = SE_CheckBox_GetUnmarkedListings();
		}
		if(unmarkedListings == "")
			alert("Please unmark at least one property to remove.");
		else if(confirm("You are about to remove " + count + " listing(s) from this list of properties. Are you sure you want to do this?"))
		{
			SE_LN_DeleteListings(frm, unmarkedListings);
		}
	}

	function SE_LN_DeleteSingleListing(frm, listingID)
	{
		if(confirm("You are about to delete a listing from this list of properties. Are you sure you want to do this?"))
		{
			SE_LN_DeleteListings(frm, listingID);
		}
	}

	function SE_LN_DeleteListings(frm, listingIDs)
	{   
	    if (!frm)
	        frm = document.forms[0];
	    
	    postAction = document.getElementById("postAction");
	    if (postAction == null)
	    {
		    postAction = document.createElement("input");
		    postAction.id = "postAction";
		    postAction.name = "postAction";
		    postAction.type = "hidden";
		    frm.appendChild(postAction);
		}
		postAction.value = "delete";
		
		deleteListings = document.getElementById("deleteListings");
		if (deleteListings == null)
		{
		    deleteListings = document.createElement("input");
		    deleteListings.id = "deleteListings";
		    deleteListings.name = "deleteListings";
		    deleteListings.type = "hidden";
		    frm.appendChild(deleteListings);
		}
		deleteListings.value =  listingIDs;
		
		markedListings = document.getElementById("markedListings");
		if (markedListings == null)
		{
		    markedListings = document.createElement("input");
		    markedListings.id = "markedListings";
		    markedListings.name = "markedListings";
		    markedListings.type = "hidden";
		    frm.appendChild(markedListings);
	    }
		markedListings.value =  SE_LN_GetMarkedListings();
		
		frm.submit();
	}

	function SE_LN_EmailSelected() {
	
	    var markedListings = SE_LN_GetMarkedListings();
	    var count = markedListings.split(/\,/).length;

	    if (count > 15)
	        alert('You currently have ' + count + ' listings selected. Please limit your selection to no more than 15 listings and try again.');
	    else {	        
	        if (markedListings == "")
	            alert("You must mark at least one listing to e-mail.");
	        else {
	            if (SE_LN_EmailListingUrl.toLowerCase().indexOf("javascript") == -1) {
	                SE_LN_OpenWin(SE_LN_EmailListingUrl + (SE_LN_EmailListingUrl.indexOf("?") > 0 ? "&" : "?") + "listingID=" + markedListings, 525, 475);
	            }
	            else {
	                emailJS = SE_LN_EmailListingUrl.replace("javascript:", "").replace("?", "");
	                emailJS = emailJS.replace("##listingids##", markedListings);
	                eval(emailJS);
	            }
	        }
	    }
	}

	function SE_LN_SendSingleEmail(emailUrl, listingID, format)
	{

		if (emailUrl.toLowerCase().indexOf("javascript") == -1)
		{
			if (emailUrl.indexOf("?") == -1) emailUrl += "?";
			SE_LN_OpenWin(SE_LN_PrepURL(emailUrl) + "listingID=" + listingID,650,475);
		}
		else
		{
			emailJS = emailUrl.replace("javascript:", "").replace("?", "");
			eval(emailJS.replace("##listingids##",listingID)) ;
		}
	}

	function SE_LN_ComparableAverages()
	{
		var markedListings = SE_LN_GetMarkedListings();
		if(SE_LN_SelectedCount < 2)
		{
			alert('You must select at least 2 properties to view statistical average information.');
		}
		else
		{
			SE_LN_OpenWin(SE_LN_PrepURL(SE_LN_ComparableAveragesUrl) + "markedListings=" + markedListings, 800, 600);
		}
	}
    	

	function SE_LN_PrepURL(url)
	{
		return url + (url.indexOf("?") > 0 ? "&" : "?") ;
	}

    function SE_VL_NewWindow(listingID)
    {
		var url = SE_LN_PrepURL(SE_LN_PropertyDetailUrl) + "format=AgentFull&listingID=" + listingID;
		SE_LN_OpenWin(url, 750, 657, '');
    }
    
	function SE_ViewSingleListing(listingID)
	{   
	    var url = SE_LN_PrepURL(SE_LN_PropertyDetailUrl) + "listingID=" + listingID;
		SE_List_CurrentListing = listingID;
		SE_OpenWin(url, 750, 657, 'detail');
    }
    
    function SE_VL(listingID, query) {   
	    if (!query && typeof(SR_DetailQueryString) != 'undefined')
	        query = SR_DetailQueryString;

	    var url = "";
        
	    if (typeof (SR_FriendlyURL) != "undefined" && SR_FriendlyURL[listingID] != null)
	        url = SE_LN_PrepURL(SR_FriendlyURL[listingID]) + "listingID=" + listingID + (query ? query : "");
        else
            url = SE_LN_PrepURL(SE_LN_PropertyDetailUrl) + "listingID=" + listingID + (query ? query : "");

        SE_List_CurrentListing = listingID;

		if (SE_List_MarkedItemsCSV || SE_List_ListingIDsCSV)
			SE_List_ViewDetail(url);
		else
			SE_Checkbox_ViewDetail(SE_LN_PrepURL(url));
	}

	function SE_Checkbox_ViewDetail(strURL)
	{
		var ck = SE_CheckBox_GetCheckBoxes();

		//Show a notice if user has over 500 listings, we ask for their patience while loading the property detail page
		if(ck.length > 2000)
		{
			alert('Notice:\n\nIt will take a few moments to load this property\'s detail due to the high number of listings (' + ck.length + ') in your results. Once the property detail page has loaded, you will be able to move between listings very quickly.\n\nClick \'OK\' to continue loading this property\'s detail.');
		}
		
		var sListingIDs = SE_CheckBox_GetAllListings();
		var sMarkedListings = SE_CheckBox_GetMarkedListings();
        
		SE_Post_ToURL(strURL, sListingIDs, sMarkedListings, SE_LN_PropertyDetailTarget, 750, 657);
	}

	function SE_PostListings_ToURL(url, windowname, width, height, guids)
	{
		var sMarkedListings = SE_LN_GetMarkedListings();
		var sListingIDs = SE_CheckBox_GetAllListings();
		if (guids == null)
		    guids = SE_GetListingIDGUIDs(sListingIDs, sMarkedListings);

		url = SE_LN_PrepURL(url) + "listingIDGUID=" + guids.listingIDGUID + "&markedListingsGUID=" + guids.markedListingsGUID;

		SE_LN_OpenWin(url, width, height, windowname);
    }

    function SE_GetListingIDGUIDs(listingIDs, markedListings) {
        var jr;

        $.ajax({
            async: false,
            cache: false,
            data: ({
                "GetListingGUIDs": "true",
                "listingIDs": listingIDs, 
                "markedListings": markedListings
            }),
            url: SE_COMMON_AJAX_HANDLER_URL,
            success: function (d, t, r) {
                jr = $.parseJSON(d); 
            },
            type: 'POST'
        });

        return jr;
    }

	function SE_Post_ToURL(url, sListingIDs, sMarkedListings, windowname, width, height)
	{
		if ((windowname) && (windowname != ""))
			SE_LN_OpenWin("", width, height, windowname);
		var _frm = document.getElementById("frmListingDetail");
        var isNewForm = false;
		if (!_frm)
		{
			isNewForm = true;
			_frm = document.createElement("form");
			_frm.id = "frmListingDetail";
			_frm.style.display = "none";		
			document.body.appendChild(_frm);
		}
		_frm.method = "POST";
		_frm.action = url;
		if (typeof(windowname) != 'undefined' && windowname != "")
			_frm.target = windowname;

		var hdnListingIDs = document.getElementById("listings");
		if (!hdnListingIDs || isNewForm)
		{
			hdnListingIDs = document.createElement("input");
			hdnListingIDs.id = "listings";
			hdnListingIDs.name = "listings";
			hdnListingIDs.type = "hidden";
			_frm.appendChild(hdnListingIDs);
		}
		hdnListingIDs.value =  sListingIDs;

		var hdnMarkedListingIDs = document.getElementById("markedListings");
		if (!hdnMarkedListingIDs || isNewForm)
		{
			hdnMarkedListingIDs = document.createElement("input");
			hdnMarkedListingIDs.id = "markedListings";
			hdnMarkedListingIDs.name = "markedListings";
			hdnMarkedListingIDs.type = "hidden";
			_frm.appendChild(hdnMarkedListingIDs);
		}
		hdnMarkedListingIDs.value =  sMarkedListings;

		_frm.submit();
	}

