
if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(elt /*, from*/)
    {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
        ? Math.ceil(from)
        : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++)
        {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
}

function getLeaf(result) {
   var leaf = null;
   for(var key in result){
     var prop = key;
     if ((typeof prop != "undefined") && (prop .toString() != "class") && (prop .toString() != "id")) { 
        leaf = result[prop];
        break;
     }
   }
   if (leaf == null)
       return result;
   else if ((typeof leaf) == "string")
	return leaf;
   else
      return getLeaf(leaf);
}

function priceQuery(house_url, price_xpath, callback) {
 
 if (price_xpath == null || price_xpath == "null")
     return;
var query = "SELECT * FROM html WHERE url='" +  house_url + "' AND xpath='" + price_xpath + "'";

var encodedQuery = encodeURIComponent(query.toLowerCase()),
        url = 'http://query.yahooapis.com/v1/public/yql?q='
            + encodedQuery + '&diagnostics=true&format=json&callback=?';
 
    $.getJSON(url, function(data) {

   var beenRedirect  = data.query.diagnostics.redirect;
   var hasError = data.query.diagnostics.url.error
   
   var hasErrorText = false;
   var res = data.query.results;
   var hasResult = false;
   
   for(var key in res){
       var sub = res[key];
       
       if ((typeof errorText != "undefined") && errorText != null) {
       
           var subText = getLeaf(sub).toString();
           if (subText.toString().indexOf(errorText, 0) > -1) {
               hasErrorText = true;
           }
       }
       if (!hasErrorText)
        hasResult = true;
   }
   

  
   var ok = (typeof hasError == "undefined") && (typeof beenRedirect == "undefined") && !hasErrorText ;
   
      if (typeof(priceUpdateCallback) == "function") {
          if (ok) {
            priceUpdateCallback(data.query.results, hasResult);
          }
          else {
              priceUpdateCallback(null, true);
          }
      }

});
 
}

function priceUpdate(house_id, sourceid, existing_price, new_price) {
   
    var d = {
            house: house_id,
            source : sourceid,
            price: new_price,
            prev_price: existing_price
        };

        $.ajax({
            type: "GET",
		data: (d),
            url: "/PriceUpdate"
        });  
   
}



//script kiddies
function showMapAll(addrValues,infoValues) {
  
    var map = null;
    var geocoder = null;
    var points = new Array();
    var bounds = new GLatLngBounds();
    var pointCount = 0;
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("propertyMainMap"));
        geocoder = new GClientGeocoder();
        $.each(
            addrValues,
            function( intIndex, objValue ){
                geocoder.getLatLng(
                    addrValues[intIndex],
                    function(point) {
                        pointCount += 1;

                        if (!point) {
                            alert(addrValues[intIndex] + " not found");
                        } else {
                            //alert(point);
                            points.push(point);
                            bounds.extend(point);
                            // all lat/long requests have been responded
                            if (pointCount == addrValues.length ) {
                                //var latSpan = bounds.toSpan().lat();


                                map.setCenter(bounds.getCenter(), 13);
                                map.setUIToDefault();
                                //var newBounds = map.getBounds();
                                //var newLatSpan = newBounds.toSpan().lat();
                                //if (latSpan/newLatSpan > .90) { map.zoomOut(); }

                                $.each(points, function(i, itm) {

                                    var marker = new GMarker(itm);
                                    GEvent.addListener(marker, "mouseover", function() {
                                        marker.openInfoWindowHtml(infoValues[i]);
                                    });
                                    map.addOverlay(marker);
                                });
                            }
                        }
                    //slow down googlemap queries
                    }
                    );

            }
            );


    }
}

function gotourl(url)
{
    window.open(url, '','toolbar=1,location=1,satus=1,menubar=1,scrollbars=1,resizable=1')
}
function showMap(address,mapdiv,walkscore,streetview) {

    //hide any walkscore if map is going to show
    var divElement = document.getElementById(mapdiv);
    if (divElement.style.display == "none") {

        hideVisibility(walkscore);
        hideVisibility(streetview);
        showVisibility(mapdiv);
    } else {
        hideVisibility(mapdiv);
    }

    var map = null;
    var geocoder = null;

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(mapdiv));
        geocoder = new GClientGeocoder();

        geocoder.getLatLng(
            address,
            function(point) {
                if (!point) {
                    alert(address + " not found");
                } else {
                    map.setCenter(point, 13);
                    map.setUIToDefault();
                    var marker = new GMarker(point);
                    map.addOverlay(marker);

                }
            }
            );
    }
}


