var YD = (typeof(YAHOO) !== 'undefined' && typeof(YAHOO.util.Dom) != 'undefined') ? YAHOO.util.Dom : null;
var YE = (typeof(YAHOO) !== 'undefined' && typeof(YAHOO.util.Dom) != 'undefined') ? YAHOO.util.Event : null;
var generalForm = null, loadingMsgSection = null, currentEntryCount = 0;
YAHOO.util.Event.onDOMReady(function() 
{
    if (YD.get("agentHelpLink") != null)
    {
        var hm = new YAHOO.widget.Menu("agentHelpMenu", { context: ["agentHelpLink", "tl", "bl"] });
        hm.addItems([
            { text: "Knowledge Base", target:"_blank", url: "http://yougotlistings.com/wiki/" },
            { text: "Contact Support",  target:"_blank", url: "http://yougotlistings.com/eticket/index.php?department=YGL%20Support" }
        ]);
        hm.render();
        YE.addListener("agentHelpLink", "click", hm.show, null, hm);
    }

    if (YD.get("agentSettingsLink") != null)
    {
        var hm2 = new YAHOO.widget.Menu("agentSettingsMenu", { context: ["agentSettingsLink", "tl", "bl"] });
        hm2.render();
        YE.addListener("agentSettingsLink", "click", hm2.show, null, hm2);
    }

    generalForm = new YAHOO.widget.Panel("yglGenernalForm",
    {
        fixedcenter:true,
        close:false,
        draggable:false,
        zindex:4,
        modal:true,
        visible:false
    });
    generalForm.setBody("<div id='yglGeneralFormContainer'></div>");
    generalForm.render(document.body);
    generalForm.setContent = function(ctn) {
        YD.get("yglGeneralFormContainer").innerHTML = ctn;
        generalForm.hide();
        generalForm.show();
    };
    loadingMsgSection = YD.get("load-msg-section");

    if (YD.get("yglSiteWarningMessage")) {
        setTimeout(function() {YD.setStyle("yglSiteWarningMessage", "display", "none"); }, 10000);
    }

    if (init != undefined)
        init();
});

