/**
 * VIP JQuery Plugin
 *	overview: This plugin is included on any page where VIP features exist. When a VIP is logged in, 
 *	all VIP services are available to the user. If a VIP is not signed in and clicks on a VIP-only link, 
 *	this class will process the request and interupt the request with the signin process. Once the 
 *	signin/registration process has completed the user will continue on as usual.
 *
 *	usage: used on all website pages that have VIP features
 *	dependencies: jQuery, thickbox, jquery.form.js
 */
(function() {
	// internal variables
	var vIPAjaxRequest = null;
	var vIPAjaxOptions = null;
	$.vIPAjaxRollback = null;	// this global variable contains the rollback function should a VIP
					// registration be cancelled. We store it globally because functions
					// from all modules will need to access it
	var vIPAjaxComplete = null;

	// dashboard variables
	var openDashboardElement = null;

	/** Initializes the favorite listings page
	  * 
	  */
	$.initFavoriteListings = function() {
		// bind to the inputs
		$('#favoriteListingsSearch #sortBy').change(function(){
			$.favoriteListingsSearch(this.value);
		});
		$('#favoriteListingsSearch #favoriteListingsNotification').change(function(){
			$.favoriteListingsToggleNotification(this.checked);
		});		
	}

	/** Initializes the saved searches page
	  * 
	  */
	$.initSavedSearches = function() {
		// bind to the inputs
		$('#savedSearchesForm #savedSearchesNotification').change(function(){
			$.savedSearchesToggleNotification(this.checked);
		});		
	}

	/** This function searches the favorite listings and reloads the appropriate div on the page
	  * 
	  * @param sortBy sorting order
	  */
	$.favoriteListingsSearch = function(sortBy) {
		vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&favoriteListingsSearch=true&sortBy="+sortBy,
			beforeSend: function(){
				$('#favoriteListingsSearch').block({message: "Searching..."});
			},
			error: function(data, error){
				alert("Error: 	$.favoriteListingsSearch(): " + error + " " + data);
			},
			success: function(data){
				$('#favoriteListingsSummaries').html(data);
			},
			complete: function (XMLHttpRequest, textStatus) {
				$('#favoriteListingsSearch').unblock();
			}
		}, function(){
			// do nothing
		});
		return false;
	}

	/** This function toggles whether the VIP recieves automatic saved searches updates or not
	  * 
	  * @param notificationValue toggle value
	  */
	$.savedSearchesToggleNotification = function(notificationValue){
		vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&savedSearchesToggleNotification=true&savedSearchesNotification="+notificationValue,
			beforeSend: function(){
				$('#savedSearchesForm').block({message: "Saving..."});
			},
			error: function(data, error){
				alert("Error: 	$.favoriteListingsSearch(): " + error + " " + data);
			},
			success: function(data){
			},
			complete: function (XMLHttpRequest, textStatus) {
				setTimeout(function(){$('#savedSearchesForm').unblock();}, 500);
			}
		}, function(){
			// do nothing
		});
		return false;
	}

	/** This function toggles whether the VIP recieves automatic favorite listing updates or not
	  * 
	  * @param notificationValue toggle value
	  */
	$.favoriteListingsToggleNotification = function(notificationValue){
		vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&favoriteListingsToggleNotification=true&favoriteListingsNotification="+notificationValue,
			beforeSend: function(){
				$('#favoriteListingsSearch').block({message: "Saving..."});
			},
			error: function(data, error){
				alert("Error: 	$.favoriteListingsSearch(): " + error + " " + data);
			},
			success: function(data){
			},
			complete: function (XMLHttpRequest, textStatus) {
				setTimeout(function(){$('#favoriteListingsSearch').unblock();}, 500);
			}
		}, function(){
			// do nothing
		});
		return false;
	}

	/** This function saves a listing into the Favorite Listings
	  * 
	  * @param element elem that this save function is in
	  *
	  */
	$.saveFavoriteListing = function(elem) {
		// get the listnum
		var elemId = $(elem).attr("id");
		var listNum = elemId.substring(elemId.indexOf('_')+1, elemId.length);
		vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			url: "listings",
			data: "pathway=6&saveFavoriteListing=true&listingNumber="+listNum,
			error: function(data, error){
				alert("Error: displayListingStatistics(): " + error + " " + data);
			},
			success: function(data){

			},
			complete: function (XMLHttpRequest, textStatus) {
				//re-initialize thickbox
				tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
				$(elem).parent().html('Saved in <b>Favorite Listings</b> (<a href="#" id="deleteFavoriteListingLink_'+listNum+'" onclick="return $.deleteFavoriteListing('+listNum+', null);">remove</a>)');
				imgLoader = new Image();// preload image
				imgLoader.src = tb_pathToImage;
			}
		}, function(){
			// do nothing
		});
		return false;
	}
	/** This function deletes a listing into the saved listings
	  * 
	  * @param listNum Listing Number of listing to save
	  * @param callback callback to make once listing is saved
	  *
	  */
	$.deleteFavoriteListing = function(listNum, callback) {
		if(callback == null){
			if($('#vipDeleteFavoriteListingLink_'+listNum).size() > 0)
				$('#vipDeleteFavoriteListingLink_'+listNum).click();
			else{
				vIPAjaxRequest = $.vIPAjax({
					type: "GET",
					url: "listings",
					data: "pathway=6&deleteFavoriteListing=true&listingNumber="+listNum,
					error: function(data, error){
						alert("Error: displayListingStatistics(): " + error + " " + data);
					},
					success: function(data){
					},
					complete: function (XMLHttpRequest, textStatus) {
						$('#deleteFavoriteListingLink_'+listNum).parent().html('<a href="#" onclick="return $.saveFavoriteListing(this);" id="saveFavoriteListingLink_'+listNum+'"><img border="0" src="t/resources/rpm3.0/images/icons/disk.png" alt="Save listing"/></a>');
					}
				}, function(){
					// do nothing
				});
			}
		}else{
			vIPAjaxRequest = $.vIPAjax({
				type: "GET",
				url: "listings",
				data: "pathway=6&deleteFavoriteListing=true&listingNumber="+listNum,
				error: function(data, error){
					alert("Error: displayListingStatistics(): " + error + " " + data);
				},
				success: function(data){
				},
				complete: function (XMLHttpRequest, textStatus) {
					callback();
					$('#deleteFavoriteListingLink_'+listNum).parent().html('<a href="#" onclick="return $.saveFavoriteListing(this);" id="saveFavoriteListingLink_'+listNum+'"><img border="0" src="t/resources/rpm3.0/images/icons/disk.png" alt="Save listing"/></a>');
	
					//re-initialize thickbox
					tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
					imgLoader = new Image();// preload image
					imgLoader.src = tb_pathToImage;
				}
			}, function(){
				// do nothing
			});
		}
		return false;
	}

	/** This function deletes a saved search
	  * 
	  * @param searchNum the unique ID for the saved search
	  *
	  */
	$.deleteSavedSearch = function(searchNum) {
		if(confirm('Are you sure you want to permanently delete this search?')){
			vIPAjaxRequest = $.vIPAjax({
				type: "GET",
				url: "vIPDashboard",
				data: "pathway=173&deleteSavedSearch=true&id="+searchNum,
				error: function(data, error){
					//alert("Error: displayListingStatistics(): " + error + " " + data);
				},
				success: function(data){
					$('#savedSearch'+searchNum).remove();
				}
			}, function(){
				// do nothing
			});
		}
		return false;
	}

	/** This function attempts to access a VIP feature of the site. If the environment does not
	  * permit this VIP feature to be accessible then false is returned, otherwise this function
	  * will run the AJAX call as it would a normal jQuery AJAX call and return true.
	  *
	  * @param options same options as for a normal AJAX call
	  * @param rollBack a function to call if the VIP Registration/login does not proceed
	  * @return returns AJAX request
	  */
	$.vIPAjax = function(options, rollback) {
		var x = this;

		// store variables globally for reference later
		this.vIPAjaxOptions = $.clone(options, true);	// store the original success function
		$.vIPAjaxRollback = rollback;
		this.vIPAjaxComplete = false;
		
		//options.url += "&t=" + Date();
		options.cache = false;
		options.success = function(data){
			var temp;
			if(x.vIPAjaxOptions.dataType == "json"){
				if(data.VIPACCESSONLY == null)
					temp = "";
				else
					temp = data.VIPACCESSONLY;
			}
			if(x.vIPAjaxOptions.dataType == "json" && temp == "VIPACCESSONLY" || 
			   x.vIPAjaxOptions.dataType != "json" && $.trim(data).search(/^{\"VIPACCESSONLY\":\"VIPACCESSONLY\"}$/g) >= 0){
				// do signup, if successful re-run call
				$.showVIPRegistration();
			}else{
				// run normal success function
				x.vIPAjaxOptions.success(data);
				x.vIPAjaxComplete = true;
			}
		};
		options.complete = function(XMLHttpRequest, textStatus){
			if(x.vIPAjaxComplete){
				// run normal success function
				if(x.vIPAjaxOptions.complete != null){
					x.vIPAjaxOptions.complete(XMLHttpRequest, textStatus);
				}
			}else{
				// run VIP login fail success function
				if(x.vIPAjaxOptions.failComplete != null){
					x.vIPAjaxOptions.failComplete(XMLHttpRequest, textStatus);
				}
			}
		};
		options.error = function(XMLHttpRequest, textStatus, errorThrown){
			alert("vIPAjax error: " + textStatus + "\n" + errorThrown);
		};

		// run the AJAX function
		return $.ajax(options);
	}

	/** This function binds the given function to the close event of the Thickbox. This is a little wierd
	  * right now (just pointing to another function) because I transplanted the guts to jquery.rpm.js. 
	  * Eventually all references to this private function should be replaced with the public function.
	  *
	  * @param onClose function to be called once the thickbox closes
	  */
	var bindThickboxClose = function(onClose) {
		$.bindThickboxClose(onClose);
	}


	/** Shows the VIP Confirm account form
	  *
	  */
	$.showVIPConfirm = function() {
		$.ajax({
			type: "GET",
			url: "listings?pathway=101&loadVIPConfirm=true",
			success: function(data){
				$.blockUI({
					message:data,
					css: {
						margin:"-87px 0px 0px -335px",
						top:"50%",
						left:"50%",
						width:"670px",
						height:"175px",
						border:"none",
						textAlign:"left",
						cursor:"default",
						backgroundColor:"transparent"
					},
					bindEvents:false
				});
				bindThickboxClose($.cancelVIPRegistration);
			},
			error: function(data, error){
			}
		});
	}

	/** Shows the VIP Complete form
	  *
	  * @param onSuccess function to be called once the user has completed VIP registration
	  * @param onFailure function to be called if the user does not complete VIP registration
	  */
	$.showVIPComplete = function() {
		$.ajax({
			type: "GET",
			url: "listings?pathway=101&loadVIPConfirmComplete=true",
			success: function(data){
				$.blockUI({
					message:data,
					css: {
						margin:"-150px 0px 0px -335px",
						top:"50%",
						left:"50%",
						width:"670px",
						height:"300px",
						border:"none",
						textAlign:"left",
						cursor:"default",
						backgroundColor:"transparent"
					},
					bindEvents:false
				});
				bindThickboxClose(function(){return $.unblockUI();});
			},
			error: function(data, error){
			}
		});
	}

	/** Shows the VIP Forgot Password form
	  *
	  * @param onSuccess function to be called once the user has completed VIP registration
	  * @param onFailure function to be called if the user does not complete VIP registration
	  */
	$.showVIPForgotPassword = function(onSuccess, onFailure) {
		$.ajax({
			type: "GET",
			url: "listings?pathway=101",
			success: function(data){
				$.blockUI({
					message:data,
					css: {
						margin:"-87px 0px 0px -335px",
						top:"50%",
						left:"50%",
						width:"670px",
						height:"175px",
						border:"none",
						textAlign:"left",
						cursor:"default",
						backgroundColor:"transparent"
					},
					bindEvents:false
				});
				bindThickboxClose($.cancelVIPRegistration);
			},
			error: function(data, error){
			}
		});
	}


	/** This function is called to signup the user
	  *
	  * @param onSuccess function to be called once the user has completed VIP registration
	  * @param onFailure function to be called if the user does not complete VIP registration
	  */
	$.showVIPRegistration = function(onSuccess, onFailure) {		
		$.ajax({
			type: "GET",
			url: "vIPDashboard?pathway=168&loadSignupForm=true",
			success: function(data){
				$.blockUI({
					message:data,
					centerY: 0, 
 					centerX: 0, 
					//css: {
						//margin:"20px 0px 0px -335px",
						//top:"0",
						//left:"50%",
						//width:"670px",
						//height:"450px",
						//border:"none",
						//textAlign:"left",
						//cursor:"default",
						//backgroundColor:"transparent",
						//position:"absolute"
					//},
					bindEvents:false
				});
				$.blockUI.defaults.css = {}; 
				bindThickboxClose($.cancelVIPRegistration);
			},
			error: function(data, error){
			}
		});
	}

	/** Cancels a VIP registration window
	  *
	  */
	$.cancelVIPRegistration = function() {
		// run the appropriate functions
		if($.vIPAjaxRollback != null){
			$.vIPAjaxRollback();
		}
		
		// remove thickbox window
		return $.unblockUI();
	}

	/** Cancels a VIP registration and highlights the VIP login panel
	  *
	  */
	$.cancelVIPRegistrationAndHighlightLogin = function() {
		// cancel the registration
		$.cancelVIPRegistration();
		
		// scroll to the top
		scroll(0,0);
		
		// put cursor in login field
		$('#loginForm').find('#username').focus();
		
		// flash the vip panel highlight
		setTimeout(function(){$('#vipPanelHighlight').fadeIn("slow", function(){
				$('#vipPanelHighlight').fadeOut("slow", function(){
					$('#vipPanelHighlight').fadeIn("slow", function(){
						$('#vipPanelHighlight').fadeOut("slow");
					});
				});
			});}, 500);
		
		return false;
	}

	/** Completes a VIP registration window when a successful signup has occurred.
	  *
	  */
	$.completeVIPRegistration = function() {
		// replace VIP login form
		setTimeout(function(){
			$.ajax({
				type: "GET",
				dataType: "text",
				url: "vIPDashboard",
				data: "pathway=168&vipSignupLogin=true",
				error: function(data, error){
					alert("Error: completeVIPRegistration(): " + error);
				},
				success: function(data){
					$('#dashboard_login').html(data);
				},
				complete: function (XMLHttpRequest, textStatus) {
					bindToLogout();
				}
			});
		}, 1000);
		
		// run the appropriate functions for success
		if(this.vIPAjaxOptions)
			$.vIPAjax(this.vIPAjaxOptions, $.vIPAjaxRollback);

		// remove thickbox window
		//return tb_remove();
		return $.unblockUI();
	}

	/** This function initializes the VIP login feature
	  *
	  */
	$.vIPDashboardInit = function() {
		var self = this;
		var rolloverImages = new Array();
		// go through each button and add appropriate listeners, events
		$("#vipMenu li a").each(function(){
			
			// add click listener
			$(this).click(function(){
				var cli = this;
				// remove all other highlights that might be active
				$("#vipMenu li a.over").each(function(){
					$(this).removeClass('over');
				});

				// check if this link is already active, if so close it
				if(self.openDashboardElement == this){
					// hide dashboard page
					$("#dashboardContent").slideUp("fast", function(){
						// load content
						$("#dashboardContent").children(".normal_module_container").html("");
					});
					
					// reset open element
					self.openDashboardElement = null;
					return false;
				}

				// set the global pointer to this as the active element
				self.openDashboardElement = this;


				// add highlighting to this link
				$(this).addClass('over');

				// show loading activity
				$.showVIPDashboardLoadingIcon();
				
				// stop and AJAX request if necessary
				if(self.vIPAjaxRequest){
					self.vIPAjaxRequest.abort();
				}

				self.vIPAjaxRequest = $.vIPAjax({
					type: "GET",
					dataType: "html",
					cache: false,
					url: "vIPDashboard?pathway=173&"+this.id+"=true", //added date qs param, previously in vipAjax 
					error: function(data, error){
						alert("Error: loadVIPWindow(): " + error);
						$.hideVIPDashboardLoadingIcon();
					},
					success: function(data){
						// hide any existing dashboard page, if it is visible
						if($("#dashboardContent:visible").size() > 0){
							$("#dashboardContent:visible").slideUp("fast", function(){
								// load content
								$("#dashboardContent").children(".normal_module_container").html(data);
							
								// show dashboard page
								$("#dashboardContent").slideDown("fast", function(){
									if(cli.id == "instantHomeEval"){
										$(document).ready(function(){
											$.graphDaysOnMarket(daysOnMarket.MLSStatsDOMs, $('#homeEvalContent').find('#daysOnMarket'));
											$.graphPrices(listingPrices.MLSStatsPrices, $('#homeEvalContent').find('#prices'));
											$.graphListedVersusSold(listedVersusSold.MLSStatsListedVersusSold, $('#homeEvalContent').find('#listedVersusSold'));
										});
									}
								});
							});
						}else{
							// load content
							$("#dashboardContent").children(".normal_module_container").html(data);
						
							// show dashboard page
							$("#dashboardContent").slideDown("fast", function(){
								if(cli.id == "instantHomeEval"){
									$(document).ready(function(){
										$.graphDaysOnMarket(daysOnMarket.MLSStatsDOMs, $('#homeEvalContent').find('#daysOnMarket'));
										$.graphPrices(listingPrices.MLSStatsPrices, $('#homeEvalContent').find('#prices'));
										$.graphListedVersusSold(listedVersusSold.MLSStatsListedVersusSold, $('#homeEvalContent').find('#listedVersusSold'));
									});
								}
							});
						}
						// hide loading activity
						$.hideVIPDashboardLoadingIcon();
						
					}
				}, function(){resetDashboard();});
			});
		});
	}
	
	/** This function toggles whether the VIP recieves automatic Market Watch updates or not
	  * 
	  * @param notificationValue toggle value
	  */
	$.marketWatchToggleNotification = function(notificationValue){
		//alert("Email Click Value: " + $("#email").val());
		if(self.vIPAjaxRequest){
			self.vIPAjaxRequest.abort();
		}
		self.vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&marketWatch=true&email="+notificationValue+"&sort="+$("#sort").val(),
			beforeSend: function(){
				$('#marketWatchSearch').block({message: "Saving..."});
			},
			error: function(data, error){
				alert("Error: saveVIPMarketWatchEmailSetting(): " + error);
				$.hideVIPDashboardLoadingIcon();
			},
			success: function(data){
				//Show save message here
			},
			complete: function(){
				setTimeout(function(){$('#marketWatchSearch').unblock();}, 500);
			}
		}, function(){resetDashboard();});
	}

	/** This function searches the Market Watch and reloads the appropriate div on the page
	  * 
	  * @param sortBy sorting order
	  */
	$.marketWatchSearch = function(sortBy){
		if(self.vIPAjaxRequest){
			self.vIPAjaxRequest.abort();
		}
		self.vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&marketWatch=true&reload=1&sort="+sortBy,
			beforeSend: function(){
				$('#marketWatchSearch').block({message: "Searching..."});
			},
			error: function(data, error){
				alert("Error: changeVIPMarketWatchSorting(): " + error);
			},
			success: function(data){
				// load content
				$("#marketWatchResults").html(data);
			},
			complete: function(){
				setTimeout(function(){$('#marketWatchSearch').unblock();}, 500);
			}
		}, function(){resetDashboard();});
	}
	
	$.homeEvaluationSearch = function(){
		//alert("Email Click Value: " + $("#email").val());
		if(self.vIPAjaxRequest){
			self.vIPAjaxRequest.abort();
		}
		self.vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&instantHomeEval=true&reload_stats=true&city=" + $("#city").val() + "&neigh=" + $("#neigh").val() + "&prop=" + $("#prop").val(),
			beforeSend: function(){
				$('#homeEvalResults').block({message: "Saving..."});
			},
			error: function(data, error){
				alert("Error: saveVIPMarketWatchEmailSetting(): " + error);
				$.hideVIPDashboardLoadingIcon();
			},
			success: function(data){
				$("#homeEvalResults").html(data);
			},
			complete: function(){
				setTimeout(function(){$('#homeEvalResults').unblock();}, 500);
				$.graphDaysOnMarket(daysOnMarket.MLSStatsDOMs, $('#homeEvalContent').find('#daysOnMarket'));
				$.graphPrices(listingPrices.MLSStatsPrices, $('#homeEvalContent').find('#prices'));
				$.graphListedVersusSold(listedVersusSold.MLSStatsListedVersusSold, $('#homeEvalContent').find('#listedVersusSold'));
			}
		}, function(){resetDashboard();});
	}

	$.homeEvaluationCityToggle = function(cValue){
		if(self.vIPAjaxRequest){
			self.vIPAjaxRequest.abort();
		}
		self.vIPAjaxRequest = $.vIPAjax({
			type: "GET",
			dataType: "html",
			url: "vIPDashboard",
			data: "pathway=173&instantHomeEval=true&reload_neigh=true&city=" + cValue,
			error: function(data, error){
				alert("Error: saveVIPMarketWatchEmailSetting(): " + error);
				$.hideVIPDashboardLoadingIcon();
			},
			success: function(data){
				$("#neigh_list").html(data);
				$.homeEvaluationSearch();
			}
		}, function(){resetDashboard();});
	}
	
	// function to show loading icon
	$.showVIPDashboardLoadingIcon = function(){
		var insertPoint = $('#dashboard_logo').css("background-image").indexOf('.jpg');
		var bg = $('#dashboard_logo').css("background-image");
		$('#dashboard_logo').css("background-image", bg.substring(0, insertPoint) + 'On' + bg.substring(insertPoint, bg.length));
	}
	
	// function to hide loading icon
	$.hideVIPDashboardLoadingIcon = function(){
		var removePoint = $('#dashboard_logo').css("background-image").indexOf('On.jpg');
		if(removePoint >= 0){
			var bg = $('#dashboard_logo').css("background-image");
			$('#dashboard_logo').css("background-image", bg.substring(0, removePoint) + bg.substring(removePoint+2, bg.length));
		}
	}


	/** This function initializes the VIP login feature
	  *
	  * @param useValue determines whether the new, converted field should continue using the old fields' value
	  */
	$.vIPLoginConvertToPasswordType = function(useValue) {
		if(useValue)
			$("#loginForm > #password").replaceWith('<input name="password" type="password" id="password" value="'+$("#loginForm > #password").attr("value")+'" class="'+$("#loginForm > #password").attr("class")+'">');
		else
			$("#loginForm > #password").replaceWith('<input name="password" type="password" id="password" value="" class="'+$("#loginForm > #password").attr("class")+'">');
	}

	/** This function initializes the VIP login feature
	  *
	  */
	$.vIPLoginInit = function() {
		// bind to logout if it's present
		bindToLogout();
		
		// bind to the form's submit event if present
		$("#loginForm").submit(function() { 
			$.ajax({
				type: "GET",
				dataType: "text",
				url: "vIPDashboard",
				cache: false,
				data: $('#'+this.id+' input').fieldSerialize() + "&t=" + Date(),
				beforeSend: function (XMLHttpRequest) {
					$.showVIPDashboardLoadingIcon();
				},
				error: function(data, error){
					alert("Error: vIPLoginInit(): " + error);
					$.hideVIPDashboardLoadingIcon();
				},
				success: function(data){
					// search the string for a relocation command. If not found it's a client logging in
					if(data.indexOf("window.l") >= 0)
						eval(data);
					else
						$('#dashboard_login').html(data);
				},
				complete: function (XMLHttpRequest, textStatus) {
					// re-init in case the login failed
					$.vIPLoginInit();
					
					// bind to the logout button in case login succeeded
					bindToLogout();

					// hide loading activity
					$.hideVIPDashboardLoadingIcon();
				}
			});

			return false;
		});

		$("#loginForm > #username").bind("focus",
			function(){
				$("#loginForm > #username").attr("value", "");
				$("#loginForm > #username").unbind("focus");
			}
		);
		$("#loginForm > #password").bind("focus",
			function(){
				// check if this field is already in error state - if so, use the same class
				$.vIPLoginConvertToPasswordType(false);
				$("#loginForm > #password").focus();
				
				$("#loginForm > #password").unbind("focus");
			}
		);
	}

	/** This function binds to 
	  *
	  */
	function bindToLogout(){
		// bind a logout event
		$('#dashboard_login').find('#logout').click(function(){
			$.ajax({
				type: "GET",
				dataType: "html",
				cache: false,
				url: "listings",
				data: "pathway=187&t=" + Date(),
				//timeout: 5000,
				beforeSend: function (XMLHttpRequest) {
					$.showVIPDashboardLoadingIcon();
				},
				error: function(data, error){
					alert("Error: loadVIPWindow(): " + error);
					$.hideVIPDashboardLoadingIcon();
				},
				success: function(data){
					$('#dashboard_login').html(data);
					$("#dashboardContent:visible").slideUp("fast", function(){
						$("#dashboardContent").children(".normal_module_container").html("");
						resetDashboard();
					});
				},
				complete: function (XMLHttpRequest, textStatus) {
					// rebind everything
					$.vIPLoginInit();
					
					// hide loading activity
					$.hideVIPDashboardLoadingIcon();
				}
			});
			return false;
		});
	}
	
