function toggleContactReason(element, url, cr, id1, id2)
{
    new Ajax.Updater(element, url, {method: 'get'});
    if (cr == 'p') {
        $(id1).show();      
        $('real-estate-agent').hide();      
    } else if (cr == 'r') {
        $(id1).show();  
        $('property-seeker').hide();    
    } else if (cr == 'o') {     
        $(id1).hide();      
        $(id2).hide();      
    }   
    $('contact-name-label').setStyle({ color : 'black' });
    $('contact-email-label').setStyle({ color : 'black' });
    $('contact-number-label').setStyle({ color : 'black' });
    $('contact-message-label').setStyle({ color : 'black' });
    $('contact-img').setStyle({ display : 'none' });    
    $('find-a-property').setStyle({ display : 'none' });            
    $('contact-name').disabled=false;    
    $('contact-email').disabled=false;    
    $('area-code').disabled=false;    
    $('contact-number').disabled=false;     
    $('contact-message').disabled=false;        
    $('send').setStyle({ display : 'block' });      
    $('send-gray').setStyle({ display : 'none' });      
    $('contact-message').value = '';            
}

function propertyInfo(t)
{
    $('contact-message').value = '';                
    if ($(t).value == '7' || $(t).value == '6' || $(t).value == '5') {
        $('property-seeker').hide();        
        $('real-estate-agent').hide();  
        $('contact-name-label').setStyle({ color : 'gray' });
        $('contact-email-label').setStyle({ color : 'gray' });
        $('contact-number-label').setStyle({ color : 'gray' });
        $('contact-message-label').setStyle({ color : 'gray' });
        $('contact-name').setStyle({ border : '1px solid gray', background : 'white'});
        $('contact-email').setStyle({ border : '1px solid gray', background : 'white' });
        $('contact-message').setStyle({ border : '1px solid gray', background : 'white' });
        $('contact-name').disabled=true;    
        $('contact-email').disabled=true;    
        $('area-code').disabled=true;    
        $('contact-number').disabled=true;      
        $('contact-message').disabled=true;  
        $('send-gray').setStyle({ display : 'block' });     
        $('send-gray').disabled=true;       
        $('send').setStyle({ display : 'none' });               
    }
    if ($(t).value == '6' || $(t).value == '5') {
        $('contact-img').setStyle({ display : 'block' });       
        $('find-a-property').setStyle({ display : 'none' });    
        $('contact-message').value = 'To enquire about a listing or advertised property, please contact the agent on the relevant property details page.\n\nJust start your search at the top of this page!';       
    } else if ($(t).value == '7') {
        $('contact-img').setStyle({ display : 'none' });    
        $('find-a-property').setStyle({ display : 'block' });                       
        $('contact-message').value = 'To find a property on our site, start your search at the top of this page!';      
    } else {
        $('contact-name-label').setStyle({ color : 'black' });
        $('contact-email-label').setStyle({ color : 'black' });
        $('contact-number-label').setStyle({ color : 'black' });
        $('contact-message-label').setStyle({ color : 'black' });
        $('contact-img').setStyle({ display : 'none' });    
        $('find-a-property').setStyle({ display : 'none' });        
        $('contact-name').disabled=false;    
        $('contact-email').disabled=false;    
        $('area-code').disabled=false;    
        $('contact-number').disabled=false;     
        $('contact-message').disabled=false;        
        $('send').setStyle({ display : 'block' });      
        $('send-gray').setStyle({ display : 'none' });              
    }
}

// parse basic plain text search value to advanced search page
function setAdvancedSearch(v,q,t)
{
    if ($('q').value != 'Enter: Suburb or Postcode or Street') {
        if (t != '') {
            new Ajax.Updater(element='', '/search/_ajax_advanced_search.php?basic_search=true&suburb_id=' + t + '&include_suburbs='+ $('include-suburbs').value + '&street=' + $('street_name').value + '&search_result=' + $('q').value, {method: 'get'}); 
        } else {
            var inc_suburbs = (v == '1') ? '&include_suburbs=' + v : '';
            new Ajax.Updater(element='', '/search/_ajax_advanced_search.php?plain_text=true&q=' + $('q').value + inc_suburbs, {method: 'get'}); 
        }
    }
}

// handle include surrounding suburbs checkbox
function setCheckBox(id)
{
    $(id).value = ($(id).value == '') ? $(id).value = '1' : $(id).value = '' ; 
}

//Reset homepage search form
function resetHomeSearchForm(f)
{
    var elms = $(f).getElements();
    for (var i = 0; i < elms.length; i++) {
        if (elms[i].type == 'select-one') {
            var opts = elms[i].getElementsByTagName('option');
            for (var j = 0; j < opts.length; j++) {
                opts[j].selected = (j === 0) ? true: false;
            }
        }
    }
}

// Reset advanced search form
function resetAdvancedSearchForm(f)
{
    var elms = $(f).getElements();
    for (var i = 0; i < elms.length; i++) {
        switch (elms[i].type) {
        case 'checkbox':
            elms[i].checked = false;
            break;
        case 'hidden':
            elms[i].value = '';
            break;
        case 'radio':
            elms[i].checked = false;
            break;
        case 'select-one':
            var opts = elms[i].getElementsByTagName('option');
            for (var j = 0; j < opts.length; j++) {
                opts[j].selected = (j === 0) ? true : false;
            }
            break;
        case 'text':
            elms[i].value = '';
            break;
        }
        if (elms[i].type == 'checkbox') {
            elms[i].checked = false;
        }
    }
    $('search-suburb-postcode').value = search_text;
    $('asearch_type').value = 'AS';
    $('search-holiday').disable();
    $('search-inspection-keywords').value = keyword_text;
    $('search-house').disable();
    $('search-apartment').disable();
    new Ajax.Updater(element='', '/search/_ajax_advanced_search.php?reset_advanced_form=true', {method: 'get'});    
}

