
$(document).ready(function () {


    $(window).scroll(function () {

        if ($(window).scrollTop() > $(".topIdentifier").offset().top) {
            $(".rightbox").css("position", "fixed");
            $(".rightbox").css("top", "0");
        }

        if ($(window).scrollTop() <= $(".topIdentifier").offset().top) {
            $(".rightbox").css("position", "relative");
            $(".rightbox").css("top", $(".topIdentifier").offset);
        }

    });


});


function searchButton(buttonName) {    
    if ($('#searchPanel').css('display')=='none')SendRequest('/Search/'+buttonName, 'searchPanel');    
    $("#searchPanel").slideToggle("slow");
}

var runningRequest = false;


function SendRequest(target, source) {
    while (target.indexOf("&amp;")>0) {
        target.replace("&amp;", "&");
    }
    $.ajax({
        type: "GET",
        url: target,
        dataType: "html",
        beforeSend: function (XMLHttpRequest) {
            $("#" + source + "wait").text("Sending your request...");
            //Pause(this,10000);
        },
        success: function (msg) {
            $("#" + source + "wait").show(1000, function () {
                setTimeout(function () {
                    $("#" + source + "wait").text("");
                }, 3000)
            });
            //$("#" + source + "wait").text("");
            $("#" + source).html(msg);
            //$("#panel").css("color", "red");
        },
        complete: function (XMLHttpRequest, textStatus) {
            //hide sending request text
        },
        error: function () {
            //error
            $("#" + source).html('Error happend, please try again later.');
        }
    });
}


function SendRequestLock(theRequest, target, source) {
    runningRequest = true;
    while (target.indexOf("&amp;") > 0) {
        target.replace("&amp;", "&");
    }
    theRequest = $.ajax({
        type: "GET",
        url: target,
        dataType: "html",
        beforeSend: function (XMLHttpRequest) {
            $("#" + source + "wait").text("Sending your request...");
            //Pause(this,10000);
        },
        success: function (msg) {
            $("#" + source + "wait").show(1000, function () {
                setTimeout(function () {
                    $("#" + source + "wait").text("")
                }, 3000)
            });
            //$("#" + source + "wait").text("");
            $("#" + source).html(msg);
            //$("#panel").css("color", "red");
            runningRequest = false;
        },
        complete: function (XMLHttpRequest, textStatus) {
            //hide sending request text
        },
        error: function () {
            //error
            $("#" + source).html('Error happend, please try again later.');
        }
    });
}


function UnSelect(source, target) {
    if ($('#' + source).attr('checked')) {
    } else {
        $('#' + target).attr('checked', false);
    }
}
function Select(source, target) {
    if ($('#' + source).attr('checked')) {
        $('#' + target).attr('checked', true);
    } else {
    }
}


function PropertyType() {
    var type = '&properties=';
    var subType = '&subtypes=';
    var hasType = false;
    var hasSub = false;
    var searchType = $('#searchType').val();
    if ($('#Residential').attr('checked')) {
        type += 'Residential';
        hasType = true;
    }
    if ($('#Condominium').attr('checked')) {
        if (hasType) type += ',';
        type += 'Condominium';
        hasType = true;
    }
    if ($('#Commercial').attr('checked')) {
        if (hasType) type += ',';
        type += 'Commercial';
        hasType = true;
    }
    if ($('#Farm').attr('checked')) {
        if (hasType) type += ',';
        type += 'Farm';
        hasType = true;
    }
    if ($('#res_optional_0').attr('checked')) {
        subType += 'res_vacant';
        hasSub = true;
    }
    if ($('#res_optional_1').attr('checked')) {
        if (hasSub) subType += ',';
        subType += 'res_resort';
        hasSub = true;
    }
    if ($('#condo_optional_0').attr('checked')) {
        if (hasSub) subType += ',';
        subType += 'con_resort';
        hasSub = true;
    }
    if ($('#com_optional_0').attr('checked')) {
        if (hasSub) subType += ',';
        subType += 'com_land';
        hasSub = true;
    }
    if ($('#farm_optional_0').attr('checked')) {
        if (hasSub) subType += ',';
        subType += 'farm_land';
        hasSub = true;
    }
    SendRequest('/Search/Map/?searchType=' + searchType + type + subType, 'searchPanel');
}

function IsNotNumeric(input) {
    return (input - 0) != input && input.length > 0;
}


