
$(document).ready(function () {
    
    /* Refine Bar, Property Type */
    $('input.idx-search-type, select.idx-search-type').bind('click', function () {
        
        /* Selected Type */
        type = $(this).val();

        /* Random Process ID */
        pid = Math.random() * 5;
        
        /* Price Ranges */
        if (type in {'Rental' : true, 'Lease' : true, 'Residential Lease' : true, 'Commercial Lease' : true}) {
            
            /* Show Rental Prices */
            $('#search_rent').show().find('select').removeAttr('disabled');
            
            /* Hide Price Ranges */
            $('#search_price').hide().find('select').attr('disabled', 'disabled');
            
        } else {
         
            /* Show Price Ranges */
            $('#search_price').show().find('select').removeAttr('disabled');
            
            /* Hide Rental Prices */
            $('#search_rent').hide().find('select').attr('disabled', 'disabled');
            
        }
        
        /* Sub-Type Selection */
        if ($('select[name="search_subtype"]').length > 0) {
            
            $.ajax({
                'url'      : '/idx/inc/php/ajax/json.php?searchTypes',
                'type'     : 'POST',
                'dataType' : 'json',
                'data'     : {
                    'pid' : pid,
                    'search_type' : type
                },
                'error'    : function (XMLHttpRequest, textStatus, errorThrown) {
                    $('input[name="search_subtype"]').hide();
                },
                'success'  : function (json, textStatus) {
                    if (typeof(json) == 'undefined' || !json) return;
                    if (typeof(json.pid) != 'undefined') {
                        if (json.pid != pid) {
                            return;
                        }
                    }
                    if (json.returnCode == 200) {
                        var html = '<select name="search_subtype">' + "\n";
                        
                        if (type == '') {
                            html += '<option value="">All Properties</option>' + "\n";
                        } else {
                            html += '<option value="">All ' + type + '</option>' + "\n";
                        }
    
                        if (json.options.length > 0) {
                            var i = 0, len = json.options.length;
                            var subtype = $('select[name="search_subtype"]').val();
                            while (i < len) {
                                var checked = (subtype == json.options[i].value) ? ' selected="selected"' : '';
                                html += '<option value= "' + json.options[i].value + '"' + checked + '>' + json.options[i].title + '</option>' + "\n";
                                i++;
                            }
                        }
    
    
                        html += '</select>';
                        var parent = $('select[name="search_subtype"]').parent();
                        $('select[name="search_subtype"]').remove();
                        parent.append(html);
    
                    }
                }
            });
            
        }
        
    });
    $('input.idx-search-type:checked, select.idx-search-type').trigger('click');
});

/* Enable Location Fields */
function enableLocations () {

    /* Return if Bounds Checked */
    if ($('input[name="map[bounds]"]').attr('checked')) return disableLocations();

    /* Return if PolygonSearch Exists */
    if (polygonControl != null || (polygonControl && polygonControl.polygonSearch)) return disableLocations();

    /* Return if RadiusSearch Exists */
    if (radiusControl && radiusControl._radiusSearches && radiusControl._radiusSearches.length != 0) return disableLocations();

    var $form = $('#idx-map-form');
    $form.find('input.location').removeAttr('disabled');
    $form.find('select.location').removeAttr('disabled');
    
    var $form = $('#searchForm');
    $form.find('input.location').removeAttr('disabled');
    $form.find('select.location').removeAttr('disabled');

    var $form = $('#idx-builder');
    $form.find('input.location').removeAttr('disabled');
    $form.find('select.location').removeAttr('disabled');

};

/* Disable Location Fields */
function disableLocations () {

    var $form = $('#idx-map-form');
    $form.find('input.location').attr('disabled', 'disabled');
    $form.find('select.location').attr('disabled', 'disabled');
    
    var $form = $('#searchForm');
    $form.find('input.location').attr('disabled', 'disabled');
    $form.find('select.location').attr('disabled', 'disabled');

    var $form = $('#idx-builder');
    $form.find('input.location').attr('disabled', 'disabled');
    $form.find('select.location').attr('disabled', 'disabled');

};

function urldecode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +   improved by: Orlando
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      bugfixed by: Rob
    // %        note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // %        note 2: Please be aware that this function expects to decode from UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    return decodeURIComponent(str.replace(/\+/g, '%20'));
}