// confirm email and passwords
function checkPasswordsEmails(f) {
    message = '';
    if (f.password.value == '') {
        message += 'Please enter your password.\n';
    }
    if (f.confirm_password.value == '') {
        message += 'Please re-enter your password.\n';
    }
    if (f.password.value != f.confirm_password.value) {
        message += 'Your passwords are not the same. Please try again.\n';
        f.confirm_password.value = '';
    }
    if (f.email.value == '') {
        message += 'Please enter your email.\n';
    }
    if (f.confirm_email.value == '') {
        message += 'Please re-enter your email.\n';
    }
    if (f.email.value != f.confirm_email.value) {
        message += 'Your email addresses are not the same. Please try again.\n';
        f.confirm_email.value = '';
    }
    if (message == '') {
        return true;
    } else {
        return false;
    }
}

// Populates hidden fields and toggles display of surrounding suburbs checkbox
function getSelectionId(text, li) {
    $('suburb_id').value = li.id;
    $('street_name').value = li.readAttribute('rel');
    if ($('street_name').value != '') {
        $('include-suburbs-label').hide();
        $('include-suburbs').checked = false;
    } else {
        $('include-suburbs-label').show();
    }
    text_value = text.value;
}

function hideCriteria(q,query_text) {
    if ($('sale_form').style.display != 'none') {
        $('sale_criteria').hide();
    } else if ($('rent_form').style.display != 'none') {
        $('rent_criteria').hide();
    } else {
        $('share_criteria').hide();
    }
    return query_text;
}

function getSelectionIdBuy(text, li) {
    $('suburb_id').value = li.id;
    $('street_name').value = li.readAttribute('rel');
    if ($('street_name').value != '') {
        $('include-suburbs-label').hide();
        $('include-suburbs').checked = false;
    } else {
        $('include-suburbs-label').show();
    }
    text_value = text.value;
    $('sale_criteria').style.display = '';
}

function getSelectionIdRent(text, li) {
    $('rent_suburb_id').value = li.id;
    $('rent_street_name').value = li.readAttribute('rel');
    if ($('rent_street_name').value != '') {
        $('rent-include-suburbs-label').hide();
        $('rent-include-suburbs').checked = false;
    } else {
        $('rent-include-suburbs-label').show();
    }
    rtext_value = text.value;
    $('rent_criteria').style.display = '';
}

function getSelectionIdShare(text, li) {
    $('share_suburb_id').value = li.id;
    $('share_street_name').value = li.readAttribute('rel');
    if ($('share_street_name').value != '') {
        $('share-include-suburbs-label').hide();
        $('share-include-suburbs').checked = false;
    } else {
        $('share-include-suburbs-label').show();
    }
    rtext_value = text.value;
    $('share_criteria').style.display = '';
}

//Finalises the suburb id and street name depending on any changes made to the text field
function setFinalSuburbID() {
    if ($('q').value != text_value) {
        $('suburb_id').value = '';
        $('street_name').value = '';
    }

    if ($('rent-q') && $('rent-q').value != rtext_value) {
        $('rent_suburb_id').value = '';
        $('rent_street_name').value = '';
    }
}

// Populates hidden fields in Advanced serach
function aGetSelectionId(text, li) {
    $('asuburb_id').value = li.id;
    $('astreet_name').value = li.readAttribute('rel');
    if ($('astreet_name').value != '') {
        $('include-suburbs-label-1').hide();
        $('include-suburbs1').checked = false;
    } else {
        $('include-suburbs-label-1').show();
    }
    text_value = text.value;
}

//Finalises the suburb id and street name depending on any changes made to the text field
function aSetFinalSuburbID(form) {
    if (form.q.value != text_value) {
        $('asuburb_id').value = '';
        $('astreet_name').value = '';
    }
}

// Set focus on search box
function setFocus(elm)
{
    if (elm.value == search_text) {
        elm.value = '';
    }
}

// Set blur on search box
function setBlur(elm)
{
    if (elm.value == '') {
        elm.value = search_text;
    }
}

// Set focus on keywords box
function setFocusKeyword(elm)
{
    if (elm.value == keyword_text) {
        elm.value ='';
    }
}

// Set blur on keywords box
function setBlurKeyword(elm)
{
    if (elm.value == '') {
        elm.value = keyword_text;
    }
}

// Set focus on date box
function setFocusDate(elm)
{
    elm.value = (elm.value == date_text) ? '' : elm.value;
    return elm.value;
}

// Set blur on date box
function setBlurDate(elm)
{
    elm.value = (elm.value == '') ? date_text : elm.value;
    return elm.value;
}

// Set focus to other box
function setFocusOther(elm)
{
    elm.value = '';
}

function setFocusHomeStyle(elm)
{
    if (elm.value == 'Enter keyword') {
        elm.value = '';
    }
}

// Set blur on search box
function setBlurHomeStyle(elm)
{
    if (elm.value == '') {
        elm.value = 'Enter keyword';
    }
}


//Toggle between two elements (i.e. elm2 and elm3 depending on the id of elm1, the link)
function toggleElements(elm1, elm2, elm3, elm4)
{
    $('suggestions').setStyle({display:'none'});
    $('rent-suggestions').setStyle({display:'none'});
    $('share-suggestions').setStyle({display:'none'});
    if (elm1 == 'sale_tab' && $(elm2).style.display == 'none') {
        $(elm2).show();
        $(elm3).hide();
        $(elm4).hide();
    } else if (elm1 == 'rent_tab' && $(elm3).style.display == 'none') {
        $(elm2).hide();
        $(elm3).show();
        $(elm4).hide();
    } else if (elm1 == 'share_tab' && $(elm4).style.display == 'none') {
        $(elm2).hide();
        $(elm3).hide();
        $(elm4).show();
    }
}