function DoSearch() {
    var price_from = $('#price_from').val();
    var price_to = $('#price_to').val();
    if (IsNotNumeric(price_from) || IsNotNumeric(price_to) ) {
        alert("Prices should be in Numeric format!");
    } else if (price_from>0 && price_to>0 && price_to - price_from <0) {
        alert("Price to should be higher than price from!");
    }else {
        if (price_from > 0) price_from = "&price_from=" + price_from;
        if (price_to > 0) price_to = "&price_to=" + price_to;
        var newAds = "";
        if ($('#newAds').attr('checked')) {
            newAds = "&newAds=yes";
        }
        var area = '&search_query=' + $('#search_query').val();
        if (area.length < 2) {
            alert("You must select a valid search area!");
        } else {
            var type = '&properties=' + $('#properties').val();
            var subType = '&subtypes=' + $('#subtypes').val();
            var searchType = $('#searchtype').val();
            $("#searchPanel").slideToggle("slow");
            $("#wrenlogo").hide();
            $("#content").html("<h1><img src='/img/loading.gif' />Please wait while we preparing your search result. </h>");
            SendRequest('/AD/?searchTerm=' + $('#properties').val(), 'sidebar');
            SendRequest('/Search/Result/?searchtype=' + searchType + type + subType + area + newAds + price_from + price_to, 'content');
        }
        
    }
}


function ShowDetails(target) {
    var targetLength = $('#' + target).html().length;
    if (targetLength > 10) {
        $('#' + target).slideToggle("slow");
        if ($('#Button' + target).html() == 'Detail') {
            $('#Button' + target).html('Hide');
            $('#' + target).addClass("DetailOpend");
        } else {
            $('#Button' + target).html('Detail');
            location.href = "#MLS" + target;
            $('#' + target).removeClass("DetailOpend");
        }
    } else {
        SendRequest('/Search/Detail/?ML_Number=' + target, target);
        $('#' + target).slideToggle("slow");
        $('#Button' + target).html('Hide');
        $('#' + target).addClass("DetailOpend");
    }
}

function CollapseAll() {
    $(".DetailOpend").slideToggle("slow");
    $(".DetailOpend").removeClass("DetailOpend");
}

var map;
var markers = [];


function codeAddress(canvas, address) {
    geocoder = new google.maps.Geocoder();
    latlng = new google.maps.LatLng(49.883333, -97.166667);
    myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById(canvas), myOptions);
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}





function codeLocation(canvas, address, latitude, longtitude) {
    geocoder = new google.maps.Geocoder();
    latlng = new google.maps.LatLng(latitude, longtitude);
    myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById(canvas), myOptions);
    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status == google.maps.GeocoderStatus.OK) {
//            map.setCenter(results[0].geometry.location);
//            markers.push(new google.maps.Marker({
//                map: map,
//                position: results[0].geometry.location
//            }));
//            markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
//                content: '<div>' + address + '</div>'
//            });
//        } else {
            addMarker(address, latitude, longtitude);
//        }
    });
    
}

function addMarker(address, latitude, longtitude) {
    var current = new google.maps.LatLng(latitude, longtitude);
    for (var i = 0; i < markers.length; i++)
        if (current.lat() === markers[i].position.lat() && current.lng() === markers[i].position.lng()) return;

    markers.push(new google.maps.Marker({
        map: map,
        position: current,
        title: address
    }));

    markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
        content: '<div>' + address + '</div>'
    });

    google.maps.event.addListener(markers[markers.length - 1], 'click', function () {
        this['infowin'].open(map, this);
    });
}


function SetPhoto(mls, photoID) {
    $("#img" + mls).attr("src", "/Image/?pictureID=" + photoID);
}

function SendEmail(MLNumber) {
    var sender = $("#senderBox" + MLNumber).val();
    var email = $("#emailBox" + MLNumber).val();
    var area = $("#areaBox" + MLNumber).val();
    var phone = $("#phoneBox" + MLNumber).val();
    var realtorOrder = $("#realtorOrder" + MLNumber).val();
    var options = "";
    if ($('#a' + MLNumber).attr('checked')) options += "a";
    if ($('#b' + MLNumber).attr('checked')) options += "b";
    if ($('#c' + MLNumber).attr('checked')) options += "c";
    if ($('#d' + MLNumber).attr('checked')) options += "d";
    if ($('#e' + MLNumber).attr('checked')) options += "e";
    if (jQuery.trim(sender).length == 0) {
        alert("Please leave your name.");
    }
    else {
        if (jQuery.trim(email).length == 0) {
            alert("Please fill your email address.");
        }
        else {

            if (email.indexOf("@") > 0 && email.indexOf(".") > email.indexOf("@")) {
                $('#email' + MLNumber).html("");
                SendRequest('/Email/Send/?ML_Number=' + MLNumber + '&sender=' + sender + '&email=' + email + '&area=' + area + '&phone=' + phone + '&options=' + options + '&realtorOrder=' + realtorOrder, 'email' + MLNumber);
            }
            else {
                alert("Please check your email address.");
            }
        }
    }

}