//Utility Functions
	function resetDashboard(){
		// remove highlighting
		$("#vipMenu li a.over").each(function(){
			$(this).removeClass('over');
		});
		self.openDashboardElement = null;
		
		// hige the loading icon
		$.hideVIPDashboardLoadingIcon();
	}
	
	/** This function displays the listedVersusSold graph in the given div with the given data
	  *
	  * @param MLSStatsListedVersusSold object containing all listed/sold data
	  * @param displayDiv jQuery object to display the graph in
	  */
	$.graphListedVersusSold = function(MLSStatsListedVersusSold, display){
		var listed = new Array();
		var sold = new Array();
		var graphTicks = new Array();
		var j = 0;
		for(var i = 0; i < 10; i++){
			// initialize data values at 0
			listed[i] = [j, 0];
			sold[i] = [j+1, 0];
			if(i == 0)
				graphTicks[i] = [j+1, '<span class="graphLegendLabel">this wk</span>'];
			else
				graphTicks[i] = [j+1, '<span class="graphLegendLabel">'+i+' wk ago</span>'];
			j = j + 3;
		}
		
		for(var i = 0; i < MLSStatsListedVersusSold.length; i++){
			var index = MLSStatsListedVersusSold[i].dayRanges.substring(0,1);
			if(MLSStatsListedVersusSold[i].dayRanges.substring(1,2) == 'l'){
				listed[index] = [index*3, MLSStatsListedVersusSold[i].listingCount];
			}else{
				sold[index] = [index*3+1, MLSStatsListedVersusSold[i].listingCount];
			}
		}

		var graphData = [
			{ data: listed, label: "# Listed"},
			{ data: sold, label: "# Sold"}];
		
		$.plot(display, graphData, 
			{
				bars: { show: true, fillOpacity: 0.8, barWidth:1},
				shadowSize: 2,
				xaxis: {
					ticks: graphTicks
					},
				yaxis: {
					min: 0,
					tickFormatter: function(val, axis){
						return '<div style="width:50px"><span class="graphLegendLabel">'+val+'</span></div>';
					}
				},
				legend: {
					backgroundOpacity:0.4,
					position: "ne",
					margin: 10,
					labelFormatter: function(label) {
						return '<span class="graphLegendLabel">' + label + '</span>';
					}
				}
			}
		);

		return false;
	}

	/** This function displays the daysonmarket graph in the given div with the given data
	  *
	  * @param MLSStatsDOMs object containing all listing DOM data
	  * @param displayDiv jQuery object to display the graph in
	  */
	$.graphDaysOnMarket = function(MLSStatsDOMs, display){

		$.plot(display, MLSStatsDOMs, {
			series: {
				pie: {
					show: true, 
					radius: 9/12,
					stroke: {
						color: '#ccc',
						width: 0
					},
					label: {
						show: true,			//use ".pieLabel div" to format looks of labels
						radius: 9/12, 		// part of radius (default 5/6)
						formatter: function(label, series) {
							return Math.round(series.percent)+'%';
						},
						background: {
							opacity: 0.55
						}
					}
				}
			},
			legend: {
				show:true,
				backgroundOpacity:0.4,
				position: "ne",
				margin: 10,
				noColumns: 2,
				labelFormatter: function(label) {
					return '<span class="graphLegendLabel">' + label + '</span>';
				}
			}
		});

		return false;
	}

	/** This function displays the price graph in the given div with the given data
	  *
	  * @param MLSStatsPrices object containing all listing pricing data
	  * @param displayDiv jQuery object to display the graph in
	  */
	$.graphPrices = function(MLSStatsPrices, display){
		var median = new Array();
		var average = new Array();
		var graphTicks = new Array();

		var j = 0;
		for(var i = 0; i < MLSStatsPrices.length; i++){
			median[i] = [j, parseFloat(MLSStatsPrices[i].medianPrice)];
			average[i] = [j, parseFloat(MLSStatsPrices[i].averagePrice)];
			graphTicks[i] = [j, '<span class="graphLegendLabel">'+MLSStatsPrices[i].dayRanges+'</span>'];
			j = j + 2;
		}

		$.plot(display, [
			{ //active listing price
				data: median,
				label: "Median Price",
				lines: { show: true, fill: true }
			},
			{ //active listing price
				data: average,
				label: "Average Price",
				lines: { show: true, fill: true }
			}], 
			{
				xaxis: {
					ticks: graphTicks,
					tickFormatter: function(val, axis){
						return '<span class="graphLegendLabel">'+val+'</span>';
					}
					},
				yaxis: {
					tickFormatter: function(val, axis){
						return '<div style="width:50px"><span class="graphLegendLabel">'+$.formatAsCurrency(val)+'</span></div>';
					}
				},
				legend: {
					backgroundOpacity:0.4,
					position: "ne",
					margin: 10,
					labelFormatter: function(label) {
						return '<span class="graphLegendLabel">' + label + '</span>';
					}
				}
			}
		);
		
		return false;
	}

	/** Initializes the VIP Registration panel
	  *
	  * @param boolean returns false to eliminate browser scroll after click on anchor
	  */
	$.initializeVIPRegistration = function() {
		// bind event to the close link
		$("#closeVIPRegistration").click(function(){return $.cancelVIPRegistration();});

		// initialize tabs
		$('#listingSearchTabs ul li:first').addClass('select');
		$('#vipRegistrationAdvertisement').children(':first').show();
		$('#listingSearchTabs ul li').click(function(){
			$('#listingSearchTabs ul li').removeClass('select');
			$(this).addClass('select');
			$('#vipRegistrationAdvertisement').children('').hide();
			$('#'+this.id+'Text').show();
		});
		

	}

})();// close ListingDetails

$(document).ready(function(){   
	$.vIPLoginInit();
	$.vIPDashboardInit();
});
