$(document).ready(function(){
	$(".opaque").fadeTo("slow", 1.0);
	$(".opaque").hover(function(){
	$(this).fadeTo("slow", 0.5);
	},function(){
	$(this).fadeTo("slow", 1.0);
	});
});


$(document).ready(function(){
	$(".selected-work").fadeTo("slow", 1.0);
	$(".selected-work").hover(function(){
	$(this).fadeTo("slow", 0.5);
	},function(){
	$(this).fadeTo("slow", 1.0);
	});
});

/* 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 embedObject(flash_file, width, height) {
	document.write('<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" width=\"'+width+'\" height=\"'+height+'\">' +
	'    <param name=\"movie\" value=\"'+flash_file+'\" />' +
	'    <param name=\"quality\" value=\"high\" />' +
	'	 <param name=\"wmode\" value=\"transparent\" />' +
	'    <embed src=\"'+flash_file+'\" quality=\"high\" wmode=\"transparent\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"'+width+'\" height=\"'+height+'\"></embed>' +
	'  </object>');
}

/* Bookmark */
function bookmarksite(title,url) {
    if (window.sidebar) { // firefox
        window.sidebar.addPanel(title, url, "");
    } else if(window.opera && window.print) { // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    } else if(document.all) { // ie
        window.external.AddFavorite(url, title);
    }
}

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 == "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;

    if (listing_type.selectedIndex != 0) {
        $.getJSON("/ajax/select_data/"+ selected_listing_type +"/" , 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");
        });
    } else {
        reset_selects("area");
    }
}

function set_suburbs(area) {
    var selected_listing_type = $("select[name='listing_type']").val();
    var selected_area = area.value;

    if (area.selectedIndex != 0) {
	    $("#area").val(selected_area);
        $.getJSON("/ajax/select_data/"+ selected_listing_type +"/"+ selected_area +"/" , function(data) {
            reset_selects("suburb");
            $.each(data, function(item) {
                $("#suburb").append($("<option />").val(this.suburb).text(this.suburb + " ("+ this.count +")"));
            });
            $("#suburb").removeAttr("disabled");
        });
    } 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;

    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");
        });
    } else {
        reset_selects("property_type");
    }
}

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);
});

function validate_contact_us() {
    var entered_code = $("#id_code").val();
    if ($('#id_name').val() == 'Your Name*' || $('#id_name').val() == 'Contact Person*') {
        alert("Please fill in your name.");
        return false;
    } else if ($('#id_number').val() == 'Your Contact Number*' || $('#id_number').val() == 'Contact Number*') {
        alert("Please fill in your contact number.");
        return false;
    } else if ($('#id_email').val() == 'Your Email Address*' || $('#id_email').val() == 'Email Address*') {
        alert("Please fill in your email address.");
        return false;
    } else if (!(val_email($('#id_email')))) {
        alert("Please fill in a valid email address.");
        return false;
    } else if ($('#id_enquiry').val() == 'Comments*' || $('#id_enquiry').val() == 'Questions or Comments*' ) {
        alert("Please fill in a comment.");
        return false;
    } else if (AjaxVerifyImageCode(entered_code) == 'False') {
        alert("Please fill in the verification code correctly.");
        return false;
    } else {
       $('#id_enquiry_form').submit();    
    }
    
}

function validate_search() {
    
    if ($('#id_listing_type').val() == '') {
        alert('Please select a listing type');
        return false;
    } else if ($('#id_province_area').val() == '') {
        alert('Please select a search area');
        return false;
    } else {
        var province_area = $('#id_province_area').val().split('|')
        var url = '/property/' + $('#id_listing_type').val() + '/' +  province_area[0] + '/'+ province_area[1] + '/'  + $('#id_suburb').val() + '/' + $('#id_property_type').val() + '/'
        $('#id_search').attr('action', url);
        return true;
    }
    return false;
   
}

function sort_results(opt) {
    window.location="?s=" + opt;
}


function AjaxVerifyImageCode(entered_code) {
  var verified = "False";
  if(entered_code!=""){
	$.ajax({
		  url: "/ajax/check_verification/"+entered_code+"/",
		  async: false,
		  success: function(msg){
			verified = msg;
		  }
	});
  }
  
  return verified;
}