// Toggle custom range form elements
function toggleCustomRange(elm1, elm2, val)
{
    if (val == 'Custom Range' || val == 'Custom Range Rent' || val == 'back' || val == 'rent_back' || val == 'Custom Range Bedroom'|| val == 'bedroom_back' || val == 'Custom Range Bathroom' || val == 'bathroom_back' || val == 'Custom Range Carspace' || val == 'carspace_back') {
        $(elm1).toggle();
        $(elm2).toggle();
        if (val == 'back') {
            $('default-low-price').selected = true;
            $('default-high-price').selected = true;
        } else if (val == 'rent_back') {
            $('default-rent-low-price').selected = true;
            $('default-rent-high-price').selected = true;
        } else if (val == 'bedroom_back') {
            $('bedroom-min').value = '';
            $('bedroom-max').value = '';
        } else if (val == 'bathroom_back') {
            $('bathroom-min').value = '';
            $('bathroom-max').value = '';
        } else if (val == 'carspace_back') {
            $('carspace-min').value = '';
            $('carspace-max').value = '';
        } else if (val == 'Custom Range Bedroom') {
            $('default-bedroom-number').selected = true;
        } else if (val == 'Custom Range') {
            $('default-price').selected = true;
        } else if (val == 'Custom Range Rent'){
            $('default-rent-price').selected = true;
        } else if (val == 'Custom Range Bathroom') {
            $('default-bathroom-number').selected = true;
        } else if (val == 'Custom Range Carspace') {
            $('default-carspace-number').selected = true;
        }
    }
}

function revertShareCategories() {
    $('search-land').removeAttribute('disabled');
    $('search-rural').removeAttribute('disabled');
    $('search-commercial').removeAttribute('disabled');
    $('search-industrial').removeAttribute('disabled');
    $('search-business').removeAttribute('disabled');
}

// Toggle price range
function togglePriceRange(type)
{
    if ($('price-range-buy').hasAttribute('disabled')) {
        $('price-range-buy').removeAttribute('disabled');
        $('low-ask-price-buy').removeAttribute('disabled');
        $('high-ask-price-buy').removeAttribute('disabled');
        $('price-range-rent').removeAttribute('disabled');
        $('low-ask-price-rent').removeAttribute('disabled');
        $('high-ask-price-rent').removeAttribute('disabled');
    }
    if (type == 'L' || type == 'E') {
        $('default-low-price').selected = true;
        $('default-high-price').selected = true;
        $('default-price').selected = true; 
        $('price-range-buy-wrap').hide();
        $('price-range-rent-wrap').show();
        if ($('search-holiday').hasAttribute('disabled')) {
            $('search-holiday').removeAttribute('disabled');
        }
        if (!$('do-not-show-auction').hasAttribute('disabled')) {
            $('do-not-show-auction').setAttribute('disabled', 'disabled');
        }
        if (type == 'E') {
            $('search-land').setAttribute('disabled', 'disabled');
            $('search-holiday').setAttribute('disabled', 'disabled');
            $('search-rural').setAttribute('disabled', 'disabled');
            $('search-commercial').setAttribute('disabled', 'disabled');
            $('search-industrial').setAttribute('disabled', 'disabled');
            $('search-business').setAttribute('disabled', 'disabled');
        } else {
            revertShareCategories();

        }
    } else if (type == 'A') {
        $('price-range-buy').setAttribute('disabled', 'disabled');
        $('low-ask-price-buy').setAttribute('disabled', 'disabled');
        $('high-ask-price-buy').setAttribute('disabled', 'disabled');
        $('price-range-rent').setAttribute('disabled', 'disabled');
        $('low-ask-price-rent').setAttribute('disabled', 'disabled');
        $('high-ask-price-rent').setAttribute('disabled', 'disabled');
        if ($('search-holiday').hasAttribute('disabled')) {
            $('search-holiday').removeAttribute('disabled');
            revertShareCategories();
        }
        if ($('do-not-show-auction').hasAttribute('disabled')) {
            $('do-not-show-auction').removeAttribute('disabled');
        }
    } else {
        console.log('else');
        $('default-rent-low-price').selected = true;
        $('default-rent-high-price').selected = true;
        $('default-rent-price').selected = true;
        $('price-range-buy-wrap').show();
        $('price-range-rent-wrap').hide();
        console.log($('search-holiday').setAttribute('disabled', 'disabled'));
        revertShareCategories();
        if ($('do-not-show-auction').hasAttribute('disabled')) {
            $('do-not-show-auction').removeAttribute('disabled');
        }
    }
}

// Toggle price range
function toggleManageListing(type)
{
    if (type == 'outsource') {
        Effect.SlideUp('upload-own', {
            duration: 0.2,
            afterFinish: function() {
                Effect.SlideDown('upload-outsource', {duration:0.4});
            }
        });
    } else {
        Effect.SlideUp('upload-outsource', {
            duration: 0.2,
            afterFinish: function() {
                Effect.SlideDown('upload-own', {duration:0.4});
            }
        });
    }
}

function show3Notes(link_elm, notes)
{
    Position.absolutize(link_elm);

    var link_top = $(link_elm).getStyle('top');
    var t = String(link_top.substring(0, (link_top.length - 2)));

    $(notes).setStyle({
        position : 'absolute',
        top      : (t - 2) + 'px',
        right    : '384px'
    });
    Effect.Appear(notes, { duration: 0.1 });
}

// Controls thumbnail image movement in carousels
function moveCarousel(dir, element, text, width, total, size)
{
    var imgs = $(element).getElementsByTagName('img');
    var x = ($(element).getStyle('left') === null) ? '0px' : $(element).getStyle('left');
    x = String(x.substring(0, (x.length - 2)));

    trackEvent('Search Results Carousel', dir, element);

    if (dir == 'next') {
        var image = (x === 0) ? 2 : ((Math.abs(x) / width) + 2);
    } else if (dir == 'prev') {
        var image = (Math.abs(x) / width);
    } else {
        return false;
    }

    if (!$(imgs[image - 1])) {
        return false;
    }

    if (dir == 'next') {

        if (x > -(width * (total - 1))) {
            new Effect.MoveBy(element, 0, 0 , { x: -width, y: 0, duration: 0.3,  transition: Effect.Transitions.sinoidal});
            if (size == 'r') {
                $(text).update('Photo ' + image + ' of ' + total);
            } else {
                $(text).update('Photo ' + image + '/' + total);
            }
            return true;
        }

    } else if (dir == 'prev') {

        if (x < 0) {
            new Effect.MoveBy(element, 0, 0 , { x: width, y: 0, duration: 0.3,  transition: Effect.Transitions.sinoidal});
            if (size == 'r') {
                $(text).update('Photo ' + image + ' of ' + total);
            } else {
                $(text).update('Photo ' + image + '/' + total);         
            }
            return true;
        }

    } else {

        return false;

    }

    return false;
}

