
// JScript source code
var FAVORITES_DIV = "favorites";
var SEARCHES_DIV = "searches";
var PRESETS_DIV = "presets";
var SHARED_PRESETS_DIV = "sharedpresets";

var favoritesAJAX = null;
var searchesAJAX = null;

//Set class name for element
function SetClass(oThis, className, status){
	window.status=(status)?status:"";
	if(oThis.className == "selected") return;
	oThis.className = className;
	return true
}

function DrawPresets() {
	setTimeout('DrawPresetsDelayed()', 1000);
}

function DrawPresetsDelayed () {
	ProtoAJAX = new Ajax.Request('/re/Service/Property/PresetsListing.php',{method:'post',onComplete:DisplayPresets, onLoading:''});	
}

function DeleteSearch(searchSID) {
	ProtoAJAX = new Ajax.Request('/re/Service/Property/DeleteSearch.php',{method:'post',parameters:'&SearchSID=' + searchSID,onComplete:DisplaySearches, onLoading:""});	
}

function DeletePreset(presetID) {
	ProtoAJAX = new Ajax.Request('/re/Service/Property/DeletePreset.php',{method:'post',parameters:'&PresetID=' + presetID,onComplete:DisplayPresets, onLoading:""});	
}

function GenerateRss (searchSID) {
	url = '/re/Service/Property/RssSearch.php?' + '&SearchSID=' + searchSID;
	window.open(url,"RE4WEBRSS","width=800, height=600, scrollbars=1");
}

function DisplaySearches () {
	//alert(ProtoAJAX.transport.responseText); //debug
	eval(ProtoAJAX.transport.responseText);
	var searches = document.getElementById(SEARCHES_DIV);
	if (searches) {
		searches.innerHTML = "";
		if (DL.length > 0) {
			for (i = 1; i <= DL.length; i++) {
				var deleteLink = '<a href="javascript:DeleteSearch(' + '\''+ DL[i][0] +'\'' +')">Delete</a>';
				var rssLink = '<a href="javascript:GenerateRss(' + '\''+ DL[i][0] +'\'' +')">Rss</a>';
				searches.innerHTML += '<li><a title="Created ' + DL[i][1] + '" href="/re/main/property/search.php?Search_SID=' + DL[i][0] + '">' + DL[i][2] + '</a>' + " (" + deleteLink + ", " + rssLink + ")</li>";
			}
		} else {
			searches.innerHTML = "<li>No Searches Available</li>";
		}
	}
}

function DisplayPresets () {
	//alert(ProtoAJAX.transport.responseText); //debug
	eval(ProtoAJAX.transport.responseText);
	var sharedpresets = document.getElementById(SHARED_PRESETS_DIV);
	var presets = document.getElementById(PRESETS_DIV);

	if (sharedpresets && presets) {
		presets.innerHTML = '<a href="/re/Entity/Property/Preset.php">Add Preset</a><br>';
		sharedpresets.innerHTML = '';
		if (PPL.length > 0) {
			for (i = 1; i < PPL.length; i++) {
				var deleteLink = '<a href="javascript:DeletePreset(' + '\''+ PPL[i][0] +'\'' +')">Delete</a>';
				var editLink = '<a href="/re/Entity/Property/Preset.php?Preset_ID=' + PPL[i][0] + '">Edit</a>';
				presets.innerHTML += '<a title="Created ' + PPL[i][1] + '" href="/re/Entity/Property/Property.php?Preset_ID=' + PPL[i][0] + '">' + PPL[i][2] + '</a>' + ' (' + editLink + ', ' + deleteLink + ')<br />';
			}
		} else {
			presets.innerHTML += "No Presets Available";
		}

		if (SPPL.length > 0) {
			for (j = 1; j < SPPL.length; j++) {
				var userLabel = SPPL[j][0];
				sharedpresets.innerHTML += '<a title="Created ' + SPPL[j][2] + '" href="/re/Entity/Property/Property.php?Preset_ID=' + SPPL[j][1] + '">' + SPPL[j][3] + '</a>' + ' (' + userLabel + ')<br />';
			}
		} else {
			sharedpresets.innerHTML += "No Shared Presets Available";
		}
	}
}

function SelectCounties(stateId) {
	ProtoAJAX = new Ajax.Request('/re/main/Service/CountyListing.php',{method:'post',parameters:'StateId=' + stateId,onComplete:DisplayCounties, onLoading:Loading});	
}

function SelectStates(countryId) {
	ProtoAJAX = new Ajax.Request('/re/main/Service/StateListing.php',{method:'post',parameters:'CountryId=' + countryId,onComplete:DisplayStates, onLoading:Loading});	
}

function Loading () {
}

function SaveCounty (countyId) {
	document.getElementById("SelectedCounty").value = countyId;
}

function SaveState (stateId) {
	document.getElementById("SelectedState").value = stateId;
}


function DisplayCounties () {
	//alert(ProtoAJAX.transport.responseText); //debug
	eval(ProtoAJAX.transport.responseText);
	var cmbCounty = document.getElementById("County");
	if (cmbCounty != null) {
		cmbCounty.options.length = 0;
		for (i = 0; i < DL.length; i++) {
			cmbCounty.options[i] = DL[i];
		}
		cmbCounty.options[0].selected = true;
	}
}

function DisplayStates () {
	//alert(ProtoAJAX.transport.responseText); //debug
	eval(ProtoAJAX.transport.responseText);
	var cmbState = document.getElementById("State");
	if (cmbState != null) {
		cmbState.options.length = 0;
		for (i = 0; i < DL.length; i++) {
			cmbState.options[i] = DL[i];
		}
		cmbState.options[0].selected = true;
	}
	var cmbCounty = document.getElementById("County");
	if (cmbCounty != null) {
		cmbCounty.options[0].selected = true;
	}
}



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DATA GRID class

