(function($) {
    $.fn.empty_value = function(empty_value){
        reset = true;
        class_name = 'empty';
        return this.each(function(){
            $(this).focus(function(){
                if ($(this).hasClass(class_name)){
                    $(this).removeClass(class_name);
                    if (reset) { $(this).val('').attr('title', ''); }
                }
            }).blur(function(){
                var val = $(this).val();
                if (!val || val == empty_value){
                    $(this).addClass(class_name).val(empty_value).attr('title', $(this).val());
                }
            }).blur();
        });
    };
})(jQuery);

function CloseDialog(){
    $('.dialog').hide();
    //$('.dropShadow').remove();
    return false;
}

function OpenDialog(dialog_id){
    CloseDialog();
    $('#'+dialog_id).show();
    //$('#'+dialog_id).dropShadow();
}

function MessageBox(msg){
    CloseDialog();
    $('#text_messagebox').html(msg);
    $('#dialog_messagebox').show();
    //$('#dialog_messagebox').dropShadow();
}

function ValidatePostalCode(value){
    // Valid formats are (X1X 1X1) or (X1X1X1) or (X1X-1X1) for CA
    // and five digits for USA
    return (value.match(/^[a-zA-Z][0-9][a-zA-Z](-| )?[0-9][a-zA-Z][0-9]$/)
         || value.match(/^[0-9][0-9][0-9][0-9][0-9]$/));
}

function ValidateEmail(value){
    return value.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
}

function ValidatePhone(value){
    var stripped = value.replace(/[\(\)\.\-\ ]/g, '');
    if (isNaN(parseInt(stripped)))
        return false;
    if (stripped.length < 10)
        return false;
    return true;
}

function PrintOrder(n){
    var f = window.open('/order/'+n+'/print/', null, 'width=1000,height=700,toolbar=no,status=no');
    f.focus();
    return false;
}

function OrderAdd(){
    $('#id_action').val('add');
    $('#id_form').submit();
    return false;
}

function OrderComplete(){
    $('#id_action').val('complete');
    $('#id_form').submit();
    return false;
}

function OrderPreview(order_id){
    if (confirm("Save changes?")) {
        $('#id_action').val('preview');
        $('#id_form').submit();
    }
    else{
        if (order_id)
            document.location.href = '/order/view/'+order_id+'/';
        else
            document.location.href = '/order/';
    }
    return false;
}