// Shows and positions notes
function showNotes(link_elm, notes)
{
    Position.absolutize(link_elm);

    var link_top = $(link_elm).getStyle('top');
    var t = String(link_top.substring(0, (link_top.length - 2)));

    $(notes).setStyle({
        position : 'absolute',
        top      : (t - 2) + 'px',
        right    : '384px'
    });
    Effect.Appear(notes, { duration: 0.1 });
}

// Hides notes
function hideNotes(link_elm, notes)
{
    $(link_elm).setStyle({
        position : 'static'
    });
    Effect.Fade(notes, { duration: 0.2 });
}

// Ajax Updater to empty note
function updateNotes(element, id) 
{
    new Ajax.Updater(element, '/listing/_ajax_delete_notes.php?id=' + id, {
        onComplete:function() {
           $('notes-link-' + id).className = 'add-notes';
            Effect.Fade('delete-' + id, { duration: 0.0 });
            hideNotes('notes-link-' + id, 'notes-' + id);
        }
    });
}

// Toggle visibility of notes with add notes link
function toggleNotes()
{
    $('property-notes-add').toggle();
    Effect.toggle('property-notes-wrap', 'blind', {duration: 0.2});
}

// Sends note to ajax php script
function editNotes(element, id, page)
{
    new Ajax.InPlaceEditor(element, id, {
        okText: 'Save & Close',
        cancelLink: false,
        formId: 'jum',
        rows: 5,
        highlightcolor: '#ffeba6',
        highlightendcolor: '#fff6d2',
        onComplete: function() {
            if (page == '1') {
               if ((this.getText() == 'Click here to add notes.') || (this.getText() == '')){
                   $('notes-link-' + id).className = 'add-notes';
                    Effect.Fade('delete-' + id, { duration: 0.0 });
                    updateNotes(element, id);
                    hideNotes('notes-link-' + id, 'notes-' + id);
                } else {
                    new Ajax.Updater('', '/listing/_ajax_log_note.php?id='+id, {method:'get'});
                    $('notes-link-' + id).className = 'have-notes';
                    Effect.Appear('delete-' + id, {duration: 0.0});
                    hideNotes('notes-link-' + id, 'notes-' + id);
                }
            } else if (page == '0') {
               if ((this.getText() == 'Click here to add notes.') || (this.getText() == '')){
                    Effect.Fade('delete-btn', { duration: 0.0 });
                    updateNotes(element, id);
                    toggleNotes();
               } else {
                    new Ajax.Updater('', '/listing/_ajax_log_note.php?id='+id, {method:'get'});
                    Effect.Appear('delete-btn', {duration: 0.0});
               }
           }
        }
    });
}

// Ajax Updater with Confirm
function deleteNotes(element, url, id, page)
{
    if (confirm('Are you sure you want to delete this note?')) {
        new Ajax.Updater(element, url, {
            onComplete:function() {
                if (page == '1') {
                   $('notes-link-' + id).className = 'add-notes';
                    Effect.Fade('delete-' + id, { duration: 0.0 });
                    hideNotes('notes-link-' + id, 'notes-' + id);
                } else if (page == '0') {
                    Effect.Fade('delete-btn', { duration: 0.0 });
                    toggleNotes();
                }

            }
        });
    } else {
        return false;
    }
}

// Toggle display of search display options
function toggleDisplayOptions()
{
    Effect.toggle('display-options-view', 'appear', {duration: 0.2});
}

// Toggle display of refine search form
function toggleRefineSearch()
{
    Effect.toggle('refine-search-form', 'appear', {duration: 0.2});
}

// Toggle display of more photos in property details
function toggleMorePhotos(photo_value)
{
    Effect.toggle('more-images-container', 'blind', {duration: 0.2});
        var get_display = Element.getStyle('more-images-container', 'display');
        if(get_display == 'block') {
            Element.update('more-photos', 'More photos (' + photo_value + ')' );
        } else {
            Element.update('more-photos', 'Less photos' );
        }
}

// Swaps main image when thumb clicked on property detail page
function swapImages(element, url)
{
    new Ajax.Updater(element, url, {
        onComplete:function() {
            new Effect.Opacity(element, {duration:0.5, from:0.5, to:1.0});
        }
    });
}

