var _FFrv;
var _isFF=false;
var _isIE=false;
var _isOpera=false;
var _isKHTML=false;
var _isMacOS=false;
var old_target = null;
var previewHeight;
var previewWidth;
var verticalOffset = 5;
var horizontalOffset = 3;
var top = 0;
var left = 0;
var slideSpeed = 20;
var currentImage;
var currentMLS;
var scrolling = false;
var timeout;
var ajaxSearchController = '/utils/ajax_search_controller';
var ajaxMLSController = '/utils/ajax_mls_controller';
var ajaxArchiveController = '/utils/ajax_archives_controller';
var ajaxDetailsController = '/utils/ajax_details_controller';
var ajaxInquireController = '/utils/ajax_inquire_controller';
var ajaxRealtorsController = '/utils/ajax_realtors_controller';

var map;
var geocoder;
var bounds;
var initPhase = true;
var mlsNo = '';
var dialogs_theme = 'alphacube';
var mapWin;
var firstImage;
var bigImages;
var city;
var dialogs_title = "East Valley Real Estate Weekly";
var popupWin = null;
var thisCity;
var thisPoint;
var thisPointHash;
var icon;
var currItem = -1;
var markerCount = 0;
var prevMLS = 0;
var nextMLS = 0;
var propIcon = new Array();

function init() {
    if(navigator.userAgent.indexOf('Macintosh')!= -1)_isMacOS=true;
    if((navigator.userAgent.indexOf('Safari')!= -1)||(navigator.userAgent.indexOf('Konqueror')!= -1))
    _isKHTML=true;
    else if(navigator.userAgent.indexOf('Opera')!= -1){
    _isOpera=true;
    _OperaRv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Opera')+6,3));
    }
    else if(navigator.appName.indexOf("Microsoft")!=-1)
    _isIE=true;
    else{
    _isFF=true;
    _FFrv=parseFloat(navigator.userAgent.split("rv:")[1])
    }
}

function jumpMenu(selObj){
    setCookie("site",selObj.options[selObj.selectedIndex].value);
    var re = new RegExp("\\?cmd1=(\\d*)");
    var cmd = document.location.href.match(re) ? "?cmd1="+RegExp.$1 : "?cmd1=0";
    eval("location='"+cmd+"'");
}

function goIsland(selObj){
    var url = selObj.options[selObj.selectedIndex].value;
    eval("location='"+url+"'");
}

function setCookie(name, value, expire) {
  document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}

function deleteCookie(Name)
{
  expireDate = new Date;
  expireDate.setDate(expireDate.getDate()-1);
  document.cookie = Name + "=; expires=" + expireDate.toGMTString();
}

function isValidEmail(str) {
    return str.match(new RegExp("^([a-zA-Z0-9_]|\\-|\\.)+@(([a-zA-Z0-9_]|\\-)+\\.)+[a-zA-Z]{2,4}$"));
}

function checkFields() {
    var i, a=checkFields.arguments;
    for(i=0;i<a.length;i++) {
        obj = document.getElementById(a[i]);
        if(!obj.value.length) {
            alert("Empty field '"+obj.name+"'");
            return false;
        }
        if (obj.name.match(/^email(.*?)/)) {
            if (!isValidEmail(obj.value)) {
                alert("Wrong email format");
                return false;
            }
        }
    }
    return true;
}

function fillRealtorName(selObj) {
    var part_id = selObj.value;
    var parts = selObj.options[selObj.selectedIndex].text.split(' ');
    if ($('realtorfirst') && $('realtorlast')) {
        if (parts[0])
            $('realtorfirst').value = parts[0];
        if (parts[1])
            $('realtorlast').value = parts[1];
    }
    if ($('realtor_id'))
        $('realtor_id').value = part_id;
}

function getRealtorInfo(selObj) {
    if (selObj.value) {
        if ($('realtorfirst'))
            $('realtorfirst').value = 'Loading...';
        if ($('realtorlast'))
            $('realtorlast').value = 'Loading...';
        if ($('phone'))
            $('phone').value = 'Loading...';
        /*
        if ($('price'))
            $('price').value = 'Loading...';
        */
        new Ajax.Request(ajaxRealtorsController,
        {
            method: 'post',
            parameters: 'id='+selObj.value,
            onSuccess: function(transport){
                var responseJS = transport.responseText.evalJSON();
                //closePopup();
                    $('realtorfirst').value = responseJS.first_name;
                    $('realtorlast').value = responseJS.last_name;
                    $('phone').value = responseJS.phone;
                    $('office').selectedIndex = responseJS.officeIndex;
                /*
                if (responseJS.price) {
                    $('price').value = responseJS.price;
                }
                */
            },
            onFailure: function(){ alert('Something went wrong...') }
        });
    } else {
        alert("You must specify year");
    }
}

function getAddress(selObj) {
    if (selObj.value) {
        if ($('address'))
            $('address').value = 'Loading...';
        new Ajax.Request(ajaxMLSController,
        {
            method: 'post',
            parameters: 'mls='+selObj.value,
            onSuccess: function(transport){
                var responseJS = transport.responseText.evalJSON();
                $('address').value = responseJS.FullAddress;
            },
            onFailure: function(){ alert('Something went wrong...') }
        });
    }
}