var myIconFormat = function(elCell, oRecord, oColumn, oData) {
	if (oData == "" || oData == null)
		elCell.innerHTML = "";
	else
	{
		var html = "";
		var icons = oData.split("||");
		for(var i = 0; i < icons.length; i++)
		{
			var parts = icons[i].split("^");
			html += "<img src='" + parts[0] + "' title='" + parts[2] + "' ";
			if (parts[1] != "")
			{
				if (parts[3] == "L")
					html += " class='clickable' onclick='window.open(\"" + parts[1] + "\");' ";
				else
					html += " class='clickable' onclick='" + parts[1] + "' ";
			}
			if (parts[4] != null && parts[4] != "")
				html += getHoverStr(parts[4]);
			if (parts[5] != null && parts[5] != "")
				html += " id='" + parts[5] + "'";
			html += "/> ";
		}
		if (html != "")
			html = html.substring(0, html.length - 1);
		elCell.innerHTML = html;
	}
}; 
var myLinkFormat = function(elCell, oRecord, oColumn, oData) {
	var parts = oData.split("^");
	if (parts[1] == "")
		var html= "<div ";
	else
		var html = "<a href='#' onclick='window.open(\"" + parts[1] + "\");' title='" + parts[2] + "' ";
	if (parts[3] != null && parts[3] != "")
		html += getHoverStr(parts[3]);
	html += ">" + parts[0] + ((parts[1] == "") ? "</div>" : "</a>");
	elCell.innerHTML = html;
}; 
var myDateFormat = function(elCell, oRecord, oColumn, oData) {
	var myDate=new Date();
	myDate.setFullYear(2008,0,1);
	if (oData < myDate)
		elCell.innerHTML = "";
	else
	{
		var month = oData.getMonth() + 1
		var day = oData.getDate()
		var year = oData.getFullYear()
		elCell.innerHTML = month + "/" + day + "/" + year;
	}
};
var myAvailFormat = function(elCell, oRecord, oColumn, oData) {
	var myDate=new Date();
	myDate.setFullYear(1970,0,1);
	var today = new Date();
	if (oData < myDate)
		elCell.innerHTML = "All-Times";
	else if (oData < today)
		elCell.innerHTML = "NOW";
	else
	{
		var month = oData.getMonth() + 1
		var day = oData.getDate()
		var year = oData.getFullYear()
		elCell.innerHTML = month + "/" + day + "/" + year;
	}
};
var myAgeFormat = function(elCell, oRecord, oColumn, oData) {
	if (oData == 0)
		elCell.innerHTML = "Today";
	else
		elCell.innerHTML = oData + " day(s)";
};
var myLastUpdateFormat = function(elCell, oRecord, oColumn, oData) {
	var parts = oData.split("^");
	if (oData == "RealTime")
		elCell.innerHTML = "<span title='Managed By Landlord'>RealTime</span>";
	else if (parseInt(parts[0]) == 0)
		elCell.innerHTML = "Today";
	else
	{
		if (parts[1] == "A")
			elCell.innerHTML = "<a id='" + oRecord.getData("id") + "age' href='javascript:void(0);' onclick=\"setListingUpdated('" + oRecord.getData("id") + "');\">" + parts[0] + " day(s)</a>";
		else
			elCell.innerHTML = parts[0] + " day(s)";
	}
};
var myMoneyFormat = function(elCell, oRecord, oColumn, oData) {
	if (oData != null && oData != "")
		elCell.innerHTML = "$" + oData;
	else
		elCell.innerHTML = "";
};
var myFeeFormat = function(elCell, oRecord, oColumn, oData) {
	if (oData == 10)
		elCell.innerHTML = "Co-Broke";
	else if (oData == 20)
		elCell.innerHTML = "None";
	else if (oData == 30)
		elCell.innerHTML = "Unknown";
	else if (oData == 35)
		elCell.innerHTML = "Negotiable";
	else if (oData == 40)
		elCell.innerHTML = "Other";
	else if (oData == 50)
		elCell.innerHTML = "Quarter Fee";
	else if (oData == 60)
		elCell.innerHTML = "Half Fee";
	else if (oData == 70)
		elCell.innerHTML = "75% Fee";
	else if (oData == 80)
		elCell.innerHTML = "Full Fee";
	else
		elCell.innerHTML = "Unknown";
};
function getHoverStr(msg) {
    if (msg == "")
        return "";
    return " onmouseover=\"showToolTip(this,'" + msg + "');\" onmouseout=\"hideToolTip();\" ";
}
function showToolTip(oThis, title) {
    if (title != null && title != "" && generalOverlay) {
        generalOverlay.cfg.setProperty("context", [oThis, "bl", "tl"]);
        if (title.length > 35)
            generalOverlay.cfg.setProperty("width", "250px");
        else
            generalOverlay.cfg.setProperty("width", "125px");
        YD.get("generalOverlayHtmlContainer").innerHTML = "<div class='tooltip-area'>" + title + "</div>";
        generalOverlay.show();
    }
}
function hideToolTip() {
    if (generalOverlay)
        generalOverlay.hide();
}
function registerKeyDownHandler(elementId, buttonId)
{
	YE.on(elementId, "keydown", function(event)
	{
			// process only the Enter key
		if (event.keyCode == 13)
		{
		    // cancel the default submit
		    event.returnValue=false;
		    event.cancel = true;
		    // submit the form by programmatically clicking the specified button
		    YD.get(buttonId).click();
		}	
	});	
}
function registerKeyDownEvent(elementId, evt)
{
	YE.on(elementId, "keydown", function(event)
	{
			// process only the Enter key
		if (event.keyCode == 13)
		{
			// cancel the default submit
		    event.returnValue=false;
		    event.cancel = true;
		    evt();
		}	
	});	
}
function removeKeyDownEvent(elementId)
{
	YE.removeListener(elementId, "keydown");
}
function findPos(obj, offset) {
	var curleft = curtop = 0;

	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}

	if (offset)
		curtop -= offset;
	return [curleft + 18,curtop + 18];
}
function selectFromList(dropDown, val)
{
	var selectedIndex = 0;
	for (i = 0; i < dropDown.options.length; i++)
	{
		if (dropDown.options[i].value.toUpperCase() == val.toUpperCase())
		{
			selectedIndex = i;
			break;
		}
	}
	dropDown.selectedIndex = selectedIndex;
}
function addToList(dropDown, val, id)
{
    try
    {
        dropDown.add(new Option(val, id),  null);
    }
    catch (e)
    {
        dropDown.add(new Option(val, id));
    }
}
function clearSelect(dropdown)
{
    while(dropdown.options.length > 0)
    {
        dropdown.removeChild(dropdown.options[0]);
    }
}
function html_entity_decode(str) 
{
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  val =  ta.value;
  val = val.replace(/\n/g, "\n");
  val = val.replace(/<br\>/g, "\n");
  return val;
}
function getElementsBySelector(selector)
{
	var i;
	var s=[];
	var selid="";
	var selclass="";
	var tag=selector;
	var objlist=[];

	if(selector.indexOf(" ")>0)
	{  //descendant selector like "tag#id tag"
    	s=selector.split(" ");
    	var fs=s[0].split("#");
    	if(fs.length==1) 
    		return(objlist);
    	
    	return(document.getElementById(fs[1]).getElementsByTagName(s[1]));
    }

    if(selector.indexOf("#")>0)
    { //id selector like "tag#id"
    	s=selector.split("#");
    	tag=s[0];
    	selid=s[1];
    }
    
	if(selid!="")
	{
    	objlist.push(document.getElementById(selid));
    	return(objlist);
    }
    
	if(selector.indexOf(".")>0)
	{  //class selector like "tag.class"
    	s=selector.split(".");
    	tag=s[0];
    	selclass=s[1];
    }
    
	var v=document.getElementsByTagName(tag);  // tag selector like "tag"
	if(selclass=="")
    	return(v);

    for(i=0;i<v.length;i++)
    {
    	if(v[i].className==selclass)
    	{
        	objlist.push(v[i]);
        }
    }

    return(objlist);
}

