/* Print */
var message = "Print this Page";
function printpage(o){
    alert("Please set your printer orientation to " + o +" and your paper size to A4")
    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);
        } 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 == "property_type") {
        $("#property_type").html(default_options);
        $("#property_type").attr("disabled","disabled");
    } else if (which == "area") {
        reset_selects("suburb");
        reset_selects("property_type");
        $("#area").html(please_select);
        $("#area").attr("disabled","disabled");
    } else if (which == "suburb") {
        reset_selects("property_type");
        $("#suburb").html(default_options);
        $("#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_areas(listing_type) {
    var selected_listing_type = listing_type.value;
	var branch_id = $("#id_branch").val();

    if (listing_type.selectedIndex != 0) {
        $.getJSON("/ajax/select_data/"+ selected_listing_type +"/?branch_id=" + branch_id , function(data) {
            reset_selects("area");
            $.each(data, function(item) {
                $("#area").append("<optgroup label='"+ this.province +"'>");
                $.each(this.regions, function(i) {
                    $("#area").append($("<option />").val(this.region).text(this.region + " ("+ this.count +")"));
                });
                $("#area").append("</optgroup>");
            });
            $("#area").removeAttr("disabled");
            update_price_ranges();
        });
    } else {
        reset_selects("area");
    }
}

function set_suburbs(area) {
    var selected_listing_type = $("select[name='listing_type']").val();
    var selected_area = area.value;
	var branch_id = $("#id_branch").val();

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

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;
	var branch_id = $("input[name='branch']").val();

    if (suburb.selectedIndex != 0) {
	    $("#listing_type").val(selected_listing_type);
        $.getJSON("/ajax/select_data/"+ selected_listing_type + "/"+ selected_area +"/" + selected_suburb +"/?branch_id=" + branch_id , 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 listing_type = $("select[name='listing_type']").val();
    var area = $("select[name='area']").val();
    var suburb = $("select[name='suburb']").val();
    var property_type = $("select[name='property_type']").val();
    var price_range = $("select[name='price_range']")
	var branch_id = $("input[name='branch']").val();

    html = "<option>Please select</option>";
    price_range.html(html);

    if ("" != listing_type) {
        // Find appropriate ranges
        price_range.append($("<option />").val('All').text('All'));
        $.getJSON("/ajax/select_data_price_ranges/", { listing_type: listing_type,
                area: area, suburb: suburb, property_type: property_type, branch_id: branch_id }, 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);
                    }
                });
            }
        });
    }
}

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 display_welcome_message() {
    $.post('/ajax/welcome-message/', function(data) {
        if (data == 'welcome_screen') {	
            $('#id_welcome_message').dialog('open');
        }
    });
}

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);
});