function getIssueArchiveMonths() {
    if ($('select_archives_year').value) {
        month = $('select_archives_months') ? $('select_archives_months').value : '';
        $('issue_archives_months').innerHTML = 'Loading...';
        new Ajax.Request(ajaxArchiveController,
        {
            method: 'post',
            parameters: 'action=months&year='+$('select_archives_year').value+'&month='+month,
            onSuccess: function(transport){
                var response = transport.responseText || '';
                $('issue_archives_months').innerHTML = response;
                getIssueArchiveCovers();
            },
            onFailure: function(){ alert('Something went wrong...') }
        });
    } else {
        alert("You must specify year");
    }
}

function getIssueArchiveCovers() {
    if ($('select_archives_year').value && $('select_archives_months').value) {
        $('issue_archives_covers').innerHTML = '<img src="/img/progress2.gif" width="90" height="16" border="0">';
        new Ajax.Request(ajaxArchiveController,
        {
            method: 'post',
            parameters: 'action=covers&year='+$('select_archives_year').value+'&month='+$('select_archives_months').value,
            onSuccess: function(transport){
                var response = transport.responseText || '';
                $('issue_archives_covers').innerHTML = response;
            },
            onFailure: function(){ alert('Something went wrong...') }
        });
    } else {
        alert("You must specify year and month");
    }
}

function getLatestCover() {
    if ($('latest_cover')) {
        new Ajax.Request(ajaxArchiveController,
        {
            method: 'post',
            parameters: 'action=latestcover',
            onSuccess: function(transport){
                var response = transport.responseText || '';
                $('latest_cover').innerHTML = response;
            },
            onFailure: function(){ alert('Something went wrong...') }
        });
    }
}

function checkAndSubmit(frm) {
    if(checkFields('YourName','YourEmail','FriendsName','FriendsEmail')) {
        doInquireRequest(frm, 'send_to_friend');
        return true;
    } else {
        return false;
    }
}

function checkAndSubmit2(frm) {
    if(checkFields('YourName','YourEmail')) {
        doInquireRequest(frm, 'send_request');
        return true;
    } else {
        return false;
    }
}

function doInquireRequest(frm, act) {
    args = 'action='+act;
    for (i=0; i<$(frm).elements.length; i++) {
        var obj = $(frm).elements[i];
        if (!obj.id.length)
            continue;
        switch (obj.type) {
            case 'checkbox':
                args += "&"+escape(obj.name)+'='+obj.checked;
                break;
            default:
                args += "&"+escape(obj.id)+'='+escape(obj.value);
            break;
        }
    }
    inquireRequest(args);
}

function inquireRequest(request) {
    new Ajax.Request(ajaxInquireController,
    {
        method: 'post',
        parameters: request,
        onSuccess: function(transport){
            var responseJS = transport.responseText.evalJSON();
            if (toBoolean(responseJS.returnValue))
                MsgBox("Thank you for your request.");
            else
                MsgBox("Something went wrong...<br>"+responseJS.debug);
        }
    });
}


function switchMapView() {
    $('propertyFullDetails').style.display = 'none';
    $('googleMap').style.display = '';
    var obj = $('map_view_button');
    obj.setAttribute('class','switch visit');
    obj.setAttribute('className','switch visit');
    obj = $('prop_view_button');
    obj.setAttribute('class','switch');
    obj.setAttribute('className','switch');
    return false;
}

function switchPhotoView() {
    $('propertyFullDetails').style.display = '';
    $('googleMap').style.display = 'none';
    var obj = $('map_view_button');
    obj.setAttribute('class','switch');
    obj.setAttribute('className','switch');
    obj = $('prop_view_button');
    obj.setAttribute('class','switch visit');
    obj.setAttribute('className','switch visit');
    return false;
}

function ensureNumeric(e) {
  var k = (typeof e.charCode == "undefined" ? e.keyCode : e.charCode);
  if (k < 32 || e.ctrlKey || e.altKey || e.metaKey)
    return true;
  return (k >= 48 && k <= 57);
}

function ensureAlphaDigit(e) {
  var k = (typeof e.charCode == "undefined" ? e.keyCode : e.charCode);
  if (k < 32 || e.ctrlKey || e.altKey || e.metaKey)
    return true;
  return ((k >= 48 && k <= 57) || (k >= 65 && k <= 90) || (k >= 97 && k <= 122));
}

function showBigImage(key) {
    $('big_photo').src = '/img/progress2.gif'
    $('big_photo').src = '/php/showicon.php?src='+escape(bigImages[key])+'&maxw=400&maxh=300';
    if (old_target!=null) {
        var oldElem = document.getElementsByName('icon_'+old_target);
        if (oldElem)
            oldElem[0].style.border = '2px Solid #F3F6E0';
    }
    old_target = key;
    var newElem = document.getElementsByName('icon_'+key);
    newElem[0].style.border = '2px Solid Red';
}

function showBigImageID(key) {
    $('big_photo').src = '/img/progress2.gif'
    if (typeof bigImages[key]=='string')
        $('big_photo').src = '/utils/show_picture_from_db?id='+bigImages[key]+'&maxw=400&maxh=640';
    else
        $('big_photo').src = '/img/noimage.gif';
    if (old_target!=null) {
        var oldElem = document.getElementsByName('icon_'+old_target);
        if (oldElem)
            oldElem[0].style.border = '2px Solid #F3F6E0';
    }
    old_target = key;
    var newElem = document.getElementsByName('icon_'+key);
    newElem[0].style.border = '2px Solid Red';
}

