function find_dependencies(field) {
    /* Walk backwards up the tree to find all dependent fields */
    var dep_list = [];
    dep_list = dep_list.concat(field);
    //alert('finding dependencies for ' + field);
    $("[class*=ajax_notify_" + field + "]").each(function(i) {
        dep_list = dep_list.concat(find_dependencies([$(this).attr('id').slice(3)]));
    });
    return dep_list;

}
function notify_field(recipient) {
    var field, dependencies, url, field_value, i, key,
        recipient_object = $('#id_' + recipient);
    if (!recipient_object.length)  {
        return;
    }
    dependencies = find_dependencies([recipient])
    //Remove first element since we know we are a dependency
    dependencies.reverse().pop();
    url = '/search/ajax/dd_list/?attribute=' + recipient + '&criteria={' ;
    for (field in dependencies) {
       field_value = $('#id_' + dependencies[field]).val();
       if(!field_value || field_value == 'all') {
            continue; 
       }
       url += '"' +  dependencies[field] + '":[';
       if (!(field_value instanceof Array)){
           field_value = Array(field_value);
       }
       for (i in field_value) {
            url += '"' + escape(field_value[i]) + '",';
       }
        //Remove last comma
        url = url.slice(0, -1);
       url += ']';
       url += ',';
    }
    //Remove last comma
    if (url.slice(-1) == ',') {
        url = url.slice(0, -1);
    }
    url += '}';
    
    key = recipient_object.attr('class').match(/key_([\w-]+)/);
    if (key) {
        key = key[1];
        url += '&key=' + key;
    }
    
    $.getJSON(url,function(data){
        var line, notify,
            rec_obj = $('#id_' + recipient),
            options = ['<option value="all" selected="selected">' + $(rec_obj[0][0]).html() + '</option>'],
            buildOption = function(i) {
                var val = data[i];
                options.push('<option value="');
                options.push(val);
                options.push('">');
                options.push(val);
                options.push('</option>');
            };
        
        $.each(data, buildOption);
        options = options.join('');
        fastReplaceSelectHtml(rec_obj, options);
        notify = recipient_object.attr('class').match(/ajax_notify_(\w+)/);
        if (notify) {
            notify = notify[1];
        }
        notify_field(notify);
    });
}

function fastReplaceSelectHtml($select, optionsHTML) {
    var beginSelect;
    if ($.browser.msie) { 
        beginSelect = $select[0].outerHTML.match(/(<select[^>]+)/im)[1];
        $select[0].outerHTML = beginSelect + '>' + optionsHTML + '</select>';
    } else {
        $select[0].innerHTML = optionsHTML;
    }
}

function verify_nums() {
    var regex = /^(\d+|(\d+,))+$/
	if($('#mls_number').val().match(regex)) {
		return true;
	}
	alert('Please check the format of the MLS numbers you entered. To search multiple MLS numbers, place a comma in between each number. (e.g. 435666,423432,653654)');
	return false;
}

function addCommas(nStr)
 {
   nStr += '';
   x = nStr.split('.');
   x1 = x[0];
   x2 = x.length > 1 ? '.' + x[1] : '';
   var rgx = /(\d+)(\d{3})/;
   while (rgx.test(x1)) {
     x1 = x1.replace(rgx, '$1' + ',' + '$2');
   }
   return x1 + x2;
}

function calc() {
    p = $('#loan_amount').val();
    i = $('#annual_interest_rate').val()/100/12;
    n = $('#term_of_loan').val() * 12;
    left = p * i * Math.pow(1 + i,n)
    right = Math.pow(1 + i,n) -1
    m = left / right
    $('#payment').html('Monthly Loan Payment: <strong>$' + addCommas(Math.round(m)) + '</strong>');
}

function submit_search() {
    if (typeof pageTracker !== 'undefined') {pageTracker._trackPageview('/goals/search/');}
    if ($('#id_island').length == 0 && $('#id_region').val() == 'all') {
      alert('Please choose a region for your search')
      return;
    }
    document.big_search.submit();
}

function setpng(elt, src) {
    $(elt).attr('src',src); 
	if ($.browser.msie && $.browser.version < 7) {
        $(elt).ifixpng();
    }
}

function choose_island(island) {
    $("select#id_island").val(island).change();
    update_map();
}

function choose_region(region) {
    $("select#id_region").val(region).change();
}

function update_map() {
    var map = $('#map-box');
    if (map.length == 0) {
        return;
    }
    map.load(
        "/imagemap/ajax/get_map/",
        { island: $("select#id_island").val() },
        function(responseText,textStatus,XMLHttpRequest) {
            if ($.browser.msie && $.browser.version < 7) {
                // transparent png fix for ie6
                src = $("#Image1").attr('src');
                                 $("#Image1").css('filter', "progid:DXImageTransform."
                                  + "Microsoft.AlphaImageLoader(src='"
                                   + src + "', sizingMethod='scale');");     
                $("#Image1").attr('src','../img/transparentpixel.gif');
        	} 
        }
    );
}

$(document).ready(function() {
    $("[class*='ajax_notify']").bind("change",function(e){
        var recipient = $('#' + e.target.id),
            field = recipient.attr('class').match(/ajax_notify_(\w+)/)[1];
        notify_field(field);
        if (e.target.id == 'id_island') {
            update_map();
        }
    });
});