// Sends refine search params to Ajax updater
function refineSearch()
{
    var formelm = $('refine-search-theform');
    var listings = $('search-results');
    var map = $('map-results');
    listings.innerHTML = 'Loading...';
    map.innerHTML = 'Loading...';
    var qs = '?refine=1';
    for (var i = 0; i < formelm.elements.length; i++) {
        if (formelm.elements[i].type == 'checkbox') {
            if (formelm.elements[i].checked) {
                qs += '&' + formelm.elements[i].name + '=' + formelm.elements[i].value;
            }
        }
        if (formelm.elements[i].type == 'select-one') {
            qs += '&' + formelm.elements[i].name + '=' + formelm.elements[i].value;
        }
        if (formelm.elements[i].type == 'hidden') {
            qs += '&' + formelm.elements[i].name + '=' + formelm.elements[i].value;
        }
    }
    new Ajax.Updater(listings, '/_ajax_refine_search_listings.php' + qs, {
        onComplete:function() {
            new Effect.Highlight(element, {evalScripts:true, duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
        }
    });
    new Ajax.Updater(map, '/_ajax_refine_search_map.php' + qs, {
        onComplete:function() {
            new Effect.Highlight(element, {evalScripts:true, duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
        }
    });
}

// Old skool new window
function newWin(url)
{
    var w = 960;
    var h = screen.height;
    var top = (screen.height-h)/2;
    var left = (screen.width-w)/2;
    window.open(url, 'homehound', 'top='+top+',left='+left+',width='+w+',height='+h+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
    return false;
}

// Adds an email to the friends list
function addEmail(element, url)
{
    new Ajax.Updater(element, url, {
        method: 'get'
    });
}

// Adds an email to the friends list if not logged in
function addEmailGuest(element, url)
{
    new Ajax.Updater(element, url, {
        method: 'get',
        onComplete: function() {
            new Ajax.Updater(element, url + '&refresh=true', {method: 'get'});
        }
    });
}

// deletes an email (or emails) from the friends list if not logged in
function confirmDeleteEmailsGuest(msg, element, url)
{
    if (confirm(msg)) {
        new Ajax.Updater(element, url, {
            method: 'get',
            onComplete:function() {
                new Ajax.Updater(element, url + '&refresh=true', {method: 'get'});
                new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
            }
        });
    } else {
        return false;
    }
}

// Puts the Update button back so email frequency can be updated
function restoreEmailFrequencySubmit(show, hide)
{
    $(show).show();
    $(hide).hide();
}

// Ajax Updater for email frequency
function updateEmailFrequency(element, url)
{
    new Ajax.Updater(element, url, {
        onComplete:function() {
            new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
        }
    });
}

// Ajax Updater used for logging printed pages and pin opens
function printProperty(element, url, pin)
{
    new Ajax.Updater(element, url);
}

// Ajax Updater
function updateWithAjax(element, url)
{
    new Ajax.Updater(element, url, {
        onComplete:function() {
            new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
        }
    });
}

// Ajax Updater
function updateShowEmailList(element, url)
{
    new Ajax.Updater(element, url, {
        onComplete:function() {
            if (!$('email-list').visible()) {
                Effect.toggle('email-list', 'blind', {duration: 0.4});
            }
            new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
        }
    });
}

// Ajax Updater with Confirm
function confirmUpdateWithAjax(msg, element, url)
{
    if (confirm(msg)) {
        new Ajax.Updater(element, url, {
            onComplete:function() {
                new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
            }
        });
    } else {
        return false;
    }
}

// Ajax Updater
function setApiKey(element, url)
{
    new Ajax.Updater(element, url, {
        onComplete:function() {
            new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#f4f4f4'});
        }
    });
}

// ---------- Google Maps ---------- //

// Gets the appropriate listing icon for map
function getGIcon(type,pin)
{
    var img = 'buy';
    if (pin != '') {
        img = pin;
    } else if (type == 'L' || type == 'H') {
        img = 'rent';
    } else if (type == 'A') {
        img = 'agent';
    } else if (type == 'SM') {
        img = 'multi-buy';
    } else if (type == 'LM' || type == 'HM') {
        img = 'multi-rent';
    }
    var icon = new GIcon();
    icon.image = 'http://hhimages.homehound.com.au/images/pins/pin-' + img + '.png';
    icon.shadow = 'http://hhimages.homehound.com.au/images/pins/pin-shadow.png';
    icon.iconSize = new GSize(30, 45);
    icon.shadowSize = new GSize(47, 45);
    icon.iconAnchor = new GPoint(15, 45);
    icon.infoWindowAnchor = new GPoint(15, 10);
    return icon;
}

function importanceOrder (marker,b) {
    return 999;
}
function is_array(input) {
    return typeof(input)=='object'&&(input instanceof Array);
}
function bubble_pagination_counter(increment) {
    $('bubble-count').update(parseInt($('bubble-count').innerHTML, 10) + increment);
}
function bubble_up(event) {
    var bubbles = $('listing-map-container').getElementsBySelector('.show');
    var shown = bubbles.first();

    if (shown.previous()) {
        shown.removeClassName('show').addClassName('hide');
        shown.previous().removeClassName('hide').addClassName('show');
        new Effect.Opacity(shown.previous(), {duration:0.5, from:0.5, to:1.0});
        bubble_pagination_counter(-1);
        if(!shown.previous().previous()) {
            $('bubble-up').setStyle({color: '#ff0000'});
        }
        $('bubble-down').setStyle({color: ''});
    }
}
bubble_up_bind = bubble_up.bindAsEventListener();

function bubble_down(event) {
    var bubbles = $('listing-map-container').getElementsBySelector('.show');
    var shown = bubbles.first();

    if (shown.next()) {
        shown.removeClassName('show').addClassName('hide');
        shown.next().removeClassName('hide').addClassName('show');
        new Effect.Opacity(shown.next(), {duration:0.5, from:0.5, to:1.0});
        bubble_pagination_counter(1);
        if (!shown.next().next()) {
            $('bubble-down').setStyle({color: '#ff0000'});
        }
        $('bubble-up').setStyle({color: ''});
    }
}
bubble_down_bind = bubble_down.bindAsEventListener();

// Displays a tooltip on a marker
function showTooltip(map, marker, tooltip)
{
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility = 'hidden';
    tooltip.innerHTML = marker.tooltip;
    var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0, 0), true), map.getZoom());
    var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
    var anchor = marker.getIcon().iconAnchor;
    var width = marker.getIcon().iconSize.width;
    var height = tooltip.clientHeight;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y - anchor.y - height)); 
    pos.apply(tooltip);
    tooltip.style.visibility = 'visible';
}

