﻿PostcodeCheckJson = null;
PostcodeCheckParams = null;
CardCheckJson = null;
CardCheckParams = null;

$(document).ready(function() {
    //validation rules
    $.validator.addMethod('dateAUS',
        function(value) {
            if (value.toString().length == 0) return true;
            Date.format = "dd/mm/yyyy";
            var dtm = Date.fromString(value);
            if (dtm == false) {
                return false;
            }
            if (dtm.getFullYear() < 1900) {
                return false;
            }
            var x = dtm.asString("dd/mm/yyyy");
            return x == value;
        },
        'Date format is dd/mm/yyyy');
    $.validator.addMethod('phoneAUS',
        function(value) {
            if (value.toString().length == 0) return true;
            var regE = new RegExp('(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|4|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)');
            return regE.test(value);
        },
        'Enter valid telephone number');
    $.validator.addMethod('postcode',
        function(value) {
            return TestPostcode(value, true);
        },
        'Enter valid postcode for your state');
    $.validator.addMethod('postcodeAnyState',
        function(value) {
            return TestPostcode(value, false);
        },
        'Enter valid postcode for your state');
    $.validator.addMethod('postcodeNoElec',
        function(value) {
            return false;
        },
        'Simply Energy does not provide Electricity to the Postcode you have provided.');
    $.validator.addMethod('postcodeNoGas',
        function(value) {
            return false;
        },
        'Simply Energy does not provide Gas to the Postcode you have provided.');
    $.validator.addMethod('nmiPrefix',
        function(value) {
            var regE = new RegExp('^\\d{4}$');
            return regE.test(value);
        },
        'Provide 4 digits');
    $.validator.addMethod('mirnPrefix',
        function(value) {
            var regE = new RegExp('^\\d{3}$');
            return regE.test(value);
        },
        'Provide 3 digits');
    $.validator.addMethod('nmiNoElec',
        function(value) {
            return false;
        },
        'Your NMI does not match any distributors in your postcode. Please re-check or select \"I don`t know\".');
    $.validator.addMethod('mirnNoGas',
        function(value) {
            return false;
        },
        'Your MIRN does not match any distributors in your postcode. Please re-check or select \"I don`t know\".');
    $.validator.addMethod('meterReadingDate',
        function(value) {
            return false;
        },
        'Must not be a Friday and at least 5 business days in the future.');
    $.validator.addMethod('requiredSelect',
        function(value) {
            return false;
        },
        'Must not be a Friday and at least 5 business days in the future.');
    $.validator.addMethod('postcodeNoElecExt',
        function(value) {
            return CheckPostcodeExt(value, "elec");
        },
        'Unfortunately Simply Energy does not supply Electricity to the Postcode you have provided.'
    );
    $.validator.addMethod('postcodeNoGasExt',
        function(value) {
            return CheckPostcodeExt(value, "gas");
        },
        'Unfortunately Simply Energy does not supply Gas to the Postcode you have provided.'
    );
    $.validator.addMethod('postcodeMultiSupExt',
        function(value) {
            return CheckPostcodeExt(value, "multiSuppliers");
        },
        'Simply Energy has multiple energy distributors in your area.'
    );
    $.validator.addMethod('years18',
        function(value) {
            var minDate = GetMinDobDate();
            var x = FormatDateToYMD($("#C_DateOfBirth").val());
            var dob = new Date(x);
            return dob <= minDate;
        },
        'You have to be at least 18 years old.'
    );
    $.validator.addMethod('supplyAddress',
        function(value) {
            return IsAddressValidated("SupplyAddress");
        },
        'Please make sure your Supply Address is valid.'
    );
    $.validator.addMethod('billingAddress',
        function(value) {
            return IsAddressValidated("PostalAddress");
        },
        'Please make sure your Mailing Address is valid.'
    );
    $.validator.addMethod('currentAddress',
        function(value) {
            return IsAddressValidated("CurrentAddress");
        },
        'Please make sure your Current Address is valid.'
    );
    $.validator.addMethod('card',
        function(value) {
            if (!value.length) {
                return true;
            }
            return CheckCardNumberExt(value);
        },
        'Please make sure your card number is valid.'
    );
    $.validator.addMethod('acceptTermsOnDetails',
        function(value) {
            if ($("#paymenttype_bill").is(":checked")) {
                return true;    //manual payment, no need to validate
            }
            var x = $("input[name=DDA_Accept_TermsConditions]:checkbox").attr("checked");
            return x;
        },
        'You have to accept terms and conditions.'
    );
    $.validator.addMethod('noElecSupply',
        function(value) {
            var x = $("input[name=electricity]:radio:checked").val();
            return x != "no";
        },
        'You will not be able to proceed with this online sign up as electricity is not being supplied to the property. Please contact our Customer Care team on 13 88 08 Monday to Friday 8.30am – 8.00pm (AEST).'
    );
    $.validator.addMethod('noGasSupply',
        function(value) {
            var x = $("input[name=gas]:radio:checked").val();
            return x != "no";
        },
        'You will not be able to proceed with this online sign up as gas is not being supplied to the property. Please contact our Customer Care team on 13 88 08 Monday to Friday 8.30am – 8.00pm (AEST).'
    );
    $.validator.addMethod('bsb',
        function(value) {
            if (value.toString().length == 0) return true;
            var regE = new RegExp('^\\d{3}-?\\d{3}$');
            return regE.test(value);
        },
        'Enter valid BSB number'
    );
    $.validator.addMethod('bankAccountNumber',
        function(value) {
            if (value.toString().length == 0) return true;
            var regE = new RegExp('^\\d{6,20}$');
            return regE.test(value);
        },
        'Enter valid bank account number'
    );


    //rcb validation
    $("#rcbForm").validate({
        onkeyup: false,
        onblur: false,
        onfocusout: false,
        rules: {
            rcbName: { required: true, minlength: 3 },
            rcbEmail: { email: true },
            rcbPhone: { required: true, phoneAUS: true }
        }
    });
    //default form button
    $("form input, form select").live("keypress", function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            var btns = $(this).parents("form").find("input[type=button].default, input[type=submit].default");
            if (btns.length) {
                btns[0].click();
                return false;
            }
        }
    });
    //load Google Analytics script
    //$("#GoogleAnalytics").load(SiteRoot() + "Home/LoadGoogleAnalytics", null, null);

    //Set maxlength of all the textarea (call plugin)  
    $().maxlength();

});