function getNextImage() {
    if (parseInt(old_target)+1<=bigImages.length-1) {
        showBigImage(parseInt(old_target)+1);
    } else
        showBigImage(0);
}

function getPrevImage() {
    if (parseInt(old_target)-1<0) {
        showBigImage(bigImages.length-1);
    } else
        showBigImage(parseInt(old_target)-1);
}

function scrollRight(speed) {
    var tbl = $('preview_layer');
    if (left>=0) {
        tbl.style.left = 0+'px';
        scrolling = false;
        return;
    }
    if (!left) {
        scrolling = false;
        return;
    }
    left += speed;
    tbl.style.left = left+'px';
    timeout = setTimeout('scrollRight('+speed+')',slideSpeed);
}

function scrollLeft(speed) {
    var tbl = $('preview_layer');
    if (tbl)
        previewWidth = $('preview_layer').clientWidth;
    else
        return;
    if (left<370-previewWidth) {
        scrolling = false;
        return;
    }
    left -= speed;
    tbl.style.left = left+'px';
    timeout = setTimeout('scrollLeft('+speed+')',slideSpeed);
}

function shiftPreviewStop() {
    scrolling = false;
    clearTimeout(timeout);
    return;
}

function shiftPreview(speed) {
    if (scrolling)
        return false;
    else {
        scrolling = true;
        if (speed>0)
            scrollRight(Math.abs(speed));
        else
            scrollLeft(Math.abs(speed));
    }
}

function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
    var x = Math.round(num * Math.pow(10,dec));
    if (x >= 0) n1=n2='';
    var y = (''+Math.abs(x)).split('');
    var z = y.length - dec;
    y.splice(z, 0, pnt);
    while (z > 3) {
        z-=3;
        y.splice(z,0,thou);
    }
    var r = curr1+n1+y.join('')+n2+curr2;
    return r;
}

function formatPrice(num) {return formatNumber(num, 0, ',', '', '', '', '', '');}

function doQuickRegionSearch(region) {
    // substitute form data
    $('locations').value = region;
    var f = document.forms[0];
    f.submit();
}

function doQuickCitySearch(city, region) {
    // substitute form data
    $('locations').value = region;
    var f = document.forms[0];
    var inp = document.createElement('input');
    inp.setAttribute('type','hidden');
    inp.setAttribute('name','alone_city');
    inp.setAttribute('value',city);
    f.appendChild(inp);
    f.submit();
}

function doMapRegionSearch(region) {
    $('location').value = region;
    doAjaxRequest2();
    closePopup();
}

function doMapCitySearch(city, region) {
    $('location').value = region;
    $('alone_city').value = city;
    doAjaxRequest2();
    closePopup();
}

function setSearchPage(page) {
    $('pageNumber').value = page;
    doSearchRequest();
}

function doNewSearchRequest() {
    if ($('mls').value.length) {
        mlsNo = $('mls').value;
        $('locationID').value = $('location').value = 'all';
    } else {
        initPhase = true;
        mlsNo = '';
        var obj = $('location');
        $('locationID').value = obj.options[obj.selectedIndex].value;
//        $('area').innerHTML = '<img src="img/progress2.gif" width="90" height="16" border="0">';
    }
    $('currLocation').innerHTML = '';
    doSearchRequest();
    return false;
}

function doNewAjaxRequest() {
    $('mls').value = '';
    $('pageNumber').value = '1';
    mlsNo = '';
    initPhase = true;
    doSearchRequest();
}

function doAjaxRequest() {
    $('mls').value = '';
    $('pageNumber').value = '1';
    mlsNo = '';
    initPhase = false;
    doSearchRequest();
}

function doAjaxRequest2() {
    $('mls').value = '';
    $('pageNumber').value = '1';
    doNewSearchRequest();
}

function doAjaxRequest3() {
    mlsNo = '';
    $('pageNumber').value = '1';
    doNewRentalSearchRequest();
}

