/* 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()
}

/* 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 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 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 validate_login() {
    if (val_email($('#id_email')) == false) {
        alert("Please enter a valid email address");
    } else if ($('#id_password').val() == 'Password') {
        alert("Please enter your password");
    } else {
        $('#id_login_form').attr('action', '/member-login/');
        $('#id_login_form').submit();
    }
}


function set_direct_url(url) {
    html = "<br>http://www.headweardirect.net/<span id='id_lbl_web_name'>%s</span>";
    if (url != '')
        html = "<br><a href='#1'>http://www.headweardirect.net/<span id='id_lbl_web_name'>%s</span></a>";
        html= html.replace(/%s/g, url);
    $('#id_direct_url').after(html);
    
}


function URLEncode (clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();

  var regex = /(^[a-zA-Z0-9_-]*)/;
    
    while (x < clearString.length) {
        char = clearString[x].replace(' ','-')
        var match = regex.exec(char);
        
        
        if (match != null && match.length > 1 && match[1] != '') {
            output += char.toLowerCase();
        }
        x++;
    }
    return output;
}

function updateWebName(webname) {
    
    if (webname!="") {
        $('#id_lbl_web_name').html(URLEncode(webname));
        $('#id_direct_url').val(URLEncode(webname));
    }   else { 
        $('#id_lbl_web_name').html('[your-website-name]');
        $('#id_direct_url').val('');
    }
    
    
}

function validate_forgot_password(form) {
    
    var img_text = document.getElementById(form).img_text.value ;
    var frm_hash = document.getElementById(form).frm_hash.value ;
    
    if (val_email('#id_email_forgot') == false) {
        alert("Please enter a valid email address");
        
    } else if (AjaxVerifyImageCode(img_text, frm_hash) == "False") {
        alert("Please enter the verification code correctly.");
        
    } else {
        $('#id_forgot_password').submit();
    }
}

function AjaxVerifyImageCode(enteredcode,imghash) {
  var verified = "False";
  if(enteredcode!="" && imghash!=""){
	$.ajax({
		  url: "/ajax/check_verification/"+enteredcode+"/"+imghash+"/",
		  async: false,
		  success: function(msg){
			verified = msg;
		  }
	});

  }
  return verified;
}
