var hMenuWidth = 0;
var fadeTimer = '';
var hoverOn = '';
var lang = GetCookie('rrg_language'); if (lang=='') $lang = 'en';

jQuery(
	function() {
		$.preload("img");
		var last=1;
		$("li", "div#midnav ul").each(
							function (index) { // Resize all tabs to fill the space
								last = index;
								var widthfix = 0;
								if (index == 0) widthfix = -20; // Improve things a bit, so last menu item isn't cut off
								if (index == $("li", "div#midnav ul").length-1) widthfix = 20;
								$(this).css('text-align', 'center'); //if (index>0) $(this).css('font-size','11px');
								$(this).width(parseInt($("#midnav").width()/ ($("li", "#midnav ul").length)));
							}
						); 

		if ($('#sm').length) slideMenu.build('sm',150,10,10,last+1);

		$("a[caption], input[caption]").tooltip({ 
    							bodyHandler: function() { 
        						return  '<h6>' + $(this).attr("caption") + '</h6>' +
        								'<p>' + $(this).attr("info") + '<br /><b>' + '</b></p>'; 
    							}, 
    							showURL: false,
    							opacity: 1 ,
    							top: -40
								});
		$("a","span.pages").tooltip({ 
    							bodyHandler: function() { 
        						return  '<h6>' + $(this).attr("caption") + '</h6>' +
        								'<p>' + $(this).attr("info") + '</p>'; 
    							}, 
    							showURL: false,
    							opacity: 1, 
    							top: -40
								});
		$('a.maplink').click(
						function() {
							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
							var href = $(this).attr('href')
							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;
						});
		$('a.print').click(
						function() {
							if ($(this).attr('href') == '#') {
								window.print();
								return false;
							}
							else // print the target page in a new window
								$(this).attr('target','_blank');
						});
		$("#login-topper").load('/shared_content/login-top-page.php?lang='+lang,
			function() {
				$(".callout-item").hover(
					function() {

						clearTimeout(fadeTimer);
						fade_timer = '';

						$(".callout").remove();
						var self = this;
						hoverOn = this.id;
						fadeTimer = setTimeout(
							function() {
								$.get('/shared_content/'+lang+'/callouts/'+self.id+".html?lang="+lang,
									function(data, status) {
										if (hoverOn == self.id) {// Suppress popup if the hover target has changed
											var p = $(self).position();
											$("#login-topper").append(data);
											var offset = ($(".callout").width() - $(self).width())/2;
											var left = (self.id == 'es' || self.id == 'en') ? 330 : (p.left-offset) ;
											// Show it if mouse hasn't moved off the callout element
											if (hoverOn !='') $(".callout").css({top: (40+p.top)+'px',left: left+'px', zindex: 99999}).fadeIn('slow');
										}
									},
									'html'
								);
							},
							4000
						);
					},
					function() {
						hoverOn = ''; // Mouse moved off, suppress callout
						if (typeof fadeTimer == 'object') clearTimeout(fadeTimer);
						setTimeout(
								function() {
									$(".callout").fadeOut('fast');
								},
								2000
						);
					}
				);
			}
		);

		$("#logout-link").live('click',
			function() {
				window.location = "logout.php";
			}
		);
		$("a", "table.favorites").live('click',
			function(e) {
				var rel = $(this).attr('rel');
				var id  = $(this).attr('id');
				var self = this;
				
				if ($(this).hasClass('detail')) {
					window.open('detail.php?id='+rel);
					return false;
				}
				if ($(this).hasClass('apply')) {
					window.open('apply_online.php');
//					window.open('application/index.php?id='+rel+'&app='+id);
					return false;
				}
				if ($(this).hasClass('search')) {
					if ($(this).hasClass('del')) {
						if (confirm("Delete this saved search?")) {
							$.get($(this).attr('href'),
								{},
								function(data, status) {
									if (data.status =='success') {
										$(self).closest('tr').remove();
									}
									else {
										alert(data.status);
									}
								},
								'json'
							);
						}
					}
					else {// Otherwise, display it in a new window
						window.open($(this).attr('href'));
					}
					return false;
				}
				var self = this;
				var target;
				if ($(this).hasClass('fav')) target= 'fav-update.php';
				if ($(this).hasClass('app')) target= 'app-update.php';
				$('img',this).attr('src','/css/loading.gif');
				$.get(target,
					{
						id:		rel,
						action: 'del'
					},
					function(data, status) {
						if (data.status == 'success') {
							$(self).closest('tr').remove();
						}
						else {
							alert(data.result);
						}
					},
					'json'
				);
				return false;
			}
		);
		$("#remember-me").live('click',
			function() {
				if ($(this).is(':checked')) {
					if(!confirm("CAUTION: You should not select this option if you are using a public/shared computer"))
						return false;
				}
			}
		);
		
	} //jQuery
);


// -------- BOOKMARK THIS PAGE

function bookmark(url,title){
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}

// ------- EMAIL TO FRIEND

function emailToFriend(domainname, group){

var initialsubj = domainname + ".com Website";
var initialmsg="Hi, I was checking out " +"http://" + domain + ".com and found this great property.  I thought you might like it.";
var	return_value = "";

	window.location = "mailto:"+return_value+"?subject="+initialsubj+"&body="+initialmsg
	return_value = null;

}
function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0 || nDays===undefined) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}
/*
function Get_Cookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
*/
function GetCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
function getParam(p) {
	var params;
	params = location.search.split("?")[1];
	if (params == undefined) return '';
	if  (params!='') params = params.toString().split('&');
	var i;
	var item;
	for (i=0; i<params.length;i++) {
		item = params[i].split('=');
		if (item[0] == p) {
			return item[1];
		}
	}
	return '';
}
// Should migrate parameter manipulations throughout older app code to use the following, added 2009-09-08
window.location.querystring = (function() {
 
    // by Chris O'Brien, prettycode.org
 
    window.location.qCollection = {};
 
    // Gets the query string, starts with '?'
 
    var querystring = window.location.search;
 
    // Empty if no query string
 

    // Decode query string and remove '?'
 
    querystring = decodeURI(querystring.substring(1));
 
   // Load the key/values of the return collection
 
    var pairs = querystring.split("&");
 
    for (var i = 0; i < pairs.length; i++) {
 
        // Empty pair (e.g. ?key=val&&key2=val2)
 
        if (!pairs[i]) {
            continue;
        }
 
        // Don't use split("=") in case value has "=" in it
 
        var separatorPosition = pairs[i].indexOf("=");
 
        if (separatorPosition == -1) {
            window.location.qCollection[pairs[i]] = "";
        }
        else {
            window.location.qCollection[pairs[i].substring(0, separatorPosition)] 
                = pairs[i].substr(separatorPosition + 1);
        }
    }
 
    // toString() returns the key/value pairs concatenated
 

    return window.location.qCollection;
})();
window.location.qString = function() {
	var idx;
	var sep="";
	var q="";
	
	for (idx in window.location.qCollection) {
		q += sep + idx + "=" + window.location.qCollection[idx]; sep = "&";
	}
	return window.location.href.split("?")[0] + (q ? "?" : "") + q;
};