function doSearchRequest() {
    currItem = -1;
    markerCount = 0;
//    if (initPhase)
//        $('area').innerHTML = '<img src="img/progress2.gif" width="90" height="16" border="0">';
    var obj = $('map_view_button');
    if (obj) {
        obj.setAttribute('class','switch visit');
        obj.setAttribute('className','switch visit');
        obj.onclick = function() { return false; }
    }
    if (obj) {
        obj = $('prop_view_button');
        obj.setAttribute('class','switch inactive');
        obj.setAttribute('className','switch inactive');
        obj.onclick = function() { return false; }
    }
    if ($('open_house'))
        $('open_house').style.display = 'none';
    if ($('public_remarks'))
        $('public_remarks').style.display = 'none';
    $('propertyFullDetails').style.display = 'none';
//    $('spanPrevNext').style.display = 'none';
    $('googleMap').style.display = '';
    $('googleMap').innerHTML = '<img src="img/progress2.gif" width="90" height="16" border="0">';
//    $('googleMap').style.background = '#F3F6E0 url(img/bg_centerblock.gif) repeat-x scroll center top';
    $('photoGallery').innerHTML = '<img src="img/progress2.gif" width="90" height="16" border="0">';
    $('pages').innerHTML = '';
    $('counters').innerHTML = '';
    $('detail_tools').innerHTML = '';
    var obj = $('location');
    var locationID = $('locationID').value = obj.options[obj.selectedIndex].value;
    // init phase for ajax_search_controller
    args = initPhase ? '&init=true' : '';
    if (mlsNo.length)
        args += "&mls="+mlsNo;
    for (i=0; i<$('ajaxpropsearch').elements.length; i++) {
        var obj = $('ajaxpropsearch').elements[i];
        if (!obj.id.length)
            continue;
        switch (obj.type) {
            case 'checkbox':
                args += "&"+escape(obj.name)+'='+obj.checked;
                break;
            case 'radio':
                args += "&"+escape(obj.value)+'='+obj.checked;
                break;
            default:
                args += "&"+escape(obj.id)+'='+escape(obj.value);
            break;
        }
    }
    searchRequest("location="+locationID+args);
}

function doAdvSearchRequest() {
    // init phase for ajax_search_controller
    $('pageNumber').value = 1;
    args = '&init=true&pageNumber=1&advanced=true';
    for (i=0; i<$('advsearch').elements.length; i++) {
        var obj = $('advsearch').elements[i];
        if (!obj.id.length)
            continue;
        switch (obj.type) {
            case 'checkbox':
                args += "&"+escape(obj.name)+'='+obj.checked;
                break;
            case 'select-multiple':
                var sel = new Array();
                for (var j=0; j < obj.options.length; j++) {
                    if (obj.options[j].selected)
                        sel.push(obj.options[j].value);
                }
                for (var j=0; j<sel.length; j++)
                    args += "&"+escape(obj.name)+'[]='+escape(sel[j]);
                break;
            default:
                args += "&"+escape(obj.id)+'='+escape(obj.value);
                break;
        }
    }
    $('propertyFullDetails').style.display = 'none';
//    $('spanPrevNext').style.display = 'none';
    $('googleMap').style.display = '';
    $('googleMap').innerHTML = '<img src="img/progress2.gif" width="90" height="16" border="0">';
//    $('googleMap').style.background = '#F3F6E0 url(img/bg_centerblock.gif) repeat-x scroll center top';
    $('photoGallery').innerHTML = '<img src="img/progress2.gif" width="90" height="16" border="0">';
    $('pages').innerHTML = '';
    $('counters').innerHTML = '';
    $('detail_tools').innerHTML = '';
    closePopup();
    searchRequest(args);
}

function searchRequest(request) {
        new Ajax.Request(ajaxSearchController,
        {
            method: 'post',
            parameters: request,
            onSuccess: function(transport){
                var responseJS = transport.responseText.evalJSON();
                //closePopup();
                if (responseJS.locationIndex) {
                    $('location').selectedIndex = responseJS.locationIndex;
                }
                if (responseJS.priceFromIndex) {
                    $('amount_from').selectedIndex = responseJS.priceFromIndex;
                }
                if (responseJS.priceToIndex) {
                    $('amount_to').selectedIndex = responseJS.priceToIndex;
                }
                if (responseJS.bedsFromIndex) {
                    $('bedrooms').selectedIndex = responseJS.bedsFromIndex;
                }
                if (responseJS.bathFromIndex) {
                    $('baths').selectedIndex = responseJS.bathFromIndex;
                }
                /*
                $('Residential').checked = (responseJS.Residential && toBoolean(responseJS.Residential)) ? true : false;
                $('Business').checked = (responseJS.Business && toBoolean(responseJS.Business)) ? true : false;
                $('Vacant_Land').checked = (responseJS.Vacant_Land && toBoolean(responseJS.Vacant_Land)) ? true : false;
                */
                $('currLocation').innerHTML = responseJS.currLocation;
                $('counters').innerHTML = responseJS.counters;
                $('pages').innerHTML = responseJS.pages;
                $('photoGallery').innerHTML = responseJS.photoGallery;
                $('googleMap').innerHTML = "";
                points = responseJS.points;
                if (points.length>10) {
                    drawGoogleMap();
                }
                // clear init phase
                initPhase = false;
            }
        });
}

function getPrevProp() {
    if (parseInt(prevMLS))
        showDetails(prevMLS);
}

function getNextProp() {
    if (parseInt(nextMLS))
        showDetails(nextMLS);
}

function addHandler(element,type,func){
    if(element.addEventListener){
        element.addEventListener(type,func,false);
    }else if(element.attachEvent){
        element.attachEvent('on'+type,func);
    }
}

function removeHandler(element,type,func){
    if(element.removeEventListener){
        element.removeEventListener(type,func,false);
    }else if(element.attachEvent){
        element.detachEvent('on'+type,func);
    }
}

function assignAjaxEvent() {
    var obj = $('location');
    addHandler(obj,'change',doNewAjaxRequest);
    for (i=0; i<$('ajaxpropsearch').elements.length; i++) {
        var obj = $('ajaxpropsearch').elements[i];
        if (obj.id) {
            switch (obj.type) {
                case 'checkbox':
                case 'radio':
                    removeHandler(obj,'click',doAjaxRequest);
                    addHandler(obj,'click',doAjaxRequest);
                    break;
                default:
                    removeHandler(obj,'change',doAjaxRequest);
                    addHandler(obj,'change',doAjaxRequest);
                    break;
            }
        }
    }
}