// Creates a marker at the given point
function createMarker(map, point, type, html, label, div, pin)
{
    var gicon = getGIcon(type,pin);
    var infowindowopen;
    var infowindowclose;
    var marker = new GMarker(point, {icon:gicon, zIndexProcess:importanceOrder});
    if (!is_array(div)) {
        div = new Array(div); // change variable div into an Array.
    }
    // If no html specified
    // don't show an infowindow
    if (html != '') {
        GEvent.addListener(marker, 'click', function() {
            if (type.indexOf('M') != -1) { // Only bind Listeneres if pin is multi dwelling
                infowindowopen = GEvent.addListener(map, 'infowindowopen', function() {
                    $('bubble-up').setStyle({color: '#ff0000'});
                    $('bubble-count').update(1);
                    $('bubble-up').update('<img width="11" height="13" src="/stylesheets/images/btn-thumb-prev.gif" alt="Previous property"/>');
                    $('bubble-down').update('<img width="11" height="13" src="/stylesheets/images/btn-thumb-next.gif" alt="Next property"/>');
                    $('bubble-up').observe('click', bubble_up_bind);
                    $('bubble-down').observe('click', bubble_down_bind);
                    infowindowclose = GEvent.addListener(map, 'infowindowbeforeclose', function() { // Cleaning up behaviours of a map bubble.
                        $('bubble-up').stopObserving('click', bubble_up_bind);                      // This events needs to be inside open event
                        $('bubble-down').stopObserving('click', bubble_down_bind);                  // as clicking on other pins will return errors.
                        GEvent.removeListener(infowindowopen);
                        GEvent.removeListener(infowindowclose);
                    });
                });
            }
            marker.openInfoWindowHtml(html);
            if (type != 'A') {
                printProperty('','/listing/_ajax_log_print.php?id='+div[0].replace("saved-property","")+'&pin=1','pin');
            } else if (type == 'A') {
                printProperty('','/listing/_ajax_log_print.php?agent_id='+div[0].replace("agent_","")+'&pin=1','pin');
            }

        });
    }
    // If no label text specified
    // don't show a tooltip
    if (label != '') {
        var img = 'buy';
        if (pin != '') {
            img = pin;
        } else if (type == 'L' || type == 'H') {
            img = 'rent';
        } else if (type == 'A') {
            img = 'agent';
        } else if (type == 'SM') {
            img = 'multi-buy';
        } else if (type == 'LM' || type == 'HM') {
            img = 'multi-rent';
        }
        var tooltip = document.createElement('div');
        marker.tooltip = '<div class="label">' + label + '</div>';
        GEvent.addListener(marker, 'mouseover', function() {
            marker.setImage('http://hhimages.homehound.com.au/images/pins/pin-' + img + '-hover.png');
            showTooltip(map, marker, tooltip);
            for (i=0; i<div.length;i++) {
                if (div[i] != '' && $(div[i])) {
                    if (div[i] != '' && $(div[i])) {
                        $(div[i]).addClassName('hilight');
                    }
                }
            }
        });
        GEvent.addListener(marker, 'mouseout', function() {
            marker.setImage('http://hhimages.homehound.com.au/images/pins/pin-' + img + '.png');
            tooltip.style.visibility = 'hidden';
            for (i=0; i<div.length;i++) {
                if (div[i] != '' && $(div[i])) {
                    $(div[i]).removeClassName('hilight');
                }
            }
        });
        // If no LHS div specified or the div doesn't exist
        // don't add mouse events
        for (i=0; i<div.length;i++) {
            if (div[i] != '' && $(div[i])) {
                $(div[i]).onmouseover = function() {
                    marker.setImage('http://hhimages.homehound.com.au/images/pins/pin-' + img + '-hover.png');
                    showTooltip(map, marker, tooltip);
                };
                $(div[i]).onmouseout = function() {
                    marker.setImage('http://hhimages.homehound.com.au/images/pins/pin-' + img + '.png');
                    tooltip.style.visibility = 'hidden';
                };
            }
        }
    }
    return marker;
}

// toggle info button your homehound
function toggleInformation(type, link_elm, show)
{
    if (show) {
        Position.absolutize(link_elm);
        var link_top = $(link_elm).getStyle('top');
        var link_left = $(link_elm).getStyle('left');
        var t = String(link_top.substring(0, (link_top.length - 2)));
        var l = String(link_left.substring(0, (link_left.length - 2)));

        switch (type) {
        case 'no_update_details':
            t -= 33;
            l -= 7;
            break;
        case 'no_register':
            t -= 33;
            l -= 107;
            break;
        case 'no_register_index':
            t -= 62;
            l -= 385;
            break;
        case 'no_map_results':
            t -= 62;
            l -= 384;
            break;
        case 'no_keywords':
            t -= 71;
            l -= 384;
            break;
        }
        if(type == 'no_keywords') {
            $('info_keyword').setStyle({
                top  : t + 'px',
                left : l + 'px'
            });
            Effect.Appear('info_keyword', {duration: 0.2});
        } else {
            $('info_update').setStyle({
                top  : t + 'px',
                left : l + 'px'
            });
            Effect.Appear('info_update', {duration: 0.2});
        }
    } else {
        var elm = (type == 'no_keywords') ? 'info_keyword' : 'info_update';
        Effect.Fade(elm, { duration: 0.4 });
    }
}

function toggleDuplicateSuburbsSubmit()
{
    var enabled = false;
    var inputs = $('search-error-form').getInputs('checkbox', 'suburb_id[]');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked) {
            enabled = true;
        }
    }
    if (enabled) {
        $('continue').show();
        $('continue-disabled').hide();
    } else {
        $('continue').hide();
        $('continue-disabled').show();
    }
}

function toggleCheckboxes(elm, action)
{
    var inputs = $(elm).getElementsBySelector('[type="checkbox"]');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].checked = (action == 'check') ? true : false;
    }
}

var tab_current = 'email-agent';
function toggleTabs(type,id)
{
    if (type == 'phone-agent') {
        new Ajax.Updater('', '/listing/_ajax_log_note.php?id='+id+'&contact=1', {method:'get'});
    }
    if (tab_current != type) {
        Effect.Fade(tab_current, {
            duration: 0,
            afterFinish: function() {
                Effect.Appear(type, {duration:0});
            }
        });
        $(tab_current.replace('-agent','-item')).className = tab_current.replace('-agent','-item');
        $(type.replace('-agent','-item')).className = type.replace('-agent','-item')+'-s';
        tab_current = type;
    }
}