var CurrentDataGrid = null; //for PRINT functionality
var CurrentDataGridsArray = new Array(); // will include all created objects of DataGrid class  
var DataGrid = function(){};
DataGrid.prototype = {
	name: "",  //This value conect with all objects, elements and IDs names// should be equal with parent element ID 
	helperName: "",
	headGridArray: null, //HEADER should be initialazed as an array like: [["key","Display Name"] , ["Id", "ID"], ["Companyname","Company Name"]] 
	dataGridArray: null,
	headTemplates: null,
	itemTemplates: null, // create cuctom view for cells by array ["{v}","<span class='NameItem'>{v}</span>","<a class='editLink'>{v}</a>"]  will replace "{i}" with curent value from dataGridArray
	pageSortedBy: null, // 
	pageSortedByField: null, // 
	pageSortedByType: null, // 
	showPaging: true,
	showOrdering: true,
	columnsArray: null, //will used if you wont exectly show only columns mentioned in this array  
	//parentElementId: "",  modified to name - please use name insted of this //This value conect with all objects, elements and IDs names 

	PrintButton: null,
	 
	numberFrom: 1,
	arrowImagesSrc: "/re/media/img/navigation/",
	
	imagesSrc: "/re/media/img/navigation/",
	printEl: null,
	printPopup: null,
	FH: null, //filter helper	
	//private
	bindSetTimeoutId: null,
	isFirstBind: true,
	printType: null,
	
	//this elements will used for request to server 
	ProtoAJAX: null,
	ServiceURL:null,
	//this elements will used for request to server end
	
	/************************ This item will used for swich functionality which will added WIDTH style atribute to headers bootons ********/
	/************************ it is temporary added - will eliminated after all screens with datalisting reworking ********/
	advancedHeaderWidth: false,

	/* *************************** Printing Properties *************************** */

	// Element which is used to transfer 'parentElement' from a printing iframe
	// It should be eleminated once we'll make changes to Grid API.
	refPrintElement: null,
	//This element will used for showing all search parameters 
	refPrintParameters: null,
	//This public method will used for finding data from server
	FindData: function (direction) {
		//refresh Print preview window
		if (this.refPrintParameters!= null && this.refPrintParameters.innerHTML != null){
			this.refPrintParameters.innerHTML = ""; 
		}
		if (this.refPrintElement != null && this.refPrintElement.innerHTML != null){
			this.refPrintElement.innerHTML = ""; 
		}
		//refresh Print preview window end
	
		this.FH.PageDirection = direction;
				
		//alert(this.FH.GetRequestParameters());
		this.ProtoAJAX = new Ajax.Request(CreateURL(this.ServiceURL),{method:'post',parameters:this.FH.GetRequestParameters(),onComplete:this.FillData.bind(this), onLoading:""});		
	},
	//This public method will used for filling data from server
	FillData : function () {
		//alert(this.ProtoAJAX.transport.responseText);
		eval(this.ProtoAJAX.transport.responseText);
		this.dataGridArray = DL;
		this.Bind("print");
	},
	Bind: function (type) {
		var oRow;
		var oCell;
		var oddRow = true;
		var parentElement = null;

		if (this.bindSetTimeoutId != null) {
			window.clearTimeout(this.bindSetTimeoutId);
		}
		if (this.isFirstBind) {
			CurrentDataGridsArray.push([this.name, this])
			this.isFirstBind = false;
		}

		// Render grid in print element context 
		if (type == "print") {
			parentElement = this.refPrintElement;
			//will add search parameters into print preview window
			if (this.refPrintParameters != null && this.refPrintParameters.innerHTML != null) {
				this.refPrintParameters.innerHTML = this.FH.RequestParametersToString();
			}			
		} else {
			parentElement = document.getElementById(this.name);
		}


		if (type != "print") {
			// Create a Print button
			this.PrintButton = document.createElement("button");
			this.PrintButton.id = "print"+ this.name;
			this.PrintButton.name = "print"+ this.name;
			this.PrintButton.innerHTML = "Print";
			this.PrintButton.setAttribute('type', 'button');
			
			// Use Prototype Event binding
			Event.observe(this.PrintButton, 'click', this.Print.bind(this));
			/*  Yahoo event binding example
			* YAHOO.util.Event.addListener(this.PrintButton, "click", this.Print, this);
			*/

			// Create a Print All button
			this.PrintAllButton = document.createElement("button");
			this.PrintAllButton.id = "printAll"+ this.name;
			this.PrintAllButton.name = "printAll"+ this.name;
			this.PrintAllButton.innerHTML = "Print All";
			this.PrintAllButton.setAttribute('type', 'button');
			
			// Use Prototype Event binding
			Event.observe(this.PrintAllButton, 'click', this.PrintAll.bind(this));

			/*  Yahoo event binding example
			* YAHOO.util.Event.addListener(this.PrintButton, "click", this.Print, this);
			*/

		}

		// Adds a CSS dataGridContainer class to the parentElement element
		Element.addClassName(parentElement, "dataGridContainer")
		parentElement.innerHTML ='<table cellpadding="0" cellspacing="0" border="0" class="dataGrid">';
		var dataTable = parentElement.firstChild;
		if (this.dataGridArray.length > 0){
			this.GetHeader(dataTable, type);
			for (i=0;i<this.dataGridArray.length;i++){
				oRow = dataTable.insertRow(-1);
				oddRow = ! oddRow;
				oRow.bgColor = oddRow?  "#D3E6F5" : "#FFFFFF";	
				if(this.showOrdering && this.IsActiveColumn(this.headGridArray[0][0])){
					//init list number
					oCell = oRow.insertCell(-1);
					oCell.innerHTML = i + this.numberFrom; 
					oCell.className = "dataGrid-cell" + this.GetCellAlign(0);
				}
				for (c=0;c<this.dataGridArray[i].length;c++){
					if (type == "print" && this.headGridArray[c+1][2]!= null && !this.headGridArray[c+1][2]) {
					// this stape will fail to attend add HTML for Print Preview
					} else {
						oCell = oRow.insertCell(-1);
						oCell.className = "dataGrid-cell" + this.GetCellAlign(c+1);				
						oCell.innerHTML = this.FillCell(this.dataGridArray[i][c], c);			
					}
				}
			}
			this.GetFooter(dataTable, type);
			var PageLoadingTemplate = "<div id=\"{name}PageLoading\" style=\"position:relative; top: 0px; left:0px; text-align:center; background-color: white; margin: 2px; visibility:hidden;\"><nobr><span style=\"color: red; margin:0px 0px 4px 0px;\" >Loading please wait ...</span><img src=\"/re/media/img/navigation/loading.gif\" title=\"Loading\" style=\"cursor:hand;\" /><nobr></div>";
			parentElement.innerHTML += PageLoadingTemplate.replace("{name}", this.name);
		} else {
			//we should show not found message 
			oRow = dataTable.insertRow(-1);
			oCell = oRow.insertCell(-1);	 	    
			oCell.colSpan = 100;
			oCell.align = "center";
			oCell.width = "100%";
			if (type == "print"){oCell.style.color= "red"; oCell.style.fontWeight="bold";} else {oCell.className = "error";}
			oCell.innerHTML = "No records found for your selection criteria. Please adjust search options and " + ((type == "print")?"use printing again.":"try again.");
		}		 				
		
		if (type != "print") {
			// Add "print" button to a "PrintBtnHolder" in a Grid Header.
			// Why are we adding at this place? Because "parentElement" is populated by content at the very end.
			// So we have dynamically get PrintBtnHolder and add button
			document.getElementById('PrintBtnHolder' + this.name).appendChild(this.PrintButton);
			document.getElementById('PrintAllBtnHolder' + this.name).appendChild(this.PrintAllButton);
		}
	},

	//private
	GetHeader: function(dataTable, type) { 
		//this method should to be improved		
		if(this.headGridArray != null) {
			var oRow;
			var oCell;
			var sortedTo = "Asc"; // could be Asc/Desc  
			
			//print buttons adding
			if (type != "print") {
				oRow = dataTable.insertRow(-1);
				oCell = oRow.insertCell(-1);	 	    
				oCell.colSpan = 100;
				oCell.align = "left";
				oCell.width = "100%";

				// Create place holder for hind
				var Hint = document.createElement("span");
				Hint.id = "Hint" + this.name;
				Hint.className = 'gridHeaderHint';
				Hint.innerHTML = 'Click on a grid headers to sort results.';
				oCell.appendChild(Hint);
						
				// Create place holder for print button. Will used by event binding.
				var PrintBtnHolder = document.createElement("span");
				PrintBtnHolder.id = "PrintBtnHolder" + this.name;
				oCell.appendChild(PrintBtnHolder);						

				// Create place holder for print all button. Will used by event binding.
				var PrintAllBtnHolder = document.createElement("span");
				PrintAllBtnHolder.id = "PrintAllBtnHolder" + this.name;
				oCell.appendChild(PrintAllBtnHolder);
				
			}			
			//print buttons adding end
			oRow = dataTable.insertRow(-1);
			oRow.className = "dataGrid-header";
			if (this.FH.PageOrderBy.split("Asc").length >= 2) {
				sortTo = "Desc";
				sortedAs = "Desc";
				this.FH.PageOrderBy = this.FH.PageOrderBy.split("Asc")[0] + sortTo;
			} else if (this.FH.PageOrderBy.split("Desc").length >= 2) {
				sortTo = "Asc";
				sortedAs = "Asc";
				this.FH.PageOrderBy = this.FH.PageOrderBy.split("Desc")[0] + sortTo;
			} else {
				this.FH.PageOrderBy = this.FH.PageOrderBy + "Asc";
				sortTo = "Asc";
				sortedAs = "Asc"; 
			}
			var cellStr = "";
			//columnsArray
			for (i=0;i<this.headGridArray.length;i++){
				if (this.dataGridArray[0].length +1 > i && this.dataGridArray[0] != null &&  this.dataGridArray[0].length != null) {
					if (type == "print" && this.headGridArray[i][2]!= null && !this.headGridArray[i][2]) {
						// this stape will fail to attend add HTML for Print Preview
					} else {
						if(this.IsActiveColumn(this.headGridArray[i][0])){
							isOrderedByThisColumn = this.FH.PageOrderBy.split(this.headGridArray[i][0]).length == 2;
							// First column can't be sortable
							//var isOrderedByThisColumn = (i>0 && this.FH.PageOrderByField == this.headGridArray[i][0]);
							var deltaPx = null;
							if (isOrderedByThisColumn) {deltaPx = 20;}							
							var cellWidth = this.GetCellWidth(i, deltaPx);

							cellStr = "<button " 
								     + ((this.advancedHeaderWidth && cellWidth !="" && cellWidth !=null)?("style=\"width:"+cellWidth+"\""):"") 
								     + " class=\"dataGrid-header-button dataGrid-cell" 
								     + this.GetCellAlign(i) + "\"";
							if (this.headGridArray[i][0] && type != "print") { //without sorting
								cellStr += "onclick=\"" + this.name + "_FH.PageOrderBy = '" + this.headGridArray[i][0] + sortTo + "';  " + this.name + "_FH.PageOrderByField = '" + this.headGridArray[i][0] + "'; " + this.name + "_FH.PageOrderByType = '" + sortTo + "'; Page" + this.name +"List('c');\" type=\"button\" tabIndex=1";
							}			
							cellStr += ">" + this.headGridArray[i][1];
							//AVB Useless code if (this.FH.PageOrderBy.split(this.headGridArray[i][0]).length == 2)
							if (isOrderedByThisColumn)
							{
								cellStr += "<img src=\"" + this.arrowImagesSrc + sortedAs + ".gif\" title=\"" + sortedAs + "\">";
							} 			
							cellStr += "</button>";							
							oCell = oRow.insertCell(-1);	 	    
							oCell.width = cellWidth;
							oCell.className = "dataGrid-cell" + this.GetCellAlign(i);
							oCell.innerHTML = cellStr;
						}
					}
				}			
			}			
		}		
	},
	//private
	IsActiveColumn: function (columnName) {
		var returnValue = false; 
		if(this.columnsArray != null){
			for (columnNumber=0;columnNumber<this.columnsArray.length; columnNumber++){
				if(this.columnsArray[columnNumber] == columnName){
					returnValue = true;
					break;
				}				
			}
		} else {
			returnValue = true;
		}
		return returnValue;	
	},
	//private
	GetCellAlign: function (i) {
		if(this.headTemplates != null && (this.headTemplates.length > i) && this.headTemplates[i][1] != null) {
			return "-" + this.headTemplates[i][1];
		}
		return "";
	},
	//private
	GetCellWidth: function (i, deltaPx) {		
		if(this.headTemplates != null && (this.headTemplates.length > i)) {
			if(this.headTemplates[i].length != null && (this.headTemplates[i].length > 1) && this.headTemplates[i][0] != null){
				return ((deltaPx)?(this.headTemplates[i][0]+deltaPx):this.headTemplates[i][0]) + "px";
			} else if (this.headTemplates[i] != null) {
				return ((deltaPx)?(this.headTemplates[i]+deltaPx):this.headTemplates[i]) + "px";	
			}
		}
		return "";
	},
	//private
	GetFooter: function (dataTable, type) {
		//constants
		var ButtonsTemplate = "<button class=\"btnPageing\" id=\"btn{name}{directionname}\" type=\"button\" onclick=\"Page{name}List('{direction}')\" disabled tabIndex=1 ><img src=\"/re/media/img/navigation/{directionname}pagedisabled.gif\" title=\"{directionname} Page\" align=\"Top\"></button>";
		var	PageInfoTemplate = "&nbsp;<span style=\"color:black;\">{first} - {last} of {count}</span>&nbsp;";
		//var PageLoadingTemplate = "<div id=\"{name}PageLoading\" style=\"position:relative; top: 0px; left:0px; text-align:center; background-color: white; margin: 2px; display: none;\"><nobr><span style=\"color: red; margin:0px 0px 4px 0px;\" >Loading please wait ...</span><img src=\"/re/media/img/navigation/loading.gif\" title=\"Loading\" style=\"cursor:hand;\" /><nobr></div>";
		
		var cellStr = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"dataGrid-navigation\"><tr><td>";
		if (type != "print"){
			cellStr += ButtonsTemplate.replace("{name}", this.name).replace("{name}", this.name).replace("{directionname}", "First").replace("{directionname}", "First").replace("{directionname}", "First").replace("{direction}", "f") ;
			cellStr += ButtonsTemplate.replace("{name}", this.name).replace("{name}", this.name).replace("{directionname}", "Previous").replace("{directionname}", "Previous").replace("{directionname}", "Previous").replace("{direction}", "p") ;
		}
		//alert(this.printType +"  "+ (type != "print" && this.printType != "all"));
		if (type == "print" && this.printType == "all") {
		}	else {
			cellStr +="</td><td width=75 align=\"right\"><nobr>";
			cellStr += PageInfoTemplate.replace("{first}", this.FH.FirstCurrentRecord).replace("{last}", this.FH.LastCurrentRecord).replace("{count}", this.FH.RecordsCount);
			cellStr +="</nobr></td><td>";
		}
		if (type != "print" ){
			cellStr += ButtonsTemplate.replace("{name}", this.name).replace("{name}", this.name).replace("{directionname}", "Next").replace("{directionname}", "Next").replace("{directionname}", "Next").replace("{direction}", "n") ;
			cellStr += ButtonsTemplate.replace("{name}", this.name).replace("{name}", this.name).replace("{directionname}", "Last").replace("{directionname}", "Last").replace("{directionname}", "Last").replace("{direction}", "l") ;
		}
		cellStr +="</td></tr></table>";
		//cellStr += PageLoadingTemplate.replace("{name}", this.name);
		var oRow;
		var oCell;		
		oRow = dataTable.insertRow(-1);
		oCell = oRow.insertCell(-1);	 	    
		oCell.colSpan = 100;
		oCell.align = "center";
		//oCell.width = "100%";		
		oCell.innerHTML = cellStr;
		this.PagingButtonsValidation();
	},
	//private function	
	PagingButtonsValidation : function () {
		if (this.FH.FirstCurrentRecord <= 1) { 
			BtnOff("btn"+this.name+"First"); BtnOff("btn"+this.name+"Previous"); 
		} else {
			BtnOn("btn"+this.name+"First"); BtnOn("btn"+this.name+"Previous");
		}
		if (this.FH.LastCurrentRecord >= this.FH.RecordsCount) { 
			BtnOff("btn"+this.name+"Next"); BtnOff("btn"+this.name+"Last"); 
		} else {
			BtnOn("btn"+this.name+"Next"); BtnOn("btn"+this.name+"Last");
		}
	},
	
	//private methods
	FillCell: function (value, cellNumber){		
		var returnText = this.itemTemplates[cellNumber];
		if (this.itemTemplates != null && this.itemTemplates[cellNumber]) {
			/* Added by Andrew	
			if (value.constructor != null && value.constructor == Array){ 
				for (a=0;a<value.length;a++) {
					returnText = returnText.replace("{v}", EscapeHTML(value[a]));			
				}
			} else {
				returnText = returnText.replace("{v}", EscapeHTML(value));
			}
			*/
			if (value.constructor != null && value.constructor == Array){ 
				for (a=0;a<value.length;a++) {
					returnText = returnText.replace("{v}", value[a]);			
				}
			} else {
				returnText = returnText.replace("{v}", value);
			}
		}		
		return returnText;		
	},
	//public
	GetPagingLoading: function (isLoading) {
		
		var pageLoadingElm = document.getElementById(this.name+ "PageLoading");
		if (pageLoadingElm != null){
			//pageLoadingElm.style.display = (isLoading)?"block":"none";
			pageLoadingElm.style.visibility = (isLoading)?"visible":"hidden";			
		}
		if (isLoading) { 
			BtnOff("btn"+this.name+"Next"); BtnOff("btn"+this.name+"Last"); 
			BtnOff("btn"+this.name+"First"); BtnOff("btn"+this.name+"Previous");			
		}
	},
	Print: function (typeOfPrint) {
		if (typeOfPrint=="all"){
			this.printType = "all";
		} else if (typeOfPrint!="all"){this.printType = "";}		
        var printWinWidth = "800px";
        var printWinHeight = "600px";
		
		/* AB USELESS 
		* this.printEl = document.getElementById(this.name+"Print");
		*/

		// Get Print element and verify whether element exists or not
		// I element doesn't exist, just create it
		if (this.printEl == null) {
			this.printElHack = document.createElement("div");
			this.printElHack.id = "UglyHackObj";
			this.printElHack.RefGrid = this;

			this.printEl = document.createElement("div");
			this.printEl.id = this.name + "Print";
			this.printEl.style.width = printWinWidth;
			this.printEl.style.height = printWinHeight;

			this.printFrame = document.createElement("iframe");
			this.printFrame.id = 'printFrameEl';
			this.printFrame.name = 'printFrame';
			// Add backward reference(will be used rom iframe)
			this.printFrame.RefGrid = this;
			// Prevent ugly IE caching
			this.printFrame.src = CreateURL("media/html/Print/DataList.html?NoIECache=" + ((new Date()).valueOf()));
			this.printFrame.style.width = "100%";
			this.printFrame.style.height = "100%";

			// Append elements
			document.body.appendChild(this.printElHack);
			this.printEl.appendChild(this.printFrame);

			document.body.appendChild(this.printEl);

            /* Avoid this syntax. Deprecated by Andrew.
			* this.printEl.innerHTML = "<iframe width=\"100%\" height=\"100%\" id=\"printFrame\" name=\"printFrame\" src=\"" + CreateURL("media/html/Print/DataList.html") + "\" scrolling = \"auto\"></iframe>";
			*/
		}
    
		if (this.printPopup == undefined || !(this.printPopup instanceof YAHOO.widget.Panel)) {
			this.printPopup = new YAHOO.widget.Panel(this.name+"Print",  {
				iframe: false, 
				fixedcenter: true, 
				constraintoviewport: true, 
				close:true, 
				visible:false, 
				draggable:true,
				underlay: "matte",
				width: printWinWidth,
				height: printWinHeight}  );

			this.printPopup.setHeader("Print Preview");
			this.printPopup.render(); 
			
			/* Bind wethod will be called on iframe loading
			* this.Bind("print");
			*/
		} else {
			// Refresh printing results
			if(this.printType == "all"){
				this.FindData('a');
			}else{
				this.FindData('c');
			}		
		}

		// Show popup window
		this.printPopup.show();
	},
	
	PrintAll: function () {
		this.Print("all");	
	}
}