function makeCustomIcons() {
    try {
        icon = new GIcon();
        icon.image = "/img/marker.png";
        icon.shadow = "/img/shadow.png";
        icon.iconSize = new GSize(18, 40);
        icon.shadowSize = new GSize(25, 40);
        icon.iconAnchor = new GPoint(6, 40);
        icon.infoWindowAnchor = new GPoint(5, 1);
        for (var i=1; i<=12; i++) {
            propIcon[i] = new GIcon(icon);
            propIcon[i].image = "/img/numbers/"+i+".png";
            propIcon[i].pdHover = "/img/numbers/"+i+"_on.png";
            propIcon[i].iconSize = new GSize(22, 38);
            propIcon[i].shadowSize = new GSize(25, 40);
            propIcon[i].iconAnchor = new GPoint(6, 38);
            propIcon[i].infoWindowAnchor = new GPoint(5, 1);
        }
    } catch (e) {}
}

function showPointOnMap() {
//    GUnload();
    if (!thisCity.length) {
        $("gmap").innerHTML = '<h5>No info</h5>';
        return;
    }
    bounds = new GLatLngBounds();
    if (GBrowserIsCompatible()) {
        map = new GMap2($("gmap"));
        map.addControl(new GLargeMapControl());
        geocoder = new GClientGeocoder();
        geocoder.getLatLng(thisPoint, function(point){ addThisProperty(point, thisPointHash)});
        map.zoomToMarkers();
    }
    else {
        $("gmap").innerHTML = '<h5>Error</h5>';
    }
}

function addThisProperty(point, prop) {
    if (point == null) {
        $("gmap").innerHTML = '<h5>No info</h5>';
        return;
    }
    bounds.extend(point);
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    map.setZoom(15); // set new zoom level
    var img = new Image();
    if (prop.Icon)
        img.src = prop.Icon;
    else
        img.src = '/img/noimage.gif';
    info = '<img class="googleimg" src="'+img.src+'" /><br />';
    info += '<b>MLS:</b> '+prop.MLS+'<br />';
    info += '<b>Price:</b> '+prop.Price+'<br />'+prop.LT+'<br />';
    info += '<b>District:</b> '+prop.District+'<br />';
    info += '<b>Address:</b> '+prop.AddressNumber+' '+prop.AddressStreet+'<br />';
    try {
        var icon = new GIcon();
        icon.image = "/img/marker.png";
        icon.shadow = "/img/shadow.png";
        icon.iconSize = new GSize(18, 40);
        icon.shadowSize = new GSize(25, 40);
        icon.iconAnchor = new GPoint(6, 40);
        icon.infoWindowAnchor = new GPoint(5, 1);
    } catch(e) {}
    var marker = new PdMarker(new GLatLng(point.y,point.x),icon);
    map.addOverlay(marker);
    marker.setOpacity(100);
    marker.pdImage = icon.image;
    marker.setTooltip(info);
    marker.setTooltipHiding(false);
    marker.display(true);
    marker.showTooltip();
}

function drawGoogleMap() {
    if (GBrowserIsCompatible()) {
        map = new GMap2($("googleMap"));
        map.addControl(new GLargeMapControl());
        geocoder = new GClientGeocoder();
        var part = [];
        parts = points.split('|');
        for (var i=0; i<parts.length; i++) {
            var items = parts[i].split('&amp;');
            for (var j=0; j<items.length; j++) {
                var tmp = items[j].split(':');
                part[tmp[0]] = tmp[1];
            }
            addPoint(part);
        }
        map.zoomToMarkers();
    } else {
            $("googleMap").innerHTML = '<h5>Error</h5>';
    }
}

function drawGoogleMap2() {
    if (GBrowserIsCompatible()) {
        map = new GMap2($("googleMap"));
        map.addControl(new GLargeMapControl());
        geocoder = new GClientGeocoder();
        var part = [];
        parts = points.split('|');
        for (var i=0; i<parts.length; i++) {
            var items = parts[i].split('&amp;');
            for (var j=0; j<items.length; j++) {
                var tmp = items[j].split(':');
                part[tmp[0]] = tmp[1];
            }
            addPoint2(part);
        }
        map.zoomToMarkers();
    } else {
            $("googleMap").innerHTML = '<h5>Error</h5>';
    }
}

function addPoint(data) {
    var tmp = {'NUM':data['NUM'], 'MLS':data['MLS'], 'Class':data['Class'], 'SF':data['SF'], 'Living':data['Living'], 'Beds':data['Beds'], 'Price':data['Price'], 'Baths':data['Baths'], 'Icon':data['Icon']};
    if (data['City'].length)
        geocoder.getLatLng(data['AddressNumber']+' '+data['AddressStreet']+', '+data['City']+', '+data['State']+', '+data['Zip'],
     function(point){ addProperty(point, tmp)});
}

