var year = 2009;
var campaignid = 23150;
var map = null;
var pointsArray = new Array();
var pushPinsDetailArray = new Array();
var aussie_omni_state;
var aussie_omni_suburbName;



$(document).ready(function() {
    /*--search suggestion--*/
$("#searchSuggestionTop").autocomplete("/searchSuggestion.aspx", { minChars: 3 }).result(function(event, item) {
    getSuburbIDBySuburbAndPostcode($(this).val());
});
$("#searchSuggestionBtm").autocomplete("/searchSuggestion.aspx", { minChars: 3 }).result(function(event, item) {
    getSuburbIDBySuburbAndPostcode($(this).val());
});
    
    //OmnitureTrackingBySuburb();
    
    // register on click event to clear the text box
    $(".searchSuggestion").click(function() {
        if ($(this).val() == 'Enter suburb or postcode') { $(this).val('') };
    });

    // register on blur event to clear set the prompt in the text box
    $(".searchSuggestion").blur(function() {
        if ($(this).val() == '') { $(this).val('Enter suburb or postcode') };
    });

    // register keypress event to catch enter and return key
    $(".searchSuggestion").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            getSuburbIDBySuburbAndPostcode($(this).val());
            return false;
        } else {
            return true;
        }
    });
    // register the click event for the go button
    $(".searchButton").click(function() {
        getSuburbIDBySuburbAndPostcode($(this).closest("div.odd").find(".searchSuggestion").val());
        return false;
    });

    $("#suburbMatchDialog").dialog(
	{
	    autoOpen: false,
	    bgiframe: false,
	    closeOnEscape: true,
	    modal: true,
	    resizable: false,
	    title: "Please select a specific suburb:"
	});
});

/*--search suggestion--*/
var suburbid;
var suburbpostcode;
//function getSuburbIDBySuburbAndPostcode(suburbpostcode) {
//    if (suburbpostcode != "Enter suburb or postcode") {
//        $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbIDBySuburbAndPostcode&suburbAndPostcode=" + suburbpostcode + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {
//            if (data.DataList != null) {
//                suburbid = data.DataList.Data["SuburbId"];
//                location.href = "/suburb.aspx?suburbID=" + suburbid;
//            }
//            else {
//                //alert('We have no data on the suburb or postcode, "' + suburbpostcode + '", as you provided it, sorry.\nPlease try re-entering the suburb name or postcode, or chose another search');
//                alert('Please enter a suburb or postcode. You can also select from the suggested areas.');
//            }
//        });
//    }
//}

function getSuburbIDBySuburbAndPostcode(suburbpostcode) {
    if (suburbpostcode != "Enter suburb or postcode") {
        $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbIDBySuburbAndPostcode&suburbAndPostcode=" + suburbpostcode + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {
            if (data.DataList != null) {
                // single result match go straight to it
                suburbid = data.DataList.Data["SuburbId"];
                location.href = "/suburb.aspx?suburbID=" + suburbid;
            }
            else {
                // do a multiple result search
                //getSuburbByFreeTextSearch(suburbpostcode);
                location.href = "/aussieSearchResult.aspx?suburbpostcode=" + suburbpostcode;
            }
        });
    }
}

// does the free text search used by the autocomplete to find multiple matches and allow user to navigate to  one
function getSuburbByFreeTextSearch(suburbpostcode)
{
	var errorPrompt = 'Please enter a suburb or postcode. You can also select from the suggested areas.';
	if (suburbpostcode != "Enter suburb or postcode") {
	    $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbAndPostcode&suburbPostcode=" + suburbpostcode + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {
	        if (data.DataList != null) {
	            // see if we got multiple results back
	            var list = data.DataList.Data;
	            if (list.length >= 0) {//is array
	                // clear the dialog contents
	                $("#suburbMatchDialog").empty();
	                $("#suburbMatchDialog").append("<p>Multiple matches for your search query were found, please select one:</p>");
	                $("#suburbMatchDialog").append("<ul>");
	                // add each match to the dialog
	                for (var i = 0; i < list.length; i++) {
	                    // todo: need to get the suburb, state and postcode in the text description
	                    $("#suburbMatchDialog").append("<li><a href='/suburb.aspx?suburbID=" + list[i].SuburbId + "'>" + list[i].SuburbPostcode + "</a></li>");
	                }
	                $("#suburbMatchDialog").append("</ul>");

	                // show the dialog to allow the user to chose the correct match
	                $("#suburbMatchDialog").dialog('open');
	            }
	            else {
	                alert(errorPrompt);
	            }
	        }
	        else {
	            alert(errorPrompt);
	        }
	    });
	}
	else
	{
		alert(errorPrompt);
	}
}