function showStreetView(address,mapdiv,walkscore,streetview) {

    //hide any walkscore if map is going to show
    var divElement = document.getElementById(streetview);
    if (divElement.style.display == "none") {

        hideVisibility(walkscore);
        hideVisibility(mapdiv);
        showVisibility(streetview);
    } else {
        hideVisibility(streetview);
    }

    var myPano;

    var geocoder = null;

    if (GBrowserIsCompatible()) {
       
        geocoder = new GClientGeocoder();

        geocoder.getLatLng(
            address,
            function(point) {
                if (!point) {
                    alert(address + " not found");
                } else {
                    var panoramaOptions = {
                        latlng:point
                    };
                    myPano = new GStreetviewPanorama(divElement, panoramaOptions);
                    GEvent.addListener(myPano, "error", handleNoFlash);


                }
            }
            );
    }
}
function handleNoFlash(errorCode) {
    if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
}
function doWalkscore(walkscore,titleAddress,itemid) {

    var ws = document.getElementById('walkscore_' + itemid);
    if (ws.style.display == "none") {

        hideVisibility('optiondiv_' + itemid);
        hideVisibility('streetview_' + itemid);
        showVisibility('walkscore_' + itemid);
        if(document.getElementById('walkscore' + itemid) == null) {
            walkscore.append('<iframe id="'+ 'walkscore' + itemid + '"  frameborder="0" style="border:0px" width="700px" height="300px" src="' +
                "http://www.walkscore.com/serve-walkscore-tile.php?wsid=917ff7154e87e4a13ce781ea97296183&street=" +
                escape(titleAddress) +  '&width=650&layout=horizontal&height=263&footheight=0' +
                '"></iframe>');


        }
    }
    else {
        hideVisibility('walkscore_' + itemid);
    }

    

}

function showWalkscore(tileAddress) {
    $("#walkscoremap").attr("src",'http://www.walkscore.com/serve-walkscore-tile.php?wsid=917ff7154e87e4a13ce781ea97296183&street=' + escape(tileAddress) +  '&width=500&layout=horizontal&height=268&footheight=18');
    $("#walkscore").dialog("open");
}



var lastShownHover = null; 

function showHover(hoverId)
{
    //hide the previous hover
    if (lastShownHover != null)
    {
        lastShownHover.style.display ="none";
    }
    var currentHover = document.getElementById(hoverId);

    currentHover.style.display ="block";
    lastShownHover = currentHover;
}


function submitSearchForm()
{
    //KEYWORD_PARAM - n
    var searchForm = document.getElementById("searchForm");
    var keyword = searchForm.n.value;
    var mode = searchForm.t.value;
    if (keyword == 'Address or Description')//watermark
        keyword = '';

    //STATE_PARAM - d
    var state = searchForm.d.value;
        
    //REGION_PARAM - c
    var region = searchForm.c.value;
    if (region == 'Suburbs separated by commas')
        region = '';
    var type = 'sale';
    if (searchForm.b[1].checked)
    {
        type = 'rent';
    }
    var cat = searchForm.a.value;
    var pageSize = 10;

    var data = {
            q: "0",
            n: keyword,
            c: region,
            d: state,
            b: type,
            s: pageSize,
            a: cat,
            t : mode
        };
        
   searchProps(data);
    return false;
}