function setTab(type, id) {
    var i = 0;
    for (i = 0; i < 9; i++) {
        $('#' + type + i).attr('class', 'bpHeader Border4');
        $('#' + type + 'Content' + i).css('display', 'none');
    }
    $('#' + type + id).attr('class', 'bpHeader Border3');
    $('#' + type + 'Content' + id).css('display', 'block');
}


function showMap(mapId) {
    $(".searchMap").hide();
    $(".searchMap1").hide();
    
    $("#" + mapId).show();
    clear_all();
    current = mapId;
    $("#search_query").val("");
}
function showMap1(mapId) {
    maplock = true;
    $(".searchMap").hide();
    $("#" + mapId).show();
    clear_all();
    current = mapId;
    $("#search_query").val("");
    MapLarger();
}

var currentNewsIndex = 1;


function setNews(id) {
    var i = 0;
    $(".newsLinkSelected").attr('class', 'newsLink');
    $("#newsLink" + id).attr('class', 'newsLinkSelected');
    $(".newsBlock").css('display', 'none');
    $("#newsBlock" + id).css('display', 'block');
    currentNewsIndex = id;
}

function showNews() {
    var nextNewsIndex = (currentNewsIndex + 1) % maxNexIndex;
    if (nextNewsIndex == 0) nextNewsIndex = maxNexIndex;
    setNews(nextNewsIndex);
}

function StartOver() {
    $("#Residential").attr('checked', true);
    $("#Condominium").attr('checked', false);
    $("#Commercial").attr('checked', false);
    $("#Farm").attr('checked', false);
    $("#newAds").attr('checked', false);
    $("#openhouseOnly").attr('checked', false);

    $("#res_optional_0").attr('checked', false);
    $("#res_optional_1").attr('checked', false);
    $("#Commercial").attr('checked', false);
    $("#condo_optional_0").attr('checked', false);
    $("#com_optional_0").attr('checked', false);
    $("#farm_optional_0").attr('checked', false);
    $('#price_from').val("0");
    $('#price_to').val("9999999");
    
    clear_all();
}

function DoSearch2() {
    var price_from = $('#price_from').val().replace(/[^\d]/g, '');

    var price_to = $('#price_to').val().replace(/[^\d]/g, '');
    var street_name = $('#StreetName').val();
    if (IsNotNumeric(price_from) || IsNotNumeric(price_to)) {
        alert("Prices should be in Numeric format!");
    } else if (price_from > 0 && price_to > 0 && price_to - price_from < 0) {
        alert("Price to should be higher than price from!");
    } else {

        if (price_from > 0) { price_from = "&price_from=" + price_from; }
        else{price_from = "";}
        if (price_to > 0) { price_to = "&price_to=" + price_to; }
        else{price_to = "";}
        var StreetName = "";
        if (street_name != null && street_name.length > 0) StreetName = "&StreetName=" + street_name;
        var newAds = "";
        var searchType = "properties";
        if ($('#newAds').attr('checked')) {
            newAds = "&newAds=yes";
        }
        if ($('#openhouseOnly').attr('checked')) {
            searchType = "openhouse";
        }
        var area = '&search_query=' + $('#search_query').val();
        if (area.length < 2) {
            alert("You must select a valid search area!");
        } else {
            var type = '';
            var subType = '&subtypes=';
            var hasType = false;
            var hasSub = false;
            if ($('#Residential').attr('checked')) {
                type += 'Residential';
                hasType = true;
            }
            if ($('#Condominium').attr('checked')) {
                if (hasType) type += ',';
                type += 'Condominium';
                hasType = true;
            }
            if ($('#Commercial').attr('checked')) {
                if (hasType) type += ',';
                type += 'Commercial';
                hasType = true;
            }
            if ($('#Farm').attr('checked')) {
                if (hasType) type += ',';
                type += 'Farm';
                hasType = true;
            }
            if ($('#res_optional_0').attr('checked')) {
                subType += 'res_vacant';
                hasSub = true;
            }
            if ($('#res_optional_1').attr('checked')) {
                if (hasSub) subType += ',';
                subType += 'res_resort';
                hasSub = true;
            }
            if ($('#condo_optional_0').attr('checked')) {
                if (hasSub) subType += ',';
                subType += 'con_resort';
                hasSub = true;
            }
            if ($('#com_optional_0').attr('checked')) {
                if (hasSub) subType += ',';
                subType += 'com_land';
                hasSub = true;
            }
            if ($('#farm_optional_0').attr('checked')) {
                if (hasSub) subType += ',';
                subType += 'farm_land';
                hasSub = true;
            }
            $("#topBlock").slideToggle("slow");
            $("#wrenlogo").hide();
            $("#content").html("<h1><img src='/img/loading.gif' />Please wait while we prepare your search result. </h>");
            SendRequest('/AD/?searchTerm=' + type, 'sidebar');
            type = "&properties=" + type;
            var requestAddress = '/Search/Result/?searchtype=' + searchType + type + subType + area + newAds + price_from + price_to + StreetName;
            SendRequest(requestAddress, 'content');
        }

    }
}