function EscapeHTML (value) {
	var div = document.createElement('div');
	var text = document.createTextNode(value);
	div.appendChild(text);
	var textReturn = div.innerHTML;
	div = null; text = null;
	return textReturn;
}

//NEW 
//PAGE FILTER all old usege of page filter should to be reworked to usege FilterHelper class. It will help to manage more than one DataGrig on the one page!!!  
var FilterHelper = function(){};

FilterHelper.prototype = {
	PageNumber: 0,
	PageDirection: "c", 
	RecordsCount: 0,
	FirstCurrentRecord: 0,
	LastCurrentRecord: 0,
	PageOrderBy: "",
	PageOrderByField: "",
	PageOrderByType: "",
	ParentElementId: "",
	SearchParameters: new Array(), // [[parametername1,parameter1],[parametername2,parameter2], ... ]
	FormParameters: function() {
		var form = document.getElementById("SubmitForm");
		var strForm = "";
		if(form) {
			strForm = Form.serialize(form);
		}
		return strForm;
	},
	GetPagingInfo: function () {
		var pageInfoElm = document.getElementById("pageInfo"); pageInfoElm.innerHTML = this.FirstCurrentRecord + " - " + this.LastCurrentRecord + " of " + this.RecordsCount; 
		this.PagingButtonsValidation();
	},
	//private function
	
	PagingButtonsValidation : function () {
		if (this.FirstCurrentRecord <= 1) { 
			BtnOff("btnFirstPage"); BtnOff("btnPreviousPage"); 
		} else {
			BtnOn("btnFirstPage"); BtnOn("btnPreviousPage");
		}
		if (this.LastCurrentRecord >= this.RecordsCount) { 
			BtnOff("btnNextPage"); BtnOff("btnLastPage"); 
		} else {
			BtnOn("btnNextPage"); BtnOn("btnLastPage");
		}
	},
	
	GetRequestParameters: function () {
		var serachParRequest = "";
		for (var i=0;i<this.SearchParameters.length;i++) {
			serachParRequest += "&"+this.SearchParameters[i][0]+"="+this.SearchParameters[i][1]; 
		}
		var formParameters = this.FormParameters();
		return (formParameters != "" ? formParameters + "&" : "") +  "&PageDirection="+this.PageDirection+"&PageNumber="+ this.PageNumber+"&PageOrderBy="+this.PageOrderBy + "&OrderByField="+this.PageOrderByField +  "&OrderByType=" + 
	this.PageOrderByType + serachParRequest;
	},
	
	RequestParametersToString: function () {
		
		var form = document.getElementById("SubmitForm");
		var elements = null;
		var strParameters = "";
		if(form) {
			elements = Form.getElements(form);
		}
		if (elements!=null){
			for (var i=0;i<elements.length;i++) {
				if(elements[i].value != null && elements[i].value != "" && elements[i].getAttribute("displayName") != null && elements[i].getAttribute("displayName") != ""){strParameters += " " + elements[i].getAttribute("displayName") + ":"+elements[i].value+","}; 
			}		
		}
		return strParameters;
	},

	GetPagingLoading: function (isLoading) {
		var pageLoadingElm = document.getElementById("pageLoading");
		pageLoadingElm.style.visibility = (isLoading)?"visible":"hidden";
		if (isLoading) { 
			BtnOff("btnNextPage"); BtnOff("btnLastPage"); 
			BtnOff("btnFirstPage"); BtnOff("btnPreviousPage"); 		
		}
	}
}
//end///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//POP UP window emulator
var POP_UP = function(){};
POP_UP.prototype = {
	name: "",
	oFrame: null,
	oThis: null,
	innerHTML: "",
	width:"0px", 
	height:"0px",
	top:"200px",
	left:"300px",
	backgroundElement: null,	
	Create: function () {

		this.oFrame = document.createElement("iframe");
		this.oFrame.id = "myFrame";
		this.oFrame.src = "/re/media/img/empty_white.gif";
		this.oFrame.style.display="none";
		this.oFrame.style.zIndex = 998;
		this.oFrame.style.width = this.width;
		this.oFrame.style.height = this.height;

		this.oThis = document.createElement("div");

		this.oThis.className = "popupElement";
		this.oThis.style.position="absolute";
		this.oThis.style.display="none";
		this.oThis.style.zIndex = 999;
		this.oThis.style.top = this.top;
		this.oThis.style.left = this.left;
		this.oThis.style.width = this.width;
		this.oThis.style.height = this.height;
		this.oThis.innerHTML = this.innerHTML;
		
		document.body.appendChild(this.oThis);
		// Get width and height in case this.width and this.height are empty
		var oDim = Element.getDimensions(this.oThis);
		this.oFrame.style.width = oDim.width;
		this.oFrame.style.height = oDim.height;

		document.body.appendChild(this.oFrame);

	},
	Open: function () {

		this.backgroundElement = document.createElement("img"); 
		this.backgroundElement.className = "popupBackgroundElement";
		//this.backgroundElement.style.width="100%";this.backgroundElement.style.height="100%";this.backgroundElement.style.cursor="wait";this.backgroundElement.style.zIndex=998;this.backgroundElement.style.position="absolute";this.backgroundElement.style.top="0px";this.backgroundElement.style.left="0px";
		this.backgroundElement.src = "/re/media/img/empty.gif";

		this.backgroundElement.style.position="absolute";
		this.backgroundElement.style.zIndex = 990;
		this.backgroundElement.style.top = 0;
		this.backgroundElement.style.left = 0;

		var bodyWidth = document.body.clientWidth;
		var docWidth = document.body.scrollWidth;
		var width = Math.max(docWidth, bodyWidth);
		var bodyHeight = document.body.clientHeight;

		this.backgroundElement.style.width = width + 'px';
		this.backgroundElement.style.height = bodyHeight + 'px';
		document.body.appendChild(this.backgroundElement);

		this.oFrame.style.display="block";		
		this.oThis.style.display="block";		

		// Center elements
		Position.center(this.oFrame);
		Position.center(this.oThis);
	},	
	Close: function () {

		if(this.oThis != null) document.body.removeChild(this.oThis);
		if(this.oFrame != null) document.body.removeChild(this.oFrame);
		if(this.backgroundElement != null)document.body.removeChild(this.backgroundElement);
	}
}