// Ajax Updater for listing rate
function updateRateListing(element, url)
{
    new Ajax.Updater(element, url, {
        onComplete:function() {
            new Effect.Highlight(element, {duration:0.5, startcolor:'#ffeba6', endcolor:'#ffffff'});
        }
    });
    if (element == 'thumb-up') {
        Effect.Fade('thumb-down',{duration:0});
        $('thumb-up').setStyle({border:'none'});
    } else {
        Effect.Fade('thumb-up',{duration:0});
    }
}

//homehound valentines function
function specialEvent(){
    var x=document.getElementById("q");
    x.value='MUM';
    x.focus();
    ac.onKeyPress('press');
    new Ajax.Updater('', '_ajax_log_click.php');
}

//if checkbox is checked disable other checkboxes that have the corresponding ids in the ids array
function disableCheckbox(checkbox,ids){
    var count = 0;
    if(!checkbox.checked){
        for (count; count<ids.length; count++){
            var box=document.getElementById(ids[count]);
            box.disabled=true;    
        }
    } else {
        for (count; count<ids.length; count++){
            var box=document.getElementById(ids[count]);
            box.disabled=false;    
        }
    }
}

//function for opening external links on new windows
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   var rel = anchor.getAttribute("rel");
    if (anchor.getAttribute("href") && (rel == "external" || rel == "external nofollow")) {
        anchor.target = "_blank";
    }
 }
}

function trackEvent(category, action, label) {
    track_result = pageTracker._trackEvent(category, action, label);
}