var request;

//Identify the typing action
$('input#StreetName').keyup(function (e) {
    e.preventDefault();
    var $q = $(this);

    if ($q.val() == '') {
        $('div#StreetHint').html('');
        return false;
    } else if (e.keyCode == 40) {
        //down arrow
        NextHint();
        return false;
    } else if (e.keyCode == 38) {
        //up arrow
        PreHint();
        return false;
    }

    //Abort opened requests to speed it up
    if (runningRequest) {
        request.abort();
    }
    SendRequestLock(request, "/Search/Street/?StreetName=" + $q.val(), "StreetHint");

});


var hintIndex = 0;
var maxHint = 0;

function NextHint() {
    if (maxHint > 0) {
        hintIndex = (hintIndex + 1) % (maxHint + 1);
        if (hintIndex < 1) hintIndex = 1;
        $(".hint").attr('class', 'clear hint');
        UseHint(hintIndex);
    }
}

function PreHint() {
    if (maxHint > 0) {
        hintIndex = (hintIndex - 1) % maxHint;
        if (hintIndex < 1) hintIndex = 1;
        $(".hint").attr('class', 'clear hint');
        UseHint(hintIndex);
    }
}

function UseHint(theIndex) {
    var aValue = $("#StreetNameHint" + theIndex).html();
    $("#StreetName").val(aValue);
    $("#StreetNameHint" + theIndex).attr('class', 'clear hint selectedStreet');
}

function GetStat() {
    var year = $("#year").val();
    var quarter = $("#quarter").val();
    var area = $("#area").val();
    $("#StatBlock").html("<img src='/img/loading.gif' />Please wait while we preparing the report!");
    SendRequest("/Resources/StatDetail/?year=" + year + "&quarter=" + quarter + "&area=" + area, "StatBlock");
}
var maplock = false;
function MapLarger() {
    $("#mapHolder").css("position", "absolute");
    $("#mapHolder").css("width", "400px");
    $("#mapHolder").css("height", "400px");
    $(".searchMap").css("width", "434px");
    $(".searchMap").css("height", "400px");
    $(".wpgImg").css("width", "434px");
    $(".ruralImg").css("width", "426px");
    $(".provinceImg").css("width", "354px");
    $("#propertyType").css("margin-top", "205px");
}

function MapSmaller() {
    if(!maplock) {
        $("#mapHolder").css("position", "relative");
        $("#mapHolder").css("width", "220px");
        $("#mapHolder").css("height", "200px");
        $(".searchMap").css("width", "217px");
        $(".searchMap").css("height", "200px");
        $(".wpgImg").css("width", "217px");
        $(".ruralImg").css("width", "213px");
        $(".provinceImg").css("width", "177px");
        $("#propertyType").css("margin-top", "0px");
    }else {
        maplock = false;
    }
}

function CheckMLS() {
    var mls = $("#ML_Number").val();
    if(mls>0) {
        SendRequest("/Search/CheckMLS/?ML_Number=" + mls, "CheckResult");
    } else {
        if ($('#openhouseOnly').attr('checked')) {
            DoSearch2();
        }
        $("#CheckResult").text("Please enter a valid MLS number.");
    }
}

function GoPage(contentPage, adPage) {
    SendRequest(contentPage, 'content'); 
    SendRequest(adPage, 'sidebar');
}
