// JavaScript Document
App.addProp.Tabs = null, App.addProp.myCal = null, App.addProp.type = null, App.addProp.ID = null, App.addProp.mode = null; 
var fxHood = null, fxResSubtype = null, fxCommSubtype = null, fxResCostIncome = null, fxCoop = null
	fxCondo = null, fxResLease = null, fxCommVacancy = null, fxCommIncome = null, 
	resSubTypeRadios = null, CommSubTypeRadios = null;
	
//mark the region id for russian proeprties to code exceptions
var russia_region_id = 5, region_id = null, description_length = 650;

window.addEvent("domready", function(){
	//exception for russia
	if ($('frm_region_id')) region_id = $('frm_region_id').value;
	if (region_id == russia_region_id){
		description_length = 2000;	
	}
	
	if (thisPage == "addProperty" || thisPage == "updateProperty" || thisPage == "submitProperty"){
	
		//============= LOCATION TAB ====================
		//create teh calendar
		if ($("frm_lease_expiration")){
			App.addProp.myCal = new Calendar({ frm_lease_expiration: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
		}
		
		if ($("estimated_listing_date")){
			App.addProp.myCal_listing_date = new Calendar({ estimated_listing_date: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
		}
		if ($("estimated_auction_date")){
			App.addProp.myCal_auction_date = new Calendar({ estimated_auction_date: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
		}
		if ($("ad_cycle_start")){
			App.addProp.myCal_adcycle_date = new Calendar({ ad_cycle_start: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
		}
		if ($("open_house_date")){
			App.addProp.myCal_oh_date = new Calendar({ open_house_date: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
		}
		
		if ($("frm_rental_start_date")){
			App.addProp.myCal_rent_start = new Calendar({ frm_rental_start_date: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
			App.txtToggle.rental_start_date = new textToggler("frm_rental_start_date", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("frm_rental_start_date").forceDate(true); 
		}
		if ($("frm_rental_end_date")){
			App.addProp.myCal_rent_start = new Calendar({ frm_rental_end_date: 'm/d/Y' }, { duration: 10, direction: 0.5, tweak: {y: -50} });
			App.txtToggle.rental_end_date = new textToggler("frm_rental_end_date", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("frm_rental_end_date").forceDate(true); 
		}
		
		if ($("frm_rental_description")){
			App.txtToggle.rental_end_date = new textToggler("frm_rental_description", { text: "Need to explain the Rental Period?", onClass: "normal", offClass: "gray" }); 
		}
		
		//========== force data type =============
		//===== numbers 
		//basic proerpty numbers
		if ($("frm_zip")){ $("frm_zip").forceNumeric(); }
		if ($("frm_sqft")){ $("frm_sqft").forceNumeric(); }
		if ($("frm_sale_price")){ $("frm_sale_price").forceNumeric(true); }
		if ($("frm_maintenance")){ $("frm_maintenance").forceNumeric(true); }
		if ($("frm_tax_deductible")){ $("frm_tax_deductible").forceNumeric(true); }
		if ($("frm_common_charges")){ $("frm_common_charges").forceNumeric(true); }
		if ($("frm_taxes")){ $("frm_taxes").forceNumeric(true); }
		if ($("frm_lease_amount")){ $("frm_lease_amount").forceNumeric(true); }
		if ($("frm_annual_expenses")){ $("frm_annual_expenses").forceNumeric(true); }
		if ($("frm_annual_income")){ $("frm_annual_income").forceNumeric(true); }
		if ($("frm_rent_amount")){ $("frm_rent_amount").forceNumeric(true); }
		
		if ($("frm_sale_price")){ $("frm_sale_price").forceNumeric(); }
		
		//property feature numbers
		if ($("frm_assessment_amount")){ $("frm_assessment_amount").forceNumeric(true); }
		if ($("frm_building_sqft")){ $("frm_building_sqft").forceNumeric(true); }
		if ($("frm_price_per_sf")){ $("frm_price_per_sf").forceNumeric(true); }
		if ($("frm_retail_sqft")){ $("frm_retail_sqft").forceNumeric(true); }
		if ($("frm_other_sqft")){ $("frm_other_sqft").forceNumeric(true); }
		if ($("frm_cap_rate")){ $("frm_cap_rate").forceNumeric(true); }
		if ($("frm_total_units")){ $("frm_total_units").forceNumeric(true); }
		if ($("frm_residential_units")){ $("frm_residential_units").forceNumeric(true); }
		if ($("frm_commercial_units")){ $("frm_commercial_units").forceNumeric(true); }
		if ($("frm_vacancy_rate")){ $("frm_vacancy_rate").forceNumeric(true); }
		if ($("frm_number_of_elevators")){ $("frm_number_of_elevators").forceNumeric(true); }
		//if ($("frm_bldg_dimension")){ $("frm_bldg_dimension").forceNumeric(true); }
		//if ($("frm_lot_dimension")){ $("frm_lot_dimension").forceNumeric(true); }
		if ($("frm_total_lot_sf")){ $("frm_total_lot_sf").forceNumeric(true); }
		if ($("frm_year_built")){ $("frm_year_built").forceNumeric(true); }
		if ($("frm_year_altered")){ $("frm_year_altered").forceNumeric(true); }
		if ($("frm_stories")){ $("frm_stories").forceNumeric(true); }
		if ($("frm_building_on_lot")){ $("frm_building_on_lot").forceNumeric(true); }
		if ($("frm_market_value")){ $("frm_market_value").forceNumeric(true); }
		if ($("frm_actual_taxes")){ $("frm_actual_taxes").forceNumeric(true); }
		if ($("frm_taxable_value")){ $("frm_taxable_value").forceNumeric(true); }
		if ($("frm_tax_per_sf")){ $("frm_tax_per_sf").forceNumeric(true); }
		
		//listing and auction details numbers
		if ($("frm_original_price")){ $("frm_original_price").forceNumeric(true); }
		if ($("frm_starting_bid")){ $("frm_starting_bid").forceNumeric(true); }
		if ($("frm_bidding_increment")){ $("frm_bidding_increment").forceNumeric(true); }
		if ($("frm_bidding_decrement")){ $("frm_bidding_decrement").forceNumeric(true); }
		
		if ($("frm_penalty")){ $("frm_penalty").forceNumeric(true); }
		if ($("frm_max_bidders")){ $("frm_max_bidders").forceNumeric(true); }
		if ($("frm_seconds_to_closure")){ $("frm_seconds_to_closure").forceNumeric(true); }
		if ($("frm_data_refresh_rate")){ $("frm_data_refresh_rate").forceNumeric(true); }
		if ($("post_closing_penalty_hours")){ $("post_closing_penalty_hours").forceNumeric(true); }
		if ($("frm_max_watchers")){ $("frm_max_watchers").forceNumeric(true); }
		if ($("maximum_bid_increment")){ $("maximum_bid_increment").forceNumeric(true); }
		
		//advertising schedule
		if ($("ad_cycle_interval")){ $("ad_cycle_interval").forceNumeric(true); }
		if ($("ad_no_of_repeat")){ $("ad_no_of_repeat").forceNumeric(true); }
		
		//services
		tempEl = $$("input.quantity");
		if (tempEl){ tempEl.forceNumeric();  }
		tempEl = null;
		tempEl = $$("input.product_price");
		if (tempEl){ tempEl.forceNumeric(true);  } 
		tempEl = null;
		
		
		//=== phone
		if ($("frm_seller_phone")){ $("frm_seller_phone").forcePhone(); }
		if ($("frm_phone")){ $("frm_phone").forcePhone(); }
		if ($("frm_agent_phone")){ $("frm_agent_phone").forcePhone(); }
		if ($("frm_attorney_phone")){ $("frm_attorney_phone").forcePhone(); }
		
		//====== dates
		if ($("frm_lease_expiration")){ 
			App.txtToggle.exp_date = new textToggler("frm_lease_expiration", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("frm_lease_expiration").forceDate(true); 
		}
		if ($("frm_assessment_date")){ 
			App.txtToggle.exp_date = new textToggler("frm_assessment_date", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("frm_assessment_date").forceDate(true); 
		}
		if ($("frm_assessment_expiration")){ 
			App.txtToggle.exp_date = new textToggler("frm_assessment_expiration", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("frm_assessment_expiration").forceDate(true); 
		}
		
		//open house dates
		if ($("open_house_date")){ 
			App.txtToggle.exp_date = new textToggler("open_house_date", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("open_house_date").forceDate(true); 
		}
		tempEl = $$("input.oh_edit_date");
		if (tempEl){ 
			tempEl.forceDate(true); 
		}
		
		
		if ($("estimated_listing_date")){ 
			App.txtToggle.exp_date = new textToggler("estimated_listing_date", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("estimated_listing_date").forceDate(true); 
		}
		if ($("estimated_auction_date")){ 
			App.txtToggle.exp_date = new textToggler("estimated_auction_date", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("estimated_auction_date").forceDate(true); 
		}
		if ($("ad_cycle_start")){ 
			App.txtToggle.exp_date = new textToggler("ad_cycle_start", { text: "mm/dd/yyyy", onClass: "normal", offClass: "gray" }); $("ad_cycle_start").forceDate(true); 
		}
		
		//===== collect the radio DOMs for later use
		if ($("subTypeRadios")) resSubTypeRadios = $("subTypeRadios").getElements("input[id^=res_sub_type]");
		if ($("subTypeRadios")) CommSubTypeRadios = $("subTypeRadios").getElements("input[id^=comm_sub_type]");
		
		
		
		
		//====================== HANDLE EVENTS =================
		//ZIP + neighborhood linkage logic
		
		var reactToZip = function(event){
			if (this.value.length == 5){
				//make sure the zip in included in teh selected city
				App.addProp.matchZipWithCityDB(this.value);
			}
		};
		if ($("frm_zip")){
			$("frm_zip").addEvents({
				"keyup": reactToZip,
				"keydown": reactToZip,
				"change": reactToZip
			});
		}
		
		
		//============= latitude and Longitude
		if ($("property_address_container")){
			var lat = $("frm_latitude"); var lng = $("frm_longitude");
			var addressInputs = $("property_address_container").getElements("input");
		}
		var checkLatLng = function(){
				var i = 0, 
				address_complete = false,
				address_field_count = 0,
				full_address = '', address = '', city = '', state = '', zip = '', country = '';
			
			//alert("asa")
			if (!(lat && lng && addressInputs)) return;
			
			//loop through them to get the address and see if it is completed
			addressInputs.each(function(el, i){
				if (el.name == 'address' && el.value.trim().clean().length > 0) { address_field_count ++; address = el.value; }
				if (el.name == 'city' && el.value.trim().clean().length > 0) { address_field_count ++; city = el.value; }
				if (el.name == 'state' && el.value.trim().clean().length > 0) state = el.value;
				if (el.name == 'zip' && el.value.trim().clean().length > 0) { address_field_count ++; zip = el.value; }
				if (el.name == 'country' && el.value.trim().clean().length > 0) { 
					country = el.value; 
					address_field_count ++; 
				}
				
			});
			
			//see if the address is complete
			if (country == 'United States'){
				if (state != '' && address_field_count >= 4) address_complete = true;
				full_address = address + ", " + city + ", " + state + " " + zip + ", " + country;
			
			//MAJOR exception for Moscow
			} else if (country == 'Россия'){ //Russia
				address_complete = false;
				full_address = address + ", " + city + ", " + country;
			} else {
				if (address_field_count >= 4) address_complete = true;
				full_address = address + ", " + city + " " + zip + ", " + country;
			}
			//alert(address_complete + " " + address_field_count);
			
			//alert(address_complete + " " + address_field_count + ": " + full_address)
			//now geocode the address
			if (address_complete){
				var geocoder = new GClientGeocoder();
				geocoder.getLatLng(full_address, function(point) {
					if (!point) {
						//alert(address + " not found");
						if (window.console) window.console.log(address + " not found");
					} else {
						if (window.console) window.console.log("lat: " + point.y + ", lng: " + point.x);
						lat.value = point.y;
						lng.value = point.x;
					}
				});
			}
		}
		//if lat/long is not there, then send a request
		if (lat && lng && addressInputs){
			if (lat.value == '' || lng.value == ''){
				checkLatLng();
			}
			addressInputs.addEvent("change", checkLatLng);
		}
		
		
		//============== Address Mapping Stuff
		tempEl = $("frm_zip");
		if (tempEl){
			var cityEl = $("frm_fk_city_id"), city_id = 0;
			if (cityEl){
				if (cityEl.value.length) { city_id = cityEl.value; }
			} 
			
			//auto suggest for the zip field
			App.zipSuggest = new autoCompleter("frm_zip", "zipSuggest", {
				method: "post",
				url: "/properties/locations_post.php",
				minLength: 0,
				query: "&step=getZipsDropdownFromCity&city_id=" + city_id,
				width: 'inherit',
				maxChoices: 0,
				className: 'autocompleter',
				className_selected: 'selected',
				className_loading: 'loading',
				zIndex: 42,
				delay: 500,
				onSelect: function(id, keyword){
					//if (id){ $("basic_search_id").value = id; } else { $("basic_search_id").value = ""; }
					checkLatLng();
				},
				onEnter: function(id, keyword){
					//$("basic_search").fireEvent("submit");
				},
				onClick: function(id, keyword){
					//$("basic_search").fireEvent("submit");
				}
			});
		}
		//the city drop down events
		tempEl = $("frm_fk_city_id");
		if (tempEl){
			
			tempEl.addEvent("change", function(event){
				var city_id = this.value;
				
				App.local.zipcodes = null; App.local.zipcodes = [];
				var zipSelect = $("frm_zip");
				$("frm_city").value = this.options[this.selectedIndex].text;
				
				if (thisPage != 'updateProperty') zipSelect.value = "";
				
				var json = new Request.JSON({
					url: "/properties/locations_post.php",
					method: "post",
					autoCancel: true,
					onComplete: function(response){
						if (response.CssClass == "success"){
							if (response.msg == "Found Zips"){ //handle zips return
								//App.local.zipcodes = response.zipcodes;
								var zips = [];
								for (i=0;i<response.zipcodes.length;i++){
									zips[zips.length] = response.zipcodes[i].zipcode;
								}
								App.local.zipcodes = zips;
								
								if (App.local.zipcodes.length == 1){
									zipSelect.value = App.local.zipcodes[0];
									checkLatLng();
								}
							} 
						}
					}
				});
				json.send("step=getZipsFromCity&city_id=" + city_id);
				
				App.zipSuggest.query = "&step=getZipsDropdownFromCity&city_id=" + city_id;
			});
			
			if (thisPage == 'updateProperty') $("frm_fk_city_id").fireEvent("change");
		}
		tempEl = null;
		
		
		//residential radio events
		if (resSubTypeRadios && listing_terms != 'rental'){
			resSubTypeRadios.addEvent("click", function(){
				tempEl = $$("#frm_common_charges, #frm_maintenance");
				if (this.value == "Co-operative"){
					fxCoop.slideIn().chain(function(){ fxResCostIncome.slideIn(); });
					fxCondo.slideOut();
					if (tempEl.length){
						tempEl[0].setProperty('disabled', 'disabled');
						tempEl[1].removeProperty("disabled");
					}
				} else if (this.value == "Condominium" || this.value == "Townhouse" || this.value == "House"){
					fxCoop.slideOut();
					fxCondo.slideIn().chain(function(){ fxResCostIncome.slideIn(); });
					if (tempEl.length){
						tempEl[1].setProperty('disabled', 'disabled');
						tempEl[0].removeProperty("disabled");
					}
				}
				tempEl = null;
				//$("resCostIncome").slide('in');
			});
		}
		
		//residetnail vacancy dropdown
		if ($("frm_res_occupancy")){
			$("frm_res_occupancy").addEvent("change", function(){
				if (this.value == "Occupied"){
					fxResLease.slideIn();
				} else {
					fxResLease.slideOut();
				}
			});
		}
		
		//commercial vacancy dropdown
		if ($("frm_comm_occupancy")){
			$("frm_comm_occupancy").addEvent("change", function(){
				if (this.value == "Partially Occupied" || this.value == "Fully Occupied" || this.value == "Occupied"){
					fxCommIncome.slideIn();
				} else {
					fxCommIncome.slideOut();
				}
			});
		}
		
		
		
		//form submit event - seller's evaluation request
		if ($("frm_submit_new")){
			$("frm_submit_new").addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				var container = $("tab_basic_details");
				var msgBox = $(document.body).getElement(".ajax_message");
				var listing_terms = this.listing_terms.value;
				App.roar.empty();
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_locationTab("submitProperty")){ 
					App.roar.alert("Property Features", "<span class='error'>Please make sure all required fields have been properly filled out. Required fields are marked with <strong>bold</strong> labels. </span>");
					return ; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var success = (result == 'success');
						var msg = json.msg;
						var listingID = json.listingID;
						
						
						if (success){
							if (App.majorUI == "admin"){
									Cookie.write ('message', "<span class='" + json.CssClass + "'>" + msg + "</span>", { duration: 0 });
									window.location.href = "/admin/properties/manage_property.php?id=" + listingID;
									return;
								} else {
									
									window.location.href = "/properties/submit_property.php?listing_terms="+listing_terms+"&confirm=1";
									return;
									//App.roar.alert("Property Features", "<span class='" + result + "'>Your property has been submitted for evaulation.</span>");
									//container.empty();
									
									//var html = "Thank you for requesting your Property Sales Proposal Package. We've sent you an email confirmation. Our agents will start reviewing your details shortly. We may contact you via email or phone if more details are needed. Otherwise, we'll email you as soon as your package is ready. <br /><br /> You can check your My Account page for updates on the Sales Proposal. <br /><br /> &raquo; <a href='/accounts/dashboard.php'>My Account</a>";
									//$("tab_basic_details").set("html", html);
								}
						} else {
							App.addProp.showMsg({ 'type': result, 'msg': msg, 'el': msgBox});
							App.roar.alert("Property Features", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		
		//form submit event - broker's new property
		if ($("frm_submit_new_broker")){
			$("frm_submit_new_broker").addEvent("submit", function(event){
				var e = new Event(event); e.stop(), mode = null, val = true;
				App.roar.empty();
				var container = $("tab_basic_details");
				var msgBox = $(document.body).getElement(".ajax_message");
				
				//======= PERFORM FORM DATA VALIDATION 
				val = App.addProp.validate_locationTab(thisPage);
				if(!val){ 
					App.roar.alert("Property Information", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var success = json.CssClass == 'success';
						var msg = json.msg;
						var listingID = json.listingID;
						
						//uncover the form panel
						container.hideLoading();
						
						if (success && listingID > 0){	//success
							//alert(App.addProp.mode)
							if (App.addProp.mode == "add"){
								Cookie.write ('message', "<span class='" + json.CssClass + "'>" + msg + "</span>", { duration: 0 });
								window.location.href = window.location.href + "?id=" + json.listingID;
							} else {
								if (App.majorUI == "admin"){
									Cookie.write ('message', "<span class='" + json.CssClass + "'>" + msg + "</span>", { duration: 0 });
									window.location.href = window.location.href;
									return;
								} else {
									App.addProp.showMsg({ 'type': 'success', 'msg': msg, 'el': msgBox});
								}
							}
							
						} else { //failure
							if (App.majorUI != "admin"){
								App.addProp.showMsg({ 'type': 'error', 'msg': msg, 'el': msgBox});
								return;
							}
						}
						App.roar.alert("Property Information", "<span class='" + json.CssClass + "'>" + msg + "</span>");
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		
	
	}
	
	if (thisPage == "updateProperty"){
		
		var tempEl = $$("#full_description, #full_description_comm");
		var handleDescriptionText = function(event){
			if (this.id.indexOf("_comm") > -1){
				var tempEl = $("description_char_count_comm");
			} else {
				var tempEl = $("description_char_count");
			}
			if (this.value.length > description_length){
				this.value = this.value.substr(0, description_length);
			}
			tempEl.set("html", ": " + (description_length - this.value.length) + " left");
			tempEl = null;
		};
		/*
		tempEl.addEvents({
			"keydown": handleDescriptionText,
			"keyup": handleDescriptionText
		});
		App.storeEvents(tempEl, "keydown");
		App.storeEvents(tempEl, "keyup");
		tempEl.fireEvent('keyup');
		*/
		tempEl = null;
		
		
		//broker - terminate listing + make listing public
		if ($("property_status")){
			$("property_status").addEvent("submit", function(event){
				var e = new Event(event); e.stop(), modeText = null, btn = null, btnText = null;
				App.roar.empty();
				
				if (this.terminate_listing){
					modeText = "You're about to terminate this listing from public viewing. \n\nTo confirm, click 'Ok'. \nOtherwise, click 'Cancel'.";
					btn = $(this.terminate_listing);
					btnText = this.terminate_listing.value;
				} else {
					modeText = "You're about to publish this listing for public viewing. Once published, the listing will have a 30 day vewing period. The listing will automatically expire after 30 days, if unless you termiate the listign earlier. \n\nTo confirm, click 'Ok'. \nOtherwise, click 'Cancel'.";
					btn = $(this.make_listing_public);
					btnText = this.make_listing_public.value;
				}
				
				var con = confirm(modeText);
				
				if(!con){ 
					return; 
				}
				
				//change the button and disable before submission
				btn.set("value", "Please Wait ...");
				btn.setProperty("disabled", "disabled");
				btn.removeClass("btnThree_3");
				btn.addClass("btnDisabled_3");
				
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var success = json.CssClass == 'success';
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (success){	//success
							Cookie.write ('message', "<span class='" + json.CssClass + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						}
						
						//enable the button
						btn.set("value", btnText);
						btn.removeProperty("disabled");
						btn.addClass("btnThree_3");
						btn.removeClass("btnDisabled_3");
						
						//show message
						App.roar.alert("Property Status", "<span class='" + json.CssClass + "'>" + msg + "</span>");
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		
		
		//form submit event
		if ($("frm_basic_details")){
			$("frm_basic_details").addEvent("submit", function(event){
				var e = new Event(event); e.stop(), mode = null, val = true;
				App.roar.empty();
				var container = $("tab_basic_details");
				var msgBox = $(document.body).getElement(".ajax_message");
				
				//======= PERFORM FORM DATA VALIDATION 
				val = App.addProp.validate_locationTab(thisPage);
				
				if(!val){ 
					App.roar.alert("Property Information", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var success = json.CssClass == 'success';
						var msg = json.msg;
						var listingID = json.listingID;
						
						//uncover the form panel
						
						if (success && listingID > 0){	//success
							//alert(App.addProp.mode)
							if (App.addProp.mode == "add"){
								Cookie.write ('message', "<span class='" + json.CssClass + "'>" + msg + "</span>", { duration: 0 });
								window.location.href = window.location.href + "?id=" + json.listingID;
							} else {
								if (App.majorUI == "admin"){
									Cookie.write ('message', "<span class='" + json.CssClass + "'>" + msg + "</span>", { duration: 0 });
									window.location.href = window.location.href;
									return;
								} else {
									App.addProp.showMsg({ 'type': 'success', 'msg': msg, 'el': msgBox});
								}
							}
							
						} else { //failure
							if (App.majorUI != "admin"){
								App.addProp.showMsg({ 'type': 'error', 'msg': msg, 'el': msgBox});
								container.hideLoading();
								return;
							}
						}
						App.roar.alert("Property Information", "<span class='" + json.CssClass + "'>" + msg + "</span>");
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		
		
		//form for residential property details
		if ($("frm_property_details")){
			$("frm_property_details").addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_property_details");
				var msgBox = $(document.body).getElement(".ajax_message");
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_resDetailsTab()){ 
					App.roar.alert("Property Features", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return ; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var success = json.CssClass == "success";
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						
						if (App.majorUI == "admin"){
							if (success){
								Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
								window.location.href = window.location.href;
								return;
							}
						} else {
							App.addProp.showMsg({ 'type': result, 'msg': msg, 'el': msgBox});
						}
						
						App.roar.alert("Property Features", "<span class='" + result + "'>" + msg + "</span>");
						//uncover the form panel
						container.hideLoading();
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		
		
		//form for commercial property details
		if ($("frm_property_details_comm")){
			$("frm_property_details_comm").addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_commercial_details");
				var msgBox = $(document.body).getElement(".ajax_message");
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_commDetailsTab()){ 
					App.roar.alert("Property Features", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return ; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var success = json.CssClass == "success";
						var msg = json.msg;
						var listingID = json.listingID;
						if (App.majorUI == "admin"){
							if (success){
								Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
								window.location.href = window.location.href;
								return;
							}
						} else {
							App.addProp.showMsg({ 'type': result, 'msg': msg, 'el': msgBox});
						}
						App.roar.alert("Property Features", "<span class='" + result + "'>" + msg + "</span>");
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		
		//form auction details form
		tempEl = $("frm_auction_details");
		//alert(tempEl.id)
		if (tempEl){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_auction_details");
				
				//======= PERFORM FORM DATA VALIDATION
				var mode = $('frm_auction_method').value;
				if(!App.addProp.validate_auctionDetailsTab(mode)){ 
					App.roar.alert("Property Features", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return ; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var success = json.CssClass == "success";
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (success){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Auction Details", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		
		
		//form for new open house
		if ($("frm_add_open_house")){
			$("frm_add_open_house").addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_open_house");
				var msgBox = $(document.body).getElement(".ajax_message");
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_openHouse()){ 
					App.roar.alert("Add New Open House", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				//make sure the time slots are in order
				var start = $("oh_start_time").value;
				var end = $("oh_end_time").value;
				var dtStart = new Date("1/1/2007 " + start);
				var dtEnd = new Date("1/1/2007 " + end);
				difference_in_milliseconds = dtEnd - dtStart;
				if (difference_in_milliseconds <= 0){
					$("oh_end_time").attachError("End Time", "End time must be set after the start time so the open  <br />house duration is at least 30 minutes or more." );
					App.roar.alert("Add New Open House", "<span class='error'>End time must be set after the start time so the open house duration is at least 30 minutes or more.</span>");
				} else {
					$("oh_end_time").detachError();
				}
				
				//return;
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var success = json.CssClass == "success";
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (success){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							if (App.majorUI != "admin"){
								App.addProp.showMsg({ 'type': result, 'msg': msg, 'el': msgBox});
							}
							App.roar.alert("Open House", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						
						//uncover the form panel
						container.hideLoading();
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
		}
		
		//toggler for the OH edit
		tempEl = $$("a.oh_edit");
		if (tempEl.length > 0){
			tempEl.addEvent("click", function(event){ event.stop(); });
			App.ohToggler = new Accordion($$('.oh_edit'), $$('.update_OH_container'), {
				show : -1,
				alwaysHide: true,
				multiopen: true,
				opacity: false,
				duration: 200	
			});
			App.storeEvents(tempEl, "click");
			tempEl = null;
		}
		
		//form submission for OH edit - update existing
		tempEl = $$(".oh_update_forms");
		if (tempEl.length > 0){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				var container = this.getElement(".update_OH_frm_container");
				App.roar.empty();
				
				//======= PERFORM FORM DATA VALIDATION
				//date validation
				if (!App.val.validateDate(this.open_house_date.value)){
					$(this.open_house_date).attachError("Open House Date", "Please supply a future date in proper format.");
					this.open_house_date.focus();
					App.roar.alert("Open House Date", "<span class='error'>Please supply a future date in proper format</span>");
					return;
				} else {
					$(this.open_house_date).detachError();
				}
				//start time
				if (this.start_time.value.length == 0){
					$(this.start_time).attachError("", "", {icon: false});
					this.start_time.focus();
					App.roar.alert("Open House Start Time", "<span class='error'>Please supply a start time.</span>");
					return;
				} else {
					$(this.start_time).detachError();
				}
				//end time
				if (this.end_time.value.length == 0){
					$(this.end_time).attachError("", "", {icon: false});
					this.end_time.focus();
					App.roar.alert("Open House End Time", "<span class='error'>Please supply an end time.</span>");
					return;
				} else {
					$(this.end_time).detachError();
				}
				
				//make sure the time slots are in order
				var start = this.start_time.value;
				var end = this.end_time.value;
				var dtStart = new Date("1/1/2007 " + start);
				var dtEnd = new Date("1/1/2007 " + end);
				difference_in_milliseconds = dtEnd - dtStart;
				if (difference_in_milliseconds <= 0){
					$(this.end_time).attachError("End Time", "End time must be set after the start time so the open  <br />house duration is at least 30 minutes or more." );
					App.roar.alert("Add New Open House", "<span class='error'>End time must be set after the start time so the open house duration is at least 30 minutes or more.</span>");
				} else {
					$(this.end_time).detachError();
				}
				
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var success = json.CssClass == "success";
						var msg = json.msg;
						var listingID = json.listingID;
						
						
						if (success){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Open House", "<span class='" + result + "'>" + msg + "</span>");
						}
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit");
			tempEl = null;
		}
		
		//media aupload form
		tempEl = $$("#frm_media_upload, #frm_report_upload");
		if (tempEl.length){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event);
				App.roar.empty();
				var container = this.getParent(".panel"); //$("tab_media_upload");
				var msgBox = $(document.body).getElement(".ajax_message");
				var frm = this;
				
				if (this.id == "frm_media_upload"){
					mode = "media";
				} else if (this.id == "frm_report_upload"){
					mode = "report";
				}
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_addMedia(mode)){ return false; } 
				
				$("iframe_uploader").addEvent("load", function(event){
					var response = $(top.iframe_uploader.document.body).get("html");
					var json = JSON.decode(response);
					var result = json.CssClass;
					var success = json.CssClass == "success";
					var msg = json.msg;
						
					if (success){
						Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
						window.location.href = window.location.href;
						return;
					} else {
						if (App.majorUI != "admin"){
							App.addProp.showMsg({ 'type': result, 'msg': msg, 'el': msgBox});
						}
						App.roar.alert("Upload Media", "<span class='" + result + "'>" + msg + "</span>");
					}
					
					container.hideLoading();
					$("iframe_uploader").removeEvents();
				});
				
				//cover the form with alpha panel
				container.showLoading();
				
			});
		}
		tempEl = null;
		
		//removing media
		var tempEl = $$("a.delete");
		if (tempEl.length > 0){
			tempEl.addEvent("click", function(event){
				event.stop();
				var con = confirm("Are you sure you'd like to remove this item?");
				if (!con) { return; }
				
				var lnk = this, str = this.href.split("?"), data = null;
				
				if (str[1]){ //make sure the request has a query string
					var urlData = new urlDecoder(str[1]);	
					
					if (urlData.items.removeImage){ //removing media form items
						var id = urlData.items.mediaID, method = "get";
						var deletionAction = function(json){
							if (json.CssClass == "success"){
								var tempEl = $("media_" + id);
								if (tempEl){ tempEl.dispose(); tempEl.destroy(); }
								tempEl = null;
								App.roar.empty();
								App.roar.alert("Remove Media", "<span class='" + json.CssClass + "'>" + json.msg + "</span>");
							} else {
								App.roar.alert("Remove Media", "<span class='" + json.CssClass + "'>" + json.msg + "</span>");
							}
						};
					} else if (urlData.items.step){
						if (urlData.items.step == "delete_open_house"){ //removing open houses
							var id = urlData.items.open_houseID, method = "post";
							data = str[1];
							
							var deletionAction = function(json){
								if (json.CssClass == "success"){
									if (App.majorUI != "admin"){
										var tempEl = $("openHouse_" + id);
										if (tempEl){ tempEl.dispose(); tempEl.destroy(); }
										tempEl = null;
									} else {
										Cookie.write ('message', "<span class='" + json.CssClass + "'>" + json.msg + "</span>", { duration: 0 });
										window.location.href = window.location.href;
										return;
									}
								} else {
									App.roar.alert("Remove Open House", "<span class='" + json.CssClass + "'>" + json.msg + "</span>");
								}
							};
						}
						if (urlData.items.step == "delete_ad_cycle"){ //removing advertisement schedule
							var id = urlData.items.adID, method = "post";
							data = str[1];
							
							var deletionAction = function(json){
								if (json.CssClass == "success"){
									Cookie.write ('message', "<span class='" + json.CssClass + "'>" + json.msg + "</span>", { duration: 0 });
									window.location.href = window.location.href;
									return;
								} else {
									App.roar.alert("Remove Advertisement Schedule", "<span class='" + json.CssClass + "'>" + json.msg + "</span>");
								}
							};
						}
						if (urlData.items.step == "delete_rider"){ //removing advertisement schedule
							var id = urlData.items.riderID, method = "post";
							data = str[1];
							
							var deletionAction = function(json){
								if (json.CssClass == "success"){
									Cookie.write ('message', "<span class='" + json.CssClass + "'>" + json.msg + "</span>", { duration: 0 });
									window.location.href = window.location.href;
									return;
								} else {
									App.roar.alert("Remove Rider", "<span class='" + json.CssClass + "'>" + json.msg + "</span>");
								}
							};
						}
					}
					
					var req1 = new Request({
						url: this.href, 
						method: method,
						autoCancel: false,
						onSuccess: function(responseText, responseXML){
							var json = JSON.decode(responseText);
							deletionAction(json);
						}
					}).send(data);
					
				}
			});
		}
		App.storeEvents(tempEl, "click"); //for garbage collection
		tempEl = null;
		
		
		//form advertising details
		tempEl = $("frm_advertising_details");
		if (tempEl){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_advertising_schedule");
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_adCycle()){ 
					App.roar.alert("Add New Ad Cycle", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return; 
				}
				
				//reset empty dates to empty from format suggestions
				var dateInputs = this.getElements("input[value=mm/dd/yyyy]");
				if (dateInputs) {
					dateInputs.setProperty("value", "");
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Advertisign Schedule", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		//form info and reports
		tempEl = $("info_and_reports_form");
		if (tempEl){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_information_reports");
				
				//======= PERFORM FORM DATA VALIDATION
				//if(!App.addProp.validate_openHouse()){ return; }
				
				//convert WYSIWYG to textarea
				//W1.toTextarea();
				W2.toTextarea();
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Information &amp; Reports", "<span class='" + result + "'>" + msg + "</span>");
						}
						//uncover the form panel
						container.hideLoading();
						
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		//form info and reports
		tempEl = $$("#send_evaluation_form, #send_proposal_form");
		if (tempEl.length > 0){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				
				//======= PERFORM FORM DATA VALIDATION
				//if(!App.addProp.validate_openHouse()){ return; }
				
				//make sure they checked the checkboxes
				if (this.id == "send_evaluation_form"){
					var container = $("tab_send_evaluation");
					var checks = $$("input.evaluation_final_check");
					var msgTitle = "Send Evaluation";
					var check_container = $("evaluation_final_check_container");
				} else {
					var container = $("tab_send_proposal");
					var checks = $$("input.proposal_final_check");
					var msgTitle = "Send Proposal";
					var check_container = $("proposal_final_check_container");
				}
				check_container.removeClass("error");
				
				var matched = true;
				checks.each(function(el, i){
					if (el.checked == false){
						matched = false;
					}
				});
				if (!matched){ 
					check_container.addClass("error");
					App.roar.alert("Warning", "<span class='error'>Please make sure to go through each of the Final Check items, and if completed, select the checkboxes before submission.</span>");
					return;
				}
				check_container.removeClass("error");
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert(msgTitle, "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		//form for removing a listing
		tempEl = $$("form.remove_listing");
		if (tempEl.length > 0){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				
				var con = confirm("You are about to remove this listing from the system. \n\nPress OK if you're sure. \nPress Cancel to discontinue.");
				if (!con){ return false; }
				
				if (this.id == "remove_evaluation_form"){
					var container = $("tab_send_evaluation");
				} else if (this.id == "remove_evaluation_form"){
					var container = $("tab_send_proposal");
				} else {
					var container = this.getParent();
				}
				
				listingID = this.listingID.value;
				
				//======= PERFORM FORM DATA VALIDATION
				//if(!App.addProp.validate_openHouse()){ return; }
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>Web ID " + listingID + ": " + msg + "</span>", { duration: 0 });
							window.location.href = "/admin/properties/incoming.php?filter=search";
							return;
						} else {
							App.roar.alert("Remove Listing", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		//Contract and Rider
		tempEl = $("add_new_rider_form");
		if (tempEl){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_contract_rider");
				
				//======= PERFORM FORM DATA VALIDATION
				if(!App.addProp.validate_addRider()){ 
					App.roar.alert("Add New Rider", "<span class='error'>Please make sure to fill in all required fields - marked with <b>bold labels</b>.</span>");
					return; 
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Contract &amp; Riders", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		//Offer services form
		tempEl = $("proposal_offer_services_form");
		if (tempEl){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_services");
				
				//======= PERFORM FORM DATA VALIDATION
				var matched = true;
				var txtFields = $$("input.quantity, input.product_price");
				txtFields.each(function(el, i){
					if (el.value.clean().trim().length == 0){
						matched = false;
						el.attachError("", "", {icon: false});
					} else {
						el.detachError();	
					}
				});
				
				if (!matched){
					App.roar.alert("Update Services", "<span class='error'>Please make sure that quantity and price fields are not blank when submitted.</span>");
					return;
				}
				
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Update Services", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		
		//Offer services form
		tempEl = $$("#frm_proposal_confirmed_services, #Cproposal_offer_services_form");
		if (tempEl){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				var container = $("tab_confirmed_services");
				
				//======= PERFORM FORM DATA VALIDATION
				//if(!App.addProp.validate_openHouse()){ return; }
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Update Services", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						//uncover the form panel
						container.hideLoading();
						
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		
		//Offer services form
		tempEl = $$("#frm_update_listing_status, #frm_skip_proposal, #frm_close_listing, #frm_hide_listing");
		if (tempEl.length){
			tempEl.addEvent("submit", function(event){
				var e = new Event(event); e.stop();
				App.roar.empty();
				
				if (this.id == "frm_update_listing_status"){
					var container = $("tab_status");
				} else {
					var container = this.getParent();
				}
				
				//======= PERFORM FORM DATA VALIDATION
				//if(!App.addProp.validate_openHouse()){ return; }
				//check before making listing public
				if (this.step.value == "make_listing_public"){
					var con = confirm("Are you sure you'd like to make this listing public?");	
					if (!con){
						return;	
					}
				} else if (this.step.value == "hide_listing"){
					var con = confirm("Are you sure you'd like to HIDE this listing from the public?");	
					if (!con){
						return;	
					}
				} else if (this.step.value == "unhide_listing"){
					var con = confirm("Are you sure you'd like to UN-HIDE this listing from the public?");	
					if (!con){
						return;	
					}
				} else 
				//check before removing listing
				if (this.step.value == "remove_listing"){
					var con = confirm("Are you sure you'd like to REMOVE this listing?");	
					if (!con){
						return;	
					}
				} else 
				//check before removing listing
				if (this.step.value == "update_listing_status"){
					
					if (this.id == "frm_update_listing_status"){
						if (!$("rdo_sold_close").checked && !$("rdo_close_nosale").checked){
							$("rdoGroup_close_status").attachError("", "", {icon: false});
							App.roar.alert("Change Listing Status", "<span class='notice'>Please choose a closing status first</span>");
							return;
						} else {
							$("rdoGroup_close_status").detachError();
						}
					}
					
					if (this.statusID.value == 8){
						var con = confirm("You are about to carry out one of the following actions: \n\n - Skip the Proposal Phase for this listing, or \n- Confirm the Sales Proposal on seller's behalf.");	
					} else {
						var con = confirm("Are you sure you'd like to close this listing now?");	
					}
					
					if (!con){
						return;	
					}
					
				}
				
				//cover the form with alpha panel
				container.showLoading();
				
				//========= set the AJAX send parameters
				this.set('send', {
					//what to do once submit action is completed
					onComplete: function(response) { 
						//******** HANDLE "POST" SUBMISSION RESPONSE *********
						var json = JSON.decode(response);
						var result = json.CssClass;
						var msg = json.msg;
						var listingID = json.listingID;
						
						if (result == "success"){
							Cookie.write ('message', "<span class='" + result + "'>" + msg + "</span>", { duration: 0 });
							window.location.href = window.location.href;
							return;
						} else {
							App.roar.alert("Change Listing Status", "<span class='" + result + "'>" + msg + "</span>");
						}
						
						
						//uncover the form panel
						container.hideLoading();
						//******* END HANDLING POST DATA RESPONSE ********
					}
				});
				//Send the form data - with delay to show fake load time
				this.send();
			});
			App.storeEvents(tempEl, "submit"); //for garbage collection
			tempEl = null;
		}
		
		
		//Offer services form
		tempEl = $$("#frm_send_closing_email_seller, #frm_send_closing_email_buyer");
		if (tempEl){
			tempEl.addEvent("click", function(event){
				var container = $("tab_status");
				
				var con = confirm("Are you sure you'd like to send this email?");
				if (!con){ return; }
				
				//======= PERFORM FORM DATA VALIDATION
				//if(!App.addProp.validate_openHouse()){ return; }
				//set the step for the post
				if (this.id == "frm_send_closing_email_seller"){
					var step = "send_closing_email_seller";
				} else if (this.id == "frm_send_closing_email_buyer"){
					var step = "send_closing_email_buyer";
				}
				var listingID = this.getProperty("rel");
				
				//cover the form with alpha panel
				container.showLoading();
				App.roar.empty();
				
				var jsonReq = new Request.JSON({
					url: "property_post.php",
					method: "post",
					autoCancel: true,
					onComplete: function(response){
						var result = response.CssClass;
						var msg = response.msg;
						var listingID = response.listingID;
						
						//uncover the form panel
						container.hideLoading();
						
						App.roar.alert("Send Email", "<span class='" + result + "'>" + msg + "</span>");
						
					}
				});
				jsonReq.send("step="+ step +"&listingID="+listingID);
				
			});
			App.storeEvents(tempEl, "click"); //for garbage collection
			tempEl = null;
		}
		
		
		
		
	} //end add/update property page code
	
});

App.addProp.showMsg = function(obj){
	//obj.type	= "error" | "success"
	//obj.msg = string
	//obj.el = the message container - DOM element
	if (obj.type){
		obj.msg = "<div class='" + obj.type + "'>" + obj.msg + "</div>";
	}
	obj.el.set('html', obj.msg);
}

//used for making sure the zip supplied is in the range
App.addProp.matchZipWithCityDB = function(zip){
	var i = 0, zips = App.local.zipcodes;
		
	//zip = zip.toInt();
	
	//check if it is within the acceptable ZIP area
	if (!zips.contains(zip)){
		//alert("sdsd");
		$("frm_zip").attachError("ZIP Code", "Your ZIP code does not match our database for the city you selected.");
		return;
	}
	$("frm_zip").detachError(); 
	
}


App.addProp.validate_locationTab = function(mode){
	var matched = true, subTypeRadios = null, radioMatch = false, radioIndex = -1, i = 0, msg = "";
	
	if (mode == "submitProperty"){
		if ($("frm_firstName")){
			//name validation
			matched = App.val.validate($("frm_firstName"), {
				required: true, minLength: 2, title: "First Name", 
				message: "Please supply your first name."
			}, matched);
		}
		
		if ($("frm_lastName")){
			//name validation
			matched = App.val.validate($("frm_lastName"), {
				required: true, minLength: 2, title: "Last Name", 
				message: "Please supply your last name."
			}, matched);
		}
		
		if ($("frm_email")){
			//name validation
			matched = App.val.validate($("frm_email"), {
				required: true, checkFormat: "email", title: "Email Address", 
				message: "Please supply a valid email address."
			}, matched);
		}
		
		if ($("frm_phone")){
			//phone
			matched = App.val.validate($("frm_phone"), {
				required: true, checkFormat: "phone", minLength: 10, title: "Phone Number", 
				message: "Supply your phone number so our agents may get back to you."
			}, matched);
		}
		/*
		if ($("submitterRole")){
			//property type validation
			matched = App.val.validate($("submitterRole"), {
				required: true, minLength: 1, title: "Your Role", 
				message: "Please tell us if you're the property owner or how you relate to the owner."
			}, matched);
		}
		*/
		if ($("frm_seller_address1")){
			//address
			matched = App.val.validate($("frm_seller_address1"), {
				required: true, checkFormat: "alphanumeric", minLength: 5, title: "Your Street Address", 
				message: "Supply your street address."
			}, matched);
		}
		if ($("frm_seller_city")){
			//address
			matched = App.val.validate($("frm_seller_city"), {
				required: true,  minLength: 3, title: "Your City", 
				message: "Supply your city name."
			}, matched);
		}
		if ($("frm_seller_zip")){
			//address
			matched = App.val.validate($("frm_seller_zip"), {
				required: true,  minLength: 3, title: "Your ZIP/Postal Code", 
				message: "Supply your ZIP or Postal code."
			}, matched);
		}
		if ($("frm_seller_country")){
			//address
			matched = App.val.validate($("frm_seller_country"), {
				required: true,  minLength: 2, title: "Your Country", 
				message: "Supply your country name."
			}, matched);
		}
		//state validation
		if ($("frm_seller_country")){
			if ($("frm_seller_country").value == "United States"){
				matched = App.val.validate($("frm_seller_state"), {
					required: true, minLength: 2, title: "State", 
					message: "Please supply your state name."
				}, matched);
			}
		}
		
		//====== broker's validation
		if ($("chk_have_broker").checked || $("chk_have_broker").selectedIndex == 1){
			if (!$("fk_owners_agent").value.clean().trim().length){
				if ($("frm_agent_firstName")){
					//name validation
					matched = App.val.validate($("frm_agent_firstName"), {
						required: true, minLength: 2, title: "Agent's First Name", 
						message: "Please supply your agent's first name."
					}, matched);
				}
				
				if ($("frm_agent_lastName")){
					//name validation
					matched = App.val.validate($("frm_agent_lastName"), {
						required: true, minLength: 2, title: "Agent's Last Name", 
						message: "Please supply your agent's last name."
					}, matched);
				}
				
				if ($("frm_agent_email")){
					//name validation
					matched = App.val.validate($("frm_agent_email"), {
						required: true, checkFormat: "email", title: "Agent's Email Address", 
						message: "Please supply your agent's valid email address."
					}, matched);
				}
				
				if ($("frm_agent_phone")){
					//phone
					matched = App.val.validate($("frm_agent_phone"), {
						required: true, checkFormat: "phone", minLength: 10, title: "Agent's Phone Number", 
						message: "Supply your agent's phone number."
					}, matched);
				}
			}
		}
		
		//====== attorney's validation
		if ($("chk_have_attorney")){
			if ($("chk_have_attorney").checked){
				if (!$("fk_owners_attorney").value.clean().trim().length){
					if ($("frm_attorney_firstName")){
						//name validation
						matched = App.val.validate($("frm_attorney_firstName"), {
							required: true, minLength: 2, title: "Agent's First Name", 
							message: "Please supply your agent's first name."
						}, matched);
					}
					
					if ($("frm_attorney_lastName")){
						//name validation
						matched = App.val.validate($("frm_attorney_lastName"), {
							required: true, minLength: 2, title: "Agent's Last Name", 
							message: "Please supply your agent's last name."
						}, matched);
					}
					
					if ($("frm_attorney_email")){
						//name validation
						matched = App.val.validate($("frm_attorney_email"), {
							required: true, checkFormat: "email", title: "Agent's Email Address", 
							message: "Please supply your agent's valid email address."
						}, matched);
					}
					
					if ($("frm_attorney_phone")){
						//phone
						matched = App.val.validate($("frm_attorney_phone"), {
							required: true, checkFormat: "phone", minLength: 10, title: "Agent's Phone Number", 
							message: "Supply your agent's phone number."
						}, matched);
					}
				}
			}
		}
		
		if ($("chk_confirm")){
			matched = App.val.validate($("chk_confirm"), {
				required: true, checked: true, title: "", 
				message: "Please select the checkbox to provide <br />your acceptance before you continue."
			}, matched);
		}
	}
	
	if (App.majorUI == "admin"){
		//==== seller's info
		//seller's phone validation{
		if ($("frm_seller_phone")){
			matched = App.val.validate($("frm_seller_phone"), {
				required: true, minLength: 1, checkFormat: "phone", title: "Seller's Phone", 
				message: "Please supply seller's phone number."
			}, matched);
		}
		
		
		//=== owner's info
		//name validation
		if ($("frm_ownerFirstName")){
			matched = App.val.validate($("frm_ownerFirstName"), {
				required: true, minLength: 2, title: "First Name", 
				message: "Please supply owner's first name."
			}, matched);
		}
		//name validation
		if ($("frm_ownerLastName")){
			matched = App.val.validate($("frm_ownerLastName"), {
				required: true, minLength: 2, title: "Last Name", 
				message: "Please supply owner's last name."
			}, matched);
		}
		//address validation
		if ($("frm_ownerAddress1")){
			matched = App.val.validate($("frm_ownerAddress1"), {
				required: true, minLength: 5, title: "Street Address", 
				message: "Please supply owner's street address."
			}, matched);
		}
		//city validation
		if ($("frm_ownerCity")){
			matched = App.val.validate($("frm_ownerCity"), {
				required: true, minLength: 2, title: "City", 
				message: "Please supply owner's city."
			}, matched);
		}
		//zip validation
		if ($("frm_ownerZip")){
			matched = App.val.validate($("frm_ownerZip"), {
				required: true, minLength: 2, title: "ZIP/Postal Code", 
				message: "Please supply owner's ZIP/Postal Code."
			}, matched);
		}
		//country validation
		if ($("frm_ownerCountry")){
			matched = App.val.validate($("frm_ownerCountry"), {
				required: true, minLength: 2, title: "Country", 
				message: "Please supply owner's country."
			}, matched);
		}
		
		//state validation
		if ($("frm_ownerCountry")){
			if ($("frm_ownerCountry").value == "United States"){
				matched = App.val.validate($("frm_ownerState"), {
					required: true, minLength: 2, title: "State", 
					message: "Please supply owner's state."
				}, matched);
			}
		}
		
	}
	
	//address 1 validation
	matched = App.val.validate($("frm_address_1"), {
		required: true, minLength: 5, checkFormat: "alphanumeric", title: "Street Address", 
		message: "Please supply the property street address. Address <br />must contain both numbers and letters."
	}, matched);
	
	
	//address 1 validation
	matched = App.val.validate($("frm_fk_city_id"), {
		required: true, minLength: 1,  title: "City Name", 
		message: "Please select a city name from the list."
	}, matched);
	
	//ZIP validation
	matched = App.val.validate($("frm_zip"), {
		required: true, minLength: 5, checkAgainst: App.local.zipcodes, title: "ZIP Code", 
		message: "Please supply the property ZIP code."
	}, matched);
	
	/*
	if ($("frm_zip").value.length == 5){
		matched = App.val.validate($("frm_neighborhood"), {
			required: true, minLength: 3, title: "Neighborhood", 
			message: "Neighbhood was not detected."
		}, matched);
	}
	*/
	
	//property type validation
	matched = App.val.validate($("frm_type"), {
		required: true, minLength: 2, title: "Property Type", 
		message: "Please choose the property type."
	}, matched);
	
	//property sub-type validation
	var propType = $("frm_type").value;
	if ($("frm_type").value.length > 0){
		
		if (propType == "Residential"){
			$("residential_sub_type").getElement(".radioGroup").detachError(); 
			subTypeRadios = $("subTypeRadios").getElements("input[id^=res_sub_type]");
			msg = "Please specify the residential property type.";
		} else if (propType == "Commercial"){
			$("commercial_sub_type").getElement(".radioGroup").detachError(); 
			subTypeRadios = $("subTypeRadios").getElements("input[id^=comm_sub_type]");
			msg = "Please specify the commercial property type.";
		}
		radioMatch = false;
		for (i=0;i<subTypeRadios.length;i++){
			if (subTypeRadios[i].checked){
				radioMatch = true;
				radioIndex = i;
				break;
			}
		}
		if (!radioMatch){
			if (propType == "Residential"){
				$("residential_sub_type").getElement(".radioGroup").attachError("Property Type", msg); 
			} else if (propType == "Commercial"){
				$("commercial_sub_type").getElement(".radioGroup").attachError("Property Type", msg); 
			}
			matched = false;
		} else {
			if (propType == "Residential"){
				$("residential_sub_type").getElement(".radioGroup").detachError(); 
			} else if (propType == "Commercial"){
				$("commercial_sub_type").getElement(".radioGroup").detachError(); 
			}
		}
		
		//the SQF and B/B
		if (mode == "submitProperty" && propType == "Residential"){
			//property square footage
			matched = App.val.validate($("frm_sqft"), {
				required: true, minLength: 2, title: "Square Footage", 
				message: "Please supply the square footage."
			}, matched);
			
			//temp exception for Russian properties
			if (region_id != russia_region_id){
				//property beds 
				matched = App.val.validate($("frm_beds"), {
					required: true, minLength: 1, title: "Number of Bedrooms", 
					message: "Please supply the number of bedrooms."
				}, matched);
				
				//property baths
				matched = App.val.validate($("frm_baths"), {
					required: true, minLength: 1, title: "Number of Bathrooms", 
					message: "Please supply the number of bathrooms."
				}, matched);
			}
		}
		
	}
	
	if (mode == "addProperty"){
		//property type validation
		matched = App.val.validate($("frm_sale_price"), {
			required: true, minLength: 4, title: "Sale Price", 
			message: "Please supply a sale price for the property."
		}, matched);
	}
	
	
	
	if ((App.majorUI == "admin" || mode == "submitProperty" || mode == "addProperty") && propType == "Residential" && radioMatch){ //address supplied + subtype has been selected  
		//added temp exception for Russian properties - should be checked if it is needed later
		if ($("frm_type").value == "Residential" && region_id != russia_region_id){
			if (!$('rentalDetailsContainer')){
				if (subTypeRadios[radioIndex].value == "Co-operative"){
					//common charges
					matched = App.val.validate($("frm_maintenance"), {
						required: true, minLength: 1, title: "CC/Maintenance", 
						message: "Please supply the CC/Maintenance charges."
					}, matched);
					
					//property baths
					matched = App.val.validate($("frm_tax_deductible"), {
						required: true, minLength: 1, title: "Taxe Deductible", 
						message: "Please supply the tax deductible percentage."
					}, matched);
				} else if (subTypeRadios[radioIndex].value == "Condominium" || subTypeRadios[radioIndex].value == "Townhouse") {
					//common charges
					matched = App.val.validate($("frm_common_charges"), {
						required: true, minLength: 1, title: "CC/Maintenance", 
						message: "Please supply the CC/Maintenance charges."
					}, matched);
					
					//property baths
					matched = App.val.validate($("frm_taxes"), {
						required: true, minLength: 1, title: "Taxes", 
						message: "Please supply the tax amount."
					}, matched);
				}
			}
			if ($("frm_rental_period")){
				//property rental period
				matched = App.val.validate($("frm_rental_period"), {
					required: true, minLength: 1, title: "Desired Rental Period", 
					message: "Please select the desired rental period."
				}, matched);
			}
			
			if ($("frm_rent_amount")){
				//property rental price
				matched = App.val.validate($("frm_rent_amount"), {
					required: true, minLength: 1, title: "Desired Rent Price", 
					message: "Please supply the desired rent price."
				}, matched);
			}
			
			if ($("frm_rental_description")){
				//property rental price
				if ($("frm_rental_description").value == "Need to explain the Rental Period?"){
					$("frm_rental_description").value = "";
				}
			}
		} else {
			
		}
	}
	
	//check for 'Sale' type listing params 
	if (App.majorUI == "admin" && mode == "updateProperty"){
		var listingType = $("frm_listing_type").value;
		//==== Sale Prices
		if (listingType == 'Sale'){
			/*
			tempEl = $("frm_original_price");
			if (tempEl){
				matched = App.val.validate(tempEl, {
					required: true, minLength: 1, checkFormat: "numeric",  title: "Original Price", 
					message: "Please supply the original price for this Non-Auction listing."
				}, matched);
			}
			tempEl = null;
			*/
			tempEl = $("frm_sale_price");
			if (tempEl){
				matched = App.val.validate(tempEl, {
					required: true, minLength: 1, checkFormat: "numeric",  title: "Listed Price", 
					message: "Please supply the listed price for this Non-Auction listing."
				}, matched);
			}
			tempEl = null;
		}
	} else if (App.majorUI == "admin" && mode == "submitProperty"){
		//var saleType = $("frm_sale_type");
		matched = App.val.validate($("frm_sale_type"), {
			required: true, minLength: 2, title: "Listing/Sale Type", 
			message: "Please choose the listing/sale type."
		}, matched);
	}
	
	//alert(matched)
	
	//======= check date formats
	tempEl = $("frm_lease_expiration");
	if (tempEl){
		matched = App.val.validate(tempEl, {
			minLength: 8, checkFormat: "date", title: "Date Format", 
			message: "Please supply a valid date in the following <br />format 'mm/dd/yyyy' i.e. 12/23/2009."
		}, matched);
	}
	
	
	/*
	//decide whether to enable second tab
	if (matched){
		//App.addProp.Tabs.enable(1);
		//App.addProp.Tabs.select(1);
	} else {
		App.addProp.Tabs.select(0);
		App.addProp.Tabs.disable(1);
	}
	*/
	return matched;
}

//residetnail details validation
App.addProp.validate_resDetailsTab = function(mode){
	var matched = true;
	
	//exception for russian properties
	if (region_id != russia_region_id){
		//beds
		matched = App.val.validate($("frm_beds"), {
			required: true, minLength: 1, title: "Number of Beds", 
			message: "Please supply the number of bedrooms."
		}, matched);
		//baths
		matched = App.val.validate($("frm_baths"), {
			required: true, minLength: 1, title: "Number of Baths", 
			message: "Please supply the number of bathrooms."
		}, matched);
		
		//total rooms
		matched = App.val.validate($("frm_total_rooms"), {
			required: true, minLength: 1, title: "Number of Rooms", 
			message: "Please supply the number of rooms."
		}, matched);
	}
	
	//SF
	matched = App.val.validate($("frm_sqft"), {
		required: true, minLength: 1, title: "Square Footage", 
		message: "Please supply the property square footage."
	}, matched);
	//desc
	matched = App.val.validate($("full_description"), {
		required: true, minLength: 200, title: "Property Description", 
		message: "Please supply the property description. (min. of 200 charachters)"
	}, matched);
	
	//check date format
	if ($("frm_assessment_date")){
		matched = App.val.validate($("frm_assessment_date"), {
			minLength: 8, checkFormat: "date", title: "Date Format", 
			message: "Please supply a valid date in the following <br />format 'mm/dd/yyyy' i.e. 12/23/2009."
		}, matched);
	}
	if ($("frm_assessment_expiration")){
		matched = App.val.validate($("frm_assessment_expiration"), {
			minLength: 8, checkFormat: "date", title: "Date Format", 
			message: "Please supply a valid date in the following <br />format 'mm/dd/yyyy' i.e. 12/23/2009."
		}, matched);
	}
	
	
	return matched;
}

//commercial details validation
App.addProp.validate_commDetailsTab = function(mode){
	var matched = true;
	
	//desc
	matched = App.val.validate($("full_description_comm"), {
		required: true, minLength: 200, title: "Property Description", 
		message: "Please supply the property description. (min. of 200 charachters)"
	}, matched);
	//SF
	matched = App.val.validate($("frm_building_sqft"), {
		required: true, minLength: 1, title: "Square Footage", 
		message: "Please supply the building square footage."
	}, matched);
	//beds
	matched = App.val.validate($("frm_total_units"), {
		required: true, minLength: 1, title: "Total Units", 
		message: "Please supply the total number of units in the building."
	}, matched);
	//baths
	matched = App.val.validate($("frm_actual_taxes"), {
		required: true, minLength: 1, title: "Actual Tax", 
		message: "Please supply the actual tax."
	}, matched);
	
	
	
	return matched;
}


//commercial details validation
App.addProp.validate_auctionDetailsTab = function(mode){
	var matched = true;
	
	
	//original price
	matched = App.val.validate($("frm_auction_method"), {
		required: true, minLength: 1, title: "Auction Method", 
		message: "Please choose an auction method to continue"
	}, matched);
	
	//original price
	matched = App.val.validate($("frm_original_price"), {
		required: true, minLength: 1, title: "Original Price", 
		message: "Please supply the original (or listed) property value."
	}, matched);
	//starting bid
	matched = App.val.validate($("frm_starting_bid"), {
		required: true, minLength: 1, title: "Starting Bid", 
		message: "Please supply the starting bid (price) for the property."
	}, matched);
	//reserve price
	matched = App.val.validate($("frm_reserve_price"), {
		required: true, minLength: 1, title: "Reserve Price", 
		message: "Please supply the min. price the bidders must match to win."
	}, matched);
	
	if (mode == 'normal'){
		//bidding increment
		matched = App.val.validate($("frm_bidding_increment"), {
			required: true, minLength: 1, title: "Biddign Increment", 
			message: "Please set the bidding increment for this property"
		}, matched);
		//Max bidders
		matched = App.val.validate($("maximum_bid_increment"), {
			required: true, minLength: 1, title: "Max Bid Increment", 
			message: "Please supply the maximum bid increment"
		}, matched);
		
		//starting bid  - Reverse Auction  
		matched = App.val.validate($("frm_starting_bid"), {
			required: true, minLength: 1, checkAgainst: "exp: LT " + $("frm_reserve_price").value.toInt(), title: "Starting Bid", 
			message: "Please supply a Starting Bid. Starting Bid in NORMAL auctions <br />must be lower than the reserve price."
		}, matched);
		
		//reserve price  - Reverse Auction  
		matched = App.val.validate($("frm_reserve_price"), {
			required: true, minLength: 1, checkAgainst: "exp: GT " + $("frm_starting_bid").value.toInt(), title: "Reserve Price", 
			message: "Please supply a Reserve Price. Reserve Price in NORMAL auctions <br />must be higher than the Starting Bid ."
		}, matched);
	}
	
	if (mode == 'reverse'){
		//Bidding Decrement - Reverse Auction  
		matched = App.val.validate($("frm_bidding_decrement"), {
			required: true, minLength: 1, checkAgainst: 'exp: GT 0', title: "Bid Decrement", 
			message: "Please supply the reverse auction's bid decrement amount. <br />Value must be greater than zero (0)."
		}, matched);
		
		//starting bid  - Reverse Auction  
		matched = App.val.validate($("frm_starting_bid"), {
			required: true, minLength: 1, checkAgainst: "exp: GT " + $("frm_reserve_price").value.toInt(), title: "Starting Bid", 
			message: "Please supply a Starting Bid. Starting Bid in REVERSE auctions <br />must be higher than the reserve price."
		}, matched);
		
		//reserve price  - Reverse Auction  
		matched = App.val.validate($("frm_reserve_price"), {
			required: true, minLength: 1, checkAgainst: "exp: LT " + $("frm_starting_bid").value.toInt(), title: "Reserve Price", 
			message: "Please supply a Reserve Price. Reserve Price in REVERSE auctions <br />must be lower than the Starting Bid ."
		}, matched);
	}
	
	//listing date
	matched = App.val.validate($("estimated_listing_date"), {
		required: true, minLength: 1, title: "Estiamted Listing Date", 
		message: "Please supply the estiamted listing date for this property"
	}, matched);
	//auction date
	matched = App.val.validate($("estimated_auction_date"), {
		required: true, minLength: 1, title: "Estiamted Auction Date", 
		message: "Please supply the estimated auction date for this property", icon: false
	}, matched);
	//auction time
	matched = App.val.validate($("estimated_auction_time"), {
		required: true, minLength: 1, title: "Estiamted Auction Time", 
		message: "Please supply the estimated auction time for this property", icon: false
	}, matched);
	
	if (mode == 'normal'){
		//seconds to closure
		matched = App.val.validate($("frm_seconds_to_closure"), {
			required: true, minLength: 1, title: "Seconds to Close", 
			message: "Please supply the number of seconds the system <br />should wait till allowing to close the <br />auction after the last bid"
		}, matched);
		//data refresh rate
		matched = App.val.validate($("frm_data_refresh_rate"), {
			required: true, minLength: 1, title: "Data Refresh Rate", 
			message: "Please supply how frequently bidder's data <br />will reload in their bidding page"
		}, matched);
	}
	
	
	if (mode == 'reverse'){
		//auction duration  - Reverse Auction  
		matched = App.val.validate($("reverse_auction_duration"), {
			required: true, minLength: 8, checkFormat: 'time', title: "Reverse Auction Duration", 
			message: "Please supply the duration time in 'HH:MM:SS' format"
		}, matched);
		//price drop interval  - Reverse Auction  
		matched = App.val.validate($("frm_price_drop_interval"), {
			required: true, minLength: 8, checkFormat: 'time', title: "Price Drop Interval", 
			message: "Please supply the price drop interval  in 'HH:MM:SS' format"
		}, matched);
	}
	
	//penalty fee
	matched = App.val.validate($("frm_penalty"), {
		required: true, minLength: 1, title: "Penalty Fee", 
		message: "Please supply the penalty fee for a winner <br />refusing to close the sale"
	}, matched);
	//post closing hours
	matched = App.val.validate($("post_closing_penalty_hours"), {
		required: true, minLength: 1, title: "Closing Window", 
		message: "Please supply the number hours allowed for the <br />winner to start closing the property after <br />winning the auction"
	}, matched);
	//Max bidders
	matched = App.val.validate($("frm_max_bidders"), {
		required: true, minLength: 1, title: "Max Bidders", 
		message: "Please supply the maximum number of online <br />bidders to be allowed for this auction"
	}, matched);
	//Max bidders
	matched = App.val.validate($("frm_max_watchers"), {
		required: true, minLength: 1, title: "Max Watchers", 
		message: "Please supply the maximum number of online <br />bidders to be allowed for this auction"
	}, matched);
	
	
	
	
	return matched;
}

//handle open house validation
App.addProp.validate_openHouse = function(){
	var matched = true;
	matched = App.val.validate($("open_house_date"), {
		required: true, minLength: 4, title: "Open House Date", 
		message: "Please supply a date for the open house."
	}, matched);
	
	
	matched = App.val.validate($("oh_start_time"), {
		required: true, minLength: 2, title: "Start Time", 
		message: "Please supply open house start time.", icon: false
	}, matched);
	
	matched = App.val.validate($("oh_end_time"), {
		required: true, minLength: 2, title: "End Time", 
		message: "Please supply open house end time.", icon: false
	}, matched);
	
	return matched;
}


//handle ad cycle validation
App.addProp.validate_adCycle = function(){
	var matched = true;
	matched = App.val.validate($("ad_media_source"), {
		required: true, minLength: 1, title: "Media Source Name", 
		message: "Please choose a media soruce name."
	}, matched);
	
	
	matched = App.val.validate($("ad_cycle_interval"), {
		required: true, minLength: 1, title: "Cycle Interval", 
		message: "Please supply the interval between advertisign dates."
	}, matched);
	
	matched = App.val.validate($("ad_cycle_start"), {
		required: true, minLength: 5, title: "Cycle Start Date", 
		message: "Please supply the cycle start date."
	}, matched);
	
	matched = App.val.validate($("ad_no_of_repeat"), {
		required: true, minLength: 1, title: "Number of Repeats", 
		message: "Please specify the number of ad dates within the cycle."
	}, matched);
	
	return matched;
}


App.addProp.validate_addMedia = function(mode){
	var matched = true;
	
	//property type validation
	if (mode == "media") {
		matched = App.val.validate($("frm_mediaType"), {
			required: true, minLength: 4, title: "Media Type", 
			message: "Please supply a media type."
		}, matched);
		
		
		matched = App.val.validate($("frm_uploadedfile"), {
			required: true, minLength: 4, title: "Media File", 
			message: "Please supply a file to upload."
		}, matched);
		
		if ($("frm_mediaType").value == "buildingBrochure" || $("frm_mediaType").value == "otherDocuments"){
			matched = App.val.validate($("frm_media_title"), {
				required: true, minLength: 4, title: "Media Title", 
				message: "Please supply a media title."
			}, matched);
			
			matched = App.val.validate($("frm_media_description"), {
				required: true, minLength: 10, title: "Media Description", 
				message: "Please supply a media description."
			}, matched)
		}
		
		if ($("photo_verify")){
			matched = App.val.validate($("photo_verify"), {
				checked: true, title: "Verify Rights", 
				message: "Please select the checkbox to verify that <br />you have rights to this media."
			}, matched);
		}
	
	} else if (mode == "report") {
		
		matched = App.val.validate($("frm_uploaded_report"), {
			required: true, minLength: 4, title: "Media File", 
			message: "Please supply a file to upload."
		}, matched);
		
		
		matched = App.val.validate($("frm_report_title"), {
			required: true, minLength: 4, title: "Media Title", 
			message: "Please supply a media title."
		}, matched);
		
		matched = App.val.validate($("frm_report_description"), {
			required: true, minLength: 10, title: "Media Description", 
			message: "Please supply a media description."
		}, matched)
		
	}
	
	return matched;
}


App.addProp.validate_addRider = function(){
	var matched = true;
	
	//property type validation
	matched = App.val.validate($("default_rider_title"), {
		required: true, minLength: 4, title: "Rider Title", 
		message: "Please supply a rider title."
	}, matched);
	
	
	matched = App.val.validate($("default_rider_description"), {
		required: true, minLength: 4, title: "Rider Description", 
		message: "Please supply the rider copy."
	}, matched);
	
	
	return matched;
}
