/* Print */
var message = "Print this Page";
function printpage(o){
    alert("Please set your printer orientation to " + o +" and your paper size to Letter")
    window.print()
}

function validate_listing_search() {
    if ($('#listing_type').val() == '') {
        alert("Please select a listing type");
        return false;
    } else {
        return true;
    }
}

/* Bookmark */
function bookmarksite(title,url) {
	if ((navigator.appName == 'Microsoft Internet Explorer') && (document.all)) { 
		window.external.AddFavorite(url, title);
	} else if (window.sidebar) { 
		window.sidebar.addPanel(title, url, "");
	} else { 
		alert('Press CTRL-D to bookmark this page.'); 
	}
}

function bookmark(type) {
    var temp_url = parent.window.location + "";
    var current_url = temp_url.substring(0,temp_url.length - 1);
    var doctitle = parent.document.title ;
    
    if (type != null) {
        if (type == 'delicious') {
            window.open("http://del.icio.us/post?title=" + doctitle + "&url=" + current_url );
        } else if (type=='twitter') {
            window.open("http://twitter.com/home?status=Check This Out... "+ current_url + "&title=" + doctitle);
        } else if (type=='google') {
            window.open("http://www.google.com/bookmarks/mark?op=add&bkmk=" + current_url + "&title=" + doctitle);
        } else if (type=='facebook') {
            window.open("http://www.facebook.com/share.php?u=" + current_url + "&title=" + doctitle);
        } else if (type=='digg') {
            window.open("http://digg.com/submit?url=" + current_url + "&title=" + doctitle);
        } else if (type=='stumbleupon') {
            window.open("http://www.stumbleupon.com/submit?url=" + current_url + "&title=" + doctitle);
        } else if (type=='windows') {
            window.open("http://www.live.com/?add=" + current_url + "&title=" + doctitle);
        }   
    }
}

function reset_selects(which) {
    var please_select = '<option value="">Please select</option>';
    var default_options = please_select + '<option value="All">All</option>';
    if (which == "sub_type") {
        reset_selects("beds");
        $("#sub_type").html('<option value="">Please select a city</option>');
    } else if (which == "area") {
        reset_selects("area");
        reset_selects("property_type");
        $("#area").html('');
        $("#area").attr("disabled","disabled");
    } else if (which == "suburb") {
        reset_selects("property_type");
        $("#suburb").html('');
        $("#suburb").attr("disabled","disabled");
    } else if (which == "price_from") {
        $("#price_from").html(default_options);
        $("#price_from").attr("disabled","disabled");
    } else if (which == "price_to") {
        $("#price_to").html(default_options);
        $("#price_to").attr("disabled","disabled");
    }
}

function set_cities() {
  $.getJSON("/ajax/select_data/cities/", function(data) {
    $("#city").dropdownchecklist("destroy");
    reset_selects("sub_type");
    $.each(data, function(item) {
      $.each(data[item], function(city) {
        $("#city").append($("<option />").val(this.city_slug).text(this.city));
      });
    });
    $("#city").dropdownchecklist({icon: {}, width: "280px", maxDropHeight: "200px", emptyText: "Please select"});
  });
}

function set_waterfront_options() {
  $.getJSON("/ajax/select_data/waterfront-options/", function(data) {
    $("#waterfront").dropdownchecklist("destroy");
    $.each(data, function(item) {
      $("#waterfront").append($("<option />").val(data[item]).text(data[item]));
    });
    $("#waterfront").dropdownchecklist({icon: {}, width: "120px", maxDropHeight: "200px", emptyText: "Optional"});
  });
}

function set_alert_cities() {
  $.getJSON("/ajax/select_data/cities/?hide_counters=true", function(data) {
      $.each(data, function(item) {
          $.each(data[item], function(city) {
            $("#county_city").append($("<option />").val(this.city_slug).text(this.city));
          });
      });
  });
}

function update_results_count() {
  $.getJSON("/ajax/results_count/",
      {
        "cities[]": $("#city").val(),
        "sub_type[]": $("#sub_type").val(),
        "waterfront[]": $("#waterfront").val(),
        "beds[]": $("#beds").val(),
        "baths[]": $("#baths").val(),
        "living_area[]": $("#living_area").val(),
        "garages[]": $("#garages").val(),
        "short_sales[]": $("#short_sales").val(),
        "price_range[]": $("#price_range").val()
      }, function(data) {
    $("#view_results").val("View Results ("+ data +")");
  });
}

function set_sub_types(city) {
  var selected_cities = $(city).val();

  $("#sub_type").val(selected_cities);
  $.getJSON("/ajax/select_data/"+ selected_cities +"/" , function(data) {
      $("#sub_type").dropdownchecklist("destroy");
      reset_selects("sub_type");
      $("#sub_type").html('');
      $.each(data, function(item) {
        $("#sub_type").append($("<option />").val(this.sub_type_slug).text(this.sub_type));
      });
    $("#sub_type").dropdownchecklist({icon: {}, width: "160px", maxDropHeight: "200px", emptyText: "Please select"});
  });
}

function set_beds() {
  var city = $("select[name='city']").val();
  var sub_type = $("select[name='sub_type']").val();

  if (city.selectedIndex != 0) {
    //$("#beds").val(selected_beds);
    $.getJSON("/ajax/select_data/"+ city +"/"+ sub_type +"/" , function(data) {
        reset_selects("beds");
        $.each(data, function(item) {
          $("#beds").append($("<option />").val(this.bedrooms).text(this.bedrooms_text));
        });
      $("#beds").removeAttr("disabled");
      update_price_ranges();
    });
  } else {
    reset_selects("beds");
  }
}