//Input type radio helper class / default ctor
function Radio() {
    this.name = null;
    this.isYes = null;
    this.isNo = null;
    this.isUnchecked = null;
    this.setValue = setValue;
}

//Input type radio helper class / ctor(name)
function Radio(name) {
    this.name = name;
    this.isYes = $("input[name=" + name + "]:checked").val() == "yes";
    this.isNo = $("input[name=" + name + "]:checked").val() == "no"; ;
    this.isUnchecked = !this.isYes && !this.isNo;
    this.setValue = setValue;
}

//Input type radio helper class / set value
function setValue(val) {
    if (val == "unchecked") {
        $("input[name=" + this.name + "]").attr("checked", false);
    } else if (val) {
        $("input[name=" + this.name + "]:even").attr("checked", true);
    } else {
        $("input[name=" + this.name + "]:odd").attr("checked", true);
    }
}

function SiteRoot() {
    return $('#rootPath').val();
}

function BoxAnimSpeed() {
    return 400;
}

function ShowLoadingImage() {
    $("body").append("<div id='TB_load'><img src='" + SiteRoot() +
        "Content/loadingAnimation.gif" + "' /></div>");
    $('#TB_load').show(); //show loader
}

function HideLoadingImage() {
    $("#TB_load").remove();
}

function LoadYesNoFromModel(modelId, radioName) {
    var value = $(modelId).val();
    var r = new Radio(radioName);
    if (value.length) {
        if (value == "True" || value == "Yes") {
            r.setValue(true);
        } else {
            r.setValue(false);
        }
    } else {
        r.setValue("unchecked");
    }
}

function SaveYesNoToModel(modelId, radioName, modelType) {
    var r = new Radio(radioName);
    if (modelType == "bool") {
        $(modelId).val(r.isUnchecked ? "" : r.isYes);
    } else {
    var value = r.isUnchecked ? "" : r.isYes ? "Yes" : "No";
        $(modelId).val(value);
    }
}

function CheckPostcodeExt(value, type) {
    var postURL = SiteRoot() + "Rates/CheckPostcode";
    var data = {};
    data["postcode"] = value;
    data["gas"] = $("#QET_ID").val();
    data["hotwater"] = $("input[name=water]:checked").val() == "yes";
    data["product"] = $("#Qu_Product").val();
    data["qrn"] = $("#Qu_Reference_No").val();
    data["nmi"] = $("#Qu_NMI_Prefix").val();
    data["mirn"] = $("#Qu_MIRN_Prefix").val();
    data["nmiDontKnow"] = $("#Qu_NMI_DontKnow").val();
    if (PostcodeCheckParams != null && objectsAreSame(PostcodeCheckParams, data)) {
        //cached data
        OnCheckPostcodeSuccess(PostcodeCheckJson, type);
    } else { //new ajax request
        $.ajax({
            cache: false,
            async: false,
            type: "POST",
            dataType: "json",
            data: data,
            url: postURL,
            success: function(json) {
                OnCheckPostcodeSuccess(json, type);
                PostcodeCheckParams = data;
                PostcodeCheckJson = json;
            }
        });
    }
    return result;
}

function OnCheckPostcodeSuccess(json, type) {
    //var jsonData = $.evalJSON(json);
    result = null;
    if (type == "elec") {
        result = json.isElecAvailable;
    } else if (type == "gas") {
        result = json.isGasAvailable;
    } else if (type == "multiSuppliers") {
        result = !json.isElecMultiSuppliers && !json.isGasMultiSuppliers;
        AfterPostcodeCheck(json);
    }
}