function doRefinement()
{
   var minPriceVal = document.getElementById("minPrice").value;
    var maxPriceVal = document.getElementById("maxPrice").value;
    //temporarily take out the price existence check since adding googlebase
    var includeEmptyPriceVal = "I";//document.getElementById("includeEmptyPrice").checked ? "I" : "X";
    var refineForm = document.getElementById("mainRefinementForm");
    var beds = refineForm.bedNumber.value + ((refineForm.bedAtleast[0].checked) ? "" : "m");
    var baths = refineForm.bathNumber.value + ((refineForm.bathAtleast[0].checked) ? "" : "m");
    var carspaces = refineForm.carspaceNumber.value + ((refineForm.carspaceAtleast[0].checked) ? "" : "m");

    var existingUrl = window.location.pathname;

    jQuery.ajax({
        url:    '/SEO',
        data: ({
            url: existingUrl,
            j: minPriceVal,
            k: maxPriceVal,
            l: includeEmptyPriceVal,
            f: beds,
            g: baths,
            h: carspaces,
            q: "0"
        }),
        type: "GET",
        success: function(result) {
            window.location = result;
        },
        async:   false
    });

}

function sort(sortparam, direction, geo)
{
    var existingUrl =  encodeURIComponent(window.location.pathname);
    var data;
    if (sortparam == 'u') {
        data = { 
            url: existingUrl,
            y: sortparam,
            u: direction
        };
    } else if (sortparam == 'v') {
        data = { 
            url: existingUrl,
            y: sortparam,
            v: direction
        };
    } else if (sortparam == 'w') {
        data = {
            url: existingUrl,
            y: sortparam,
            w: direction
        };
    }
    else if (sortparam == 'x') {
        data = {
            url: existingUrl,
            y: sortparam,
            x: direction
        };
    }
  
   if (geo) {
       searchPropsByGeo(data);
   }
   else {
       searchProps(data);
   }
}


function clearAllSort(geo)
{
    var existingUrl = getExistingUrl();
    data = {
            url: existingUrl,
            y: 'E'
        };
        
       if (geo) {
       searchPropsByGeo(data);
   }
   else {
       searchProps(data);
   }
}

function searchProps(d) {
     jQuery.ajax({
        url:    '/SEO',
        data: (d),
        type: "GET",
        success: function(result) {
            window.location = result;
        },
        async:   false
    });
}

function searchProps2(d) {
    var ret = null;
     jQuery.ajax({
        url:    '/SEO',
        data: (d),
        type: "GET",
        success: function(result) {
           ret = result;
        },
        async:   false
    });
    return ret;
}

function getExistingUrl() {

    var existingUrl = window.location.toString();
    var pos = existingUrl.toString().indexOf(seo_url, 0)
    existingUrl = existingUrl.substring(pos, existingUrl.length );
    existingUrl = encodeURIComponent(existingUrl);
    return existingUrl;
}




function propMouseOver(e, jobid) {
    var top = 0, left = 0;
    var myTarget = e;

    while (myTarget != document.body && myTarget != null) {
        top += myTarget.offsetTop;
        left += myTarget.offsetLeft;
        myTarget = myTarget.offsetParent;
    }

    left = left + 15;
    var detailDiv = document.getElementById("detailDiv");

    detailDiv.style.left = left + "px";
    detailDiv.style.top = top + "px";
    detailDiv.style.visibility ="visible";
    
    var jobDomEle = document.getElementById('fullDesc' + jobid);
    var jobDetailDomEle = document.getElementById('jobDetailContent');
    jobDetailDomEle.innerHTML = jobDomEle.innerHTML;
    
    var sourcelinkDomEle = document.getElementById('sourcelink' + jobid);
    var applyNowLink = document.getElementById("applyNowLink");
    var fulldetailLink = document.getElementById("fullDetailLink");
    applyNowLink.href = sourcelinkDomEle.href;
    applyNowLink.target ="_blank";
    fulldetailLink.href="/job_" + jobid +".html";
}
function propMouseOut() {
    var optionPane = document.getElementById("detailDiv");
    optionPane.style.visibility ="hidden";
}

function toggleSavedJobs(anAnchor, linkValue)
{
    if (anAnchor.innerHTML == "save property")
    {
        anAnchor.innerHTML = "remove property";
        addSavedJob(linkValue);
    }
    else
    {
        anAnchor.innerHTML = "save property";
        removeSavedJob(linkValue);
		
        //ok, check if we are in the basket
        var viewMode = gup("view");
        if (viewMode != null && viewMode == "basket")
        {
            var savedJobs = readCookie("savedItems");
            if (savedJobs != null)
            {
                //check if we still have any save
                gotoSavedResultsUrl();
            }
            else
            {
                gotoAllResultsUrl();
            }
        }
		

    }
	
}