function getOptionName(optionId, options)
{
	for (var i = 0; i < options.length; i++)
	{
		if (options[i].id == optionId)
			return options[i].name;
	}	
	
	return null;
}
function MultiSelector(ctId, tGroup, hd, aGroup)
{
	// Get the controls from the selector 
	this.selector = YD.get(ctId + "-multi-selector");
	this.clear = YD.get(ctId + "-clear");
	this.message = YD.get(ctId + "-multi-selector-msg");
	this.selections = YD.get(ctId);
	this.controlId = ctId;
	this.header = hd;
	this.tagGroup = tGroup;
	this.allGroup = aGroup;
	this.optionDialog = null;
	this.isShowFullMessage = false;
	this.columnWidth = 175;
	this.isAll = null;
	var oThis = this;
	
	this.showOptions = function()
	{
		if (oThis.isAll)
			var options = oThis.allGroup;
		else
			var options = oThis.tagGroup;
		if (oThis.optionDialog == null)
		{
			var html = "";
	        oThis.optionDialog =    
		     new YAHOO.widget.SimpleDialog(oThis.controlId + "dialog",    
	                                  { fixedcenter : true,  
		                                zindex:100,
	                                    visible: false,   
	                                    draggable: false,   
	                                    close: true,   
	                                    text: html,   
	                                    buttons: [ { text:"Ok", handler:oThis.select, isDefault:true }, 
	                                    			{ text:"Clear", handler:oThis.clear},  
	                                               { text:"Cancel",  handler:oThis.cancel} ]   
	                                  } );   
	        if (oThis.header)
			    oThis.optionDialog.setHeader(oThis.header);
			else
				oThis.optionDialog.setHeader("Select options...");
			oThis.optionDialog.render(document.body);
			oThis.isAll = false;
		}
		
		oThis.optionDialog.show();
		oThis.refreshOptions(oThis.isAll);
	};
	this.refreshOptions = function(isAll)
	{
		oThis.isAll = isAll;
		if (oThis.isAll)
			var options = oThis.allGroup;
		else
			var options = oThis.tagGroup;
		
		var html = "";
		var columns = 0;
		var columnCount = 15;
		
		for (var i = 1; i <= options.length; i = i + columnCount)
		{
			columns++;
		}
		html += "<table>";
		for(var i = 0; i < columnCount; i++)
		{
			html += "<tr>";
			
			for (var j = 0; j < columns; j++)
			{
				var ind = i + (j * columnCount);
				
				if (options[ind] != null)
				{
					if (options[ind].id != undefined)
					{
						if (oThis.selections.value.indexOf("," + options[ind].id + ",") != -1 )
							html += "<td style='padding:2px;'><input type=\"checkbox\" id=\"" + oThis.controlId + options[ind].id + "Option\" checked> <label for=\"" + oThis.controlId + options[ind].id + "Option\">" + options[ind].name + "</label></td>";
						else
							html += "<td style='padding:2px;'><input type=\"checkbox\" id=\"" + oThis.controlId + options[ind].id + "Option\"> <label for=\"" + oThis.controlId + options[ind].id + "Option\">" + options[ind].name + "</label></td>";
					}
					else
						html += "<td style='padding:2px;'><input type=\"checkbox\" id=\"" + oThis.controlId + ind + "Option\"> <label for=\"" + oThis.controlId + ind + "Option\">" + options[ind] + "</label></td>";
				}
			}
			html += "</tr>";
		}
		html += "</table>";
		oThis.optionDialog.cfg.setProperty("text", html);
		oThis.optionDialog.hide();
		oThis.optionDialog.show();
		if (YD.get("multiSelectShowAll") != undefined) 
		{
			YE.on("multiSelectShowAll", "click", oThis.showAllOptions);
			YD.get("multiSelectShowAll").checked = isAll;
		}
		
		for (i = 0; i < options.length; i++)
		{
			if (options[i].id != undefined)
				YD.get(oThis.controlId + options[i].id + "Option").checked = (oThis.selections.value.indexOf("," + options[i].id + ",") != -1);
			else
				YD.get(oThis.controlId + i + "Option").checked = (oThis.selections.value.indexOf("," + options[i] + ",") != -1);
		}
	};
	this.showAllOptions = function()
	{
		if (YD.get("multiSelectShowAll").checked)
			oThis.refreshOptions(true);
		else
			oThis.refreshOptions(false);	
	};	
	this.select = function()
	{
		var ids = ",";
		if (oThis.isAll)
			var options = oThis.allGroup;
		else
			var options = oThis.tagGroup;
		for (var i = 0; i < options.length; i++)
		{
			if (options[i].id != undefined)
			{
				if (YD.get(oThis.controlId + options[i].id + "Option").checked)
					ids += options[i].id + ",";
			}
			else
			{
				if (YD.get(oThis.controlId + i + "Option").checked)
					ids += options[i] + ",";
			}
		}
		if (ids == ",")
			ids = "";
		
		oThis.showDisplayMsg(ids);
		oThis.optionDialog.hide();
	};	
	this.showDisplayMsg = function(idStr)
	{
		var msg = "";
		var ids = idStr.substring(1, idStr.length - 1).split(",");

		for (var i = 0; i < ids.length; i++)
		{
			if (oThis.tagGroup[0].id != undefined)
				var optionName = getOptionName(ids[i], oThis.tagGroup);
			else
				var optionName = ids[i];
			if (optionName != null)
				msg += optionName + ", ";
		}
	
		if (msg.length > 0)
			msg = msg.substring(0, msg.length - 2);
	
		if (msg.length > 17 && !oThis.isShowFullMessage)
			oThis.message.innerHTML = "(" + msg.substring(0, 17) + "...)";
		else if (msg.length > 0)
			oThis.message.innerHTML = "(" + msg + ")";
		else
			oThis.message.innerHTML = "(None Selected)";
		oThis.selections.value = idStr;
	};	
	this.setSelections = function(options)
	{
		if (options == null)
			return;
		if (isArray(options)) {
			if (options.length > 0)
			{
				var ids = ",";
				for (var i = 0; i < options.length; i++)
				{
					if (options[i].id != undefined)
						ids += options[i].id + ",";
					else
						ids += options[i] + ",";
				}
				oThis.showDisplayMsg(ids);	
			}	
		}
		else
			oThis.showDisplayMsg("," + options.id + ",");	
	};
	this.reset = function()
	{
		oThis.message.innerHTML = "(None Selected)";
		oThis.selections.value = "";
	};
	this.clear = function()
	{
		var options = oThis.tagGroup;
		for (var i = 0; i < options.length; i++)
		{
			if (options[i].id != undefined)
				YD.get(oThis.controlId + options[i].id + "Option").checked = false;
			else
				YD.get(oThis.controlId + i + "Option").checked = false;
		}
	};
	this.cancel = function()
	{
		oThis.optionDialog.hide();
	};
	YE.on(this.selector, "click", function() { oThis.showOptions(false); });
	YE.on(this.clear, "click", oThis.reset);
}
function isArray(obj) {
	if (obj === null || obj === undefined)
		return false;
   else if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}