/*--get suburbID from url--*/
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/*--get rating by suburbID and get suburbPostcode for title--*/
function getRatingByCampaignIDAndSuburbID() {
    suburbid = getUrlVars()["suburbID"];
    $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetRatingByCampaignIDAndSuburbID&campaignID=" + campaignid + "&suburbID=" + suburbid + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {
        var rating1 = data.DataList.Data["Rating1"];
        var rating2 = data.DataList.Data["Rating2"];
        var rating3 = data.DataList.Data["Rating3"];
        var totalRating = data.DataList.Data["TotalRating"];
        $("#_totalRatingLabel").text(totalRating);
        $("#rating1").progressbar({ value: rating1 * 10 });
        $("#rating2").progressbar({ value: rating2 * 10 });
        $("#rating3").progressbar({ value: rating3 * 10 });
    });
}

/*--go to local view page according to the suburbID--*/
function goToSuburb(suburbid){
    location.href = "/suburb.aspx?suburbID=" + suburbid;
}

/*--send an email when reporting an inappropriate comment--*/
function reportComment(a) {
    urlStr = "/aussie_ReportComment.aspx?sendermessage=The%20following%20comments%20is%20inappropriate.%20MessageLogId:"+ a;
    $.get(urlStr, function(data){
    alert('You have reported this text as inappropriate.  Ninemsn will investigate and remove if deemed inappropriate.');
	});

    // supress link click
    return false;
}

/*--RHC - Home Price--*/

/*--RHC - Home Price - format value--*/
function FormatValue(value, valueSymbol, renderZero) {
    var newValue;
    if ((value == 0) || (value == ""))
    //render the zero value if chosen
        if (renderZero) {
        newValue = 0 + valueSymbol;
    }
    else {
        newValue = "n/a";
    }
    else {
        if (valueSymbol == '$') {
            newValue = valueSymbol + value;
        }
        else {
            newValue = value + valueSymbol;
        }
    }
    return newValue;
}


/*--RHC - Home Price - insert comma in the price--*/
String.prototype.commafy = function() {
    return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
        return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
    });
}
Number.prototype.commafy = function() {
    return String(this).commafy();
}

/*----*/
function GeneratePopupContent(listitem, formType) {
    var description;
    description = "<BR><b>" + listitem.PropertyCategorisation + "</b><BR>";
    description = description + "Sold Median Price: " + FormatValue(listitem.SoldMedianPrice.commafy(), '$', false) + "<BR>";
    description = description + "Annual Median Growth: " + FormatValue(listitem.SuburbMedianGrowthPercentage, '%', false) + "<BR>";

    switch (formType) {
        case 'hotspotForm':
            description = description + "Average Days On Market: " + FormatValue(listitem.AverageDaysOnMarket, ' days', false) + "<BR>";
            description = description + "Average Discount: " + FormatValue(listitem.AverageDiscount, '%', false) + "<BR>";
            break;
        case 'rentalForm':
            description = description + "Rent Median Price: " + FormatValue(listitem.RentMedianPrice.commafy(), '$', false) + " /week <BR>";
            description = description + "Gross Rental Yield: " + FormatValue(listitem.Grossrentalyield, '%', false) + "<BR>";
            break;
        default: break;
    }


    return description;

}

/*--RHC - Home Price - get data--*/
function GetRegionalAndSuburbData() {
    suburbid = getUrlVars()["suburbID"];
    $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetRegionalAndSuburbDataBySuburbID&suburbId=" + suburbid + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

        if (data.DataList == null) {
            document.getElementById('resultFormError').innerHTML = "There are no results matching your suburb";
            document.getElementById('resultFormError').style.display = 'block';
            ResetMap();
        }


        var f = 0;
        var longitude, lattitude;
        var propertyCategorisationType;
        var description = "";
        //
        // used if we have no match for lat/long
        // JS_OMNTR_PAGETYPEIDENTIFIER2 is suburb, and JS_OMNTR_PAGETYPEIDENTIFIER is state
        //
        var findText = JS_OMNTR_PAGETYPEIDENTIFIER2 + ", " + JS_OMNTR_PAGETYPEIDENTIFIER;

        if (data && data.DataList && data.DataList.Data) {
            var list = data.DataList.Data;

            if (list.length >= 0) {//is array

                for (var i = 0; i < list.length; i++) {
                    longitude = list[i].Longitude;
                    lattitude = list[i].Lattitude;                    
                    
                    //checks if there is a row ahead for same suburb data but for Units

                    if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
                        $("#suburbName").html(list[i].SuburbName);
                        $("#regionName").html(list[i].RegionName);
                        $("#stateName").html(list[i].State);


                        propertyCategorisationType = list[i].PropertyCategorisation;
                        //House stats
                        if (propertyCategorisationType == 'HOUSE') {
                            $("#HouseMedianPrice").html(FormatValue(list[i].SoldMedianPrice.commafy(), '$'), false);
                            $("#HouseAnnualMedianGrowth").html(FormatValue(list[i].SuburbMedianGrowthPercentage, '%'), false);
                            $("#HouseAverageTimeMarket").html(FormatValue(list[i].AverageDaysOnMarket, ' days', false));
                            $("#HouseAverageDiscount").html(FormatValue(list[i].AverageDiscount, '%'), false);
                        }
                        //Unit stats
                        if (propertyCategorisationType == 'UNIT') {
                            $("#UnitsMedianPrice").html(FormatValue(list[i].SoldMedianPrice.commafy(), '$'), false);
                            $("#UnitsAnnualMedianGrowth").html(FormatValue(list[i].SuburbMedianGrowthPercentage, '%', false));
                            $("#UnitsAverageTimeMarket").html(FormatValue(list[i].AverageDaysOnMarket, ' days', false));
                            $("#UnitsAverageDiscount").html(FormatValue(list[i].AverageDiscount, '%', false));
                        }

                        description = description + GeneratePopupContent(list[i], 'result');

                        AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);

                        //get names for omniture page tracking by suburb
                        aussie_omni_state = list[i].State;
                        aussie_omni_suburbName = list[i].SuburbName;
                    }
                }
            }
            GetMap(pushPinsDetailArray, pointsArray, 'myMap', findText);
        }
    });
}