function toggleRefinement(h3ID)
{
    var h3Element = document.getElementById(h3ID);
    if (h3Element != null)
    {
        if (h3Element.className != "closed")
            h3Element.className ="closed";
        else
            h3Element.className="";
    }
}

function toggleAdvanceSearch()
{
    $('#searchHide').toggle();
     $('#mapsearch').toggle();
}

function toggleVisibility(divID)
{
	
    var divElement = document.getElementById(divID);
    if (divElement.style.display != "block")
        divElement.style.display ="block";
    else
        divElement.style.display="none";
}
function hideVisibility(divID)
{
    var divElement = document.getElementById(divID);
    divElement.style.display="none";

}
function showVisibility(divID)
{
    var divElement = document.getElementById(divID);
    divElement.style.display ="block";
}

function settupBaskets(viewMode)
{
    var savedJobs = readCookie("savedItems");

    if (savedJobs != null)
    {
        var jobIdStr = "" + unescape(savedJobs);

        var jobIds = jobIdStr.split(" ");
		

        for (i = 0; i < jobIds.length; i++)
        {
			
            var saveElement = document.getElementById(jobIds[i]);
            if (saveElement != null)
            {
                saveElement.innerHTML ="remove";
            }
        }
    }
	
    if (viewMode == "B")
    {
        //ok, show the submenu of empty and send email basket
        var clearSearchProperties = document.getElementById('clearSearchProperties');
        var emailBasket = document.getElementById('emailBasket');
        if (clearSearchProperties != null)
            clearSearchProperties.style.visibility = 'visible';
        if (emailBasket != null)
            emailBasket.style.visibility = 'visible';
    }
    else
    {
        //disable them
        var clearSearchProperties = document.getElementById('clearSearchProperties');
        var emailBasket = document.getElementById('emailBasket');
        if (clearSearchProperties != null)
            clearSearchProperties.style.visibility = 'hidden';
        if (emailBasket != null)
            emailBasket.style.visibility = 'hidden';
    }
}


function gotoSavedResultsUrl()
{
    var currentSavedJobs = readCookie("savedItems");
    if (currentSavedJobs != null) {
        var existingUrl = window.location.toString();
        var suffix = "/my_search_properties";
        var pos = existingUrl.toString().indexOf(suffix, existingUrl.length - suffix.length);
        if (pos == -1) {
            window.location = existingUrl + "/my_search_properties";
        }
    }
    else {
        alert("No properties have been saved!");
    }
}

function getParamVal(param)
{
    var currentLocation = "" + window.location;
    var tokens = currentLocation.split("/");

    for (var i = 1; i < tokens.length; i++)
    {
        var index = tokens[i].indexOf(param);
        if (index  > -1)
        {
            return tokens[i].substring(index);
        }
        else
        {
            return null;
        }
    }
    return null;
}



function switchMode(mode)
{
    var existingUrl = getExistingUrl();

    $.get("/SEO", {
        url: existingUrl,
        t: mode
    },
    function(data){
        window.location = data;
    });
}




function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec(window.location);
    if( results == null )
        return "";
    else
        return results[1];
}


function gotoAllResultsUrl()
{
    //ok, show the submenu of empty and send email basket
    var clearSearchProperties = document.getElementById('clearSearchProperties');
    var emailBasket = document.getElementById('emailBasket');
    if (clearSearchProperties != null)
        clearSearchProperties.style.visibility = 'hidden';
    if (emailBasket != null)
        emailBasket.style.visibility = 'hidden';

    var existingUrl = window.location.toString();
    
     var suffix = "/my_search_properties";
     var pos = existingUrl.toString().indexOf(suffix, existingUrl.length - suffix.length);
     if (pos !== -1) {
            window.location = existingUrl.toString().substring(0, pos);
       }

  
}