function addPoint2(data) {
    var tmp = {'NUM':data['NUM'], 'MLS':data['MLS'], 'Type':data['Type'], 'SF':data['SF'], 'Beds':data['Beds'], 'Price':data['Price'], 'Baths':data['Baths'], 'Icon':data['Icon']};
    if (data['City'].length)
        geocoder.getLatLng(data['Address']+', '+data['District']+', '+data['Zip'], function(point){ addProperty2(point, tmp)});
}

function addProperty(point, prop) {
    if (point == null) {
        return;
    }
    bounds.extend(point);
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

    var img = new Image();
    if (prop.Icon)
        img.src = unescape(prop.Icon);
    else
        img.src = '/img/noimage.gif';

    var tooltip = '<img class="googleimg" src="'+img.src+'" /><br />';
    tooltip += 'MLS# '+prop.MLS+'<br />';
    tooltip += prop.Living+' living<br />';
    tooltip += prop.Beds+' br / '+prop.Baths+' ba<br />';
    tooltip += '<strong>'+prop.Price+'</strong>';

    icon = propIcon[prop.NUM];
    var marker = map.getMarkerById(prop.MLS);
    if (marker == null) {
        var marker = new PdMarker(new GLatLng(point.y,point.x),icon);
        marker.pdImage = icon.image;
        marker.pdHover = icon.pdHover;
        map.addOverlay(marker);

        GEvent.addListener(marker, 'mouseover', function() {
            highlightMarker(marker);
        });

        GEvent.addListener(marker, 'mouseout', function() {
            highlightItem(-1);
        });

        GEvent.addListener(marker, 'click', function() {
            showDetails(marker.mlsNo);
        });

    } else {
        // re-use marker
        marker.display(true);
        marker.setPoint(new GLatLng(point.y,point.x));
        marker.setImage(icon.image);
        marker.pdImage = icon.image;
        marker.pdHover = icon.pdHover;
        marker.oldImagePath = "";
    }
    marker.setOpacity(100);
    marker.hovering = false;
    marker.mlsNo = prop.MLS;
    marker.setTooltip(tooltip);
    marker.setId(prop.MLS);

    markerCount++;
}

function addProperty2(point, prop) {
    if (point == null) {
        return;
    }
    bounds.extend(point);
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

    var img = new Image();
    if (prop.Icon)
        img.src = unescape(prop.Icon);
    else
        img.src = '/img/noimage.gif';

    var tooltip = '<img class="googleimg" src="'+img.src+'" /><br />';
    tooltip += prop.Type+'<br />';
    tooltip += prop.SF+' sf land<br />';
    tooltip += prop.Beds+' br / '+prop.Baths+' ba<br />';
    tooltip += '<strong>'+prop.Price+'</strong>';

    icon = propIcon[prop.NUM];
    var marker = map.getMarkerById(prop.MLS);
    if (marker == null) {
        var marker = new PdMarker(new GLatLng(point.y,point.x),icon);
        marker.pdImage = icon.image;
        marker.pdHover = icon.pdHover;
        map.addOverlay(marker);

        GEvent.addListener(marker, 'mouseover', function() {
            highlightMarker(marker);
        });

        GEvent.addListener(marker, 'mouseout', function() {
            highlightItem(-1);
        });

        GEvent.addListener(marker, 'click', function() {
            showRentalDetails(marker.mlsNo);
        });

    } else {
        // re-use marker
        marker.display(true);
        marker.setPoint(new GLatLng(point.y,point.x));
        marker.setImage(icon.image);
        marker.pdImage = icon.image;
        marker.pdHover = icon.pdHover;
        marker.oldImagePath = "";
    }
    marker.setOpacity(100);
    marker.hovering = false;
    marker.mlsNo = prop.MLS;
    marker.setTooltip(tooltip);
    marker.setId(prop.MLS);
    markerCount++;
}

function highlightMarker(marker) {
    propertyId = -1;
    if (marker)
        propertyId = marker.getId();
    highlightItem(propertyId);
}

function highlightItem(propertyId) {
    if (currItem != -1) {
        marker = map.getMarkerById(currItem);
        if (marker) {
            marker.setImage(marker.pdImage);
            marker.hovering = false;
            marker.hideTooltip();
        }

        obj = $("mls" + currItem);
        objA = $("price" + currItem);
        if (obj)
            obj.style.backgroundColor = "white";
        if (objA)
            objA.style.color = "#a25729";

    }
    currItem = propertyId;

    if (currItem != -1) {
        marker = map.getMarkerById(currItem);
        if (marker) {
            marker.setImage(marker.pdHover);
            marker.hovering = true;
            marker.showTooltip();
        }
        obj = $("mls" + currItem);
        objA = $("price" + currItem);
        if (obj)
            obj.style.backgroundColor = "#DD6326";
        if (objA)
            objA.style.color = "white";

    }
}

function closePopup() {
    if (popupWin)
        popupWin.close();
    Dialog.closeInfo();
}

function MsgBox(msg) {
    Dialog.alert('<br>'+msg, {title:dialogs_title, className:dialogs_theme, width:500, height:120, showEffect: Element.show, hideEffect: Element.hide, okLabel:'OK', buttonClass: 'okButton', ok:function(win) {closePopup(); return true;} });
}

