/*
	Global functions to extend whole site functionality
*/

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;}
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {return true;
            }
        }
    }
     return false;
}

function str_replace(search, replace, subject) {
	return subject.split(search).join(replace);
}


function gAddCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
};


$.fn.clearForm = function() {
	return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
		return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea')
		this.value = '';
	else if (type == 'checkbox' || type == 'radio')
		this.checked = false;
	else if (tag == 'select')
		this.selectedIndex = -1;
	});
};



function showLoginPanel(message, redirect_url) {
	var redirect = window.location;
	if (redirect.pathname == '' || redirect.pathname == '/' || redirect.pathname == '/login_signup' || redirect.pathname == '/login_signup/') redirect = '/account';
	window.location = '/login_signup/?r='+redirect;
	return false;
 	if (message) {
		$("#f_login_message").show().text(message);
	}
	$("#logindiv").show();
	$("#forgetpassworddiv").hide();
	$("#f_login_conteiner").show();
	if (redirect_url) {
		$("#f_page").attr({value: redirect_url});
	}
	$("#email").focus();
	$(".cancel").bind("click", function(){
		$("#f_login_message").empty();
		$("#f_login_conteiner").hide();
		return false;
	});
}

$(document).ready(function() {
	
	/* testing for Neighborhood Guide */
	if ($('.hoodhover').length > 0) {
		
		var imgwidth = 194;
		
		$('.hoodhover')
		.bind('mouseover', function(){
			var order = $(this).metadata().order;
			$('#map_hoverholder').css('background', 'url(/img/manhattanmap/mm_hover.gif) -'+(order*imgwidth)+'px 0 no-repeat');
		})
		.bind('mouseout', function(){
			$('#map_hoverholder').css('background', 'none');
		});
	}; // end manhattan hover map

	// Buy/Rent
	$('#buyrent_tabs li:first-child a').click(function(){
		$(this).parent('li').addClass('buyrent-tab-selected').parent('ul').find('li:last-child').removeClass('buyrent-tab-selected');
		$('#buypanel').show();
		$('#rentpanel').hide();
		return false;
	});
	$('#buyrent_tabs li:last-child a').click(function(){
		$(this).parent('li').addClass('buyrent-tab-selected').parent('ul').find('li:first-child').removeClass('buyrent-tab-selected');
		$('#buypanel').hide();
		$('#rentpanel').show();
		return false;
	});
	
	// Hint text
	$('.f_hint').each(function(){
		var e = $(this), initval = e.val(), staticval = e.attr('value');
		e.bind('focus', function() {if (e.val() == initval) e.val('');})
		.bind('blur', function() {if (e.val() == '') e.val(initval);});			
	});
	
	// Makes lists "selectable"
	$('.f_selectable').each(function(){
		var a_group = $(this).find('a');
		a_group.click(function(){
			a_group.each(function(){$(this).removeClass('hilite-selected');});
			$(this).addClass('hilite-selected');
		});															 
  });
	
	// Select All buttons
	if ($('.selectall')) {
		$('.selectall').bind('click', function(){
			if ($(this).hasClass('f_sel_true')) {
				$(this).removeClass('f_sel_true')
				.find('span').html('Select all')
				.parent('a').parent('div').find('input').attr('checked', false)
				.parent('label').parent('li').parent('ul').each(function(){updateFancy($(this))});
			} else {
				$(this).addClass('f_sel_true')
				.find('span').html('Deselect all')
				.parent('a').parent('div').find('input').attr('checked', 'checked')
				.parent('label').parent('li').parent('ul').each(function(){updateFancy($(this))});
			};
			return false;
		});
	};
	
	if ($('.deselectall')) {
		$('.deselectall').bind('click', function(){
			$('input[name="hoods[]"]').attr('checked', false).parent('label').parent('li').removeClass('f_sel');
			$('.selectall').removeClass('f_sel_true').find('span').html('Select all');
		});
	};
	
	var downtown_allchked = ($('#findhome_downtown input').length == $('#findhome_downtown input:checked').length);
	var midtown_allchked = ($('#findhome_midtown input').length == $('#findhome_midtown input:checked').length);
	var uptown_allchked = ($('#findhome_uptown input').length == $('#findhome_uptown input:checked').length);
		
	if (downtown_allchked) $('#findhome_downtown .selectall').addClass('f_sel_true').find('span').html('Deselect all');
	if (midtown_allchked) $('#findhome_midtown .selectall').addClass('f_sel_true').find('span').html('Deselect all');
	if (uptown_allchked) $('#findhome_uptown .selectall').addClass('f_sel_true').find('span').html('Deselect all');
	
	/****************************************/
	// Fancylist: structure LI (LABEL (INPUT SPAN))
	$('.f_fancylist').each(function(){
		$(this).find('label').bind('click', function(){
			var input = $(this).find('input');
			// If input is a radio, remove all .f_sel first from radios of same name
			if (input.attr('type') == 'radio') {
				var inputname = input.attr('name');
				$(this).parent('li').parent('ul')
				.find('input[name="'+inputname+'"]')
				.each(function(){$(this).parent('label').parent('li').removeClass('f_sel');});
			};
			var chkd = input.attr('checked');
			if (chkd) $(this).parent('li').addClass('f_sel'); else $(this).parent('li').removeClass('f_sel');
		});
		updateFancy($(this));
	});
	
	// Prevent text selection
	$('.f_fancylist label')
	.bind('selectstart', function(){return false;})
	.bind('mousedown', function(){return false;})
	.bind('mouseenter', function(){$(this).css({'cursor': 'pointer'});});	
	
	// Make sure image reflects checkbox state
	function updateFancy(fl) {
		$(fl).find('input').each(function(){
			if ($(this).attr('checked')) $(this).parent('label').parent('li').addClass('f_sel'); else $(this).parent('label').parent('li').removeClass('f_sel');
		});
	};
	
	// Filter populator
	//$('#findhome_size').find('input').bind('click', function(){
		
	//});
	
	function winheight() {
		return parseInt($(window).height());
	};

 //////////////////////////////

 function preload(iarray) {
 imageObj = new Image();
 for(i=0; i<iarray.length; i++) {
 imageObj.src = IMG_PATH + iarray[i];
 };
 };
 


 if ($("#logmeinopen")) {
   	$("#logmeinopen").bind("click", function(){
		showLoginPanel();
	});
 }
  
 if ($("#relogin")) {
   	$("#relogin").bind("click", function(){
		showLoginPanel();
	});
 }
 
 if ($("#email_frm")) {
	 $("#loginfrm").bind("click", function () {
		 login();
	});
 }
 $('#password_frm').keyup(function(e) {
	 if(e.keyCode == 13) {
		 login();
	 }
 });
 function login () {
		var email = $("#email_frm").attr('value');
   		var pass = $("#password_frm").attr('value');
   		var url = "/action/login/";
    	$.post(url, {"login": email, "pass": pass},
    		function(data){
	        data = eval(data);
	        if (data.responsecode >= 200) {
	        		if (data.responsecode == 202) {
//	        			$("#login_message").show();
//	        			$("#login_message").text("You are already logged in!");
	        			window.location = '/account';
	        		} else {
	        			$("#flmessage").attr("value", data.message);
	        			$("#f_lm").submit();
//	        			window.location = '/login_signup';
	        		}
	        } else {
	        	re = /\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}/;
        		match = email.match(re);
        		if (match === null ) {
        			reoUrl = "/reo/servLogin.jsp";
        			$.post(reoUrl, {"txtUserId": email, "txtPassword": pass});
        			blogUrl = "/content/wp-login.php";
        			$.post(blogUrl, {"log": email, "pwd": email, "testcookie": "1", "wp-submit": "Log In"},
        			
	        			function(data){

	        				
							var redirect = window.location;
							//open this if want to redirect user to page where was 
							//if (redirect.pathname == '' || redirect.pathname == '/' || redirect.pathname == '/login_signup' || redirect.pathname == '/login_signup/') 
								redirect = '/account';
				 			window.location= redirect;
						}
			        );
        		} else {
        			
        			// register a pageTracker event for login
        			if (typeof window._cTrack == 'function') _cTrack('user', 'login');
        			
						var redirect = window.location;
						//open this if want to redirect user to page where was 
						//if (redirect.pathname == '' || redirect.pathname == '/' || redirect.pathname == '/login_signup' || redirect.pathname == '/login_signup/') 
							redirect = '/account';
			 			window.location= redirect;
        		}
	        }
    	}); 
 }
 if ($("#ftpd")) {
	 $("#ftpd").bind("click", function(){
		$("#logindiv").slideUp("slow");
		$("#forgetpassworddiv").slideDown("slow");
		$("#forget_login").focus();
		$("#try").bind("click", function(){
			$("#logindiv").slideDown("slow");
			$("#forgetpassworddiv").slideUp("slow");
			
		});
	 });
 }
 if ($("#logmein")) {
   		$("#logmein").bind("click", function(){
   		var email = $("#email").attr('value');
   		var pass = $("#password").attr('value');
   		var url = "/action/login/";
    	 $.post(url, {"login": email, "pass": pass},
	        function(data){
	        data = eval(data);
	        if (data.responsecode >= 200) {
	        		if (data.responsecode == 202) {
	        			$("#login_message").show();
	        			$("#login_message").text("You are already logged in!");
	        		} else {
	        			$("#logindiv").slideUp("slow");
	        			$("#forgetpassworddiv").slideDown("slow");
	        			$("#sendPass").bind("click", function() {
        						$.getJSON("/action/forgetpassword/?login="+$("#forget_login").attr("value"), function(dataf) {
        							$("#sendPass").unbind();
        							if (dataf.responsecode == '101') {
        								$("#f_forget_message").empty();
        								$("#forgetpassworddiv").hide();
        								$("#logindiv").show();
//        								$("#f_login_message").text("Your password has been sent to your email");
        								alert("Your password has been sent to your email");
//        								$("#f_login_message").show();
        								$("#password").empty();
        							} else {
//        								$("#f_forget_message").text("Sorry we cound not find your email ");
        								alert("Sorry we cound not find your email ");
//        								$("#f_forget_message").show();
        							}
        						});
        					});
	        			
	        			$("#try").bind("click", function(){
	        					$("#logindiv").slideDown("slow");
	        					$("#forgetpassworddiv").slideUp("slow");
	        					
	        			})
	        		}
	        	} else {
	        		re = /\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}/;
	        		match = email.match(re);
	        		if (match === null ) {
	        			reoUrl = "/reo/servLogin.jsp";
	        			$.post(reoUrl, {"txtUserId": email, "txtPassword": pass});
	        			blogUrl = "/content/wp-login.php";
	        			$.post(blogUrl, {"log": email, "pwd": email, "testcookie": "1", "wp-submit": "Log In"},
	        			
		        			function(data){
	
		        				var url = '';
								if ($("#f_pagex").attr("value").length != 0) {
									url = $("#f_pagex").attr("value");
								}
					 			window.location= url;
							}
				        );
	        		} else {
	        			
	        			// register a pageTracker event for login
	        			if (typeof window._cTrack == 'function') _cTrack('user', 'login');
	        			
	        			var url = '';
							if ($("#f_pagex").attr("value").length != 0) {
								url = $("#f_pagex").attr("value");
							}
				 			window.location= url;
	        		}
	        			
		 		}
	        });
		});
		}
 if ($("#logmeout")) {
   		$("#logmeout, .logmeout").bind("click", function(){
   		d = new Date();
   		url = "/action/logout/"+d.getTime();
    	 $.getJSON(url,
	        function(data){
	        	url = "/";
	        	if ($("#f_page").attr("value").length != 0) {
					url = $("#f_page").attr("value");
				}
		 		window.location=url;
	        });
		});
		}
 if ($("#signmeup")) {
 	$("#signmeup").bind("click", function(){
 	
		if ($("#r_password")[0].value != $("#r_repassword")[0].value) {
			if ($("#passerror")) {
				$("#passerror").text("not eq");
			} else {alert("not eq");}
			alert("please verify password");
			$("#r_repassword")[0].value = "";
			$("#r_repassword").focus();
			return false;
		}

   		url = "/action/signup/";

		if ($("#referral").attr("value") == 'OLR_listing') {
			$('#detailsConversionsiFrame').attr('src', '/conversions/olr_signup');
		}
    	 	
   	 	$.post(url, {"email": $("#r_email").attr("value"), "pass":$("#r_password").attr("value"), "name": $("#name").attr("value"), "referral": $("#referral").attr("value")},
        function(data) {
        
			data = eval(data);
			
	        if (data.responsecode >= 200) {
	        	alert(data.message);
        	} 
        	else {
    			// register a pageTracker event for signup
        		if (typeof window._cTrack == 'function') _cTrack('user', 'signup');
        		
				url = "/";
	        	if ($("#f_page").attr("value").length != 0) {
					url = $("#f_page").attr("value");
				}				
	        	if ($("#f_pagex").attr("value").length != 0) {
					url = $("#f_pagex").attr("value");
				}
				
	 			window.location = url;
	 		}
        });
	});
}