Event.observe(window, 'load', function() {
    externalLinks();
    $$('h2.browse').each(function(s) {
        toggleSEOLinks(s);
        s.observe('click', function(event) {
            toggleSEOLinks(s);
        });
    });
    if (typeof(swfobject) == "object") {
        var flashvars = {};
        var attributes = {};
        var params = {};

        params.wmode = "transparent";

        swfobject.embedSWF("/media/ratesonline.swf?20100430", "ratesonline", "415", "200", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
        swfobject.embedSWF("/media/ratesonline-panel.swf?20091113", "ratesonline-panel", "420", "190", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
        swfobject.embedSWF("/media/ratesonline.swf?20100430", "ratesonline-fact-sheets", "415", "200", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

        //swfobject.embedSWF("/media/ratesonline-listing-details-300x250.swf?20100511", "ratesonline-listing-details-300x250", "300", "250", "9.0.0", "expressInstall.swf", {clickTAG:"http://www.ratesonline.com.au/hh/free-home-loan-advice"}, params, attributes);
        //swfobject.embedSWF("/media/ratesonline-search-results-250x600.swf?20100514", "ratesonline-search-results-250x600", "250", "600", "9.0.0", "expressInstall.swf", {clickTAG:"http://www.ratesonline.com.au/hh/free-home-loan-advice"}, params, attributes);
    }
    /* Easy Roommate JS */
    $$('body#search-results-body div.share-listing li.no-preview').each(function(s) {
        s.toggle();
    });

    /* Advertising Tabs */
    if ($$('div.advertising').length != 0) {
        $('market-trends').addClassName('inactive');
        $('market-trends').addClassName('js');

        $('tab-overview').observe('click', function() {
            $('market-trends').addClassName('inactive');
            $('overview').removeClassName('inactive');
        });

        $('tab-market-trends').observe('click', function() {
            $('overview').addClassName('inactive');
            $('market-trends').removeClassName('inactive');
        });
    }

    /* SMS */
    if ($$('div.sms').length != 0) {
        $$('li.sms a').first().observe('click', function() {
            $$('div.sms').first().toggleClassName('hide');
        });

        $$('a.sms_link').first().observe('click', function() {
            $$('div.sms').first().toggleClassName('hide');
        });

        $$('a.sms_close').first().observe('click', function() {
            closeSMS();
        });

        $$('div.message_ok a').first().observe('click', function() {
            closeSMS();
        });

        $('sms_mobile').observe('focus', function() {
            if (this.value == 'Enter your mobile number') {
                this.value = '04';
            }
        });

        $('sms_mobile').observe('blur', function() {
            if (this.value == '' || this.value == '04') {
                this.value = 'Enter your mobile number';
            }
        });

        $('sms_form').observe('submit', function() {
            sms_mobile = $('sms_mobile').value;
            sms_property_id = $('sms_property_id').value;
            if (sms_mobile != '' && sms_property_id != '') {
                $('sms_loading').removeClassName('hide');
                new Ajax.Updater('', '/listing/_ajax_send_sms.php?mobile='+sms_mobile+'&id='+sms_property_id, {
                    onComplete:function(sms_response) {
                        if (sms_response.responseText == 'error') {
                            $('sms_error').removeClassName('hide');
                        } else {
                            $$('div.message_preview').first().hide();
                            $$('div.message_form').first().hide();
                            $$('div.message_ok').first().removeClassName('hide');
                        };
                        $('sms_loading').addClassName('hide');
                    }
                });
            }
        });
    }

    $$('body#search-results-body div.share-listing h4').each(function(s) {
        s.observe('click', function(event) {
            // If first list item is hidden, display
            if (!s.next().descendants().first().visible()) {
                s.next().descendants().each(function(e) {
                    if (e.inspect() != '<span>') {
                        e.toggle();
                    }
                    /*if (e.hasClassName('preview')) {
                        e.toggle();
                    }*/
                });
                s.addClassName('expand');
            // Else if next item under the fold is hidden, display
            } else if (!s.next().descendants().first().next(2).visible()) {
                s.next().descendants().each(function(hiddenElement) {
                    Element.extend(hiddenElement); // Stops IE from return TypeErrors.
                    if (hiddenElement.hasClassName('no-preview') && !hiddenElement.hasClassName('preview')) {
                        hiddenElement.toggle();
                    } else if (hiddenElement.inspect() != '<span>') {
                        hiddenElement.addClassName('no-preview');
                    }
                });
                s.addClassName('expand');

            // Else hide everything.
            } else {
                s.next().descendants().each(function(e) {
                    if (e.hasClassName('no-preview')) {
                        e.toggle();
                    }
                });
                s.removeClassName('expand');
            }
        });
    });
    /* End Easy Roommate JS */
    revereGeocodeSearchResults();
});

function closeSMS() {
    $$('div.sms').first().addClassName('hide');
    $$('div.message_preview').first().show();
    $$('div.message_form').first().show();
    $$('div.message_ok').first().addClassName('hide');
    $('sms_error').addClassName('hide');
}

function toggleSEOLinks(e) {
    e.siblings().each(function(sibling) {
        sibling.toggle();
    });
    e.toggleClassName('collpased');

}

/*
*   OSA
*/
function getOASAdCode(sitepage, listpos, query, target){

    if (sitepage == undefined){
        sitepage = 'homehound.com.au';
    }
    if (listpos == undefined){
         listpos = 'Bottom,Top,Right2,x01,Middle1';
    }
    if (query == undefined){
        query = '';
    }
    if (target == undefined){
        target = '_top';
    }
   
    //configuration
    OAS_url = 'http://oascentral.homehound.com.au/RealMedia/ads/';
    //OAS_sitepage = window.location.hostname + window.location.pathname;
    OAS_sitepage = sitepage;
    OAS_listpos = listpos;
    OAS_query = query;
    OAS_target = target;
    //end of configuration
    OAS_version = 10;
    OAS_rn = '001234567890'; 
    OAS_rns = '1234567890';
    OAS_rn = new String (Math.random()); OAS_rns = OAS_rn.substring (2, 11);
    
    OAS_version = 11;
    if (navigator.userAgent.indexOf('Mozilla/3') != -1 || navigator.userAgent.indexOf('Mozilla/4.0 WebTV') != -1)
      OAS_version = 10;
    if (OAS_version >= 11)
      document.write('<SCRIPT LANGUAGE=JavaScript1.1 SRC="' + OAS_url + 'adstream_mjx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '?' + OAS_query + '"><\/SCRIPT>');

    document.write('');

}

function OAS_AD(pos) {
    if (OAS_version >= 11) OAS_RICH(pos);
    else OAS_NORMAL(pos);
}

function OAS_NORMAL(pos) {
      document.write('<A HREF="' + OAS_url + 'click_nx.cgi/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" TARGET=' + OAS_target + '>');
      document.write('<IMG SRC="' + OAS_url + 'adstream_nx.cgi/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" BORDER=0></A>');
}

function revereGeocodeSearchResults() {
    if ($$('body#search-results-body span.suburb-name').length && (location.hash != '')) {
        var hash = location.hash.replace('#', '');
        var hash = hash.split(',');
        var lat = parseFloat(hash[0]);
        var lng = parseFloat(hash[1]);
        var latlng = new GLatLng(lat, lng);
        var geocoder = new GClientGeocoder();
        var sourcedlocation = geocoder.getLocations(latlng, function(response) {
            if (response && response.Status.code == 200) {
                $$('body#search-results-body span.suburb-name').first().update(response.Placemark[0].address);
            }
        });
    }
}


function google_ad_request_done(google_ads) {
    /*
    * This function is required and is used to display
    * the ads that are returned from the JavaScript
    * request. You should modify the document.write
    * commands so that the HTML they write out fits
    * with your desired ad layout.
    */
    var s = '';
    var i;

    /*
    * Verify that there are actually ads to display.
    */
    if (google_ads.length == 0) {
        return;
    }


    if (google_ads.length) {

        try {
            if (homehound_google == 'serp') {
                s += '<a href=\"' + google_info.feedback_url + '\" style="color:000000">Ads by Google</a><br>'

                for (i = 0; i < google_ads.length; ++i) {

                    s += '<br><a class="serp-ad-title" href="' +
                    google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
                    google_ads[i].visible_url + '\';return true">' +
                    google_ads[i].line1 + '<br></a> <span class="serp-ad-text">' +
                    google_ads[i].line2 + 
                    google_ads[i].line3 + '<br></span> <a class="serp-ad-link" href="' +
                    google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
                    google_ads[i].visible_url + '\';return true">' +
                    google_ads[i].visible_url + '</a><br>';
                }
            } else if (homehound_google == 'home') {
                s += '<ul id="ads">';
                s += '<li id="ads-by-google"><a href=\"' + google_info.feedback_url + '\">Ads by Google</a></li>';
                for (i = 0; i < google_ads.length; ++i) {
                    if ((i + 1) == google_ads.length) {
                        var li_class = ' class="last"';
                    } else {
                        var li_class = '';
                    }

                    s += '<li' + li_class + '><h3><a class="serp-ad-title" href="' +
                    google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
                    google_ads[i].visible_url + '\';return true">' +
                    google_ads[i].line1 + '</h3></a> <span class="serp-ad-text">' +
                    google_ads[i].line2 + '<br>' +
                    google_ads[i].line3 + '</span><br><a class="serp-ad-link" href="' +
                    google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
                    google_ads[i].visible_url + '\';return true">' +
                    google_ads[i].visible_url + '</a><br></li>';
                }
                s += '</ul>';
                s += '</div>';
            } else {
                throw('Unkown homehound_google value: ' + homehound_google);
            }
        } catch(err) { 
                /* Default behaviour */
                s += '<a href=\"' + google_info.feedback_url + '\" style="color:000000">Ads by Google</a><br>'

                for(i = 0; i < google_ads.length; ++i) {

                s += '<br><a style="text-decoration:none" href="' +
                google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
                google_ads[i].visible_url + '\';return true"> <span style="text-decoration:underline"> <b>' +
                google_ads[i].line1 + '</b><br></span></a> <span style="color:#000000">' +
                google_ads[i].line2 + '<br>' +
                google_ads[i].line3 + '<br></span> <span><a style="color:#008000;text-decoration:none" href="' +
                google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' +
                google_ads[i].visible_url + '\';return true">' +
                google_ads[i].visible_url + '</span></a><br>';

            }
        }

    }
    document.write(s);
    return;
}