function set_property_types(suburb) {
    var selected_listing_type = $("select[name='listing_type']").val();
    var selected_area = $("select[name='area']").val();
    var selected_suburb = suburb.value;

    if (suburb.selectedIndex != 0) {
	    $("#listing_type").val(selected_listing_type);
        $.getJSON("/ajax/select_data/"+ selected_listing_type + "/"+ selected_area +"/" + selected_suburb +"/", function(data) {
            reset_selects("property_type");
            $.each(data, function(item) {
                $("#property_type").append($("<option />").val(this.property_type).text(this.property_type + " ("+ this.count +")"));
            });
            $("#property_type").removeAttr("disabled");
            update_price_ranges();
        });
    } else {
        reset_selects("property_type");
    }
}

function update_price_ranges() {
    var city = $("select[name='city']").val();
    var sub_type = $("select[name='sub_type']").val();
    var min_beds = $("select[name='beds']").val();
    var price_range = $("select[name='price_range']")
    
    html = "<option>Please select</option>";
    price_range.html(html);

    if ("" != city) {
        // Find appropriate ranges
        price_range.append($("<option />").val('All').text('All'));
        $.getJSON("/ajax/select_data_price_ranges/", { city: city,
                sub_type: sub_type, min_beds: min_beds }, function(data) {
            $.each(data, function(i, item) {
                price_range.append($("<option />").val(item.value).text(item.text + " ("+ item.count +")"));
            });
            // Select option
            qs = new Querystring();
            pr = qs.get('price_range');
            if ("All" != pr && "Please select" != pr) {
                $("select[name='price_range'] option").each(function() {
                    if (this.value == pr) {
                        price_range.val(pr);
                    }
                });
            }
        });
        if (min_beds) {
          $("#price_range").removeAttr("disabled");
        }
    }
}

function set_price_range(listing_type, price_from, price_to) {
    var selected_listing_type = listing_type.value;

    if (listing_type.selectedIndex != 0) {
    	$.getJSON("/ajax/price_range/"+ selected_listing_type + "/", function(data) {
			reset_selects("price_from");
            reset_selects("price_to");
            $.each(data, function(item) {
    			$("#price_from").append($("<option />").val(this.value).text(this.text));
                $("#price_to").append($("<option />").val(this.value).text(this.text));
            });
            if (price_from) {
                $("#price_from option[value=" + price_from +"]").attr("selected", "selected");
            }
            if (price_to){
                $("#price_to option[value=" + price_to + "]").attr("selected", "selected");
            }
            $("#price_from").removeAttr("disabled");
            $("#price_to").removeAttr("disabled");
        });
    } else {
		  reset_selects("price_from");
      reset_selects("price_to");
    }
}

function validate_email_friend(name, email, rec_name, rec_email, form) {
    if ($('#'+name).val() == 'Your Name *'){
        alert('Please enter your name.');
    } else if($('#'+email).val() == 'Your Email Address *'){
        alert('Please enter your email.');
    } else if (!(val_email($('#'+email)))){
        alert('Please enter a valid email address.');
    } else if($('#'+rec_name).val() == 'Recipients Name *'){
        alert('Please enter your recipient\'s name.');
    } else if($('#'+rec_email).val() == 'Recipients Email Address *'){
        alert('Please enter your recipient\'s email.');
    } else if(!(val_email($('#'+rec_email)))){
        alert('Please enter a valid recipient\'s email address.');
    } else {
        $('#'+form).submit();
    }
}

function val_email(ele) { 
    if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($(ele).val()) == false){
	    return false; 
    } else {
        return true;
    }
}

function change_active_img(current_image, direction, gallery_size) {
    current_image = parseInt(current_image);
    (direction=='next') ? next=current_image+1 : next=current_image-1 ;
    if (next==0) next = gallery_size; 
    else if (next>gallery_size) next = 1;             

    $('#id_img'+(current_image)).hide();
    $('#id_img'+(next)).show();
    $('#current_image').html(next);
}

function display_confirmation() {
    $.post('/ajax/delete-session/confirm_msg/', function(data) {
        if (data != '') {
            $('#id_confirmation').show();
            $('#id_confirmation_p').html(data);
            $('#id_confirmation').dialog({'modal': true});
        }
    });
}

function M_getEventTarget(e) {
    var src = e.srcElement ? e.srcElement : e.target;
    return src;
}

function M_keyPressCommon(evt, handler, input_handler) {
    var evt = (evt) ? evt : ((event) ? event : null);
    if (evt) {
        var src = M_getEventTarget(evt);
        var nodename = src.nodeName;
        var key, code;
        if (evt.keyCode) {
            code = evt.keyCode;
        } else if (evt.which) {
            code = evt.which;
        }
        key = String.fromCharCode(code);
        if (nodename == "TEXTAREA" || nodename == "INPUT" ) {
            if (typeof input_handler != 'undefined') {
                return input_handler(evt, src, code, key);
            }
            return true;
        }
        if (evt.altKey || evt.altLeft ||
            evt.ctrlKey || evt.ctrlLeft ||
            evt.metaKey) {
            // Ignore if any modifier keys are set
            return true;
        }

        if (key == '?' || code == (window.event ? 27 /* ESC */ : evt.DOM_VK_ESCAPE)) {
            if ($('#id_about').dialog("isOpen")) {
                $('#id_about').dialog('close');
            } else {
                $('#id_about').dialog('open');
            }
            return false;
        }
    }
    return true;
}

function M_dashboardKeyPress(evt) {
    return M_keyPressCommon(evt, function(key) {});
}

$().keypress(function(evt) {
    return M_dashboardKeyPress(evt);
});


