// Implement client-side features for photolist.php and list.php
	var globalParams = new Array();

jQuery(
	function() {
// Collect input parameters we need to pass to other pages
	var top; var bottom; var title; var refer; var key; var user; var br; var gar; var area;
		if (top = getParam('top')) globalParams.push('top='+top);
		if (bottom = getParam('bottom')) 	 globalParams.push('bottom='+bottom);
		if (title = getParam('title')) 	 	 globalParams.push('title='+title);
		if (referral = getParam('referral')) globalParams.push('referral='+referral);
		if (key   = getParam('key'))   	 	 globalParams.push('key='+key);
		if (user  = getParam('user'))  	 	 globalParams.push('user='+user);
		if (br    = getParam('br'))  	 	 globalParams.push('br='+br);
		if (gar   = getParam('gar'))  	 	 globalParams.push('gar='+gar);
		if (grade = getParam('grade'))  	 globalParams.push('grade='+grade);
		if (area  = getParam('area'))  	 	 globalParams.push('area='+area);
		
		globalParams = globalParams.join('&');

		$.preload(".house", {placeholder:'../images/NOphoto.jpg',notFound:'../images/NOphoto.jpg'});
		
		$("a", ".top-menu").click(
			function(event) {
				var $self = $(this);
				var action = $self.attr('href');
				var option = $self.attr('rel');
				switch (option) {
					case "checked": ;
									var selections = $.cookie('rrg_favorites');
									if (selections) {
										openURL(action, option, '?ns=1&idlist=' + selections);
									}
									else
										noSelections();
								break;
					case "favorites": ;
									var $target = $("div#mid_1col");
									loggedIn(function() {signup($target)},function() {showfavs()});
/*									if (!$.cookie('rrg_username')) {
										favPopup();
									}
									else {
										openURL(action, option,'?ns=1&id=myfavs');
									}
*/
								break;
					case "all": 
									openURL(action, option,'');
								break;
					case "br":
								return;
								break;
				}
				event.stopPropagation();
				return false;
			}
		);

		$("input.checkall").click(
				function() {
					var value = $(this).attr('checked');
					$("input.checkbox:not(:disabled)").each(
							function() {
									$(this).attr('checked', value);
									updateFavorites($(this).val(), value);
							});
				}
		);
		$("input.checkbox").click(
				function() {
					updateFavorites($(this).val(), $(this).attr('checked'));
				}
		);
		$("a.view").click(
				function() {
					$(this).attr('href',$(this).attr('href') + (globalParams ? '&' + globalParams : ''));
				}
		);
		$("a#home-link").click(
						function() {
								if ($(this).hasClass('home'))
								$(this).attr('href',$(this).attr('href').toString().split('&')[0] + '&' + selections);
						}
		);
		$("a#list-link").click(
						function() {
							var selections = getSelections();
							if (selections)
								$(this).attr('href',$(this).attr('href').toString().split('?')[0] + '?' + selections);
							else
								return noSelections();
						}
		);
		$("a#maplist-link").click(
						function() {
							var selections = getSelections();
							if (selections) {
								//var query_string='';
								var sep = '';
								var query_string = window.location.search; if (query_string) sep = "&"; else sep = "?";
								var href = $(this).attr('href').toString().split('?')[0] + query_string+sep+selections; // Map selected properties
								return mapWindow(href);
							}
							else
								return noSelections();
						}
		);
		$("a.map").click(
					function() {
						return mapWindow($(this).attr('href'));  // Map specific property
					}
		);
		$("a#print-link").click(
						function() {
							var selections = getPrintSelections();
							if (selections) selections = "?"+selections; else selections = '';
							window.open($(this).attr('href')+selections,'photolist','width=670,height=250,left=0,top=0');
							return false;
						}
		);
		$("a#home-link").click(
						function() {
								$(this).attr('href',$(this).attr('href').toString().split('&')[0] + '&' + selections);
						}
		);
		$('input#ad_str, input#ad_num')
			.addClass('watermark')
            .click(function(e) {
                if ($(this).attr('rel') !== '' && this.value === $(this).attr('rel'))
                    this.value = '';
                else
                    this.select();
            })
            .focus(function(e) {
                $(this).removeClass('watermark');
            });
		$("input#listhead").change(
				function() {  // Alter the tooltip as the checkbox is checked/unchecked
					var info;
					if ($(this).attr('checked'))
						info = translations['checkall1'];
					else
						info = translations['checkall0'];
						
					$(this).tooltip({ 
    							bodyHandler: function() { 
        						return  '<h6>' + $(this).attr("caption") + '</h6>' +
        								'<p>' + info + '<br /><b>' + '</b></p>'; 
    							}, 
    							showURL: false,
    							opacity: 1 
								});
				}
		);

		$("a#unselectall").click(
				function() {
					SetCookie(cookieFavorites,'');
					evalFavorites();
					clearAll();
					return false;
				}
		);
		$("a#showall").click(
				function() {
				// Peel off parameter and update the href target
					$(this).attr('href',$(this).attr('href').toString().split('#')[0].split('&')[0].split('?')[0] + '?' + getIdlistFromCookie()+"&ns=1");
				}
		);
		
		$("a#showfav").click(
			function() {
				var $target = $("div#mid_1col");
				loggedIn(function() {signup($target)},function() {showfavs()});
				return false;
			}
		);
		
		$("input#search-button").click(
				function() {  // When clicking, remove any 'watermarked' field data so it doesn't enter into the search criteria
					if ($('input#ad_str').val() == $('input#ad_str').attr('rel')) $('input#ad_str').val('');
					if ($('input#ad_num').val() == $('input#ad_num').attr('rel')) $('input#ad_num').val('');
				}
		);

		if ($("div.list-page").length != 0) {
			$("div#potbottom").append("<img id='bmol' style='position:absolute;bottom:108px;right:14px' src='images/build_my_own_list.gif' />");
			$("#bmol").css('cursor','pointer').click(
				function() {
					var $target = $("div#mid_1col");
					//loggedIn(function() {signup($target)},function() {bmol($target)});
					bmol($target)
					return false;
				}
			);
			
			$(".favs").click(// Drop down menu
				function() {
					var $target = $("div#mid_1col");
					loggedIn(function() {signup($target)},function() {menuFavClicks($(this));});
					return false;
				}
			);
		}
		$("#bmol-closer").live('click',
			function() {
				$(this).parent().remove();
			}
		);
 	 evalFavorites();
     restoreFavorites();
     $("input#listhead").change(); // Initialize it (before any click has occurred, after initial value has been set)  
   //  favToggle();   
	}  // jQuery function
);
		function menuFavClicks($elem) {
			var which;
			var title;
			var act;

			if ($elem.hasClass('fav-del')) {
				which = 'remove the property from '; 
				title = 'Add to Favorites';
				act = 'del';
			}
			else {
				which ='add the property to';
				title = 'Delete from Favorites';
				act = 'add';
			}
			if (confirm("This will "+which+" 'my favorites'")) {
				var $self = $elem;
				$.get($elem.attr('href'),
					{
						action: act
					},
					function(data, status) {
						if (data.status =='success') {
							if (act =='del') {
								$self.removeClass('fav-del').addClass('fav-add').attr('title',title);
							}
							else {
								$self.removeClass('fav-add').addClass('fav-del').attr('title',title);
							}
						}
						else {
							alert(data.result);
						}
						
					//	favToggle();
						
					}
					,'json'
				);
			}
			return false;
		}
		
		function showfavs() {
			var i;
			var id = new Array();
			var $favs = $("a.fav-del");
			for (i = 0; i < $favs.length; i++) {
				id.push($favs[i].rel);
			}
			id = id.join(',');
			window.location = "list.php?id=myfavs";
		}
		
		function loggedIn(f1, f2) {
		var onfalse = f1;
		var ontrue  = f2;
		$.get('shared_content/login-status.php',
			{},
			function(data, status) {
				if (data.loggedin==false) {
					onfalse();
				}
				else {
					ontrue();
				}
			},
			'json'
		);
	}
	
	function openURL(action, option, params) {
		if (action =='/map/popup-list.php') {	// Maps open as a popup
			window.open(action+params);
		}
		else {
			window.location = action+params;
		}
	}
	function bmol($target) {
		$.get(	'build-my-own-list.php?'+globalParams,
				{},
				function(html, status) {
					$target.append(html);
					$(".bmol-button").unbind('click').click(
						function() {
							if ($(this).val() == 'Save') {
								loggedIn(
									function() {signup($target)},
									function() {
										bmolSaver(
											$("[name='bmol_name']").val(), 
											$("#br").val(),
											$("#area").val(),
											$("#grade").val(),
											$("#gar").attr('checked'),
											$("[name='bmol_email']").attr('checked')
										);
									}
								);
								
							}
							else {
								if ($(this).val() == 'Cancel') {
									$("#bmol-form").remove();
									return false;
								}
								else {
									var loc = window.location.toString().split("?")[0];
									window.location = loc+
													"?br="   + $("#br :selected").val() +
													"&area="  + $("#area :selected").val() +
													"&grade="+ $("#grade :selected").val() +
													"&gar="  + ($("#gar").attr('checked') ? 1 : "");
								}
							}
							return false;											
						}
					);

				},
				'html'
			)
		return false;
	}

	function bmolSaver(saveas, b, a, gr, ga, em) {
		$.post('my-favorites-save.php',
			{
				name: saveas,
				br:		b,
				area:	a,
				grade:	gr,
				gar:	ga ? "1" : "",
				email:	em ? "1" : ""
			},
			function(data, status) {
				alert(data.status);
			},
			'json'
		);
		return false;
	}
	function favToggle() { // link below the list that filters on favorites
	 if ($("a.fav-del").length > 0) {
	     $("a#showfav").show();
     }
     else {
	     $("a#showfav").hide();
     }
	}
	function favPopup() {
	// not-logged user sees this popup
		$("div#mid_1col").remove("#fav-popup");
		$.get('dialog-favorites.php',
			{},
			function(html, status) {
				$("div#mid_1col").append(html);
				$("#cancel-button").click(
					function() {
						$("#fav-popup").remove();
					//	favToggle();
						return false;
					}
				);
			},
			'html'
		);
	}
	
	function mapWindow(href) {
	// Open the map popup window
		var h=800;
		if (screen)
			if (screen.availheight)
				h = screen.availheight; // IE 5.5/6
			else 
				h = screen.height;
		h = h - 50;  //  Slightly less that full height
		if (globalParams) {
			if (href.toString().indexOf('?'))
				href += "&"+globalParams;
			else
				href += "?"+globalParams;
		}
		window.open( href, 'maplink', 'height='+h+',width=800,resizable=1,left=0,top=0' );
		return false; // Popup window was opened, so don't open the link in the current window
}