// BUTTONS
function BtnOff(btnId) {
 	var btnEl = document.getElementById(btnId);
	if (btnEl != null && !btnEl.disabled) {
		btnEl.className = btnEl.className + "disabled";
		var imgSrcs = btnEl.firstChild.src.split('.gif');
		var imgSrc = imgSrcs[0] + "disabled.gif";	
		btnEl.firstChild.src = imgSrc;
		btnEl.disabled = true;
	}
}

function BtnOn(btnId) {
 var btnEl = document.getElementById(btnId);
 if (btnEl != null) {
	btnEl.disabled = false;
    btnEl.className = btnEl.className.replace("disabled","");
	btnEl.firstChild.src = btnEl.firstChild.src.replace("disabled","");
 } 
}

/* Center extension to Prototype's Position object 
* http://lists.rubyonrails.org/pipermail/rails-spinoffs/2006-February/002311.html
*/
Position.center = function(element){
	var options = Object.extend({
		zIndex: 999,
		update: false
	}, arguments[1] || {});
	element = $(element)
	if(!element._centered){
		Element.setStyle(element, {position: 'absolute'});
		element._centered = true;
	}
	var dims = Element.getDimensions(element);
	Position.prepare();
	var winWidth = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
	var winHeight = self.innerHeight ||	document.documentElement.clientHeight || document.body.clientHeight || 0;
	var offLeft = (Position.deltaX + Math.floor((winWidth-dims.width)/2));
	var offTop = (Position.deltaY + Math.floor((winHeight-dims.height)/2));
	element.style.top = ((offTop != null && offTop > 0) ? offTop : '0')	+ 'px';
	element.style.left = ((offLeft != null && offLeft > 0) ? offLeft : '0') + 'px';
	if(options.update){
	    /*This may froze browser
		Event.observe(window, 'resize', function(evt){
			Position.center(element);
		}, false);
		*/
		/* This may froze browser
		*Event.observe(window, 'scroll', function(evt){
		*	Position.center(element);
		*}, false);
		*/
	}
}
//UTIL 
function CreateURL(subUrl){var val=window.location.href.split('/'); return val[0]+'//'+val[2]+'/'+val[3]+'/'+subUrl;}