function alertMsg(msg) {
    Dialog.alert('<br>'+msg, {title:dialogs_title, className:dialogs_theme, width:500, height:120, showEffect: Element.show, hideEffect: Element.hide, okLabel:'OK', buttonClass: 'okButton'});
}

function showProgress() {
    Dialog.info("", {className:'alert', width:16, height:16, showProgress: true, showEffect: Element.show, hideEffect: Element.hide});
}

function hideProgress() {
    Dialog.closeInfo();
}

function showPrintVersionPopup(id) {
//    showProgress();
    popupWin = new Window({title:dialogs_title, className:dialogs_theme, width:600, height:650, showEffect: Element.show, hideEffect: Element.hide, resizable:false, closable:true, minimizable: false, maximizable:false, draggable: true, destroyOnClose: true, onClose: closePopup});
    popupWin.setAjaxContent("/popups/detailsprintversion?id="+id, {method:'get'}, true, true);
    popupWin.setZIndex(10000);
}

function showSendToFriendPopup(id) {
//    showProgress();
    popupWin = new Window({title:dialogs_title, className:dialogs_theme, width:600, height:450, showEffect: Element.show, hideEffect: Element.hide, resizable:false, closable:true, minimizable: false, maximizable:false, draggable: true, destroyOnClose: true, onClose: closePopup});
    popupWin.setAjaxContent("/popups/sendtofriend?id="+id, {method:'get'}, true, true);
    popupWin.setZIndex(10000);
}

function showRequestInfoPopup(id) {
//    showProgress();
    popupWin = new Window({title:dialogs_title, className:dialogs_theme, width:600, height:450, showEffect: Element.show, hideEffect: Element.hide, resizable:false, closable:true, minimizable: false, maximizable:false, draggable: true, destroyOnClose: true, onClose: closePopup});
    popupWin.setAjaxContent("/popups/request_info?id="+id, {method:'get'}, true, true);
    popupWin.setZIndex(10000);
}

function showDriveMapPopup(id) {
//    showProgress();
    popupWin = new Window({title:dialogs_title, className:dialogs_theme, width:600, height:550, showEffect: Element.show, hideEffect: Element.hide, resizable:false, closable:true, minimizable: false, maximizable:false, draggable: true, destroyOnClose: true, onClose: closePopup});
    popupWin.setAjaxContent("/popups/driving_map?id="+id, {method:'get'}, true, true);
    popupWin.setZIndex(10000);
}

function showMapPopup() {
//    showProgress();
    popupWin = new Window({title:dialogs_title, className:dialogs_theme, width:635, height:340, showEffect: Element.show, hideEffect: Element.hide, resizable:false, closable:true, minimizable: false, maximizable:false, draggable: true, destroyOnClose: true, onClose: closePopup});
    popupWin.setAjaxContent("/popups/map_search", {method:'get'}, true, true);
    popupWin.setZIndex(10000);
}

function showDetails(mls) {
    var obj = $('map_view_button');
    if (obj) {
        obj.setAttribute('class','switch');
        obj.setAttribute('className','switch');
        obj.onclick = function() { switchMapView(); return false; }
    }
    obj = $('prop_view_button');
    if (obj) {
        obj.setAttribute('class','switch visit');
        obj.setAttribute('className','switch visit');
        obj.onclick = function() { switchPhotoView(); return false; }
    }
    obj = $('mls' + currentMLS);
    if (obj) {
        currentMLS = mls;
        obj.removeClassName('currentMLS');;
    }
    obj = $('mls' + mls);
    if (obj) {
        currentMLS = mls;
        obj.addClassName('currentMLS');
    }
    if ($('open_house'))
        $('open_house').style.display = 'none';
    if ($('public_remarks'))
        $('public_remarks').style.display = 'none';
    if ($('googleMap'))
        $('googleMap').style.display = 'none';
//    if ($('spanPrevNext'))
//        $('spanPrevNext').style.display = '';
    if ($('propertyFullDetails'))
        $('propertyFullDetails').style.display = '';
    if ($('detail_tools'))
        $('detail_tools').innerHTML = '';
    if ($('previews'))
        $('previews').innerHTML = '';
    if ($('other_props'))
        $('other_props').innerHTML = '';
    if ($('big_photo'))
        $('big_photo').src = '/img/progress2.gif';
    // reset preview left position
    left = 0;
    if ($('icons_preview'))
        $('icons_preview').innerHTML = '';
    new Ajax.Request(ajaxDetailsController,
    {
        method: 'post',
        parameters: 'mls='+mls,
        onSuccess: function(transport){
            var responseJS = transport.responseText.evalJSON();
            if ($('previews'))
                $('previews').innerHTML = responseJS.previews;
            if ($('other_props'))
                $('other_props').innerHTML = responseJS.details;
            if ($('detail_tools'))
                $('detail_tools').innerHTML = responseJS.tools;
            if ($('open_house') && responseJS.open_house) {
                $('open_house').innerHTML = unescape(responseJS.open_house);
                $('open_house').style.display = '';
            }
            if ($('public_remarks') && responseJS.public_remarks) {
                $('public_remarks').innerHTML = unescape(responseJS.public_remarks);
                $('public_remarks').style.display = '';
            }
            if (!toBoolean(responseJS.returnValue)) {
                $('big_photo').src = '/img/blank.gif';
                return;
            }
            prevMLS = responseJS.prevMLS;
            nextMLS = responseJS.nextMLS;
            initMortgage();
            firstImage = responseJS.firstImage;
            var tmp = responseJS.bigImages;
            if (tmp.length) {
                bigImages = tmp.split(',');
                showBigImage(parseInt(firstImage));
                new DragScrollable('scrollable_photo');
            } else {
                $('big_photo').src = '/img/noimage_large.gif';
            }
//            if (!_isKHTML) {
//                var mypage = document.location.href.replace( /(.*)#.*/, "$1");
//                document.location.href = mypage + "#property_details";
//            }
        }
    });
}

