var slidespeed=3000;
var slideplay=1;
var slideShowTimeout = "";
$(document).ready(function() {
if($("#map_holder_container.visible").size() > 0) { 
$("a.photo-popup-zoom").hide();
} else {
$("a.photo-popup-zoom").show();
}
$('.ui-widget-overlay').live('click', function() { $(".ui-dialog-content").dialog("close"); });
$("a.rf-tweet-button").click(function() { 
window.open($(this).attr('href'), "tweet", "location=yes,toolbar=no,width=500,height=350,left=" + Math.round((screen.width-500)/2) + ",top=" + Math.round((screen.height-350)/2) + "");
return false;
});
$("a.rf-print-button").click(function() { 
window.open($(this).attr('href'), "tweet", "location=no,menubar=yes,toolbar=yes,width=760,height=600,left=" + Math.round((screen.width-760)/2) + ",top=10");
return false;
});
$("a.action-listing-report").click(function() {
$('#popupReport').dialog({
modal: true,
title: "Report Listing",
width: '500',
height: $(window).height() > 300 ? '300' : $(window).height()-50,
minHeight: $(window).height() > 300 ? '300' : $(window).height()-50,
maxHeight: $(window).height()-20
}); 
$('#popupReport').dialog('open');
if($(this).attr('listingId')) {
$('#popupReport input[name=listingID]').val($(this).attr('listingId'));
} 
return false; 
});
$("a.action-listing-send").click(function() {
$('#popupEmail').dialog({
modal: true,
title: "Send to Friend",
width: '500',
height: $(window).height() > 300 ? '300' : $(window).height()-50,
minHeight: $(window).height() > 300 ? '300' : $(window).height()-50,
maxHeight: $(window).height()-20
}); 
$('#popupEmail').dialog('open');
if($(this).attr('listingId')) {
$('#popupEmail input[name=listingID]').val($(this).attr('listingId'));
} 
return false; 
});
$('#frmReport').ajaxForm({ 
type: 'post',
dataType: 'json', 
beforeSubmit: function(arr, myform, options) {
if(!validateformReport(document.getElementById('frmReport'))){
return false;
}
$('#frmReport').find('ul.errors').remove(); 
$("#loading").show();
$("#loading").width($('#frmReport').width()); 
$("#loading").offset($('#frmReport').parents(".ui-dialog").offset()); 
$('#frmReport').addClass('ui-state-disabled');
$('#frmReport').find('#buttonEmailMe').addClass('ui-state-disabled').find('span.ui-button-text').text('Sending...'); 
return true;
}, 
success: function(response) {
$('#frmReport').find('#buttonEmailMe').removeClass('ui-state-disabled').find('span.ui-button-text').text('Send'); 
$('#frmReport').removeClass('ui-state-disabled');
$("#loading").hide();
if(response.status == "ok") {
$('#popupReport').dialog('close');
alert('Your report has been sent');
} else {
alert('Error: ' + response.errors);
$('#frmReportSuccess').hide();
$('#frmReportContent').show(); 
}
}
}); 
$('#frmEmail').ajaxForm({ 
type: 'post',
dataType: 'json', 
beforeSubmit: function() {
$('#frmEmail').find('ul.errors').remove(); 
$("#loading").show();
$("#loading").width($('#frmEmail').width()); 
$("#loading").offset($('#frmEmail').parents(".ui-dialog").offset());
$('#frmEmail').addClass('ui-state-disabled');
$('#frmEmail').find('#buttonEmailMe').addClass('ui-state-disabled').find('span.ui-button-text').text('Sending...'); 
return true;
}, 
success: function(response) {
$('#frmEmail').find('#buttonEmailMe').removeClass('ui-state-disabled').find('span.ui-button-text').text('Send'); 
$('#frmEmail').removeClass('ui-state-disabled');
$("#loading").hide();
if(response.status == "ok") {
/*$('#frmEmailContent').hide();
$('#frmEmailSuccess').show();
$('#frmEmailSuccess').focus();
$('#frmEmailError').hide();*/
$('#popupEmail').dialog('close');
alert('Your message has been sent');
} else {
$("#siimage").attr('src', '/securimage/securimage_show.php?sid=' + Math.random()); 
alert('Error: ' + response.errors);
/*$('#frmEmailError').append('<ul class="errors"><li>'+response.errors+'</li></ul>'); 
$('#frmEmailError').show(); */
$('#frmEmailSuccess').hide();
$('#frmEmailContent').show(); 
}
}
}); 
$("a.link_contact").click(function() {
if($(this).hasClass('link_contact_phone')) {
$('#popupContact').html($("#loading").html());
$('#popupContact').dialog({
modal: true,
title: "Phone Landlord",
width: '400' 
});
$('#popupContact').load("/phone_me.php?listingID="+$(this).attr('listingId') + '&ajax=1');
$('#popupContact').dialog('open');
} else { 
$('#popupContactEmail').dialog({
modal: true,
title: "Email Landlord",
width: '650',
height: $(window).height() > 600 ? '600' : $(window).height()-50,
minHeight: $(window).height() > 600 ? '600' : $(window).height()-50,
maxHeight: $(window).height()-20
}); 
$('#popupContactEmail').dialog('open');
/*if ($("#recaptcha_area").length == 0){
Recaptcha.create("6Lfs-McSAAAAAKc19EPM3QwCs3J4b-Z4WcbLsLoX", "EmailCaptchaContainer", {
theme: "clean",
callback: Recaptcha.focus_response_field
});
} else {
Recaptcha.reload(); 
}*/
$("#siimage").attr('src', '/securimage/securimage_show.php?sid=' + Math.random()); 
$("#ct_captcha").val("");
} 
return false; 
});
$('#frmEmailMe').ajaxForm({ 
type: 'post',
dataType: 'json', 
beforeSubmit: function() {
if(!validateformemailme(document.getElementById('frmEmailMe'))) {
return false;
}
$('#frmEmailMe').find('ul.errors').remove(); 
$("#loading").show();
$("#loading").width($('#frmEmailMe').width()); 
$("#loading").offset($('#frmEmailMe').parents(".ui-dialog").offset());
$('#frmEmailMe').addClass('ui-state-disabled');
$('#frmEmailMe').find('#buttonEmailMe').addClass('ui-state-disabled').find('span.ui-button-text').text('Sending...'); 
return true;
}, 
success: function(response) {
$('#frmEmailMe').find('#buttonEmailMe').removeClass('ui-state-disabled').find('span.ui-button-text').text('Send'); 
$('#frmEmailMe').removeClass('ui-state-disabled');
$("#loading").hide();
if(response.status == "ok") {
/*$('#frmEmailMeContent').hide();
$('#frmEmailMeSuccess').show();
$('#frmEmailMeSuccess').focus();
$('#frmEmailMeError').hide();*/
$('#popupContactEmail').dialog("close");
alert('Your message has been sent');
} else {
$("#siimage").attr('src', '/securimage/securimage_show.php?sid=' + Math.random()); 
alert('Error: ' + response.errors);
/*$('#frmEmailMeError').append('<ul class="errors"><li>'+response.errors+'</li></ul>'); 
$('#frmEmailMeError').show(); */
$('#frmEmailMeSuccess').hide();
$('#frmEmailMeContent').show(); 
}
}
});
$(".pic_holder_overlap, #slideshow-zoom, a.photo-popup-zoom").live("click", function() { 
var hrefToOpen = $(".slideshow_element.visible a[href]").attr("href");
if(hrefToOpen) {
hrefToOpen = hrefToOpen.replace(/viewimage/, 'photos') + '&ajax=1';
} else {
hrefToOpen = "/photos.php?imageID="+$(this).attr('imageId') +"&listingID="+$(this).attr('listingId') + '&ajax=1'
}
$('#popupPhotos').html($("#loading").html());
$('#popupPhotos').dialog({
modal: true,
title: "Property Photos",
width: '700',
height: $(window).height() > 550 ? '500' : $(window).height(), 
position: 'center',
resize: function(event, ui) { 
var topMargin = Math.round(($('#popupPhotos').height()-$('#thePhoto').height()-90)/2);
if(topMargin < 0) { topMargin = 0; }
topMargin = topMargin > 0 ? topMargin : 5; 
$('#popupPhotos #thePhoto').css('max-height', ($('#popupPhotos').height()-90) + 'px').css('max-width', ($('#popupPhotos').width()-150) + 'px'); 
$('#popupPhotos .image-wrapper').css("margin-top", topMargin + 'px'); 
} 
});
$('#popupPhotos').load(hrefToOpen, function() { 
$('#popupPhotos #thePhoto').css('max-height', ($('#popupPhotos').height()-90) + 'px');
var topMargin = Math.round(($('#popupPhotos').height()-$('#thePhoto').attr('mh')-90)/2);
if(topMargin < 0) { topMargin = 0; }
topMargin = topMargin > 0 ? topMargin : 5; 
$('#popupPhotos .image-wrapper').css("margin-top", topMargin + 'px');
});
$('#popupPhotos').dialog('open'); 
return false;
});
$('.listing-photos-page a.btn-next-blue').live('click', function() {
var nextLI = $('#all-images li.active').next(); 
if(nextLI.size()>0) {
nextLI.click();
} else {
$('#all-images li:first').click();
}
});
$('.listing-photos-page a.btn-prev-blue').live('click', function() {
var nextLI = $('#all-images li.active').prev(); 
if(nextLI.size()>0) {
nextLI.click();
} else {
$('#all-images li:last').click();
}
});
$("ul#all-images li").live('click', function() {
$("ul#all-images li").removeClass("active");
$(this).addClass("active");
$("#thePhoto").attr("src", '/images/spacer.gif');
$(".thePhoto.image-caption").html($(this).find('.image-caption').html());
$(".thePhoto.image-description").html($(this).find('.image-description').html());
var topH = ($('#popupPhotos').height()-$(this).attr('imgheight')-90)/2;
topH = topH > 0 ? topH : 5;
$('#popupPhotos .image-wrapper').css("margin-top", Math.round(topH) + 'px');
$("#thePhoto").attr("src", $(this).attr('href'));
return false;
});
$(".ui-scroller a.btn-prev").live('click', function() {
var ul = $(this).parents(".ui-scroller").find('ul:first');
ul.prepend(ul.children('li:last')); 
});
$(".ui-scroller a.btn-next").live('click', function() {
var ul = $(this).parents(".ui-scroller").find('ul:first');
ul.append(ul.children('li:first')); 
});
if($("#map_holder").size() > 0) {
var latlng = new google.maps.LatLng($("#latitude").val(), $('#longitude').val());
var zoom = 15; 
var myOptions = {
zoom: zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_holder"), myOptions); 
gMapMarker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
icon: $('#icon').val()
}); 
}
slideShowTimeout = setTimeout("slideit(1)",slidespeed);
$('a#show-howfarto').click(function() {
$("#howfarto").dialog({
title: "How Far To...",
modal: true,
width: 450,
minHeight: 375,
position: 'center'
});
$("#howfarto").tabs({
show: function(event, ui) { 
var panel = $('#' + ui.panel.id);
$(panel).find("a.btn_close").button();
if($(panel).hasClass('loaded')) {
return true;
}
if(ui.panel.id == 'howfarto-landmarks') { 
$(panel).find('li[lat]').each(function() { 
var landmark = new google.maps.LatLng($(this).attr('lat'), $(this).attr('lng'));
$(this).find(".distance").html(
Math.round(google.maps.geometry.spherical.computeDistanceBetween(landmark, latlng)/100)/10 + ' km'
);
});
} 
if(ui.panel.id == 'howfarto-bus') {
var busContainer=$(panel).find("#howfarto-bus-result");
$.get(busContainer.attr('src'), function(result) {
busContainer.html('<ul style="list-style: none;"></ul>');
var ul = busContainer.find('ul');
var lines=result.split("#");
var counter = 0;
for(i=0;i<lines.length;i++) {
var fields=lines[i].split(",");
if(fields[5]) {
counter++;
ul.append('<li>' + '<span>' + fields[5] + '</span> - ' + fields[4] + '</li>');
}
} 
if(counter==0) {
ul.append('<li>No bus routes found</li>'); 
} 
});
var lrtContainer=$(panel).find("#howfarto-lrt-result");
$.get(lrtContainer.attr('src'), function(result) { 
lrtContainer.html('<ul style="list-style: none;"></ul>');
var ulrt = lrtContainer.find('ul');
var counter = 0;
var stations = [];
$(result).find('marker').each(function(){
var station = new google.maps.LatLng($(this).attr('lat'), $(this).attr('lng'));
var distance = Math.round(google.maps.geometry.spherical.computeDistanceBetween(station, latlng));
stations[stations.length] = { title: $(this).attr('title'), distance: distance } ;
}); 
stations.sort(function(a,b){return a.distance - b.distance}); 
for(i=0;i<stations.length;i++) {
counter++;
ulrt.append('<li>' + stations[i].title + ' - <span class="distance">' + Math.round(stations[i].distance/10)/100 + ' km</span></li>'); 
if(i>=2) {
break;
}
}
if(counter==0) {
ulrt.append('<li>No LRT stations found</li>'); 
} 
}, 'xml');
}
if(ui.panel.id == 'howfarto-amenities') {
getAmenities(latlng);
}
if(ui.panel.id == 'howfarto-postalcode') {
if($.cookie('zip')) {
getPostalCodeDistance($.cookie('zip'), '#howfarto-postalcode-result', 'zip'); 
}
if($.cookie('address')) {
getPostalCodeDistance($.cookie('address'), '#howfarto-address-result', 'address'); 
}
}
$(panel).addClass('loaded');
}
});
return false;
});
$('#howfarto .btn_close').live('click', function() {
$('#howfarto').dialog("close");
return false;
});
});
function getAmenities(searchpoint)
{
myresults = new Array();
search_markers = new Array();
searchid = -1;
var vars = searchpoint.lat() + ',' + searchpoint.lng();
var message = "0";
var csv = ""; 
var url = '/maps/code/perform_search_lite.php'; 
var data = {
v: '1.0',
rsz: 'large',
sll: searchpoint.lat() + ',' + searchpoint.lng(),
sspn: '0.015,0.03'
}; 
data.q='grocery stores'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "groceries", searchpoint);
}, 'json'); 
data.q='drug stores'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "drugs", searchpoint);
}, 'json'); 
data.q='fitness facilities'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "fitness", searchpoint);
}, 'json'); 
data.q='bars'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "bars", searchpoint);
}, 'json'); 
data.q='coffee shops'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "coffeeshops" , searchpoint);
}, 'json'); 
data.q='cinemas'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "cinemas" , searchpoint);
}, 'json'); 
data.q='retail stores'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "retail" , searchpoint);
}, 'json'); 
/* data.q='parks'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "parks" , searchpoint);
}, 'json'); */
data.q='daycare'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "daycare" , searchpoint);
}, 'json'); 
data.q='off-leash parks'; 
$.get( url, data, function(response) {
processAmenities(data.q, response, "offleash" , searchpoint);
}, 'json'); 
}
function processAmenities(type, data, targetDiv, searchpoint) {
var targetDivId = targetDiv;
var mySelect = $('#'+targetDivId);
var closestKm = 9999;
var amenities = [];
var amenitiesRF = [];
for(i=0;i<data.responseData.results.length;i++) { 
var point2 = new google.maps.LatLng(parseFloat(data.responseData.results[i].lat),parseFloat(data.responseData.results[i].lng));
var thisDistance = Math.round(google.maps.geometry.spherical.computeDistanceBetween(searchpoint, point2)/10)/100;
var orig = data.responseData.results[i].titleNoFormatting; 
var title = data.responseData.results[i].titleNoFormatting;
title = title.replace("&#39;",""); 
title = title.replace("&#38;","&"); 
title = title.replace("'","");
if (title.length > 30){title = title.substr(0,30); title = trim(title);}
var caption = title + " ( " + thisDistance + " km)";
if(parseFloat(thisDistance)>10) {
continue;
}
if(parseFloat(closestKm) > parseFloat(thisDistance)) {
closestKm = thisDistance;
}
amenities[amenities.length] = { caption: caption, distance: parseFloat(thisDistance) };
}
for(i=0;i<data.responseData.resultsRentfaster.length;i++) { 
var point2 = new google.maps.LatLng(parseFloat(data.responseData.resultsRentfaster[i].lat),parseFloat(data.responseData.resultsRentfaster[i].lng));
var thisDistance = Math.round(google.maps.geometry.spherical.computeDistanceBetween(searchpoint, point2)/10)/100;
var orig = data.responseData.resultsRentfaster[i].titleNoFormatting; 
var title = data.responseData.resultsRentfaster[i].titleNoFormatting;
title = title.replace("&#39;",""); 
title = title.replace("&#38;","&"); 
title = title.replace("'","");
if (title.length > 30){title = title.substr(0,30); title = trim(title);}
var caption = title + " ( " + thisDistance + " km)";
if(parseFloat(closestKm) > parseFloat(thisDistance)) {
closestKm = thisDistance;
}
amenitiesRF[amenitiesRF.length] = { caption: caption, distance: parseFloat(thisDistance) };
}
amenities.sort(function(a,b){return a.distance - b.distance}); 
if(amenities.length) {
mySelect.append('<optgroup label="Google Results"></optgroup>');
var optgroup = mySelect.find("optgroup[label*=Google]");
var amenitieslength = amenities.length > 5 ? 5 : amenities.length;
for(i=0;i < amenitieslength;i++) {
optgroup.append('<option>' + amenities[i].caption + '</option>');
}
}
if(amenitiesRF.length>0) {
mySelect.append('<optgroup label="RentFaster.ca Results"></optgroup>'); 
var optgroup = mySelect.find("optgroup[label*=RentFaster]");
for(i=0;i<amenitiesRF.length;i++) {
optgroup.append('<option>' + amenitiesRF[i].caption + '</option>');
}
}
mySelect.children('option:first').text(mySelect.children('option:first').text().replace(/xxx/, closestKm));
mySelect.removeClass('not-processed');
if(closestKm <9999 ) {
mySelect.show();
} else {
mySelect.hide();
}
if($('#howfarto-amenities-result select.not-processed').size()==0) {
$('#howfarto-amenities-result .small-loading').hide(); 
}
}
function slideit(myDirection){ 
if (slideplay!=1) { 
return; 
} 
if(slideShowTimeout!="") {
clearTimeout(slideShowTimeout);
}
slideShowTimeout = setTimeout("slideit(1)",slidespeed);
var visibleElement = $("#slideshow_holder > .slideshow_element.visible").attr('id');
if(!visibleElement) {
var visibleElement = $("#slideshow_holder > .slideshow_element:first").attr('id'); 
$("#"+visibleElement).addClass('visible'); 
}
if(myDirection==1) { 
var nextElement = $("#slideshow_holder > #"+visibleElement).next(); 
} else {
var nextElement = $("#slideshow_holder > #"+visibleElement).prev();
} 
if(nextElement && nextElement.hasClass('slideshow_element')) { 
nextElement.addClass('visible');
$("#slideshow_holder > #"+visibleElement).removeClass('visible');
} else { 
$("#slideshow_holder > #"+visibleElement).removeClass('visible');
if(myDirection==1) { 
$("#slideshow_holder > .slideshow_element:first").addClass('visible');
} else {
$("#slideshow_holder > .slideshow_element:last").addClass('visible');
}
}
if($("#map_holder_container.visible").size() > 0) { 
$("a.photo-popup-zoom").hide();
} else {
$("a.photo-popup-zoom").show();
}
} 
function pauseShow(isStart) {
if(isStart==1) {
slideplay=1;
slideit(1);
} else {
slideplay=0;
}
$("#buttons_holder").removeClass("slideshow-playing");
if(slideplay) {
$("#buttons_holder").addClass("slideshow-playing");
} 
}
function pauseNext(pauseDirection) {
slideplay=1;
doblend=false;
slideit(pauseDirection);
doblend=true;
pauseShow(0);
}
function getPostalCodeDistance(postalcode, destination, cookiename)
{
$.cookie(cookiename, postalcode, { expires: 30, path: '/' });
var coordfields; var mydist; var findpoint;
var codeline = '';
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng($("#latitude").val(), $('#longitude').val());
if (geocoder) {
geocoder.geocode({ address: postalcode, location: latlng }, function(result, status) {
var newContent = '';
if(status==='ZERO_RESULTS') {
newContent = 'Unable to locate postal code'; 
} else if (status!=='OK') {
newContent = 'Unable to calculate distance'; 
} else {
newContent = 'Distance to ' + postalcode + ': ' 
+ Math.round(google.maps.geometry.spherical.computeDistanceBetween(result[0].geometry.location, latlng)/100)/10
+ ' km';
}
$(destination).html(newContent);
});
} else {
$(destination).html('Unable to calculate distance'); 
}
$(destination).show();
return false; 
}
