// 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'});
		
		$("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");
				}
		);
		$("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() {
					$.get(	'build-my-own-list.php?'+globalParams,
							{},
							function(html, status) {
								$("div#mid_1col").append(html);
								$("#bmol-closer").click(
									function() {
										$("#bmol-form").remove();
									}
								);
								$(".bmol-button").click(
									function() {
										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;											
									}
								);
								$("form").keyup(
									function(e) {
										$("#bmol-submit").click();
										return false;
									}
								);
							},
							'html'
						)
					return false;
				}
			);
		}
     evalFavorites();
     restoreFavorites();
     $("input#listhead").change(); // Initialize it (before any click has occurred, after initial value has been set)

	}  // jQuery function
);
	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;
	}