/*--omniture tracking--*/
function OmnitureTrackingBySuburb() {

    JS_OMNTR_PAGETYPENAME = 'money_suburbreview';
    JS_OMNTR_PAGETYPEIDENTIFIER = aussie_omni_state;
    JS_OMNTR_PAGETYPEIDENTIFIER2 = aussie_omni_suburbName;

    alert(JS_OMNTR_PAGETYPEIDENTIFIER);
    alert(JS_OMNTR_PAGETYPEIDENTIFIER2);
}

/*--RHC - Community - get data--*/
function GetDemographicData() {
    suburbid = getUrlVars()["suburbID"];
    $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetDemographicDataBySuburbID&suburbId=" + suburbid + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

        if (data && data.DataList && data.DataList.Data) {
            var list = data.DataList.Data;

            if (list) {//is array

                $("#Population2006").html(FormatValue(list.Population2006, '', false));
                $("#MedianResidentsAge").html(FormatValue(list.MedianResidentsAge, '', false));
                $("#MedianHouseholdWeeklyIncome").html(FormatValue(list.MedianHouseholdWeeklyIncome, '$', true));
                $("#Rented").html(FormatValue(list.Rented, '', false));
                $("#FullOwned").html(FormatValue(list.FullOwned, '', false));
                $("#BeingPurchased").html(FormatValue(list.BeingPurchased, '', false));
            }
        }
    });
}

function moreSuburbData() {
    suburbid = getUrlVars()["suburbID"];
    location.href = "/aussiePriceMapping.aspx?formType=results&suburbID=" + suburbid;
}

/*--RHC - map--*/
function AddGeocodePoint(pointsArray, pushPinsDetailArray, i, lattitude, longitude, title, description, suburbID) {
    //add geocode to position array
    pointsArray[i] = new VELatLong(lattitude, longitude, 0, VEAltitudeMode.RelativeToGround)

    //add details for popup hover
    pushPinsDetailArray[i] = [title, description];
}

function ResetMapArrays() {
    pushPinsDetailArray = [];
    pointsArray = [];
}

var map;
function ResetMap() {
    var map = new VEMap('myMap');
    map.SetDashboardSize(VEDashboardSize.Small);
    map.LoadMap(new VELatLong(-28.48295117535531, 134.296875), 4, 'Road', true, VEMapMode.Mode2D, true, 0);
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers)
}

function GetMap(pushPinsDetailArray, pointsArray, mapID, findText) {
    suburbid = getUrlVars()["suburbID"];
    map = new VEMap(mapID);
    map.SetDashboardSize(VEDashboardSize.Small);
    map.LoadMap();
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers)

    //sets best focused map view based on points in array
    if (pointsArray.length < 1) 
   { 
        // show the map at the suburb by text
        map.Find(null, findText)
    }
    else 
    {
        map.SetMapView(pointsArray);
    }
    map.SetZoomLevel(14);

    //Add suburb pushpin layer
    var myShapeLayer = new VEShapeLayer();
    map.AddShapeLayer(myShapeLayer);

    //loops through arrays to plot pushpin and pushpin details
    for (i = 0; i < pushPinsDetailArray.length; i++) {
        var pin = new VEShape(VEShapeType.Pushpin, pointsArray[i]);
        pin.SetTitle(pushPinsDetailArray[i][0]);
        pin.SetDescription(pushPinsDetailArray[i][1]);
        pin.SetMoreInfoURL(pushPinsDetailArray[i][2]);
        //pin.SetPhotoURL("http://marcgrabanski.com/img/jQuery-logo.gif");
        myShapeLayer.AddShape(pin);
    }
    myShapeLayer.SetClusteringConfiguration(VEClusteringType.Grid);
}

// disclaimer Popup window code

function disclaimerpopup(url) {
	popupWindow = window.open(
		url,'popUpWindow','height=500,width=500,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes')
}