var cookieFavorites = 'rrg_favorites';
var favorites = '';

	function evalFavorites() {
	// Count how many selections have been made and display status
		var cookie = $.cookie(cookieFavorites);
		var links;
		
		if (cookie===null || cookie == '') favorites = new Array(); else favorites = cookie.split(',');
			if (favorites.length) {
	   			$("span#selection-count").html(favorites.length);
	   			$("a#unselectall").show();
	   			$("a#showall").show();
   			}
   			else {
	   			$("span#selection-count").html('0');
	   			$("a#unselectall").hide();
	   			$("a#showall").hide();
   			}
		$("label.selection-status").show();
	}

	function updateFavorites(id, value) {
	// Merge current 'checked' checkboxes into the cookie containing saved values
		var cookie = $.cookie(cookieFavorites);
		if (cookie===null || cookie == '') favorites = new Array(); else favorites = cookie.split(',');
		var idx = favorites.indexOf(id);
		if (!value) {
			if (idx != -1)
				favorites.splice(idx,1);  // Remove if exists
		}
		else {
			if (idx == -1)
				favorites.push(id);						// Add if not exists
		}
		
		SetCookie(cookieFavorites, favorites.join(','));
		evalFavorites();
	}

	function restoreFavorites() {
	// Restore any prior checkbox selections
		var cookie = $.cookie(cookieFavorites);
		if (cookie===null || cookie == '') favorites = new Array(); else favorites = cookie.split(',');
   			var i;
   			for (i = 0; i < favorites.length;i++) {
    			$("input.checkbox[value="+favorites[i]+"]").attr('checked',true);
  		}
	}

	function getPrintSelections() {
		var idlist;
		resetFavorites();
		if (idlist = getIdlistFromUrl())
			return new Array(idlist, 'ns=1', globalParams).join("&");	// The list specified via URL
		else
			return new Array('ns=1', globalParams).join("&");			// Print all properties, excluding SOLD ones
	}
	
	function getIdlistFromCookie() {
	// Return an idlist for the saved id's
		var idlist;
		var cookie = GetCookie(cookieFavorites);
		if (cookie == '') favorites = new Array(); else favorites = cookie.split(',');
		if (idlist = favorites.toString()) return 'idlist=' + idlist;
		return;
	}
	
	function getSelections() {
	// Return an idlist for the current 'checked' checkboxes
		var selections = new Array();
		var all = true;
		var count = 0;
		$("input.checkbox:not(:disabled)").each(
				function() {
					if ($(this).attr('checked')) {
						selections.push($(this).val());
						count++;
					}
					else
						all = false;
				}
			);
		if (count == 0) {
			return false;
		}
		else {
			return new Array('idlist=' + selections.join(','), globalParams).join("&");
		}
	}
	function noSelections() {
		alert('Sorry, nothing was selected.')
		return false; // Nothing to do, don't open the link
	}

	function clearAll() {
	// Reset all checkboxes to 'unchecked'
		$("input.checkbox").attr('checked',false);
	}
//  A method of the Array object that's missing from some javascript implementations	
		if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	function getIdlistFromUrl() {
	//  Obtain this URL parameter, if it is present: 'idlist=value'
		var idlist = document.location.toString().split('?')[1];
		var params = new Array;
		if (idlist) {
			idlist = idlist.split("&");
			var i, param;
			for (i=0;i<idlist.length;i++) {
				param = idlist[i].split('=');
				if ((param[0] == 'idlist' || param[0] == 'br') && param[1]) 
					params.push(param[0] + '=' + param[1]);
			}
			if (params.length) {
				return params.join('&').toString();
			}
			else {
				return false;
			}
		}
	}
	function resetFavorites() {
	// Run down the checkboxes and rebuild the favorites cookie
		SetCookie(cookieFavorites,'');
		$("input.checkbox:not(:disabled)").each(
							function() {
									var value = $(this).attr('checked');
									if ($(this).attr('checked', value)) {
										updateFavorites($(this).val(), value);
									}
							}
		);
		return;
	}
	function signup($target) {
		if ($("form#login-signup-form").length==0) {
			$.get('shared_content/login-or-signup.html',
				{},
				function(html, status) {
					$target.append(html);
					$("#bmol-form").remove();
				},
				'html'
			);
		}
	}