//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////

var app = {
	httpFolder: '/re/Service'
}

app.util = {
    trim: function(str) {
        return str.replace( /^\s*(\S*(\s+\S+)*)\s*$/, "$1" );
    }
}

app.property = {}
app.property.favorites = {

	property_id: null, 
	listEl: null, 
	addEl: null,
	favoriteName: null, 

	init: function(property_id, listEl, opt) {
		// TODO use onDOMReady
		//YAHOO.util.Event.onDOMReady(function() { 
		YAHOO.util.Event.addListener(window, "load", function() { 
			this.property_id = property_id;
			// Favorites UL listing
			this.listEl	= $(listEl);

			// Possible add button
			if (opt && opt.addEl) {
				this.addEl = $(opt.addEl);
			
				var oSelf = this;
				//Register event
				YAHOO.util.Event.addListener(this.addEl, "click", oSelf.add, oSelf);

			}
			if (opt && opt.favoriteName) {
				this.favoriteName = $(opt.favoriteName);
			}
		}.bind(this));
	},

	/**
	* Add to favories
    * @param id Property ID
	*/
	add: function(ev, oSelf) {
		var req = new Ajax.Request(app.httpFolder + '/Property/FavoritesAdd.php',
			{method:'post',
			// Serialize selected postcodes
			parameters:'Property_ID=' + encodeURIComponent(oSelf.property_id) + 
			'&FavoriteName=' + encodeURIComponent(oSelf.favoriteName.value),
			onComplete:oSelf.renderList.bind(oSelf), 
			onLoading:null});	
	},

	renderList: function(doc) {
		// Parse the JSON document
		var jsonData = eval('(' + doc.responseText + ')');

		// Check if had errors on a server
		if (jsonData.Errors.length > 0) {
			alert(jsonData.Errors.join("\n"));
		}
		else {
			// Process FavoriteListing
			if (this.listEl) {
				this.listEl.innerHTML = "";
				var result = "";
				var DL = jsonData.FavoriteListing;
				if (DL.length > 0) {
					for (i = 0; i < DL.length; i++) {
						result += '<li><a title="Created ' + DL[i].CreationDate + '" href="/re/main/property/view.php?Property_ID=' + DL[i].Property_ID + '">' + DL[i].Name + '</a>' + " (" + 
						'<a href="javascript:app.property.favorites.del(' + DL[i].Property_ID + ')">Delete</a>' + 
						 ")</li>";
					}
				} else {
					result = "<li>No Favorites Available</li>";
				}
				this.listEl.innerHTML = result;
			}

			// Show information
			if (jsonData.Info.length > 0) {
				alert(jsonData.Info.join("\n"));
			}
		}
	},

	del: function(property_id) {
		var req = new Ajax.Request(app.httpFolder + '/Property/FavoriteDelete.php',
			{method:'post',
			// Serialize selected postcodes
			parameters:'Property_ID=' + encodeURIComponent(property_id),
			onComplete:this.renderList.bind(this), 
			onLoading:null});	
	}

}