function toBoolean(inputString){
    if(typeof(inputString)=="string")
        inputString=inputString.toLowerCase();
    switch(inputString){
        case "1":
        case "true":
        case "yes":
        case "y":
        case "on":
        case 1:
        case true:
        return true;
        break;
    default: return false;
    }
}

function calculateRates(value) {
    var table = document.getElementById("calculatableRates");
    if (!table || !table.rows || table.rows.length < 1) {
        return;
    }
    var re = /calculate/i;
    // see all rows
    for (var j=0;j<table.rows.length;j++) {
        var row = table.rows[j];
        for (var i=0;i<row.cells.length;i++) {
            var cell = row.cells[i];
            var id = cell.getAttributeNode('id');
            var val = cell.getAttributeNode('val');
            if (id && id.value.match(re) && val) {
                if (parseFloat(val.value))
                    cell.innerHTML = printf(parseFloat(val.value)/value,2);
            }
        }
    }
}

function printf(v,d){
    var z='00000000';
    v=v*1;
    d=Math.min(z.length,Math.max(0,Math.floor(d*1)));
    var n=v<0;
    v=Math.abs(v);
    var f=''+(v-Math.floor(v))+z;
    v=''+Math.floor(v);
    n=n&&((v*1)||(f*1))?'-':'';
    var s=(d?('.'+f.substring(2,2+d)):'');
    for(var i=1;i<=v.length;i++){
        s=v.substring(v.length-i,v.length-i+1)+s;
        if(!(i%3)&&(i<v.length)){
            s=','+s}}
    return n+s;
}

// quick date/time chooser block adding
function add_new_date() {
    var mnths = new Array('','January','February','March','April','May','June','July','August','September','October','November','December');
    var oDiv = $('dates');
    var tm = new Date;
    var month=tm.getMonth()+1;
    var year=tm.getYear();
    year+=year<200?1900:0;
    var day=tm.getDate();
    var sel = '';
    var tmp =
'<label for="date" class="description">Date</label>'+
'<select name="post_d[]">';
    for (var i=1; i<=31; i++) {
        sel = day==i ? 'selected="selected"' : '';
        tmp += '<option value="'+i+'" '+sel+'>'+i+'</option>';
    }
    tmp += '</select>'+
'<select name="post_m[]">';
    for (var i=1; i<=12; i++) {
        sel = month==i ? 'selected="selected"' : '';
        tmp += '<option value="'+i+'" '+sel+'>'+mnths[i]+'</option>';
    }
    tmp += '</select>'+
'<select name="post_y[]">';
    for (var i=0; i<=1; i++)
        tmp += '<option value="'+(year+i)+'">'+(year+i)+'</option>';
    tmp += '</select>'+
'<input type="button" name="del_date" id="del_date" class="button" value="Delete This Date" onclick="delete_date(\'date_'+dates_counter+'\'); return false;" />'+
'<br><br>'+
'<label for="timehourfrom" class="description">Time of Open House</label>'+
'<select name="post_timehourfrom[]" id="timehourfrom[]" style="width: 4.5em;">';
    for (var i=1; i<=12; i++)
        tmp += '<option value="'+i+'">'+i+'</option>';
    tmp += '</select>'+
'<select name="post_timeminfrom[]" id="timeminfrom[]" style="width: 4.5em;">'+
'<option value="00" selected="selected">00</option>'+
'<option value="15">15</option>'+
'<option value="30">30</option>'+
'<option value="45">45</option>'+
'</select>'+
'&nbsp;-&nbsp;'+
'<select name="post_timehourto[]" id="timehourto[]" style="width: 4.5em;">';
    for (var i=1; i<=12; i++)
        tmp += '<option value="'+i+'">'+i+'</option>';
    tmp += '</select>'+
'<select name="post_timeminto[]" id="timeminto[]" style="width: 4.5em;">'+
'<option value="00" selected="selected">00</option>'+
'<option value="15">15</option>'+
'<option value="30">30</option>'+
'<option value="45">45</option>'+
'</select>'+
'<select name="post_timemerto[]" id="timemerto[]" style="width: 4.5em;">'+
'<option value="AM">AM</option>'+
'<option value="PM" selected="selected">PM</option>'+
'</select><br>'+
'<label class="description">&nbsp;</label><br><br>';
    var oSubDiv  = document.createElement("DIV");
    oSubDiv.setAttribute("id", 'date_'+dates_counter);
    oSubDiv.innerHTML = tmp;
    oDiv.appendChild(oSubDiv);
    dates_counter++;
    return;
}

function delete_date(elem) {
    var oDiv = $(elem);
    oDiv.parentNode.removeChild(oDiv);
}