/* #submitsearch action replaced with submit action of parent form */
$('#generalsearch').bind('submit', function(e){
	e.preventDefault();
	window.location="/search/" + URLEncode($("#searchfield")[0].value);
});

//  http://www.albionresearch.com/

function URLEncode(str) {
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < str.length; i++ ) {
		var ch = str.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    // unsupported unicode character, add +
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};




 
 //storing Lead form action here to be visible also from blogs thats why checking if id exists before binding event
	if ( $("#ask_button") ) {
		$("#ask_button").bind("click", function(){
				
			var btn = $(this);
			
			$('#send_success_message, #send_fail_message').hide();
			
			if ( !$('#detail_fn').val() || !$('#detail_em').val() ) { // either first name or email are blank
				
				$("#send_fail_message").show().html('First name and email address are required').css('color', 'red');
				
			} else {
			
				// show loading graphic, hide message fields if they are open
				$('#send_process_img').show();
				$('#send_success_message, #send_fail_message').hide();
				
				var form = $("#askForm").formToArray();
				var url = "/action/servelead/?";
				$.getJSON(url, form, function(data){

					$('#send_process_img').hide();
					
					var iframeSrc = '/conversions/listing';
					
					if ($("#ask_button").attr('name') == 'neighborhood_guide') {
						iframeSrc = '/conversions/listing/neighborhood_guide'
					}
					if ($("#ask_button").attr('name') == 'my_account') {
						iframeSrc = '/conversions/forms'
					}
					if ($("#ask_button").attr('name') == 'building') {
						iframeSrc = '/conversions/building'
					}
					if ($("#ask_button").attr('name') == 'new_dev') {
						iframeSrc = '/conversions/new_development'
					}
					if ($("#ask_button").attr('name') == 'olr_details') {
						iframeSrc = '/conversions/olr_details'
					}					
					
					$('#detailsConversionsiFrame').attr('src', iframeSrc);
					
					if (data.responsecode == '101') {
						$("#send_success_message").slideDown(200); //.fadeTo(3000, 1).slideUp(200);
						$('#askForm').clearForm(); // clearForm plugin in tregny.js
					} 
					else {
						$("#send_fail_message").slideDown(200);
					};
				});
			};
		});  
	}	
		
		
	/* For Manhattan Neighborhood Guides (all blogs) */
	/*if ($('#mng2_seeallcats')) {
		$('#mng2_seeallcats').bind('click', function(){
			if ($('.mng2-allcats').is(':hidden')) {
				// hide panels, show all cats link
				$('.mng2-catholder').hide();
				$('.mng2-allcats').show();
				$(this).html('Go Back to Panels');
			} else {
				$('.mng2-catholder').show();
				$('.mng2-allcats').hide();
				$(this).html('Show All Categories');
			}
		});
	};*/
}); // end $(document)