function getGridSize(offset) {
    var height = YD.getClientHeight();
    var h = height - 240;
    if (offset != undefined && offset != null)
        h = h - offset;
    return h + "px";
}
function getPopupSize(offset)
{
	var height = YD.getClientHeight();
	if (height > 650)
		height = 600;
	else
		height -= 50;
	if (offset != null && offset != undefined)
		height = height - offset;
	return height + "px";
}
function countDown(sec)
{
	if (sec == 0)
	{
		YAHOO.util.Connect.asyncRequest("GET", ((YGL_URL) ? YGL_URL : "") + "ajaxServices/keepLive.php");
		setTimeout("countDown(300);", 1000);
	}
	else 
	{
		setTimeout("countDown(" + (sec - 1) + ");", 1000);
	}
}
Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (findIndex=0; findIndex<this.length; findIndex++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[findIndex])) {
        if (!returnArray) { returnArray = []; }
        returnArray.push(findIndex);
      }
    } else {
      if (this[findIndex]===searchStr) {
        if (!returnArray) { returnArray = []; }
        returnArray.push(findIndex);
      }
    }
  }
  return returnArray;
};
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};
function showYglGeneralForm(html, width) {
    YD.get("yglGeneralFormContainer").innerHTML = html;
    generalForm.cfg.setProperty("width", ((width) ? width + "px" : ""));
    generalForm.show();
}
function cancelYglGeneralForm()
{
	YD.get("yglGeneralFormContainer").innerHTML = "";
	generalForm.hide();
}
function showError(error)
{
	YD.get("yglGeneralFormContainer").innerHTML = "<div class=\"general-section\"><div class=\"title\">Error:</div></div><div class='error' style='width:400px;'>" + error + "</div>"
		+ "<div class=\"submit-section\"><input type=\"button\" id=\"closeErrorButton\" name=\"closeErrorButton\" value=\"Close\" onclick=\"cancelYglGeneralForm();\" /></div>";
	generalForm.show();
}
function showWarning(warning)
{
	YD.get("yglGeneralFormContainer").innerHTML = "<div class=\"general-section\"><div class=\"title\">Warning:</div></div><div class='error' style='width:400px;'>" + warning + "</div>"
		+ "<div class=\"submit-section\"><input type=\"button\" id=\"closeErrorButton\" name=\"closeErrorButton\" value=\"Close\" onclick=\"cancelYglGeneralForm();\" /></div>";
	generalForm.show();
}
function isResponseValid(res)
{
	if (res.indexOf("WRN:") != -1)
	{
		cancelYglGeneralForm();
		showWarning(res.substring(4));
		return false;
	}
	else if (res.indexOf("ERR:") != -1)
	{
		cancelYglGeneralForm();
		showError(res.substring(4));
		return false;
	}
	else
		return true;
}
function showLoadingMsg(msg)
{
	YD.get("loading-message").innerHTML = msg;
	YD.setStyle("loading-msg-section", "display", "block");
}
function hideLoadingMsg()
{
	YD.get("loading-message").innerHTML = "";
	YD.setStyle("loading-msg-section", "display", "none");
}
function YGLEntryQuickInput(inputEle, titleStr, selectionArray)
{
	this.input = inputEle;
	this.title = titleStr;
	this.selections = selectionArray;
	this.entryOverlay = null;
	this.entryCount = ++currentEntryCount;
	var oThis = this;
	
	this.show = function()
	{
		if (oThis.entryOverlay == null)
		{
			oThis.entryOverlay = new YAHOO.widget.Overlay("entryOverlay" + oThis.input, { visible:false, constraintoviewport:false } ); 
			oThis.entryOverlay.setBody("<div id='entryOverlayHtmlContainer" + oThis.input + "'></div>");
			oThis.entryOverlay.render(document.body); 
		}
		oThis.entryOverlay.cfg.setProperty("context", [oThis.input, "tl", "bl"]);
		oThis.entryOverlay.cfg.setProperty("zindex", 100);
		oThis.entryOverlay.show();
		oThis.showSelectionHtml();
	}
	this.hide = function()
	{
		setTimeout("YD.setStyle('entryOverlay" + oThis.input + "', 'visibility', 'hidden');", 250);
	}
	this.showSelectionHtml = function()
	{
		var html = "<div style='padding:5px;background-color:#fff6d7;border:solid 1px gray;'><table style='min-width:70px;font-size:1.1em;'>";
		html += "<tr><td style='width:50%;'></td><td style='width:50%;text-align:right;'><img src='images/close.gif' class='clickable' onclick='YD.setStyle(\"entryOverlay" + oThis.input + "\", \"visibility\", \"hidden\");' /></td></tr>";
		var i = 0;
		while(i < oThis.selections.length)
		{
			html += "<tr><td style='width:50%;border:dotted 1px gray;padding-left:3px;padding-right:3px;' class='clickable' id='selectionLink-" + oThis.input + "-" + i + "'><a id='selectionLink-" + oThis.input + "-" + i + "Link' href='javascript:void(0);'>" + oThis.selections[i] + "</a></td>";
			i++;
			if (oThis.selections[i] != null)
				html += "<td class='clickable' style='border:dotted 1px gray;padding-left:3px;padding-right:3px;' id='selectionLink-" + oThis.input + "-" + i + "'><a id='selectionLink-" + oThis.input + "-" + i + "Link' href='javascript:void(0);'>" + oThis.selections[i] + "</a></td></tr>";
			else
				html += "<td></td></tr>";
			i++;
		}
		html += "</table></div>";
		
		
		YD.get("entryOverlayHtmlContainer" + oThis.input).innerHTML = html; 
		for(i = 0; i < oThis.selections.length; i++)
		{
			YE.on("selectionLink-" + oThis.input + "-" + i, "click", oThis.select);
			YE.on("selectionLink-" + oThis.input + "-" + i, "mouseover", function() { YD.setStyle(this, "background-color", "#c6e5fd"); } );
			YE.on("selectionLink-" + oThis.input + "-" + i, "mouseout", function() { YD.setStyle(this, "background-color", ""); } );
		}
	}
	
	this.select = function()
	{
		YD.get(oThis.input).value = YD.get(this.id + "Link").innerHTML;
	}
	
	YE.on(this.input, "focus", this.show);
	YE.on(this.input, "blur", this.hide);
}