//////////////////////////////////////////////////////////////////////////////////////////////////////
/*
app.copier.init([
	{events: ['change'], elements: ['Email', 'Media_Email']},
	{events: ['change'], elements:['B_FirstName', 'A_FirstName']},
]);
*/
app.copier = {
	opt: null,

	init: function(opt) {
		this.opt = opt;
		// Loop through configuration options
		for (var i = 0, len = opt.length; i < len; ++i) {
			var elements = opt[i].elements;
			// loop through elements
			for (var j = 0, el_len = elements.length; j < el_len; ++j) {
	        	// Add listener
				var el = $(elements[j]);
				if (el) {
					//Register events
					for (var k = 0, ev_len = opt[i].events.length; k < ev_len; ++k) {
						YAHOO.util.Event.addListener(el, opt[i].events[k], this.copy.bind(this));
					}
	    		}
	    	}
		}
	},

	copy: function(ev) {
		// Get event element
		var source = YAHOO.util.Event.getTarget(ev);

		try 
		{
			// Find copy instances
			for (var i = 0, len = this.opt.length; i < len; ++i) {
				var elements = this.opt[i].elements;
				// loop through elements
				for (var j = 0, el_len = elements.length; j < el_len; ++j) {
					if (source.id == elements[j])
					{
						// Loop through all elements and update their value
						var copyElements = elements;
						for (var k = 0, evel_len = copyElements.length; k < evel_len; ++k) {
							// Do not update source element
							if (source.id != copyElements[k])
							{
								var el = $(copyElements[k]);
								if (el) {
									// Do we update input element?
									if (el.nodeName == 'INPUT' && el.type == 'text'){
										if (app.util.trim(el.value) == ''){ 
											el.value = source.value;
										}
									}
									else if (el.nodeName == 'SELECT'){
										// Change only empty selects: "" or 0
										if (el.value == "" || el.value == 0) {
											for (var n = 0, optLen = el.options.length; n < optLen; ++n){
												if (el.options[n].value == source.value) {
													el.options[n].selected = true;
													break;
												}
											} 
										} //if
									}
									else {
										if (app.util.trim(el.innerHTML) == '') {
											el.innerHTML = source.value;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		catch (e) { 
			// do nothing
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Application task processing
*/
app.task = {
	// Checkbox element which initiated status change
	source: null, 
	// Selected status
	Selected: null,

	// Register events
	init: function(el) {
		YAHOO.util.Event.addListener($(el), 'click', this.updateStatus.bind(this));
	},

	/////////////////////////////////////////////
	updateStatus: function(ev)
	{
		// Get event element
		var source = YAHOO.util.Event.getTarget(ev);
		if (source.type != "checkbox") return;

		this.source = source;
		this.selected = this.source.checked;
				
		if (this.selected)
		{
			Status = 'Complete' ;
		}
		else
		{
			Status = 'Open' ;
		}

		// Save section using AJAX call
		var Request = new Ajax.Request(
			app.httpFolder + "/Task/UpdateStatus.php", 
			{
				parameters: "Task_ID=" + encodeURIComponent(this.source.id) + "&Status=" + encodeURIComponent(Status), 
				onComplete: this.onComplete.bind(this),
				onFailure: this.onFailure.bind(this),
				method: 'post',
				asynchronous:true 
			}
		);
				
		//alert(Request) ;
	},
	////////////////////////////////
	onComplete: function (transport) 
	{
		// Parse the JSON document
		var response = eval('(' + transport.responseText + ')');

		// Check if had errors on a server
		if (response.Errors.length > 0) {
			// restore checkbox's state
			this.source.checked = !this.selected;

			alert(response.Errors.join("\n"));
		}
		else {
			// Display confirmation message
			if (this.source.checked)
				alert ("Task has been marked as completed.");
			else
				alert ("Task has been marked as open.");
		}
	},
	///////////////////////////////
	onFailure: function (transport) 
	{
		// restore checkbox's state
		this.source.checked = !this.selected;
				
		alert("Error communicating with the server: " + transport.responseText.stripTags());
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Application map viewer
*/
app.mapMiniViewer = {
	mapEl: null,
	// Google Map Object
	gMap: null, 
	// Default zoom, used to set initial map center
	defaultZoom: 14,

	// Map configuration options
	DefaultMapType: 'Normal',
	NormalMap: true,
	SatelliteMap: true,
	HybridMap: true,
	// Map Controls
	// Creates a control with buttons to pan in four directions, and zoom in and zoom out.
	SmallMapControl: false,
	// 	Creates a control with buttons to pan in four directions, and zoom in and zoom out, and a zoom slider.
	LargeMapControl: false,
	// Creates a control with buttons to zoom in and zoom out.
	SmallZoomControl: true,
	// Creates a control that displays the map scale.
	ScaleControl: false,

	// Register events
	init: function(mapEl) {
		this.mapEl = document.getElementById(mapEl);
		if (GBrowserIsCompatible()) {

			//First of all, add event to free resources on window unload
			YAHOO.util.Event.addListener(window, 'unload', GUnload);
			
			// load map 
			this.loadMap();

		}
		else {
			alert("Sorry, the Google Maps API is not compatible with this browser");
		}
	},

	loadMap: function()
	{

		if (this.gMap == null)
		{
			// Map options
			var opt = {}
			opt.mapTypes = []
			if (this.NormalMap) {
				opt.mapTypes.push(G_NORMAL_MAP);
			}
			if (this.SatelliteMap) {
				opt.mapTypes.push(G_SATELLITE_MAP);
			}
			if (this.HybridMap) {
				opt.mapTypes.push(G_HYBRID_MAP);
			}

			this.gMap = new GMap2(this.mapEl, opt); 

			//this.gMap.setCenter(new GLatLng(37.4419, -122.1419), 13); 

			//Enable double click
			this.gMap.enableDoubleClickZoom();

			// Add controls
			if (this.SmallMapControl) {
				this.gMap.addControl(new GSmallMapControl());
			}
			if (this.LargeMapControl) {
				this.gMap.addControl(new GLargeMapControl());
			}
			if (this.SmallZoomControl) {
				this.gMap.addControl(new GSmallZoomControl());
			}
			if (this.ScaleControl) {
				this.gMap.addControl(new GScaleControl());
			}

			if (opt.mapTypes.length > 1) {
				this.gMap.addControl(new GMapTypeControl());
			}
			
		}
	},

	// Set map center
	setCenter: function(lat, lon)
	{
		var point = new GLatLng(lat, lon);
		this.gMap.setCenter(point, this.defaultZoom);
	},

	// Add overlay to a map
	addOverlay: function(lat, lon)
	{
		var point = new GLatLng(lat, lon);
		//Check if the map was initialized by setCenter() since it was created.
		if (!this.gMap.isLoaded()) {
			this.gMap.setCenter(point, this.defaultZoom);
		}
		this.gMap.addOverlay(new GMarker(point));
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Map geocoder (drag and drop support)
*/
app.mapGeocoder = {

	/* Accuracy Levels
	* 0 	Unknown location. (Since 2.59)
	* 1 	Country level accuracy. (Since 2.59)
	* 2 	Region (state, province, prefecture, etc.) level accuracy. (Since 2.59)
	* 3 	Sub-region (county, municipality, etc.) level accuracy. (Since 2.59)
	* 4 	Town (city, village) level accuracy. (Since 2.59)
	* 5 	Post code (zip code) level accuracy. (Since 2.59)
	* 6 	Street level accuracy. (Since 2.59)
	* 7 	Intersection level accuracy. (Since 2.59)
	* 8 	Address level accuracy. (Since 2.59)
	*/

	accuracy: [
		{
			version: '2.67',
			levels: [
				1, //0
				4, //1
				7, //2
				9, //3
				10, //4
				11, //5
				13, //6
				14, //7
				16 //8
			]
		}
	],

	/**
	* Register map click event
	* @param	none
	*/
	registerMapClick: function() 
	{
		GEvent.addListener(this.gMap, "click", function(overlay, point) {
			// Add dragable marker
			this.addDragableMarker(point);

			// Run callback method
			this.onMapClick(point.lat(), point.lng());
		}.bind(this));
	},

	/**
	* Add dragable marker to a map
	* @param	none
	*/
	addDragableMarker: function(point) 
	{
		this.gMap.clearOverlays();
		var marker = new GMarker(point, {draggable: true});
		this.gMap.addOverlay(marker);
			
		GEvent.addListener(marker, "dragend", function() {
			// Run callback method
			var point = marker.getPoint();
			this.onMapClick(point.lat(), point.lng());
		}.bind(this));
	},

	// Add dragable overlay to a map
	addDragableOverlay: function(lat, lon)
	{
		var point = new GLatLng(lat, lon);
		//Check if the map was initialized by setCenter() since it was created.
		if (!this.gMap.isLoaded()) {
			this.gMap.setCenter(point, this.defaultZoom);
		}
		this.addDragableMarker(point);
	},

	/**
	* Geocode given address and re-center map. Geocode using GClientGeocoder or Yahoo service.
	* @param	{String}	location	Location address
	*/
	geocode: function(address) 
	{
		// Is GClientGeocoder defined
		if (this.gGeocoder == null)
			this.gGeocoder = new GClientGeocoder();
			
		if (this.gGeocoder) 
		{
			/* use more advanced method with results analyses
			this.gGeocoder.getLatLng(
				address,
				function(point) 
				{
					if (!point) 
					{
						alert(address + " not found");
					} else 
					{
						this.gMap.setCenter(point, 14);
					}
				}.bind(this));
			*/

			// Use accuracy for setting proper zoom level
			this.gGeocoder.getLocations(
				address,
				function(response) 
				{
					if (!response || response.Status.code != 200) {

						alert("\"" + address + "\" not found");
					} else {
						place = response.Placemark[0];
						accuracy = place.AddressDetails.Accuracy;
						point = new GLatLng(place.Point.coordinates[1],
											place.Point.coordinates[0]);
						if (this.debug) this.LogWriter.log('"' + address + '" geocoded to accuracy ' + accuracy + ", which is converted to " + this.accuracy[0].levels[accuracy] + ' zoom level', "Info");
						this.gMap.setCenter(point, this.accuracy[0].levels[accuracy]);

						// Add dragable marker 
						this.addDragableMarker(point);

						//Run callback method
						this.onGeocode(place.Point.coordinates[1], place.Point.coordinates[0], this.accuracy[0].levels[accuracy]);
					}
				}.bind(this));
		}
	},

	// Geocode hook
	onGeocode: function(lat, lon, accuracy){},
	// 
	onMapClick: function(lat, lon){}

}

Object.extend(app.mapGeocoder, app.mapMiniViewer);