function addSavedJob(jobId)
{
    var savedJobs = readCookie("savedItems");
    if (savedJobs == null)
        savedJobs = "" + jobId;
    else
        savedJobs = unescape(savedJobs) + " " + jobId;
	
    createCookie("savedItems", escape(savedJobs), 1);
}

function removeSavedJob(jobId)
{
    var savedJobs = readCookie("savedItems");
    if (savedJobs == null)
        return;
	
    savedJobs = unescape(savedJobs).replace(jobId, "");
    savedJobs = savedJobs.replace("  ", " ");
    createCookie("savedItems", escape(savedJobs), 1);
}



function clearSearchProperties()
{
    eraseCookie("savedItems");
    gotoAllResultsUrl();
}

function createCookie(name,value,days) 
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toUTCString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
    var nameEQ = name + "=";
    var ca = (""+document.cookie).split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0)
        {
            var cookieVal =  c.substring(nameEQ.length,c.length);
            //ok, ignore empty strings
            if (unescape(cookieVal).replace(/\s/g,"") == "")
                return null;
            else
                return cookieVal;
				
        }
    }
    return null;
}

function eraseCookie(name) 
{
    createCookie(name,"",-1);
}



$(document).ready(function()
{
    $("#searchRegion").autocomplete("/suggestion.jsp", {
        multiple: true,
        matchContains: true,


        extraParams: {
            st: function() {
                return $("#searchState").val();
            },
            kw: function() {
                return $("#searchRegion").val();
            }
        }
    });

    // Define what happens when the textbox comes under focus
    // Remove the watermark class and clear the box
    $("#keyword").focus(function() {

        $(this).filter(function() {

            // We only want this to apply if there's not
            // something actually entered
            return $(this).val() == "" || $(this).val() == "Address or Description"

        }).removeClass("watermarkOn").val("");

    });

    // Define what happens when the textbox loses focus
    // Add the watermark class and default text
    $("#keyword").blur(function() {

        $(this).filter(function() {

            // We only want this to apply if there's not
            // something actually entered
            return $(this).val() == ""

        }).addClass("watermarkOn").val("Address or Description");

    });
	    
    $("#searchRegion").focus(function() {

        $(this).filter(function() {

            // We only want this to apply if there's not
            // something actually entered
            return $(this).val() == "" || $(this).val() == "Suburbs separated by commas"

        }).removeClass("watermarkOn").val("");

    });

    // Define what happens when the textbox loses focus
    // Add the watermark class and default text
    $("#searchRegion").blur(function() {

        $(this).filter(function() {

            // We only want this to apply if there's not
            // something actually entered
            return $(this).val() == ""

        }).addClass("watermarkOn").val("Suburbs separated by commas");

    });



});


$(function() {

    $('#email_result').hide();
    $('input.text-input').css({
        backgroundColor:"#FFFFFF"
    });
    $('input.text-input').focus(function(){
        $(this).css({
            backgroundColor:"#FFDDAA"
        });
    });
    $('input.text-input').blur(function(){
        $(this).css({
            backgroundColor:"#FFFFFF"
        });
    });


    $("#submit_btn").click(function() {
        // validate and process form
        // first hide any error messages
        $('.error').hide();


        var email = $("input#email").val();
        apos=email.indexOf("@");
        dotpos=email.lastIndexOf(".");
        if (apos<1||dotpos-apos<2)
        {
            $('#email_result').html("You must enter a valid email");
            $("#email_result").show();
            $("input#email").focus();
            return false;
        }

        var dataString = 'mail='+ email +"&time=" + new Date() ;

        $('#email_result').show();
        $('#email_result').html("<h3>Sending Email. Please wait...</h3>");

        $.ajax({
            type: "GET",
            url: "/mailsender",
            data: dataString,
            timeout: 20000,
            error: function(){
                alert("We cannot process your request at this time. Please try again later!");
            },
            success: function() {

                $('#emailForm').hide();
                $('#email_result').show();
                $('#email_result').html("<h3>Successfully sent ...</h3><p>Check your mailbox soon.</p>")
                .hide()
                .fadeIn(1500, function() {
                    $('#email_result').hide();
                });
            }

        });
        return false;
    });
});