$(document).ready(function(){
        var showRecent = 0;
	//getRecentApt(1, showRecent);
        $.get("/action/getRecentBar/", function(data){
            showRecent = data;
            getRecentApt(1, showRecent);
            if (showRecent != 1) {
                $('#show_it').show("slow");
                $("#mainC").hide("slow");
            }
        });
	$('#hide_it a').click (function(){
		$('.recent_viewed').hide('slide',{direction:'down'},500);
		$('#show_it').show('slide',{direction:'down'},500);
                $.get("/action/setRecentBar/?close=1");
		});
	$('#show_it a').click(function(){
		$('#show_it').hide('slide',{direction:'down'},500);
		$('.recent_viewed').show('slide',{direction:'down'},500);
                $.get("/action/setRecentBar/?close=0");
});
});
	

function setRecentAptNextPrev() {}
            
function getRecentApt(page, show) {

	$.getJSON("/action/getrecentapt/json/", {"page":page}, function(data){
		if (data.result.count > 0) {
                        if (show == 1) {
                            $('#show_it').hide("slow");
                            $("#mainC").show("slow");

                        }

			$("#recently_viewed_container").empty();
			var r_conteiner = "";
			for (var i= 0; i < data.result.rows.length; i++) {
				var item = data.result.rows[i];
				// console.log(item);
                            
				var excl = '';
				if (item.blg_list_source_id_ptr == 3 || item.blg_show_as_exclusive == 'Y') {
                                    
                                        if (item.apt_number.length > 0) {
                                            
                                            excl = "#"+item.apt_number;
                                        }
				}

				var size = item.size;
				if (size == 'Other') {
					size = '';
				}

				var blg_address_type = item.blg_address_type.toLowerCase();
				var addressLine = item.blg_address_number + ' '
					+ item.blg_address_direction  + ' ' 
					+ item.blg_address_name + ' '
					+ blg_address_type.charAt(0).toUpperCase() + blg_address_type.slice(1)+' '+excl;
				r_conteiner += '<div class="recent_container"><ul class="recent_details"><li><a href="/details/'
					+item.id+'" ><span id="detail_addr">'
					+ addressLine.substr(0,20)  +'</span></a></li><li>'+size+' $'+item.price+'</li></ul>' 
					+ '<ul class="save_close">' 
					// + '<li><img src="/images/recent_close.gif" alt="close"/></li>' 
					+ '<ul class="save_close">'  
					+ '<li>';
					
				if (item.stared)
					r_conteiner += '<a href="javascript:void(0)" class="s_starred starmar" id="s_' + item.id + '"><img src="/css/img/i/star_sm.png" border="0" /></a>';
				else
					r_conteiner += '<a href="javascript:void(0)" class="s_notstarred starmar" id="s_' + item.id + '"><img src="/css/img/i/star_sm_blank.png" border="0" /></a>';						
					
				r_conteiner += '</li>'
					+ '</ul></div>';
			}
                          
			$("#recently_viewed_container").append(r_conteiner);
			
			if (page > 1) {
			
				$("#prevPage").show();
				$("#prevPage").unbind();
				
				$("#prevPage").bind("click", function(){
					getRecentApt(page-1, 1);
				});
			} 
			else {
				
				$("#prevPage").hide();
			}
			if (page*4 < data.result.count) {
			
				$("#nextPage").show();
				$("#nextPage").unbind();
                              
				$("#nextPage").bind("click", function() {
					getRecentApt(page+1, 1);
				});
			} 
			else {
				$("#nextPage").hide();
			}
			
			$(".starmar").click(function(){

				var id = $(this).attr("id").substr(2);
					
				if ($(this).hasClass('s_notstarred')) {
					url = "/action/addstar/" + id;
					var item = $(this);
					$.getJSON(url , false,  function(data) {
						if (data.responsecode == 101) {
							item.addClass('s_starred').removeClass('s_notstarred').html('<img src="/css/img/i/star_sm.png" border="0" />');
						} 
						else if (data.responsecode == 203) {
							showLoginPanel("You should be logged in to save listing");
						} 
						else {
							alert( 'Oops! There was an error saving this listing - did you already save it?\n\nTry refreshing the page to update results.'  ); 
						}
					});
				}
				else {
					url = "/action/deletestar/" + id;
					var item = $(this); 						
					$.getJSON(url , false,  function(data) {
						if (data.responsecode == 101) {
							item.addClass('s_notstarred').removeClass('s_starred').html('<img src="/css/img/i/star_sm_blank.png" border="0" />');
						} 
						else if (data.responsecode == 203) {
							showLoginPanel("You should be logged in to save listing", "findahome");
						} 
						else {
							alert( 'Oops! There was an error saving this listing - did you already save it?\n\nTry refreshing the page to update results.'  ); 
						}
					});						
				}
			});
		} else {
                    $("#mainC").hide();
                    $("#show_it").hide();
                }
	});
}