function parse_str (str, array){
    // http://kevin.vanzonneveld.net
    // +   original by: Cagri Ekin
    // +   improved by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   reimplemented by: stag019
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: stag019
    // -    depends on: urldecode
    // +   input by: Dreamer
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: When no argument is specified, will put variables in global scope.
    // *     example 1: var arr = {};
    // *     example 1: parse_str('first=foo&second=bar', arr);
    // *     results 1: arr == { first: 'foo', second: 'bar' }
    // *     example 2: var arr = {};
    // *     example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
    // *     results 2: arr == { str_a: "Jack and Jill didn't see the well." }

    var glue1 = '=', glue2 = '&', array2 = String(str).replace(/^&(.*)$/, '$1').replace(/^(.*)&$/, '$1').split(glue2),
    i, j, chr, tmp, key, value, bracket, keys, evalStr, that = this,
    fixStr = function (str) {
        return that.urldecode(str).replace(/([\\"'])/g, '\\$1').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
    };

    if (!array) {
        array = this.window;
    }

    for (i = 0; i < array2.length; i++) {
        tmp = array2[i].split(glue1);
        if (tmp.length < 2) {
            tmp = [tmp, ''];
        }
        key   = fixStr(tmp[0]);
        value = fixStr(tmp[1]);
        while (key.charAt(0) === ' ') {
            key = key.substr(1);
        }
        if (key.indexOf('\0') !== -1) {
            key = key.substr(0, key.indexOf('\0'));
        }
        if (key && key.charAt(0) !== '[') {
            keys    = [];
            bracket = 0;
            for (j = 0; j < key.length; j++) {
                if (key.charAt(j) === '[' && !bracket) {
                    bracket = j + 1;
                }
                else if (key.charAt(j) === ']') {
                    if (bracket) {
                        if (!keys.length) {
                            keys.push(key.substr(0, bracket - 1));
                        }
                        keys.push(key.substr(bracket, j - bracket));
                        bracket = 0;
                        if (key.charAt(j + 1) !== '[') {
                            break;
                        }
                    }
                }
            }
            if (!keys.length) {
                keys = [key];
            }
            for (j = 0; j < keys[0].length; j++) {
                chr = keys[0].charAt(j);
                if (chr === ' ' || chr === '.' || chr === '[') {
                    keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
                }
                if (chr === '[') {
                    break;
                }
            }
            evalStr = 'array';
            for (j = 0; j < keys.length; j++) {
                key = keys[j];
                if ((key !== '' && key !== ' ') || j === 0) {
                    key = "'" + key + "'";
                }
                else {
                    key = eval(evalStr + '.push([]);') - 1;
                }
                evalStr += '[' + key + ']';
                if (j !== keys.length - 1 && eval('typeof ' + evalStr) === 'undefined') {
                    eval(evalStr + ' = [];');
                }
            }
            evalStr += " = '" + value + "';\n";
            eval(evalStr);
        }
    }
}$(document).ready(function () {

    /* My Bookmarked Listings */
    $('#navi-favorites').hoverIntent(
        function(){
            if ($('#favs-menu').hasClass('loaded')) {
            } else {
                $('#favs-menu').load('/idx/inc/php/ajax/favourites.php', function () {
                    $(this).addClass('loaded');
                    $('#favs-menu .photos img').rewImgSizer({ method: 'crop', scale: 1.25 });
                });
            }
            $('#favs-menu').fadeIn();
            $(this).addClass('hover');
        },
        function(){
            $('#favs-menu').hide();
            $(this).removeClass('hover');
        }
    );

    /* My Saved Searches */
    $('#navi-searches').hoverIntent(
        function(){
            if ($('#searches-menu').hasClass('loaded')) {
                $('#searches-menu').show();
            } else {
                $('#searches-menu').load('/idx/inc/php/ajax/saved_searches.php', function () {
                    $(this).addClass('loaded').show();
                });
            }
            $('#searches-menu').fadeIn();
            $(this).addClass('hover');
        },
        function(){
            $('#searches-menu').hide();
            $(this).removeClass('hover');
    });

    $('#navi-searches').live('mouseout', function() {
        $('#searches-menu').hide();
    });

});
/* hide while loading */
$('#feature .panes').css({'position':'absolute', 'left':'-999em'});

/* Onload */
$(document).ready(function () {

    $("ul.tabs").tabs("div.panes > div",{
        'tabs'    : 'li',
        'effect'  : 'fade',
        'onClick' : function() {
            $('#feature .photo img:visible').not('.fixed').each(function(){
                $(this).css({width:'auto', height:'auto'}).rewImgSizer({method:'crop'}).addClass('fixed');
            });
        }
    });
    
        
    	$('#feature .panes').css({'position':'relative', 'left':'0'});
    
    
                        $(document).ready(function () {
                $('#lec5-find-homes form').bind('change', function () {
                    $('span.idx-results-count').text('Searching...');
                    $.ajax({
                        'url'      : '/idx/inc/php/ajax/json.php?searchCount',
                        'data'     : $(this).serialize(),
                        'type'     : 'POST',
                        'dataType' : 'json',
                        'cache'    : false,
                        'success'  : function (data, textStatus, XMLHttpRequest) {
                            if (typeof(data.count) != 'undefined' && data.count > 0) {
                                var properties_count = data.count.toLocaleString();
                                if (properties_count.indexOf('.') != -1) {
                                    properties_count = properties_count.substr(0, properties_count.indexOf('.'));
                                }
                                $('span.idx-results-count').text(properties_count + ' Properties');
                            } else {
                                $('span.idx-results-count').text('Zero Properties');
                            }
                        }
                    });
                }).trigger('change');
            });
            
});