function objectsAreSame(x, y) {
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName] && typeof x[propertyName] != 'object') {
         objectsAreSame = false;
         break;
      }
   }

   return objectsAreSame;
}

function CheckCardNumberExt(value) {
    var postURL = SiteRoot() + "Details/CheckCardNumber";
    var data = {};
    data["number"] = value;
    if (CardCheckParams != null && objectsAreSame(CardCheckParams, data)) {
        //cached data
        OnCheckCardSuccess(CardCheckJson);
    } else { //new ajax request
        $.ajax({
            cache: false,
            async: false,
            type: "POST",
            dataType: "json",
            data: data,
            url: postURL,
            success: function(json) {
                OnCheckCardSuccess(json);
                CardCheckParams = data;
                CardCheckJson = json;
            }
        });
    }
    return result;
}

function OnCheckCardSuccess(json) {
    result = json;
}

function InitRcbForm() {
    if ($("#rcbDiv").length) {
        $("#TB_ajaxContent").html("");
        var url = "TB_inline?&amp;height=500&amp;width=250&amp;inlineId=rcbDiv&amp;modal=false";
        tb_show("", url);

        if ($("#C_Primary_Contact").length && $("#C_Primary_Contact").val().length) {
            $("input[name=rcbName]").val($("#C_Primary_Contact").val() + " " + $("#C_Primary_LastName").val());
        }
        if ($("#C_Email_Address").length && $("#C_Email_Address").val().length) {
            $("input[name=rcbEmail]").val($("#C_Email_Address").val());
        }
        if ($("#phoneInput").length && $("#phoneInput").val().length) {
            $("input[name=rcbPhone]").val($("#phoneInput").val());
        }
    }
}

function RemoveDuplicateMessages() {
    var reqTextOld = 'This field is required.';
    var reqTextNew = 'Please fill in all required fields.';
    $("#error-ul li label:contains('" + reqTextOld + "'), #error-ul li label:contains('" + reqTextNew + "')").not(":first").css({ "display": "none" }).parent().css({ "display": "none" });
    $("#error-ul li label:contains('" + reqTextOld + "'):first").text(reqTextNew).css({ "display": "block" }).parent().removeAttr("style");
	var arrowposi = ($(".errorcontainer").height() + 20) + "px"; // fixes issues in IE with arrow not moving when needed
	$(".errorcontainer span.arrow").css({"top":arrowposi});
}

function FormatDateToYMD(date) {
    var r = null;
    try
    {
        var s = new String(date);
        r = s.substr(6, 4) + "/" + s.substr(3, 2) + "/" + s.substr(0, 2);
    } catch (e) { }
    return r;
}

function HideBoxMessages() {
    $("#addressVerification, #multipleListings, #structuredAddress, #multipleSuppliers, #existingCustomer, #movingToNewPremises, #noConnection, #rcbDiv").hide();
    $("#rcbTeaser").show();
}

function Capitalise(elem) {
    var tmpStr;
    var tmpChar;
    var preString;
    var postString;
    var strlen;
    var el = $(elem);
    tmpStr = el.val();
    strLen = tmpStr.length;
    if (strLen > 0) {
        tmpChar = tmpStr.substring(0, 1).toUpperCase();
        postString = tmpStr.substring(1, strLen);
        tmpStr = tmpChar + postString;
    }
    el.val(tmpStr);
}

jQuery.fn.maxlength = function() {
    $("textarea[maxlength]").keypress(function(event) {
        var key = event.which;
        //all keys including return.  
        if (key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if (length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}

$.fn.error = function(msg) {
    if ($(this).next().filter("label.error").length) {
        $(this).next().text(msg);
    } else {
        $(this).after("<label class='error' for='" + $(this).attr("id") + "'>" + msg + "</label>");
    }
}

$.fn.clearErrors = function() {
    $(this).find("label.error").remove();
}

$.fn.nopaste = function() {
    $(this).bind('paste', function(e) {
        e.preventDefault();
    });
}

$.fn.noEnter = function() {
    $(this).keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            e.preventDefault();
        }
    });
}

$.fn.clickbutton = function(button_selector) {
    $(this).keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(button_selector).click();
            return false;
        } else {
            return true;
        }
    });
}

function IsValidDate(d) {
    if (Object.prototype.toString.call(d) !== "[object Date]")
        return false;
    return !isNaN(d.getTime());
}

function TestPostcode(value, testState) {
    if (value.toString().length == 0) return true;
    var pc = 0 + value;
    var state = null;
    if ($("#C_Supply_State").length) {
        state = $("#C_Supply_State").val();
    }
    if (!testState || state == null) {
        return (pc >= 3000 && pc <= 3999) || (pc >= 5000 && pc <= 5999);
    } else if (state == "VIC") {
        return pc >= 3000 && pc <= 3999;
    } else if (state == "SA") {
        return pc >= 5000 && pc <= 5999;
    }
}